Friday, May 1, 2026

Untyped case statement

Yet another blog post reminding how useful a compiler could be. Even for projects mainly using typed languages, it is often required to write some code with at least optional types like Typescript/Javascript or Groovy. For the latter of them quite good use case could be to have a jenkins pipeline implemented. This way I have spent some time just having to read more carefully, as what you see may be not exactly how actually things work. The code looked like this:


def aStr = 'x'
switch (aStr) {
  case 'x' || 'y':
    println('x or y')
    break;
  default:
    println('default')
    break;
}

At first glance, it looks like it should match when aStr is either 'x' or 'y'. Right?

Wrong.

The output is:


default

What actually happens?

Similar piece of code landend in my jenkins and I've spent hours trying to find the bug in a code that looks quite good.

The expression 'x' || 'y' doesn't create an "or" condition for the case statement. Instead, it evaluates to a boolean true (since both strings are truthy in Groovy). So the case statement effectively becomes:


case true:

And since aStr is the string 'x', not the boolean true, it never matches. It will always fall through to the default case.

Interestingly, JavaScript has a similar gotcha, though with a twist. In JavaScript, 'x' || 'y' evaluates to 'x' (the first truthy value), so the case becomes case 'x':. This would actually match when aStr is 'x', printing "x or y". But when aStr is 'y', it falls through to default. So the "or" logic still doesn't work as intended - it only matches one of the values. Different language, different behavior, same trap.

Testing with 'y' gives the same result:


def aStr = 'y'
switch (aStr) {
  case 'x' || 'y':
    println('x or y')
    break;
  default:
    println('default')
    break;
}
// Output: default

The correct way

Use a regular expression pattern instead:


def aStr = 'y'
switch (aStr) {
  case ~/x|y/:
    println('expr x or y')
    break;
  default:
    println('default')
    break;
}
// Output: expr x or y

Or use multiple case statements:


switch (aStr) {
  case 'x':
  case 'y':
    println('x or y')
    break;
  default:
    println('default')
    break;
}

Summary

Dynamic typing gives you flexibility, but it won't catch these subtle logical errors at compile time. What looks like an "or" condition is actually a boolean expression that evaluates before the case comparison even happens.

A typed language with proper pattern matching would have caught this at compile time. Or at least made you think twice about what you're actually expressing.

Sunday, April 19, 2026

File upload in Quarkus

One constant thing in IT is that changes are getting quicker and quicker.
People who work in this business won't get bored. Definitely good place to be.

Recently I have been trying to implement the file upload functionality with Quarkus.
While the framework is building on a well established standards dated back to J2EE standard, the recent APIs are changing - and this happened quite often. The ecosystem has evolved through several REST implementations - RESTEasy Classic, RESTEasy Reactive, and now Quarkus REST (which is essentially RESTEasy Reactive rebranded).

What I have found was: the great post and video from Sebastian - explainging all the details, despite the update post are no longer the way Quarkus file upload works.

So let's revise the topic with some (again maybe in Quarkus wolrd not most shiny and recent - at the time you are reading this) but stable API: MultipartFormDataInput. It's actually the recommended approach when you need fine-grained control over multipart request parsing.

@Slf4j
@EndpointPath("/upload")
class UploadEndpoint {


    @POST
    Response upload(MultipartFormDataInput input) {

        var metadata = metaDataIfNotFile(input.values)

        var files = extractFiles(input.values, metadata)

        files
            .forEach { write(it) }

        Response.status(201).entity(metadata).build()

    }


    def write(DataItem data) {
        var uploads = Paths.get("./my-uploads")
        var path = uploads.resolve(data.getFilename())
        try {
            if(!Files.exists(uploads)) {
                Files.createDirectories(uploads)
            }
            Files.write(path, data.data)
        } catch (e) {
            e.printStackTrace()
        }
    }


    static def metaDataIfNotFile(Map<String, Collection<FormValue>> formData) {
        formData
            .findAll { it.value.every { !it.fileItem } }
            .collectEntries { k,  formValues ->
                [ (k): formValues.collect { it.value } ] }
    }


    def extractFiles(Map<String, Collection<FormValue>> values, metadata) {
            values
                .findAll { it.value.find { it.fileItem } }
                .collectMany { extractData(it, metadata) }
    }

    def extractData(Map.Entry<String, Collection<FormValue>> entry, meta) {
            entry.value
                .findAll { it.fileItem && it.fileName?.trim() }
                .collectMany { tryData(it, meta) }
    }

    def tryData(FormValue formValue, meta) {
        try {
            [
                [
                    data    : Files.readAllBytes(formValue.getFileItem().file),
                    filename: formValue.fileName,
                    metaData: meta
                ] as DataItem
            ]
        } catch (e) {
            e.printStackTrace()
           []
        }
    }
}

@ToString @EqualsAndHashCode
class DataItem {
    byte[] data
    String filename
    Map<String, Collection<String>> metaData
}

You can test it with curl:

curl -X POST http://localhost:8080/upload -F "file=@/path/to/file"

