Sunday, January 25, 2015

Enabling Shared Folder Feature in Virtual Box

To be able to share a folder from host to guest VMs, you need to install Guest Additions. To install it, click on Devices menu and then Install Guest Additions... And then the setup files will be mounted to the CD-ROM drive of the guest OS. Suppose your guest OS is Windows 8 (32 bit) so you can double click on the file VBoxWindowsAddition-x86.exe to install it. After the installation has finished, you'll see your shared folder appear as a new drive if you already configured it.

Please note that if you click on Install Guest Additions... and then nothing happens, it's probably because of your virtual CD-ROM drive is already being mounted to something else. If it is, you should unmount it first.

To unmount it:
1. Go to the settings of the OS guest and click Storage
2. Select the mounted file under the virtual CD-ROM drive for example, Controller IDE.
3. Click on the disc symbol next to CD/DVD Drive combobox and then Remove disk from virtual drive 


Tuesday, January 20, 2015

Ivy HelloWorld example


What is Ivy?

Ivy is additional set of Ant task created by Apache. It's packaged as JAR file and needs to be put in $ANT_HOME/lib, just like other third-party tasks. (To create your own task, you need to create a Java class that extends org.apache.tools.ant.Task)

Ivy contains a set of tasks (resolve, cachepath, retrieve, install, publish) which works like Apache Maven phases. For example, the resolve task downloads all dependencies from Maven's public repository and stores them in ivy cache (~/.ivy2/cache directory).

Why Ivy?

One of the reasons is you are familiar with Ant and you don't want to spend more time to learn Maven.




HelloWorld Example


We are going to show how to use Ivy to compile Java HelloWorld program.

1. Downloading Ivy
Suppose you already installed Ant and then you can download Ivy from http://ant.apache.org/ivy/download.cgi

2. Installing Ivy
cp apache-ivy-2.2.0/ivy-2.2.0.jar $ANT_HOME/lib
3. Creating HelloWorld.java

Suppose we are currently in $WORKSPACE directory then create the file in the directory $WORKSPACE/src/com/vathanakmao/ivytest/ as following:
package com.vathanakmao.ivytest;

import org.apache.commons.lang.StringUtils;

public class HelloWorld {

         public static void main(String[] args) {

                 String string = StringUtils.upperCase("Hello World!");

                 System.out.println(string);

         }

}

4. Creating build.xml file
<project name="test ivy" default="resolve"
                          xmlns:ivy="antlib:org.apache.ivy.ant">

        <target name="resolve" description="resolve dependencies with ivy">
                <ivy:resolve />
                <ivy:cachepath pathid="default.classpath"/>
        </target>

        <target name="compile" depends="resolve" description="Compile">
                <mkdir dir="build/classes" />
                <javac srcdir="src" destdir="build/classes">
                        <classpath refid="default.classpath" />
                </javac>
        </target>
</project>
The resolve task () will fetch the artifacts from Maven's public repository http://repo1.maven.org/maven2 and put them in cache (~/.ivy2/cache).

The cachepath task () creates an Ant path with the given ID default.classpath, pointing to ivy cache directory consisting of the resolved artifacts. Then, the javac task will look for the artifacts in the cache because we declare it as the classpath with refid.

5. Creating ivy.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<ivy-module version="2.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">

    <info organisation="com/vathanakmao/ivytest" module="helloworld" status="integration"></info>

    <dependencies>
         <dependency org="commons-lang" name="commons-lang" rev="2.6" />
    </dependencies>
</ivy-module>

6. Compiling
ant compile



Monday, January 19, 2015

Embedding Jetty Server: HelloWorld example

Jetty has a slogan, "Don't deploy your application into Jetty. Deploy Jetty into your application". This means that instead of bundling you application as a standard WAR deployed in Jetty, you can use Jetty server as a software component in a Java program just like any POJO.

1. Download the following JAR files:

- Jetty aggregate jar file from http://central.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/9.3.0.M1/jetty-all-9.3.0.M1.jar Jetty is decomposed into many different dependencies or JAR files. The aggregate JAR file contains all classes of the dependencies. It should not be used for production. All dependencies should be managed by Maven.

- Servlet API 3.0 from http://central.maven.org/maven2/org/eclipse/jetty/orbit/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.jar Please note that Jetty 9 is compatible with Servlet 3.0 so it won't work with Servlete 2.5.


2. Create handler class, HelloWorld.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class HelloWorld extends AbstractHandler {

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletExce$
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("<h1>Hello World</h1>");
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        server.setHandler(new HelloWorld());
        server.start();
        server.join();
    }
}

