Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Friday, 10 August 2012

How to Convert a Byte Array Into an Hexadecimal String?

Trying to convert a byte array into an hexadecimal and back to the same byte array manually, can be tricky. The Hex class of the Apache Commons library offers a solution:
byte[] ba = { 4, 55, -27, 99, 42, 0, -1 };

String toHex = Hex.encodeHexString(ba);
byte[] retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));

ba = new byte[0];
toHex = Hex.encodeHexString(ba);
retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));
The generated output is:
Hexadecimal : 0437e5632a00ff
Expected    : [4, 55, -27, 99, 42, 0, -1]
Retrieved   : [4, 55, -27, 99, 42, 0, -1]

Hexadecimal :
Expected    : []
Retrieved   : []
More Java tips & tricks here.

How to Encode and Decode Data to Base64 in Java?

In order to encode a string (or a byte array) into Base64, and then decode it into its original state, one can use the following piece of code:
String s = "String to encode/decode in Base64 with DataTypeConverter";

String coded = DatatypeConverter.printBase64Binary(s.getBytes());
byte[] retr = DatatypeConverter.parseBase64Binary(coded);

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
System.out.println();
The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHdpdGggRGF0YVR5cGVDb252ZXJ0ZXI=
Expected  : String to encode/decode in Base64 with DataTypeConverter
Retrieved : String to encode/decode in Base64 with DataTypeConverter

For input/output streams, one can use the following:
String s = "String to encode/decode in Base64 using streams";

ByteArrayOutputStream collect = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(collect);

b64os.write(s.getBytes());
b64os.close();

byte[] ba = collect.toByteArray();
String coded = new String(ba);

InputStream is = new ByteArrayInputStream(ba);
Base64InputStream b64is = new Base64InputStream(is);

byte[] retr = IOUtils.toByteArray(b64is);

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
The above uses an external library to convert the InputStream into a byte array. The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHVzaW5nIHN0cmVhbXM=
Expected  : String to encode/decode in Base64 using streams
Retrieved : String to encode/decode in Base64 using streams
The code examples are available from Github, in the Java-Core-Examples directory.

More Java tips & tricks here.

Thursday, 2 August 2012

How to Add License Headers to Code Files via Maven?

This post explains how to automate the inclusion of headers in code files via Maven. We will add the following header (the code sample is available on GitHub) :
/**
 * Copyright (C) 2010-2012 MyCompany - All rights reserved.
 */
This header is based on a template located in src/main/resources/fileHeader.txt:
Copyright (C) ${h_inceptionYear}-${h_currentYear} ${h_copyrightOwner} - All rights reserved.
It contains three ${parameters} which are configured in the pom.xml. Two are defined in the properties:
<properties>
  ...
  <inceptionYear>2010</inceptionYear>
  <copyrightOwner>MyCompany</copyrightOwner>
</properties>
One is computed via a plugin (the current year):
<!-- Creating current year element -->
<plugin>
  <groupId>org.codehaus.groovy.maven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.0</version>
  <executions>
    <execution>
      <phase>validate</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          import java.util.Date
          import java.text.MessageFormat
          def vartimestamp = MessageFormat.format("{0,date,yyyy}", new Date())
          project.properties['currentYear'] = vartimestamp
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>
The template location, together with the parameters mapping and the types of files to ignore, is configured here:
  <!-- Adding header to file -->
  <plugin>
    <groupId>com.mycila.maven-license-plugin</groupId>
    <artifactId>maven-license-plugin</artifactId>
    <version>1.8.0</version>
    <configuration>
      <!-- Template location -->
      <header>src/main/resources/fileHeader.txt</header>
      <properties>
        <!-- Values to be substituted in template -->
        <h_inceptionYear>${inceptionYear}</h_inceptionYear>
        <h_currentYear>${currentYear}</h_currentYear>
        <h_copyrightOwner>${copyrightOwner}</h_copyrightOwner>
      </properties>
      <strictCheck>true</strictCheck>
      <excludes>
        <exclude>**/*.html</exclude>
        <exclude>**/*.xml</exclude>
        <exclude>**/*.txt</exclude>
        <exclude>**/*.ec</exclude>
        <exclude>**/*.log</exclude>
        <exclude>**/*.css</exclude>
        <exclude>**/*.js</exclude>
        <exclude>**/*.jsp</exclude>
        <exclude>**/*.md</exclude>
      </excludes>
    </configuration>
    <executions>
      <execution>
        <phase>validate</phase>
        <goals>
          <goal>format</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

During the build process, proper headers are added (or updated) in code files:
/**
 * Copyright (C) 2010-2012 MyCompany - All rights reserved.
 */