Files land in `./my-uploads/` directory.

The full working example can be found in my github.


Quark - a kind of white cheese from Germany. 
Source: wikipedia, authored by Elskeletto


Saturday, February 22, 2025

Timeout for manual jobs in gitlab

There is a timeout functionality in gitlab pipelines. The running jobs are terminated after reaching configured period of time. However if the job has a manual step - it may hang in that state forever, as it is not actively running. This functionality is missing. See also: https://gitlab.com/gitlab-org/gitlab-runner/-/issues/29574.

But we do not need to wait for gitlab implementation of that feature.

Our solution will consist of an assisting watchdog job, run in parrallel in a separate stage. As this will require new `.gitlab-ci.yml` file, we will use an extra `util` repository, to handle it. Our util pipeline It will invoke a shell script that will just check whether the time passed is already above the limit, we have declared. We will need to pass some arguments like - the parent project id - so we can check the state and eventually terminate it, and the timeout value itself - so our solution is flexible and we avoid to hardcode it in watchdog.

In the parent pipeline we need to add a `watchdog` stage. We need to invoke the utility watchdog pipeline by calling build.

main pipeline
stages: [watchdog, build, deploy]
  
watch_pipeline:
  stage: watchdog
  trigger:
    project: your-group/util
    branch: main
  variables:
    PARENT_PIPELINE_ID: $CI_PIPELINE_ID
    PARENT_PROJECT_URL: $CI_PROJECT_URL
    MAX_PIPELINE_TIMEOUT: 3600          # 1 hour
 
 # later the build goes and whatever

Here is the `.gitlab-ci.yml` in util project:

stages:
  	- watchdog
  
watch_pipeline:
  	stage: watchdog
  	image: find_some_image_that_has_bash_curl_jq
  	script:
  		- bash ./watchdog.sh
  	allow_failure: true
    when: always
    parallel: 1

And the last piece is the script itself:

#!/bin/bash
set -euo pipefail  
  
printf "PARENT_PROJECT_URL=%s\nPARENT_PIPELINE_ID=%s\nMAX_PIPELINE_TIMEOUT=%s\n" \
  "$PARENT_PROJECT_URL" "$PARENT_PIPELINE_ID" "$MAX_PIPELINE_TIMEOUT"

echo "Watching pipeline $PARENT_PIPELINE_ID in $PARENT_PROJECT_URL"
echo "Max time: $MAX_PIPELINE_TIMEOUT sekund"


readonly START_TIMESTAMP=$(date +%s)

CURRENT_TIMESTAMP=$(date +%s)
ELAPSED_TIME=$((CURRENT_TIMESTAMP - START_TIMESTAMP))

if [ "$ELAPSED_TIME" -gt "$MAX_PIPELINE_TIMEOUT" ]
then
    echo "Cancelling pipeline: ${PARENT_PIPELINE_ID}!"

    curl --request POST \
         --header "PRIVATE-TOKEN: $TOKEN" \
         --header "Accept: application/json" \
         "$CI_API_V4_URL/projects/$PARENT_PROJECT_ID/pipelines/$PARENT_PIPELINE_ID/cancel"
fi
  

Last thing that is required is to add our Personal Access Token as TOKEN variable in gitlab CICD settings/variables. Make it protected and masked, so nobody can read it and access it. Unfortunatelly CI_JOB_TOKEN would not work in this case, due to missing permissions.

Wednesday, January 29, 2025

Docs should be versioned

Concept of having documentation stored and versioned as code is nothing new.

I have just opened not-so-fresh Michal's article regarding that (https://www.michalbartyzel.pl/blog/documentation-as-code PL), Fang suggested some marvelous solutions to approach the topic of living documentation (https://fayndee.me/techie/blog/api-documentation-as-code) even earlier.

So we do generate the docs out of the versioned source code, markup, reStructured text or asciidocs.

I am reffering to something else.

Treating the documentation as part of the product. As a contract between your team and the teams who consume it. The docs should be versioned as APIs are, the link urls must be versioned.

This is so clear, we search Javadocs or Postgresql docs and we can see immediately what version we are reffering to.
BTW postgres also allows comments on doc pages which may also be a source of priceless knowledge.

If the docs are outdated - yes we can show the warnining.

There is no value to get docs links changing every two weeks and forcing the consumers to update their link collection each time you rename a file.

Sunday, September 10, 2023

Using .env with maven

Dotfiles are quite popular in ruby and js ecosystem.
They are not popular however in java world as we can use maven (still not 0xDEAD ;) and pass configuration directly from the command line or create script for that. But why not take some standards from the other universes?
Having other ways to configure app provided by eg. spring boot it may be still useful for java developers.

You can use .env file to inject variables into your maven build, then it can get picked by spring boot and passed to configuration eg. while running tests.
Use case is to avoid putting the secrets into version control, while letting local integration tests to run. Without any extra script files and using tool that is known by other developers.