3. Compiling

> javac -cp javax.servlet-3.0.0.v201112011016.jar:jetty-all-9.3.0.M1.jar HelloWorld.java

4. Running

> java -cp .:javax.servlet-3.0.0.v201112011016.jar:jetty-all-9.3.0.M1.jar HelloWorld.java
2015-01-04 21:15:28.066:INFO::main: Logging initialized @140ms
2015-01-04 21:15:28.175:INFO:oejs.Server:main: jetty-9.3.0.M1
2015-01-04 21:15:28.248:INFO:oejs.ServerConnector:main: Started ServerConnector@7afc02c8{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2015-01-04 21:15:28.250:INFO:oejs.Server:main: Started @329ms

Open browser and type http://localhost:8080 and then you should see "Hello World".








Saturday, January 17, 2015

Parsing ISO 8601-compliant String to java.util.Date

To parse a string representation of date in ISO 8601 format, for example, 2015-01-18T01:01:01Z, you can use javax.xml.bind.DatatypeConverter class (included in JDK since version 1.6 update 4). The class is part of JAXB API. Please see JAXB for more details.

Please see the code snippet below on how to use it.
System.out.println(DatatypeConverter.parseDateTime("2014-10-15T01:01:01Z").getTime());
The parseDateTime() method returns java.util.Calendar object.



Why not use java.text.SimpleDateFormat class?

The example below works the same.
SimpleDateFormat formatter = new SimplateDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
System.out.println(formatter.parse("2014-10-15T01:01:01Z").getTime());
But the ParseException will be thrown if the date string is in another ISO 8601 format, for example, "2014-10-15T01:01:01+07:00". DatatypeConverter still works for this format and other ISO 8601 formats.





Reference
https://jaxb.java.net/tutorial/section_1_1-Introduction.html#About JAXB
https://jaxb.java.net/guide/Which_JAXB_RI_is_included_in_which_JDK_.html

Thursday, January 8, 2015

Making gray background for code block in Blogger posts

You might want to have gray background for your code block to make it more readable as below.
> echo "Hello World!"

1. Go to your Blogger dashboard and click on Template then Edit HTML.
2. Add the following code above the </head> tag and save.
<style>
pre.codeblock {
   background:#E8E8E8;
}
</style>
3. Create a new post and add the following code.
<pre class="codeblock">
> echo "Hello World!"
</pre>


Downloading and Installing Jetty

Jetty is a web server and servlet container. In 2009, it moved its core components to the projects of Eclipse Foundation, in order to broaden licensing and community of the project.


Installation

1. Download the latest distribution here http://download.eclipse.org/jetty/
2. Extract the distribution file jetty-distribution-9.2.6.v20141205.zip, for example.
3. Start Jetty:
> cd jetty-distribution-9.2.6.v20141205
> java -jar start.jar
2015-01-02 20:51:35.971:INFO::main: Logging initialized @1044ms
2015-01-02 20:51:36.063:WARN:oejs.HomeBaseWarning:main: This instance of Jetty is not running from a separate {jetty.base} directory, this is not recommended.  See documentation at http://www.eclipse.org/jetty/documentation/current/startup.html
2015-01-02 20:51:36.351:INFO:oejs.Server:main: jetty-9.2.6.v20141205
2015-01-02 20:51:36.370:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/Users/vathanakmao/workspace/jetty-distribution-9.2.6.v20141205/webapps/] at interval 1
2015-01-02 20:51:36.424:INFO:oejs.ServerConnector:main: Started ServerConnector@69121bc1{HTTP/1.1}{0.0.0.0:8080}
2015-01-02 20:51:36.425:INFO:oejs.Server:main: Started @1497ms
4. Open browser and type http://localhost:8080/ You will see error 404 page below. It means Jetty is running but there is no any default page to serve. You can check in the jetty-distribution-9.2.6.v20141205/webapps directory. It's empty. In previous versions of Jetty, there are default page included.





















Tuesday, January 6, 2015

Searching for specific Blogger posts by label


Searching by a label

In the textbox located on a top navigation bar for the page, you can type label:java to search for posts with label java.

Or you can type one of the following URLs in browser. They are equivalent.

http://myt8chnote.blogspot.com/search?q=label%3Ajava
http://myt8chnote.blogspot.com/search/label/java





Searching by multiple labels

You can search for all posts with label java and all posts with label php by typing in the textbox:

