Menu

Posts tagged with ‘java’

Apache Commons Lang: Memoizer

kinow @ Jan 08, 2017 18:34:03

The current release of Apache Commons Lang is 3.5. The upcoming release, probably 3.6, will include a new feature, added in a pull request: a Memoizer implementation. Check out the ticket LANG-740 for more about the implementation being added to [lang].

The book Java Concurrency in Practice introduces readers to the Memoizer, and has also a public domain implementation available for download (besides that, the book has also lots of other interesting topics!).

In summary, Memoizer is a simple cache, that will store the result of a computation. It receives a Computable object, responsible for doing something that will be stored by the Memoizer. Here’s a simple code to illustrate how that will work in your Java code.

// Computation to be stored in the cache
Computable<String, String> getFormattedCurrentDate = new Computable<String, String>() {
    @Override
    public String compute(String fmt) throws InterruptedException {
        return new SimpleDateFormat(fmt).format(new Date());
    }
};

// Our memoizer
Memoizer<String, String> dateCache = new Memoizer<>(getFormattedCurrentDate);

// To illustrate its use
for (int i = 0; i < 10; i++) {
    try {
        // S -> Millisecond
        System.out.println(dateCache.compute("HH:mm:ss:S Z dd/MM/YYYY"));
        // Regardless of this sleep call, we get the same result every iteration
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

The computable created (getFormattedCurrentDate) will be called only once, and stored in a map. The parameter passed in the #compute() method will be used as key in the map. So choose your parameter wisely :-) The output of the example will be similar to the following one.

19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017
19:15:57:854 +1300 08/01/2017

In the example above I used a for-loop to illustrate what will happen. Even though we call the memoizer #compute() method several times, followed by Thread#sleep(); only one result, the first to be computed, will be returned.

So that’s all for today. Hope you learned something about this new class, that must be available in the next release of Apache Commons Lang.

Happy hacking!

ps: [lang] uses Java 7, so that is why we do not have a functional instead of the Comparable

<p class="postmetadata">

    <small>tags 
     [&nbsp;<a
        href="/tag/java"
        rel="tag">java</a>&nbsp;]&nbsp;

     [&nbsp;<a
        href="/tag/programming"
        rel="tag">programming</a>&nbsp;]&nbsp;

     [&nbsp;<a
        href="/tag/apache%20software%20foundation"
        rel="tag">apache software foundation</a>&nbsp;]&nbsp;

    </small>


    <br/>
    <small>posted in 
    [&nbsp;<a
        href="/blog"
        title="View all posts in blog"
        rel="category tag">blog</a>&nbsp;]&nbsp;
    category </small>

</p>

Apache Commons Text

kinow @ Jan 07, 2017 20:39:03

There is a new component in Apache Commons: Apache Commons Text. The 1.0 release might be announced in the next weeks. The current site is still in the Commons Sandbox, but it will change with the 1.0 release. The promotion from the sandbox happened a few days ago in the project mailing list.

Here’s the project description: Apache Commons Text is a library focused on algorithms working on strings.

There was a thread on the mailing list some time ago (Oct/2014) when we first discussed the component idea. Since then many people contributed porting code from Apache Commons Lang, Apache Lucene, donating code from existing projects, and with new ideas.

It is important to be aware that certain parts of Apache Commons Lang are being marked as deprecated, and will be removed in the future, after Apache Commons Text 1.0 is out. For example: StringUtils, and RandomStringUtils.

That will happen probably in a 4.x release of Apache Commons Lang, if everything goes well with Apache Commons Text :-)

And there are already future features in branches too. It was decided that these features needed further work, so they will probably be included in next releases.

So that’s a little bit of background on the new component that will be released soon. If you have code using Apache Commons Lang, you might be interested in staying tuned to release announcements in the mailing list!

And should you have suggestions and would like to contribute, feel free to join and start a thread in the mailing list, open a JIRA issue, or submit a pull request.

Happy hacking!

Changing Spring Boot environment variables in the command line

kinow @ Nov 21, 2016 21:26:03

This week while helping developers and testers to experiment with a backend application, some of them found useful to learn a simple trick to change Spring Boot properties when you can run the application locally (our testers build, compile, change the code, how cool is that?).

Here’s how it works. Say you have the following settings in your application’s application.properties:

my.application.database.username=sa
my.application.database.password=notasimplepassword

And that you want to change these parameters in order to, for instance, create an application error, so that you can code and test what happens to the frontend application in that situation.

You replace dots by underscores, and put all your words in upper case. So the variables above would be: MY_APPLICATION_DATABASE_USERNAME and MY_APPLICATION_DATABASE_PASSWORD.

Furthermore, you do not need to edit your application.properties file, if you are on Linux or Mac OS. You can start the application and override environment variables at the same time with the following syntax.

$ MY_APPLICATION_DATABASE_USERNAME=olivei MY_APPLICATION_DATABASE_PASSWORD=7655432222a mvn clean spring-boot:run

This way your application will start with the new values.

Happy hacking!

—EDIT—

As pointed by Stéphane Nicoll (thanks!), you could change the property values without having to use the upper case syntax.

mvn -Dmy.application.database.username=anotheruser clean spring-boot:run

And he even included a link to docs! ♥ the Internet and Open Source!

Content negotiation with Spring Boot and React

kinow @ Nov 07, 2016 20:07:03

A few days ago I had a bug in a system built with Spring Boot and React. The frontend application was using a REST client in React, built in a similar way to what is found in the documentation, and also in blogs.

import rest from 'rest';
const Rest = () => rest.wrap(mime);

However, for one of the Spring Boot application endpoints, the React component was not working. The response seemed to be OK in the Network tab, of the browser developer tools. But the component was failing and complaining when parsing the response.

Turns out that the frontend was sending the request with the header Accept: text/plain, application/json. And Spring Boot was just using its default content negotiation and returning what the frontend requested: a text plain version of, what looked like, JSON.

The quick fix was to request the content as JSON in React.

import rest from 'rest';
import mime from 'rest/interceptor/mime';
const Rest = () => rest.wrap(mime , { mime: 'application/json' } );

Now we will revist the backend to return the JSON content, as content, regardless of what the user asks :-)

Happy hacking!

Strings transliteration in Java with Apache Commons Lang

kinow @ Aug 09, 2014 12:49:33

Rosalind is a website with a curated set of exercices for bioinformatics, organized hierarchily. In some of these examples you are required to replace characters (nucleotides) by other characters. It is a rather common task for developers, like when you need to replace special characters in user’s names.

There are different ways of describing it, such as translate, replace, or transliterate. The latter being my favorite definition.

In Python I know that there are several different ways of transliterating strings [1][2]. But in Java I always ended up using a Map or a Enum and writing my own method in some Util class for that.

Turns out that Apache Commons Lang, which I use in most of my projects, provided this feature. What means that I will be able to reduce the length of my code, what also means less code to be tested (and one less place to look for bugs).

String s = StringUtils.replaceChars("ATGCATGC", "GTCA", "CAGT"); // "TACGTACG"
System.out.println(s);

What the code above does, is replace G by C, T by A, C by G and A by T. This process is part of finding the DNA reverse complement. But you can also use this for replacing special characters, spaces by _, and so it goes.

Happy hacking!