There is of course a maven plugin for that:
<groupid>io.github.mjourard</groupid>
<artifactid>env-file-maven-plugin</artifactid>
I have prepared a small example of usage with groovy and spring boot.
You can find it here: https://github.com/konopski/using-dotenv-with-maven.

It is a simplest spring boot application containing one bean (TheBean) which is using to configuration values. The very standard stuff to obtain a DB connection.
@Component
class TheBean {

    @Value('${spring.datasource.username}')
    String username

    @Value('${spring.datasource.password}')
    String pass
//...
Now spring lets us deliver the actual values using externalized config mechanism . Typically we use properties files and spring profiles. In our example there is a 'dev' profile defined, that provides a clear text password. It is good enough if you remeber to keep the dedicated profile properties file out of your version control.
The file (application-dev.properties) can look like this:
spring.datasource.password=secret
In the main application.properties file we do not define this entry - so in case it is missing (eg. ommiting the profile) the app will not start.

You can also have another mechanism controlling your password. Spring will take a corresponding definition from system environment.
In our case it is delivered by our .env file.
SPRING_DATASOURCE_PASSWORD=t3st_s3cr3t
That is verified in ApplicationTest class:

@SpringBootTest
class ApplicationTests {

    @Autowired TheBean bean

//...

    @Test
    void shouldReadFromDotEnv() {
            bean.pass == "t3st_s3cr3t"
    }
}
We can also use different values by using spring's properties overriding, adding to our .env file:
OVERRIDE_DB_PASS=password_override
And test for that:

@SpringBootTest(
    properties = ['spring.datasource.password=${OVERRIDE_DB_PASS}'] )
class PropsOverrideTest {

    @Autowired TheBean bean

//...

    @Test
    void shouldOverride() {
        bean.pass == "password_override1"
    }

}
For me this approach is quite clean, allows easy sharing among the team and composes quite well with existing environment.
And remember to keep your passwords away from git.

Friday, September 27, 2019

Map or any other option?

I must admit that sometimes we can go too far with using Optionals as silver bullet. Let's take a look at a simple mapper class, defined like this:
class Mapper {
  Optional<Dto> map(Optional<Entity> input) {
    //... implementation
  } 
}
At first passing an Optional instance looks like a good idea - we want to be safe from null values, we express our defensive intent in types. What can go wrong? Let's now take a look at how this mapper may be used.
Entity entity = //...
Dto dto = mapper.map(Optional.of(entity)).get();
Well, typical code involving the mapper is packing the input entity into an instance of Optional, just to get to output value. Even worse could look usage for a collection.
List ents = //...
List<dto> dtos = ents.stream()
  .map(Optional::of)
  .map( x -> mapper.map(x) )
  .map(Optional::get)
  .collect(toList());
Instead of using type system and compiler to our benefit, we lie about our input value - which we actually know that is never null. Not only we do not use the knowledge we already have, but put extra burden of reading through the wrapping on reader's eyes. I do not mention creating extra instances of Optional, and making common use of calling .get() - which is not best practice. I do not want to get familiar to that.
What I also do not like in the code is forcing the user of our mapper to provide object wrapped into the very implementation of Optional. Actually mapper should not care which implementation of Optional I use. There are more than the standard one, and they may have some properties that are more useful for me in the context of my implementation. Last thing, we may observe here is that the API actually mimics what the Optionals are expected to provide - the map method itself.
What we need is just:
Dto map(Entity in) {
//....
}
That simple.
Implementation of very mapping is what should be provided directly by mapper, without requirement for a wrapped value. We should require that value will be non-null. Optionality should be handled in client code somewhere else, we will not tolerate null values anyhow, right? Such mapper can be also easily used when applied to streams or collections. We save machine's memory from wrapping non-null values into Optionals and our precious eyes from reading the code that would cause the latter.

Friday, July 19, 2019

Woobie Doobie - switching database access library in Scala

Doobie is getting more and more popular as a database access tool in modern applications. This year on Scalar conference voting Doobie won over its competition - particularly Slick. Not without a reason. Recently my project also dropped Slick.
Doobie gave us nearly immediately:
  • easier learning curve - it is about plain, old SQL ;
  • more compile time verification - now you do not need to run your query to find out your type mapping is broken ;
  • referential transparency and better integration with effects system used in project ;
  • no hacking needed when you need to select more columns than unfamous 22. One particular issue that came out quite early was a bit tricky to resolve with given message:
    [error] Cannot construct a parameter vector of the following type:
    [error]
    [error]   Boolean(true) :: shapeless.HNil
    [error]
    [error] Because one or more types therein (disregarding HNil) does not have a Put
    [error] instance in scope. Try them one by one in the REPL or in your code:
    [error]
    [error]   scala> Put[Foo]
    [error]
    [error] and find the one that has no instance, then construct one as needed. Refer to
    [error] Chapter 12 of the book of doobie for more information.
    
    Studying chapter 12 did not help. Here is the query that caused the issue:
    sql"select one_col, two_col from TABLE where flag = ${true} "
    
