java.net.Socket default values

The Java Socket class has some properties that control the connection but you may notice that there are no default values mentioned in the JavaDoc?!

I was wondering what are the defaults and are there any differences between JVMs and platforms and this is the result of this experiment:

JDK 1.5 Oracle Database 11.2 internal JVM/ Oracle Enterprise Linux 6.5
KeepAlive:false|OOBInline:false|ReceiveBufferSize:87380|ReuseAddress:false|SendBufferSize:16384|SoLinger:-1|SoTimeout:0|TcpNoDelay:false|TrafficClass:0

JDK 1.6 – Windows 10 64 bit
KeepAlive:false|OOBInline:false|ReceiveBufferSize:43690|ReuseAddress:false|SendBufferSize:8192|SoLinger:-1|SoTimeout:0|TcpNoDelay:false|TrafficClass:0

JDK 1.6 – Oracle Enterprise Linux 6.5
KeepAlive:false|OOBInline:false|ReceiveBufferSize:65536|ReuseAddress:false|SendBufferSize:65536|SoLinger:-1|SoTimeout:0|TcpNoDelay:false|TrafficClass:0

It seems odd but the size of the read and write buffers have great differences over each platform and if you have to write networking code, you have to take this into account in edge cases where reliability and network latency are an issue.

What happened to Java

I remember the early days of Java in the year of 1996. It was an overwhelming success.

Having a C like syntax but without the worry for memory management it was like a fresh air. Almost every big software tool vendor jumped on the Java bandwagon with tools. There were dozen IDEs : IBM with VisualAge, Kawa, Symantec with VisualCafe, Borland with JBuilder. Even Microsoft had their IDE – Visual J++ (part of Visual Studio).

Starting with client side programming (Java applets) soon the language was adopted for embedded programming (cell phones were shipping with a stripped Java virtual machine) and then for server applications.

The EJB specification for server side Java programming was born just a year after. A lot of Enterprise application servers were born from this demand for Java technology: Resin, WebLogic, WebSphere, Sybase Enterprise app server, just to name a few.

After the Dot-com bubble things calmed down for a while. Some of the leading Java tool vendors discontinued their products. Open source tools were born, eating from their market as well. I remember basing one small app for students curriculum upload on Tomcat 3.1 and servlets. I think that there was some bug in Tomcat which led to restart of the whole computer (Windows 2000 server machine) on each few uploads – a very bad lesson for me.

A lot of years has passed since then. The owner company of Java no longer exists. A lot of the Java tool vendors also no longer exist having the same faith of being accused by larger companies. Java is no longer a hype, it’s a mainstream language used in a lot of applications with billions of code lines, that have to be supported.

A some type of rebirth was given to the language by Google by making Java the primary language for Android applications. This is like having a second life, probably Google managers thought about the millions Java programmers and how easy will be for them to switch to mobile phone development knowing already the language syntax.

But anyway Java at its current state is dominated by open source tools. Only rich companies afford to buy commercial IDEs, application servers or software libraries, but they are minority.

What’s the future of the language? No one can predict, but Java is here to stay at least for the next 15-20 years.

JShell comming after PowerShell

There was a time when Java was fresh and bleeding edge technology (I was sixteen at that time:). Time has passed and after a few year Microsoft made a similar language running on a virtual machine called .NET. Microsoft started by copying the good features of Java, but avoiding the bad things (like JAR hell, e.g.)

Ironically today almost 20 year later, Oracle as the new owner of Java is trying to catch up with .NET by cloning features from it. The fresh example is JShell which is a close match to PowerShell.

Only the future will tell how widespread will it become.

 

Java EE 8 with MVC 1.0

If you are a Java web developer probably you’ve already heard of the new MVC 1.0 framework that ships with Java EE 8.0.

It’s interesting that JSF will also be there, so its still alive too. The thing that makes me wander is why another framework, just to keep you busy migrating old code and shooting on a moving target.

Only time will show how well it will be adopted, but being the lonely wolf I don’t like it on the first place because of the tremendous amount of annotations. This is really Enterprise!

