Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, August 9, 2016

Ant Java Compilation Classpath

If there are many jar files in the classpath, instead of specifying all of them, include all jar files in a folder this way: http://stackoverflow.com/questions/6103516/ant-adding-multiple-jars-in-classpath-dynamically

Saturday, February 20, 2016

Tuesday, December 15, 2015

JSch Error "com.jcraft.jsch.JSchException: reject HostKey" Even After Host Key Has Been Added

Usually when this error happens, all you need to do is to add the host key in a normal SSH session. However, this can also happen when the host key is in a format that JSch does not recognise or support e.g. I had a problem with a "ecdsa-sha2-nistp256" encoded host key.

To fix this I had to use the "ssh-keyscan -t rsa <hostname>" command (on the server) to obtain the host key in rsa format and then I manually added that to the "known_hosts" file.

Reference: http://anahorny.blogspot.sg/2013/05/solution-for-comjcraftjschjschexception.html

Tuesday, March 24, 2015

Monday, February 16, 2015

Java Enum Assign Values

For Java Enums, the values are normally auto-assigned starting from 0.

To assign specific value, see the example here: http://stackoverflow.com/questions/8811815/is-it-possible-to-assign-numeric-value-to-an-enum-in-java

Saturday, January 3, 2015

SimpleDateFormat Strange Results / Thread Safety

SimpleDateFormat can give strange results when running on a server when multiple threads share the same instance. This is because it is not thread-safe due to intermediate results being stored in instance variables. To avoid this problem always instantiate a new SimpleDateFormat object when needed or find a way to ensure there is one instance per thread (e.g. using ThreadLocal).

References:

Wednesday, November 12, 2014

Friday, September 5, 2014

AWS SES Send HTML Email With Java API

It is not clear in the documentation whether it is possible to send a multi-part email with both Plain Text and HTML components via AWS SES.

I did a test and verified that it is supported in this way:
Body body = new Body();
Content textContent = new Content().withData("text content");
body.withText(textContent);
Content htmlContent = new Content().withData("html content");
body.withHtml(htmlContent);

The resulting email will be a multi-part email with both Plain Text and HTML components.

Monday, July 14, 2014

Java sendRedirect https becomes http

This can happen when your Servlet contain is behind a load-balancer and when your load-balancer is handling SSL, and when you are redirecting using a relative URL.

In such a situation, you can't use relative URL. You will instead have to specify the absolute URL to redirect to i.e. the URL starting from "https://".

Wednesday, July 2, 2014

Java HTTP Client: SSL Self-Signed Certificates & IP Address Hostnames

By default, a Java based HTTP client will not allow connection to a "https" endpoint when the server-side certificate is self-signed, and also in the situation where the server uses an IP address rather than a hostname.

They will require separate solutions. For the self-signed certificate, we can use this code to tell Java to trust all certificates.

TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
   public X509Certificate[] getAcceptedIssuers(){return null;}
   public void checkClientTrusted(X509Certificate[] certs, String authType){}
   public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};

try {
   SSLContext sc = SSLContext.getInstance("TLS");
   sc.init(null, trustAllCerts, new SecureRandom());
   HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {}

For the IP address issue, which will throw an error (CertificateException: No subject alternative names present), we can use the following code:

      HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
           public boolean verify(String hostname, SSLSession session){
                 // you may choose to return true all the time here or return true for certain IPs
           }
       });

Note: this solution has been tested to work with the Jersey REST client.

References:

Java Hide Command Line Input

If you are asking the user to key in a password and wish to hide it while the user is typing it, the usual approach would not be able to support that.

The solution is to use the java.io.Console class. Other than the "readLine" method for the normal reading of input, it also has a "readPassword" method where nothing is shown as it is typed.

The only downside is that this cannot be used inside an IDE environment.

Saturday, September 28, 2013

Java Still Going Strong

I've always believed in using Java for the backend because of its performance, maturity, versatility, availability of open source tools/libraries and also you can have large teams work on projects together without things getting messy.