    It turns out that Doobie (actually Shapeless) does not handle properly the inlined true literal. What is needed is just to extract it to separate value:
    val flag = true
    sql"select one_col, two_col from TABLE where flag = ${flag} "
    
    That resolves the problem. It would also work if we added type annotation:
    sql"select one_col, two_col from TABLE where flag = ${true: Boolean} "
    
    It's up to you which way you prefer.
  • Wednesday, October 31, 2018

    Remove one file from git commit to a remote branch

    Ooops, I did it again. Commited and pushed one file too much.
    ? git push --set-upstream origin bugfix/JRASERVER-65811
    
    What now? How to remove the file from a public commit?

    Let's first go back to the base branch.
    ? git checkout -
    
    Switched to branch 'develop'
    Your branch is up to date with 'origin/develop'.
    
    I assume I may have some changes in my local copy so first need to clean it. I am going to delete my local branch.
    ? git branch -D bugfix/JRASERVER-65811
    Deleted branch bugfix/JRASERVER-65811 (was 5e17f72f).
    
    Next step is to synchronize with remote repository and fetch the branch again.
    ? git pull
    remote: Enumerating objects: 119, done.
    remote: Counting objects: 100% (119/119), done.
    remote: Compressing objects: 100% (119/119), done.
    remote: Total 119 (delta 41), reused 0 (delta 0)
    Receiving objects: 100% (119/119), 43.63 KiB | 1.82 MiB/s, done.
    Resolving deltas: 100% (41/41), done.
    From gitlab:project/frontend
       736ac14a..ea0ba57e  bugfix/JRASERVER-65811-allopenissues -> origin/bugfix/JRASERVER-65811-allopenissues
    Already up to date.
    
    I can now switch to the branch back.
    ? git checkout bugfix/JRASERVER-65811
    Switched to a new branch 'bugfix/JRASERVER-65811'
    Branch 'bugfix/JRASERVER-65811' set up to track remote branch 'bugfix/JRASERVER-65811' from 'origin'.
    
    Time to bring the last commit into staging.
    ? git reset --soft HEAD^
    
    I can see this was done by showing status.
    ? git status
    On branch bugfix/JRASERVER-65811
    Your branch is behind 'origin/bugfix/JRASERVER-65811' by 1 commit, and can be fast-forwarded.
      (use "git pull" to update your local branch)
    
    Changes to be committed:
      (use "git reset HEAD ..." to unstage)
    
            new file:   src/app/lktree/lktree.component.spec.ts
            modified:   src/app/modules/spaces/data/space-datasource.ts
            modified:   src/app/modules/spaces/document-details/document-details.component.html
            modified:   src/app/modules/spaces/spaces-tree/spaces-tree.component.ts
            modified:   src/app/modules/user-context/data/user-context-datasource.ts
    
    The first of files is the one I want to extract and unstage from to working copy. This simply undo git add.
    ? git reset src/app/lktree/lktree.component.spec.ts
    
    Yeah! My changes are now in state I wanted!
    ? git status
    On branch bugfix/JRASERVER-65811
    Your branch is behind 'origin/bugfix/JRASERVER-65811' by 1 commit, and can be fast-forwarded.
      (use "git pull" to update your local branch)
    
    Changes to be committed:
      (use "git reset HEAD ..." to unstage)
    
            modified:   src/app/modules/spaces/data/space-datasource.ts
            modified:   src/app/modules/spaces/document-details/document-details.component.html
            modified:   src/app/modules/spaces/spaces-tree/spaces-tree.component.ts
            modified:   src/app/modules/user-context/data/user-context-datasource.ts
    
    Untracked files:
      (use "git add ..." to include in what will be committed)
    
            src/app/lktree/
    
    I can commit again - this time the right files.
    ? git commit src/app/modules/spaces/ src/app/modules/user-context/data/user-context-datasource.ts -m "JRASERVER-65811: allopenissues"
    [bugfix/JRASERVER-65811 80002b42] JRASERVER-65811: allopenissues
     4 files changed, 60 insertions(+), 25 deletions(-)
    