package com.mypackage;

public class MyClass {

  // ...

}

Friday, 27 July 2012

How to Process LessCss .less Files into .css Files in a Maven Build Process?

Sample Maven LessCss Project
Thanks to Marcel Overdijk's plugin, it is now possible to process .less LessCss files into .css file during the maven build process.

Let's consider a maven web project, one can create a /css and a /less directory. The latter contains the source .less files, and the former will contain the processed .css files.

One should add the following plugin and dependency in pom.xml:
  <dependency>
    <groupId>org.lesscss</groupId>
    <artifactId>
      lesscss-maven-plugin
    </artifactId>
    <version>1.3.0</version>
  </dependency>

  <plugin>
    <groupId>org.lesscss</groupId>
    <artifactId>lesscss-maven-plugin</artifactId>
    <version>1.3.0</version>
    <configuration>
      <sourceDirectory>
        ${project.basedir}/src/main/webapp/less
      </sourceDirectory>
      <outputDirectory>
        ${project.basedir}/src/main/webapp/css
      </outputDirectory>
      <compress>false</compress>
      <includes>
        <include>example.less</include>
      </includes>
      </configuration>
    <executions>
      <execution>
        <goals>
          <goal>compile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

This configuration will convert the example.less file into a example.css file during the maven build process. Any existing .css file is overwritten at each build process.

A Maven project sample is available from Git.

How to Access Files/Data in the Resource Directory at Runtime?

A common concern of developers using Maven for the first time is how to access a file (binary or text) declared as a resource in Maven. Contrary to typical NetBeans projects (for example), maven insists on using a standard directory structure (more on Maven concepts here):

My Project
  |-src
    |-main
      |-java
      | |-MyPackage
      |   |-MyClass.java
      |-resources
        |-MyPackage
          |-MyData.txt

In a standard NetBeans project, since MyClass.java uses MyData.txt, both are (often) located in the same directory corresponding to the MyPackage Java package. However, in a Maven project, code is separated from data in different directories.

Some developers believe that the Maven directory structure will be replicated in the .jar after compilation. Therefore, they are tempted to try to open the data resource with a strategy similar to this one:
String loc = new File(".").getAbsolutePath()
  + "\src\main\resources\MyPackage\MyData.txt";
FileInputStream FIS = new FileInputStream(new File(loc));
...
In other words, they believe they have to handle the Maven directory structure themselves, including the absolute path to the current .jar location. This does not work.

First, one must keep in mind that Maven does not "push" its directory structure in .jars. Both MyClass.java and MyData.txt will be located in the same \MyPackage directory within the .jar. You can check this by opening the .jar with winzip for example.

The solution is the following (resource location is relative to Myclass location or package (*)):
InputStream IS = MyClass.class
    .getResourceAsStream("MyData.txt");

Caveat - Encoding Issue

If your data is not binary, you need to pay attention to the encoding format in the file itself (for example, set it to UTF-8) and make sure it is the same encoding as in your Maven project. You should have the following setting in your pom.xml:
<properties>
  <project.build.sourceEncoding>
    UTF-8
  </project.build.sourceEncoding>
  ...
<properties>
This is an issue that took me hours to solve, because encoding/display errors would only happen at runtime.

(*) More on absolute and relative path here.

REM: This post is a follow-up to an answer I provided on Stackoverflow.com.