label:java|label:php

Or access the following URL in browser:

http://myt8chnote.blogspot.com/search?q=label:java|label:php








Reference

http://www.mybloggertricks.com/2014/01/17-best-search-techniques-in-blogger.html




Highlighting source code in Blogger post

You might want to hightlight the source code in your post as below:

public void formatCode() {
   System.out.println("Hello World!");
}

We can do it using SyntaxHightlight javascript framework as following:

Note that If your blog is using Dynamic template, it does not work. It works with only Simple template. Blogger also allows you to switch template but make sure you backup the current template first.


1. Open your blog's template page

















2. Click the Edit  HTML button to edit the template

















3. Copy the following code and paste it above the </head> tag and then save the template

<link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css"></link>
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css" rel="stylesheet" type="text/css"></link>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript"/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script language='javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
SyntaxHighlighter.all();
</script>

Note that you can exclude some JS libs, for example shBrushVb.js, if you're not gonna use it so that you won't hurt the performance of the blog.

I had a problem with blogger that when my page was loading, it tried to download the javascript and css files using https protocol instead of http, in which the site does not support that so i downloaded those files and uploaded them to Dropbox and replace the domain alexgorbatchev.com with the dropbox domain.

4. Create a new post and click on HTML button and copy the code below and paste it there

<pre class="brush:java">
public void formatCode() {
   System.out.println("Hello World!");
}
</pre>


If it's XML code, you can use <pre class="brush:xml"> instead and you need to escape the html characters (for example, < or > ) first. You may use any online tools to do it such as http://www.bloggersentral.com/p/html-escape-tool.html


5. Now it will take effect for all new and existing posts but you can see the syntax hightlight for only the published posts and only when you're viewing them, not editing or previewing. As the owner, you can view the post from the following page:

























Reference:
http://www.craftyfella.com/2010/01/syntax-highlighting-with-blogger-engine.html


Construct Amaon S3 object download URL

Syntax 1:

https://<bucket-region>.amazonaws.com/<bucket-name>/<object-id>

Assume we created the bucket mybucket with the region ap-southeast-1 and we upload the object with ID myfile.txt then the URL would be:

https://ap-southeast-1.amazonaws.com/mybucket/myfile.txt



Syntax 2:

https://<bucket-name>.s3.amazonaws.com/<object-id>


According to the example above, the URL would look like:

https://mybucket.s3.amazonaws.com/myfile.txt

Note that if the bucket name contains dot (.) character, you may encounter the following error when trying to get the object using RestTemplate class of Java Spring framework.

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://gg.backend-test-ap-southeast-1.s3.amazonaws.com/portal/194/174120/products/1413876472.8028_14_o.jpg": java.security.cert.CertificateException: No subject alternative DNS name matching gg.backend-test-ap-southeast-1.s3.amazonaws.com found.; nested exception is javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching gg.backend-test-ap-southeast-1.s3.amazonaws.com found.
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:525)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:473)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)
at com.goldengekko.mch.service.AmazonS3ManagerIntegrationTest.testPutObject(AmazonS3ManagerIntegrationTest.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching gg.backend-test-ap-southeast-1.s3.amazonaws.com found.
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.springframework.http.client.SimpleBufferingClientHttpRtestPutObjectequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:49)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:510)
... 26 more
Caused by: java.security.cert.CertificateException: No subject alternative DNS name matching gg.backend-test-ap-southeast-1.s3.amazonaws.com found.
at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:191)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:93)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:347)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:203)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
... 40 more




Monday, January 5, 2015

Extract text from a string using Java regular expression

In the example below, you can extract the URL path from a complete URL:

String regex = "\\A(http://|https://)(.[^/]*)(.+)";
String url = "http://example.com/portal/194/174120/products/1413876472.8028_14_o.jpg";
Matcher matcher = Pattern.compile(regex).matcher(url);
if (matcher.find()) {
 String contextPath = matcher.group(3);
 return contextPath;
}

and the result is:

/portal/194/174120/products/1413876472.8028_14_o.jpg



Reference:
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

Guessing file content type

You can get file content type from a URL as following:

String fileUrl = "http://example.com/myimage.jpg";
String contentType = URLConnection.guessContentTypeFromName(fileUrl);

and the result would be:

image/jpeg

There is another method to guess file content type from input stream instead, URLConnection.guessContentTypeFromStream(InputStream) but if the server does not return content type of the file in the response header when you access it, the method would return null. Guessing content type from file name still work in this case.