    Last commit is to overwrite the remote branch. Do not do it at home ;)
    ? git push --force
    

    Friday, June 22, 2018

    Authenticating with deploy keys in Jenkins pipelines

    While using M$ github you may use deploy keys dedicated to a specific repository instead of giving your private key to Jenkins. And yes, it is possible to use deploy key in Jenkins pipelines.

    To be able to manage your ssh identity you need first to install sshagent plugin.




    BTW If you are running Jenkins instance on M$ windows machine remember to add sshagent (eg. from your git distribution) to your %PATH%.



    Generate a key pair.
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    


    Goto Credentials in Jenkins left-side main menu. Add credentials of type 'SSH Username with private key'. You can paste the created private key into text area.



    In M$ github repository settings now you can add corresponding public key.



    In your pipeline code you can use credentials when you surround eg. git calls with sshagent block.

                    sshagent(credentials: ['throw-me-away-key']) {
                        bat """git pull origin master"""
                    }
    



    If you get errors make sure that you are not using friendly name but right ID of credential in Jenkins.


    10:09:04 FATAL: [ssh-agent] Could not find specified credentials
    10:09:04 [ssh-agent] Looking for ssh-agent implementation...
    10:09:04 [ssh-agent]   Exec ssh-agent (binary ssh-agent on a remote machine)
    10:09:04 $ ssh-agent
    10:09:04 SSH_AUTH_SOCK=/tmp/ssh-vCKYmwW5gfvP/agent.5592
    10:09:04 SSH_AGENT_PID=5572
    10:09:04 [ssh-agent] Started.
    10:09:04 [original] Running batch script
    10:09:04 
    10:09:04 C:\Program Files (x86)\Jenkins\workspace\lk-pipeline-0\original>git pull 
    10:09:06 $ ssh-agent -k
    10:09:06 git@github.com: Permission denied (publickey).
    10:09:06 fatal: Could not read from remote repository.
    10:09:06 
    10:09:06 Please make sure you have the correct access rights
    10:09:06 and the repository exists.
    10:09:06 unset SSH_AUTH_SOCK;
    10:09:06 unset SSH_AGENT_PID;
    10:09:06 echo Agent pid 5572 killed;
    10:09:06 [ssh-agent] Stopped.
    

    Friday, January 12, 2018

    OOP is not dead: Elegant Objects

    Recently I have observed a growing wave of what I describe as kind of anti-design movement. Experienced people find out they have been doing it wrong. One say: TDD is dead, other: we do not need interfaces. Script kiddies Dynamic language programmers claim strongly typed languages are broken. It comes even to a very last discovery that short methods are pure evil!
    I've just spoken to a programmer, who had nearly 20 years of experience with Java, yet trying to convince me that interfaces are useless, just because for that long time he had never written an alternative implementation of method. In same conversation however, he praised ORMs for possibility of painless exchanging of DB engine!
    The leitmotiv of this new heresy is that we can easily cut off the effort introduced by OOP, design patterns, TDD, DDD or any other, until now considered a good practice and focus on delivering just what matters - the `business value` itself. So that we can successfully bill the client and go to the next project. This sounds good. That may make sense. If your project is not going to be maintained for years, please feel free to skip paradigms. Use spaghetti architecture. Use mixed javascript, php, perl and have fun with testing on production. Building a prototype is a kind of development. Write once and dispose the code soon. But in project that is planned for more than three months this approach is just as wrong like murdering your client with an axe and taking their money. Just like Vikings did.

    Wikingowie (Wolin 2018 04)

    It is all about maintainability. If you use dynamic typing but do not cover your app with test, expect your work will get broken by colleagues siting next to you and following your discipline. If you do not use interfaces - I expect I know already how your tests look like. Like `null`. If you prefer not to extract method I know how lightweight your code is. I have seen java class source code that had over 1 megabyte! Imagine how fast you can deliver business value in such a project. If you think design is a waste - yeah... I was there, I have seen important application presenting different results on each subpage, thanks to `if` pyramid of doom, copied, pasted and happily living its own life. It does cost. Believe me. Technical debt is not something that will disappear by just forgetting the matter.


    Elegant Objects by Yegor Bugayenko gives you some kind of framework. By following author's 23 pieces of advice you can learn how to use Object Oriented Paradigm in real language like Java. Yegor conducts personalized object (Mr. Object) through journey of life. The very similar way as we personalize actors using eg. Akka and follow some important rules - not forced by language itself. This concept seems to be core of author's approach to improve maintainability of software we create. When we interact with a person, we stick to some polite way of communication, assuming we are not talking to an idiot. Same holds for our objects.

    There are some other helpful tricks and lot of strong opinions on using some code constructs and patterns/antipatterns. The book gives number of easy to remember code examples. Explains or recall you why constructor injection is the only right way and why `static` is not welcomed (even if we do now FP in Java). If you are more interested in the content of the book - I can recommend Tomek's review and page of Yegor Bugayenko.

    Some of author's rules I think may be a bit controversial and exaggerated - at least in context of my last project. The only point I really didn't like was actually Yegor's approach to C++, a bit unfair as this language can be as object oriented as Java is.

    I am not imposing that there is only one way to create maintainable software. Whether you will use header files to separate contract from implementation or will you use java interfaces or maybe free monads that define program separated from its interpretation. It is up to you. But please, take some set of rules, and keep to them in consistent manner. That is what your client pays you for.

    Friday, December 8, 2017

    Always say "Junk fix", never "quick fix"

    software development area - names are almost only context that can be added to a computation. By using common vocabulary we build shared understanding of how things work and what is their meaning. When we communicate with outside world using our language we also put a corner stone under the how eg. business people will be able to visualize system we are responsible for.

    One of the greatest examples of metaphor used to explain the nature of projects to stakeholders is a term coined by Ward Cunningham - technical debt. In very illustrative way it mimics well known figure of a financial debt to explain the costs or possible impact that unmaintained software brings to owners. In the opposite pole I can see a term used so often, while bringing so much confusion and leading to misunderstandings and even conflicts in many organisations. I mean the "quick fix". Quick and dirty, when we tend often to forget how dirty it was, leaving it in our software just to make it rot. Please keep in mind each time you say "quick fix" what you really communicate is "cheap fix". Is it what you meant? Will it be that quick in the final picture? Or it is just half done, ad hoc patch that will not consist solution, but maybe bring counter productive impact to changed process?



    About the false velocity of quick fixes
    Recently I have watched Netflix "Cooked" series of four, visually elaborated stories about food and eating. It was about the real food, that brings value to our life, as opposed to what is often offered to us, mass product of industry, optimized for price only, washed from nearly everything our body needs. The junk food.

    I find this being a perfect metaphor to what is often offered as a "quick fix". This word junk explains exactly nature of the fix without giving a false assumption that anything cheap is being discussed. Let's be clear about it.
    It is a "junk fix", not "quick fix".

    Sunday, November 12, 2017

    Stand IT up!

    Recently I had a pleasure to join a presentation on how sitting at work is degrading ones health. IT industry is at highest risk. What unhealthy position does to us has serious, even fatal consequences in long term.



    Our way of living is far away from what is natural living that human bodies are created for. This has so many aspects and long term factors that cannot be neutral for our health.

    What we do to our bodies is what we call technical debt. Unfortunately, this project has very limited time dedicated for refactoring. Medicine is now clear about it. Sitting at work can take YEARS from our lifetime. 

    IT is a fantastic community. We exchange knowledge to improve our skills. We are professionals willing to deliver our best to our business partners and apply best practices we know. We are able to suppress all practices regarding our job, that we considered harmful.

    Why not apply this approach to ourselves? Stop unhealthy practices that damage the only thing which really belongs to us - our body? There are scientific, medical, cultural and moral reasons for standing up at work. Changing small habits seems an easy way to live much happier, healthy life. I am convinced!

    TLDR; quit sitting, it kills.

    Friday, July 7, 2017

    I want my Rhino back! Switching to Nashornless.

    In JDK 8 default scripting engine had been changed. Nashorn replaced Rhino. I understand all positives of this change and how good the use of InvokeDynamic is, etc.
    But this change may be also seen as a breaking change. Which is quite normal in world of JavaScript btw :D And do not expect compile time errors! It is almost like node experience...

    Ok, your old Rhino-specific code will not run with Nashorn. However, I have been using it for years, and truly speaking missing it a lot. I wrote test tooling scripted by Rhino, glue code that connects ETL to Java or dynamic backend of application, allowing website maintenance with no redeployment. Still, it is possible to go back to old good JavaScript implementation. So let's make our Rhino great again!

    We could, of course, use it like we did it before JDK 6: add just a lib to our project and evaluate script by means delivered by specific Mozilla implementation.

    If we are more familiar with Java scripting in JSR-223 style we would need extra code that is Sun specific part, already removed from recent Java. But fortunately someone already did the job for us and provided alternative JSR-223 wrapper that uses original Rhino and provides all extra classes that are required by standardized engines.
    Let's just add dependency to pom.xml file:
        <dependency>
            <groupId>org.mozilla</groupId>
            <artifactId>rhino</artifactId>
            <version>1.7.7.1</version>
        </dependency>
        <dependency>
            <groupId>cat.inspiracio</groupId>
            <artifactId>rhino-js-engine</artifactId>
            <version>1.7.7.1</version>
        </dependency>
    

    And yes, now we can use old, good, nashornless Rhino again! Just one more thing to remember is to use right scripting engine instead of "javascript".

    new ScriptEngineManager().getEngineByName("rhino");
    


    Thursday, June 8, 2017

    No pride, no prejudice: Effective Java

    While reading programmers' blogs you can be exposed not only to shiny technical stuff, as well you can meet author's private opinion. It's positive, as human being we want to share our opinions with others. But some opinions seem weired - and only possibility is to get used to that. One blogger dissed proggrammers' meetups, other advocated abortion, another one prefered null checks over Optional, million others actively hate statically typed languages. Not mentioning Emacs fans...

    Some time ago I read a blog post in which author rejected idea of reading "Effective Java". Blogger had explained that book must be clearly outdated as 2nd edition was released in 2008 and he is not going to loose time for reading things like string concatenation vs using StringBuilder.
    Well...

    Fortunately this classical book is easy to defend, even for not such-a-proficient-blogger like me.
    Well recognized Java bestseller is not really about outdated micro-optimations on low layer (which btw may also be a good topic to know). It is not about what is different from C in Java.

    This book introduces readers into variety of interesting topics.
    After reading you will (not only) be more aware of why immutability is important in contemporary software, how to structure data better, or how to use compiler to ensure type safety to work for your benefit. It will encourage you to use language constructs that support safe coding (eg. using enums), name things correctly (like use static factory methods) and depict constructs that are problematic (eg. clone). And explain variance in generics... :D


    My personal observation is that Bloch's book was for some Java guys a first step into typed functional programming with Scala or even Haskell. I have seen lot of smart who followed this path. They could of course years ago assume that their knowledge of Java and enterprise technologies was good enough and they do not need to read one more book on `efficiency`.
    I think that they had a very good and respectable attitude to their own knowledge.
    Be like them. Do not believe you already know everything, rather as a software engineer you must be open to learn, read and try new things out. And sometimes read 10 years (or even more) old books.

    Wednesday, March 1, 2017

    Generating model with inheritance from swagger specification

    The post on generating java model with inheritance from swagger specification is on Zooplus company blog.




    BTW I must admit I like more code formatting options on ghost platform than what I have here with blogger.

    Saturday, January 21, 2017

    The great red dragon and the novice programmer

    As a novice software developer at some point of time you will find enlightenment. You will understand what is the source of Power. Power of perfect code development. Power of ideal expression ideas to text. SOLID and clean, intentional and free of any accidental complexity.

    You will desire that Power. Like the Pilgrim admired the power of The Great Red Dragon. But still you need a transformation. Pilgrim needed his victims to see his beauty, as he himself admired the Red Dragon. You will instead look at code you work with. The real code. Ugly. Legacy. Half year old code written on 2 releases backward Spring version. You will show your vict... sorry, colleagues that bad code. And yourself as a powerful Red Dragon. But... You're not yet him.

    You need your transformation. I was there too. Now I know. Please keep in mind one thing. Consult your more experienced colleagues before you start making that code better. Example from my transformation. I spent some time years ago to refactor piece of code using collection to keep objects of various classes. Then cascade of instanceOf... This was looking for me as an unacceptable implementation. Unfortunately, my employer would have been more happy if I had focused on my tasks instead of refactoring code that was correctly working since years. From his perspective my hard work was not considered as productive. Now I know I just was not able to recognize which part of system needs what kind of refactoring.

    Here I must refer to Procent's excellent talk with Jarek Palka (in Polish). You can find out a lot of important hints regarding working with legacy code. Which is code you have just commited. One of hints is why compulsive refactoring may affect your projects and may cause inability to deliver.

    After years I learnt that system I was working with was actually quite good thanks to good design and correct, efficient, event driven architecture. As a young developer, influenced by Clean-Code evangelism, I was focused on local parts, not on wider scope. Lot of implementation details were given to novice programmers and far from ideal. They SHOULD be better, but system was good enough to resist local code ugliness. Please try to learn what is important in your system first, before you start assuming that whoever wrote some piece of code was an ignorant or does not even know the programming language. Remember you have not yet transformed into The Great Red Dragon.

    Sunday, December 4, 2016

    Using groovy for tests

    While I already has some exposure to dynamic languages - also those working under control of JVM, until now I had not touched Groovy, despite its presence on JUG meetings, conferences etc. I could of course see lot of value in tools like Spock, Geb or recently popular Gradle. However that was for me more a nice-to-have, rather than a must.
    So with pleasure I am now discovering really nice points of using Groovy - as language that powers the tests and complements the Java main sources. It turns out that even with no frameworks mentioned above, you can benefit just from using Groovy in your test. Here are the reasons:
    1. You already know almost all of syntax. Old good Java code will probably just work. It is not like JavaScript, which is similar to Java just in name. Rest things you need you can find in documentation - which is quite good and answers most of my questions.
    2. Forget semicolons, alias imported objects, use list and map literals, multiline strings, use def. Almost like Scala.
    3. No more @VisibleForTesting. Groovy allows you to break object members visibility. Maybe it is not best idea to look into internal state of objects, but now you can. At least tested methods do not need to be kept in package visibility.
    4. Power assert. This looks just like Java assert. But output on your console when there is a failure... I just love this feature. Just take a look:
      Assertion failed:
      
      assert apiResponse.code() >= 200 && apiResponse.code() < 300
             |           |      |      |  |           |      |
             |           404    true   |  |           404    false
             |                         |  retrofit2.Response@42d0a255
             |                         false
             retrofit2.Response@42d0a255
      
      
    5. BigDecimal everywhere. 42.0 is not a float any longer. If your code has something in common with money you can feel relief.
    6. @TypeChecked. Why not just use compiler? With Groovy you can! It is so nice when machine corrects your errors.
    I am not convinced whether Groovy is language of future :> But definitely worth trying.

    Friday, October 7, 2016

    IT Aristocracy to guillotine! How to treat IT head hunters?

    Recently JUG in Warsaw published a newsletter containing quite an unusual link to an article created by a professional IT recruiter. The author is asking a very interesting question - why is she and her colleagues regulary offended by potential candidates, who are belonging to group of best educated engineers, holding lucrative position on job market. Top rated IT people. The "IT Aristocracy". I was touched. So I decided to appeal, to you readers.

    Dear programmers!

    I know you get 100 calls from desperate head hunters each week. I am aware, they are disturbing our flow of mind and taking us from zone away so we need to spend counterproductively next half hour to recover. But, hey, isn't that you who posted your phone/email on linkedin and N other jobboards along with shiny CV full of keywords? Is it more or less ridiculous than guys posting their ID into facebook? Have you expected that none of invited to your professional/social network recruiters ever call you? They may of course have sometimes be prepared to talk to you less than expected. Not knowing all that 3,4 letters acronyms and not knowing technology stack. That's right. They have no clue. That is why YOU are doing the job worth 6x more that what people you talk to by phone earn. They just have not dedicated half of their lives to profound depths of technological magic.
    Nothing bad will happen also when we expose unprofessional behavior on the other side and talk about problems in our two-way communication. I am also aware not everyone is able to do it in such an elegant form as Rafal did.
    Sometimes all of us have bad day, or just have been contacted by company which fired them 3 years ago. I can understand that each of us could behave less professionally in some conditions. Me too. I am sure that soft-skilled recruiters are also able to understand and forgive that.
    But primitive, vulgar offence is not "unprofessional behavior"! That is not acceptable! Das ist unglaubich!!! That kind of freaks must be stigmatized!
    Otherwise we, as the "computer people" will receive back from our society just hatred for being vulgar jerks. Just imagine that could have happened just before this or next government is run out of (our...) money and seeks for new taxpayers. Who will be the most unpopular group in our society? Whose heads will that revolution demand? Are you ready for fiscal guillotine?
    One day, sooner or later, you will be looking forward to change your job. One day you will wish the head hunters to call you, and treat you not like just one more CV from million. That people are really able to help you get where you want. Unless you're a dick.
    TL;DR If you are frustrated buy the rubber duck! Never offend head hunters.

    Thursday, May 19, 2016

    Changing merge request target branch in gitlab

    TDLR; 
    Yes, it's possible with API usage.
    There is even a script that chamges target branch with minimal configuration.

    Gitlab is increasingly popular alternative for Github, commonly used by corporations that are able to save monthly fee for Github. It's open source project and front end and its usability seems to be still behind commercial and successful predecessor.
    In my opinion Merge Requests are functionality that is exceptionally affected by suboptimal design. You just need to get used to it and train yourself not to click big green 'Click me' button, which causes MR to be merged. And changing the target branch of merge request seems to be impossible.
    Thanks to careful readers among my colleagues, I have found out that this option exists, however only way to do it is to use Gitlab API. The API (similarly to Jenkins) utilizes concept of private token. It is a secret that allows a user to authenticate using unique token instead standard username and password. Maybe it is not most secure way, but certainly that is easy and convenient. Each HTTP request to Gitlab API that is performed in some user context, must contain that private token. It may be sent as a header or url parameter. Depending on your deployment configurationone of that ways may or may not be disabled ;> Url parameter worked for me quite well.
    To edit a Merge Request we need to know project it relates to, as well as MR identifier, which is not same as visible in GUI (that one is referred to as iid, unique in project scope).
    Operation will take 3 HTTP calls. First is ment to retrieve project id by its name.
    GET /projects/search/:name_to_find
    
    I assume there are no more than one projects found by given name.
    Second will convert id from GUI to MR id.
    GET /projects/:id/merge_requests?iid=42
    
    or you can select manually from all opened MRs.
    GET /projects/:id/merge_requests?state=opened
    
    Knowing project id and MR id we can now update target branch by sending simple json object carrying new target branch as a value.
    PUT /projects/:id/merge_request/:merge_request_id
    { "target_branch": "the_target_br" }
    
    In my case I had to remove plural form `s` from merge_requests in url (that was different from API documentation, but I assume it's change in some other version of Gitlab). I was happy this option was possible, however I must admit I had to write the script to make the changing user friendly.

    Saturday, April 2, 2016

    massive directory name case change

    Some time ago I had a disk failure. One project code was affected. I managed to restore almost all data, but result was often a file with name changed to upper case. As this happened to a windows machine, I could probably live with that, but it turned out package name in java is case sensitive, and Idea was not able to do quick fix as quickly as I would expect. Manual change is not an option for a developer.
    So let's automate that. Solution would be to recursively visit each directory and in case its case is wrong - rename. You can have that in java, I would rather be happy to have that in script, however I am not sure whether scripting cmd or bash port on windows will actually handle that rename sanely.
    Fortunately there is nice tool in python that accomplishes the same goal - os.walk. Usage is trivial and script is portable to any platform. File system paths can be also abstracted easily with os.path.join. There is even a method in python string that checks case of whole content - so you will not write any extra loop iterating over characters. Python handles nicely filtering in list comprehensions - so it is possible to use the condition in for statement.
    from os import walk, rename
    from os.path import join
    
    for (dirpath, dirnames, filenames) in walk( join('src', 'main', 'java') ):
      for d in [f for f in dirnames if f.isupper()]:
           rename(join(dirpath, d), join(dirpath, d.lower()))
    
    As you can see some APIs may be even more developer friendly than what is in Java standard. Now came the difficult part - for some reason git was unable to recognize character case change in filenames. It happens that some default on windows is aligned with os approach to case sensitivity. Making git see the difference is changing its configuration:
    git config core.ignorecase false