OpenPGP encryption in Android

I came across a very easy to use Java library that can be used for Android application development when we need OpenPGP encryption functionality.The library was downloaded from the web site of the developer DidiSoft at OpenPGP Library for Android

Bellow is a short demo code that illustrates how to perform basic OpenPGP encryption over a data stream obtained from a file located in the /assets folder of the application. The encrypted output is then stored in a file OUTPUT.txt located in the private context path of the application. The public key that is used to encrypt the data is also in the /assets folder of the application.

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;

import com.didisoft.pgp.PGPException;
import com.didisoft.pgp.PGPLib;

public class EncryptDemo extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TextView tv = new TextView(this);

  // encrypt
  try {
    // create an instance of the library
    PGPLib pgp = new PGPLib();

    InputStream dataStream = null;
    InputStream keyStream = null;
    OutputStream outStream = null;
    boolean error = false;
    try {
      AssetManager assets = ctx.getAssets();
      // load data and public key stream
      dataStream = assets.open(INPUT_txt);
      keyStream = assets.open(public_key);

      // specify output stream
      outStream = ctx.openFileOutput("OUTPUT.pgp", MODE_PRIVATE);

      // This is just a file name label that will be associated with the encrypted data
      String internalFileNameLabel = "INPUT.txt";

      // specifies will the output be ASCII armored or binary
      boolean asciiArmor = true;

      // specifies should integrity check information be appended
      boolean withIntegrityCheck = false;

     // call encrypt method
     pgp.encryptStream(dataStream, internalFileNameLabel, keyStream, outStream, asciiArmor, withIntegrityCheck);
  } catch (Exception e) {
   error = true;
   tv.append("Error:");
   tv.append(e.getMessage());
  } finally {
    // cleanup
    if (dataStream != null) {
      dataStream.close();
    }
    if (keyStream != null) {
     keyStream.close();
    }
    if (outStream != null) {
     outStream.close();
    }
  }

  if (!error)
     tv.append("The file was successfully encrypted.");

  setContentView(tv);
 }
}

This library really simplifies the OpenPGP development in Android. The only drawback is that it is a commercial implementation and costs money:(

NoClassDefFoundError

NoClassDefFoundError, ClassNotFoundException and ClassCastException are well known to every Java software developer. In a trivial “Hello World” application it is obvious what do they mean. But in the more complicated when we have a chain of class loaders for example in an application server it is sometimes tricky why do they appear. In this post I will try to explain some scenarios from my practice when they have appeared.

ClassNotFoundException

The example code below is a usual suspect that may throw ClassNotFoundException.

Class clazz = Class.forName("AnUnavailableClass");

In the case above it is understood that if the current class loader does not know of a class with name  AnUnavailableClass it will throw ClassNotFoundException. But here is a scenario when this exception will also be thrown and at first sight it is very strange.

Suppose that we have a web application (e.g. EJB) that is  loading a custom SecurityProvider:

if (Security.getProvider("MyProvider") == null)
Security.addProvider(new MyProvider);

The above code runs fine on first execution. On application deploy the ClassLoader that first loaded MyProvider is destroyed and a new class loader is created,  but the SecurityProvider hold the old reference that points to the first already garbage collected ClassLoader. And the result is ClassNotFoundException.

NoClassDefFoundError

This exception is thrown when we try to reference a class that the current ClassLoader does not know about. The usual case is that we have missed a Jar file from the application class path.

ClassCastException

The code below is the usual suspect for this exception

MyClass myObj = (MyClass) obj;

But a more cumbersome case also exists that throws the same exception. If by mistake our application has two different versions of a Jar file and we reference a class from it, the ClassLoader may load at run-time a class from the old version of the Jar file instead of the new one (the one that we expect). Another common case for this error is when we try to create an instance from a serialized object.

Conclusion

This post tried to explain a few cases from my practice as a Java software engineer that I met NoClassDefFoundError, ClassNotFoundException and ClassCastException.