How to calculate the message digest in Java

A message digest is an important concept in cryptography. A digest is an array of bytes created by a hashing formula. It is used to make sure that some digital information has not been tampered with. In a sense it is a footprint of an object, such as a file. If someone modifies the file then the footprint also changes. Then we know that the file has been changed. Another word for a message digest is checksum. There are various hashing algorithms to perform the calculation. SHA-256 and MD5 are the most common ones.

For an example you can check out the Apacha log4j2 download page here. You’ll see a column called “checksum” for various files. If you click on one of those you’ll see the MD5 hash of the file in a relatively human readable form, such as “31826c19fff94790957d798cb1caf29a”.

Java and other popular programming languages have built-in classes to construct a message digest. Let’s see an example from Java.

Read more of this post

Concatenate strings with the StringJoiner class in Java 8

Java 8 introduces a new object which enables you to join individual strings: the StringJoiner.

The StringJoiner has two overloads. The simpler one accepts a delimiter:

StringJoiner sj = new StringJoiner(" | ");
sj.add("Hello").add("my").add("dear").add("world!");

System.out.println(sj.toString());

Read more of this post

Using the Comparator class in Java 8 to compare objects

Java 8 comes with a range of built-in implementations of the Comparator interface.

Consider the following Employee class:

public class Employee
{
    private UUID id;
    private String name;
    private int age;

    public Employee(UUID id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
        
    public UUID getId()
    {
        return id;
    }

    public void setId(UUID id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }    
    
    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }    
}

…and the following list of employees:

Read more of this post

Exploring a directory with the Java 8 Stream API

We saw an example of using the Java 8 Stream API in File I/O in this post. We saw how the Files object was enhanced with the lines() method to open a line reader stream to a text file.

There are other enhancements related to streams that make is simple to explore a directory on your hard drive. The following code example will collect all folders and files within the c:\gitrepos folder and add them to an ArrayList:

Path gitReposFolderPath = Paths.get("c:\\gitrepos");
gitReposFolderPath.toFile().getName();
try (Stream<Path> foldersWithinGitReposStream = Files.list(gitReposFolderPath))            
{
    List<String> elements = new ArrayList<>();
    foldersWithinGitReposStream.forEach(p -> elements.add(p.toFile().getName()));            
    System.out.println(elements);
}
catch (IOException ioe)
{

}

I got the following output:

[cryptographydotnet, dotnetformsbasedmvc5, entityframeworksixdemo, owinkatanademo, signalrdemo, singletondemoforcristian, text.txt, webapi2demo, windowsservicedemo]

The code returns both files and folders one level below the top directory, i.e. the “list” method does not dive into the subfolders. I put a text file into the folder – text.txt – just to test whether in fact all elements are returned.

Say you only need files – you can use the filter method:

foldersWithinGitReposStream.filter(p -> p.toFile().isFile()).forEach(p -> elements.add(p.toFile().getName())); 

This will only collect text.txt.

Let’s try something slightly more complex. We’ll organise the elements within the directory into a Map of Boolean and List of Paths. The key indicates whether the group of files are directories or not. We can use the collect method that we saw in this post:

try (Stream<Path> foldersWithinGitReposStream = Files.list(gitReposFolderPath))            
{
    Map<Boolean, List<Path>> collect = foldersWithinGitReposStream.collect(Collectors.groupingBy(p -> p.toFile().isDirectory()));
    System.out.println(collect);
}

This prints the following:

{false=[c:\gitrepos\text.txt], true=[c:\gitrepos\cryptographydotnet, c:\gitrepos\dotnetformsbasedmvc5, c:\gitrepos\entityframeworksixdemo, c:\gitrepos\owinkatanademo, c:\gitrepos\signalrdemo, c:\gitrepos\singletondemoforcristian, c:\gitrepos\webapi2demo, c:\gitrepos\windowsservicedemo]}

So we successfully grouped the paths.

As mentioned above the “list” method goes only one level deep. The “walk” method in turn digs deeper and extracts sub-directories as well:

try (Stream<Path> foldersWithinGitReposStream = Files.walk(gitReposFolderPath))
{
    List<String> elements = new ArrayList<>();
    foldersWithinGitReposStream.filter(p -> p.toFile().isFile()).forEach(p -> elements.add(p.toFile().getAbsolutePath()));
    System.out.println(elements);
}

We can also instruct the walk method to go n levels down with an extra integer argument:

try (Stream<Path> foldersWithinGitReposStream = Files.walk(gitReposFolderPath, 3))

View all posts related to Java here.

Waiting for background tasks to finish using the CountDownLatch class in Java

Imagine the situation where you execute a number of long running methods. Also, let’s say that the very last time consuming process depends on the previous processes, let’s call them prerequisites. The dependence is “sequential” meaning that the final stage should only run if the prerequisites have completed and returned. The first implementation may very well be sequential where the long running methods are called one after the other and each of them blocks the main thread.

However, in case the prerequisites can be executed independently then there’s a much better solution: we can execute them in parallel instead. Independence in this case means that prerequisite A doesn’t need any return value from prerequisite B in which case parallel execution of A and B is not an option.

In this post we’ll examine this situation and see how to implement it in Java using the CountDownLatch class.

Read more of this post

Reading text files using the Stream API in Java 8

We discussed the Java 8 Stream API thoroughly on this blog starting here. We mostly looked at how the API is applied to MapReduce operations to analyse data in a stream.

The same API can be applied to File I/O. Java 8 adds a new method called “lines” to the BufferedReader object which opens a Stream of String. From then on it’s just standard Stream API usage to filter the lines in the file – and perform other operations on them in parallel such as filtering out the lines that you don’t need.

Here’s an example how you can read all lines in a file:

String filename = "c:\\logs\\log.txt";
File logFile = new File(filename);
try (BufferedReader reader = new BufferedReader(new FileReader(logFile));)
{
    StringBuilder fileContents = new StringBuilder();
    Stream<String> fileContentStream = reader.lines();
    fileContentStream.forEach(l -> fileContents.append(l).append(System.lineSeparator()));
    System.out.println(fileContents.toString());
}
catch (IOException ioe)
{

}

We simply append each line in the stream to a StringBuilder.

In my case the log.txt file has the following contents:

hello
this is a line
next line
this is another line
…and this is yet another line
goodbye

As we’re dealing with the Stream API the usual Map, Filter and Reduce methods are all available to be performed on the text. E.g. what if you’re only interested in those lines that start with “this”? Easy:

fileContentStream.filter(l -> l.startsWith("this"))
                    .forEach(l -> fileContents.append(l).append(System.lineSeparator()));

The StringBuilder will now only hold the following lines:

this is a line
this is another line

You can also use the Path and Files objects that were introduced in Java 7. The Files object too was extended with a method to get hold of the Stream object. The below example is equivalent to the above:

Path logFilePath = Paths.get("C:\\logs\\log.txt");
try (Stream<String> fileContentStream = Files.lines(logFilePath))            
{
    StringBuilder fileContents = new StringBuilder();
    fileContentStream.filter(l -> l.startsWith("this"))
            .forEach(l -> fileContents.append(l).append(System.lineSeparator()));
    System.out.println(fileContents.toString());
}
catch (IOException ioe)
{

}

View all posts related to Java here.

Insert a non-existent value into a Map in Java 8

Consider the following Employee class:

public class Employee
{
    private UUID id;
    private String name;
    private int age;

    public Employee(UUID id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
        
    public UUID getId()
    {
        return id;
    }

    public void setId(UUID id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }    
    
    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

Let’s put some Employee objects into a hash map:

Read more of this post

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: