Tuesday, 6 October 2015

Why we need serialVersionUID and how to generate it?

Why?

The best answer is from Java doc for java.io.Serializable

In two words:
1. helps to check if class version during deserialization is the same;
2. should be private;
3. is better than generated as the last one can cause errors.

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in anInvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.

How to generate it?

Basically any number but Intellij Idea can generate it for you:

File -> Settings ->Inspections -> Java -> Serialization issues:
check Serializable class without 'serialVersionUID'

Once changes are applied, Intellij Idea will warn you that your class without serialVersionUID and suggest to generate it for you :)

Thursday, 10 September 2015

How to mock static methods during unit testing?

Well, static mock is not implemented in Mockito, so we have to use PowerMock to achieve this:

Let's say we have the following class:

package com;

import
java.net.InetAddress;
import
java.net.UnknownHostException;

public final class
SystemUtils {

  
public static final String UNKNOWN_HOST = "Unknown";

   public static
String getHostName() {
      String hostname =
UNKNOWN_HOST;
      try
{
         InetAddress addr = InetAddress.getLocalHost()
;
        
// Get hostname
        
hostname = addr.getHostName();
     
} catch (UnknownHostException e ) {
         System.
out.println("catch UnknownHostException...");
     
}
     
return hostname;
  
}
}

and we need to test that UnknownHostException is thrown.
So our goal is to mock InetAddress.getLocalHost() and ask it to return an exception so SystemUtils.getHostName() will return 'Unknown'.

First import all needful libs:

<properties>

    <junit.version>4.11</junit.version>

    <mockito.version>1.10.19</mockito.version>

    <powermock.version>1.6.2</powermock.version>

</properties>



<dependency>
    <groupId>
junit</groupId>
    <artifactId>
junit</artifactId>
    <version>
${junit.version}</version>
    <scope>
test</scope>
</dependency>

<dependency>
    <groupId>
org.mockito</groupId>
    <artifactId>
mockito-all</artifactId>
    <version>
${mockito.version}</version>
    <scope>
test</scope>
</dependency>

<dependency>
    <groupId>
org.powermock</groupId>
    <artifactId>
powermock-api-mockito</artifactId>
    <version>
${powermock.version}</version>
    <scope>
test</scope>
</dependency>

<dependency>
    <groupId>
org.powermock</groupId>
    <artifactId>
powermock-module-junit4</artifactId>
    <version>
${powermock.version}</version>
    <scope>
test</scope>
</dependency>

<dependency>
    <groupId>
org.powermock</groupId>
    <artifactId>
powermock-module-junit4-rule</artifactId>
    <version>
${powermock.version}</version>
    <scope>
test</scope>
</dependency>

And test would look the following way:

import com.SystemUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.stubbing.answers.ThrowsExceptionClass;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static org.junit.Assert.assertEquals;


@RunWith(PowerMockRunner.class)
@PrepareForTest(SystemUtils.class)
public class SystemUtilsTest {

    @Test
    public void testGetHostName() throws UnknownHostException {
        PowerMockito.mockStatic(InetAddress.class);
        PowerMockito.when(InetAddress.getLocalHost())
                .then(new ThrowsExceptionClass(UnknownHostException.class));
        String actualValue = SystemUtils.getHostName();
        assertEquals("On exception expected unknown value", SystemUtils.UNKNOWN_HOST, actualValue);
    }
}

How to set log file with custom name in log4j2?

Sometimes having log4j2.xml file with default naming can be a problem if several projects share the same classpath. In order to change logger file at runtime the below method can be used:


public static void logAppInfo(String configFileName) {
    URL fileUrl = SLF4JHello.class.getClassLoader().getResource(configFileName);
    if (fileUrl == null) {
        throw new RuntimeException("File not found: " + configFileName);
    }
    try {
    LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    loggerContext.setConfigLocation(fileUrl.toURI());
    loggerContext.updateLoggers();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

How to enable smart import in Intellij Idea 14?

To enable auto-import and auto optimize imports go to:

Intellij Idea 14 -> Settings -> Editor -> General -> Auto Import

and check two options:

1. Optimize import on the fly
2. Add unambiguous imports on the fly

Tuesday, 14 July 2015

How to set timezone in Weblogic?

1. Open file in Notepad
../{your_weblogic_folder}/user_projects/domains/{your_domain_name}/bin/setDomainEnv.cmd

2. Add to the property %JAVA_PROPERTIES% -Duser.timezone=GMT.
Line should look the following way:
set JAVA_PROPERTIES=%JAVA_PROPERTIES% %EXTRA_JAVA_PROPERTIES% -Duser.timezone=GMT

Friday, 3 July 2015

How to write / read BLOB to / from Oracle database?

WRITE:

To transform String value into blob just execute your_string.getBytes();

String blobValue = "long blob";
bytes[] bytes = blobValue.getBytes();
int rows = getJdbcTemplate().update("update MY_TABLE set BLOB_COLUMN = ? where ROWID = '1'", bytes);

READ:

we can either read blob from database in Blob class or transform into String. To transform it into String we will need additional custom method:

public static String sqlBlobToString(Blob blob) {

StringBuilder stringBuilder = new StringBuilder();

try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(blob.getBinaryStream())) {
       while ((string = bufferedReader.readLine()) != null) {
              stringBuilder.append(string);
       }
 } catch (IOException e) {
       throw new RuntimeException(e);
}
return stringBuilder;
}


Querying from database:

String s = sqlBlobToString(getJdbcTemplate().queryForObject("select BLOB_COLUMN from MY_TABLE where ROWID = '1'", Blob.class));

Note: I am using java.sql.Blob

How to write / read CLOB to / from Oracle database?

WRITE:

there is no problems with clob saving into db - just keep it in String value and regularly save it:

String clobValue = "long clob";
int rows = getJdbcTemplate().update("update MY_TABLE set CLOB_COLUMN = ? where ROWID = '1'", clobValue);

READ:

we can either read clob from database in Clob class or transform into String. To transform it into String we will need additional custom method:

public static String sqlClobToString(Clob clob) {

StringBuilder stringBuilder = new StringBuilder();

try(BufferedReader bufferedReader = new BufferedReader(clob.getCharacterStream()) {
       while ((string = bufferedReader.readLine()) != null) {
              stringBuilder.append(string);
       }
 } catch (IOException e) {
       throw new RuntimeException(e);
}
return stringBuilder;
}

Querying from database:

String s = sqlClobToString(getJdbcTemplate().queryForObject("select CLOB_COLUMN from MY_TABLE where ROWID = '1'", Clob.class));

Note: I am using java.sql.Clob