So it's good to see these articles, which also provide a good inside look at Twitter's struggles with Ruby on Rails and its subsequent migration to Java:

Friday, October 19, 2012

Java Obtain Thread Dump

In Java, a thread dump can be useful in giving you some clues when an application is hanging or consuming a lot of CPU resources (e.g. infinite loop).

Obtaining one is actually quite easy, via the "jstack" utility shipped with the JDK.

Just login to the server and issue the command "jstack <pid>".

Sunday, August 19, 2012

Java Reflection: Access a Private Field

It is possible to access private fields in Java classes using the Reflection API (as long as the Security Manager isn't configured to prevent this).

This is done by adding "field.setAccessible(true);" before trying to obtain the value of the field.

Example code:


Field field = SomeClass.class.getDeclaredField(fieldName);
feld.setAccessible(true);
return field.get(obj);

Sunday, June 17, 2012

Java: Short to Bytes

Here's how to do it:


public static byte[] shortToBytes(short theShort) {
   byte[] theBytes = new byte[2];
   theBytes[0] = (byte)((theShort >> 8) & 255);
   theBytes[1] = (byte)(theShort & 255);

   return theBytes;
}

The purpose of the "& 255" bitwise operator is to ensure that all bits before the last byte are 0.

Java: Bytes to Short

Here is how to convert bytes to short in Java, with a function to prove/test it:


private static short bytesToShort(byte[] theBytes) {
   short msb = theBytes[0];
   short lsb = (short)(theBytes[1] & 255);
   msb = (short)(msb << 8);
       
   short result = (short)(msb | lsb);
   return result;
}
// for testing the bytesToShort functionpublic static void main(String[] args) throws Exception {
   int numValues = Short.MAX_VALUE - Short.MIN_VALUE + 1;
   short[] testValues = new short[numValues];
   for (int i = 0; i < testValues.length; i++) {
       testValues[i] = (short)(Short.MIN_VALUE + i);
   }
   int numWrongAnswers = 0;
   for (int i = 0; i < testValues.length; i++) {
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(bos);
       dos.writeShort(testValues[i]);
       byte[] theBytes = bos.toByteArray();
       short s = bytesToShort(theBytes);

       String correct = "";
       if(s == testValues[i]){
               correct = "yes";
       }
       else {
               numWrongAnswers++;
               correct = "NO!!!!!!!!!!!";
       }
       System.out.println("original: " + testValues[i] + " converted: " + s + " OK? " + correct);
       }
       System.out.println("numWrongAnswers: " + numWrongAnswers);
}

Tuesday, June 12, 2012

Java HMAC-SHA256

While MD5 or SHA256 can be used to verify the integrity of a transmitted file, it doesn't guarantee that the file came from an authorized source. One way to do it is to use HMAC-SHA256 to create a signed hash. It uses a symmetric key approach where both sides are in possession of an identical key.

To verify that the file is signed by the same key, just sign the payload with the HMAC-SHA256 algorithm and the key, and then verify that the outputs are the same.

Java provides this functionality out-of-the-box in the javax.crypto package.

Code Sample:

byte[] payload = <the payload to sign>;
byte[] signatureBytes = <the sent signature>;
String key = "XXXXXXXXXXXXXX";
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] keyBytes = key.getBytes("US-ASCII");
SecretKey secretKey = new SecretKeySpec(keyBytes,hmacSha256.getAlgorithm());

hmacSha256.init(secretKey);
hmacSha256.update(payload);

byte[] signedPayload = hmacSha256.doFinal();

boolean result = Arrays.equals(signedPayload, signatureBytes);

Friday, June 1, 2012

Executable JAR Classpath Gotcha

When you use "java -jar" to run an executable JAR file, the CLASSPATH environment variable and the "-cp" parameter doesn't take effect. Instead, you have to put the classpath inside the manifest file, such that the manifest file has the following lines:

Main-Class: com.xxx.xxx.Main
Class-Path: abc.jar xyz.jar