Popular Posts
Activate IIS GIZP compress 1. Set metabase editable for editing. 2. Add a new extension for gzip. 3. Edit the file c:\windows\system32\inetsrv\MetaBase.xml Add file... Sublime Text hotkeys 編輯 Ctrl + X 刪除行 Ctrl + Enter 插入下一行 Ctrl + Shift + Enter 插入前一行 Ctrl + Shift + ↑ 往上移動一行 C... Tomcat GET encoding edit server.xml : <Connector     URIEncoding="UTF-8"     connectionTimeout="20000"     port="8080"     prot...
Stats
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop

Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago.

// Enable SSL connection
HttpsURLConnection.setDefaultSSLSocketFactory(new MySocketFactory1());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
});

URL address = new URL(url);
HttpsURLConnection urlConnection = (HttpsURLConnection) address.openConnection();
InputStream in = urlConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[128];
int len = 0;
while ((len = in.read(buffer)) > 0) {
    baos.write(buffer, 0, len);
}
baos.close();
in.close();
MySocketFactory1.java
package com.prhythm.google.myapplication2.app;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by nanashi07 on 15/5/23.
 */
public class MySocketFactory1 extends SSLSocketFactory {

    SSLContext context;
    SSLSocketFactory factory;

    public MySocketFactory1() {
        try {
            init();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    void init() throws KeyManagementException, NoSuchAlgorithmException {
        context = SSLContext.getInstance("SSL");
        context.init(null, new X509TrustManager[]{new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }}, new SecureRandom());
        factory = context.getSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return factory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return factory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return factory.createSocket(s, host, port, autoClose);
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return factory.createSocket(host, port);
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
        return factory.createSocket(host, port, localHost, localPort);
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return factory.createSocket(host, port);
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return factory.createSocket(address, port, localAddress, localPort);
    }
}
javax.net.ssl.SSLHandshakeException: Connection closed by peer
05-24 07:54:11.626    1697-1716/com.prhythm.google.myapplication2.app E/Test﹕ error
    javax.net.ssl.SSLHandshakeException: Connection closed by peer
            at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
            at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:302)
            at com.android.okhttp.Connection.upgradeToTls(Connection.java:197)
            at com.android.okhttp.Connection.connect(Connection.java:151)
            at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
            at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
            at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
            at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
            at com.prhythm.google.myapplication2.app.MainActivity$1.doInBackground(MainActivity.java:41)
            at com.prhythm.google.myapplication2.app.MainActivity$1.doInBackground(MainActivity.java:26)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)

After track and search from some technical articles, I found this TLS/SSL Default Configuration Changes, finally. Base on this, I've made some changes for my SSLSocketFactory to add cipher suites setting. Now it works fine again.

MySocketFactory2.java
package com.prhythm.google.myapplication2.app;

import com.prhythm.core.generic.util.Cube;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Set;

/**
 * Created by nanashi07 on 15/5/23.
 */
public class MySocketFactory2 extends SSLSocketFactory {

    SSLContext context;
    SSLSocketFactory factory;
    String type;

    public MySocketFactory2() {
        try {
            init();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    void init() throws KeyManagementException, NoSuchAlgorithmException {
        context = SSLContext.getInstance(type = Cube.from("SSL", "TLS").random());
        context.init(null, new TrustManager[]{new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                System.out.printf("[CLIENT] chain = %s, authType = %s%n", Arrays.toString(chain), authType);
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                System.out.printf("[SERVER] chain = %s, authType = %s%n", Arrays.toString(chain), authType);
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }}, new SecureRandom());
        factory = context.getSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return getCipherSuites().toArray(String.class);
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return getCipherSuites().toArray(String.class);
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return configCipherSuites(factory.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return configCipherSuites(factory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
        return configCipherSuites(factory.createSocket(host, port, localHost, localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return configCipherSuites(factory.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return configCipherSuites(factory.createSocket(address, port, localAddress, localPort));
    }

    Cube<String> getCipherSuites() {
        return Cube.from("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
                "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
                "SSL_DHE_DSS_WITH_DES_CBC_SHA",
                "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
                "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
                "SSL_DHE_RSA_WITH_DES_CBC_SHA",
                "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA",
                "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
                "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA",
                "SSL_DH_anon_WITH_DES_CBC_SHA",
                "SSL_DH_anon_WITH_RC4_128_MD5",
                "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
                "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
                "SSL_RSA_WITH_3DES_EDE_CBC_SHA",
                "SSL_RSA_WITH_DES_CBC_SHA",
                "SSL_RSA_WITH_NULL_MD5",
                "SSL_RSA_WITH_NULL_SHA",
                "SSL_RSA_WITH_RC4_128_MD5",
                "SSL_RSA_WITH_RC4_128_SHA",
                "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
                "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
                "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256",
                "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
                "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
                "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384",
                "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
                "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
                "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
                "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
                "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
                "TLS_DH_anon_WITH_AES_128_CBC_SHA",
                "TLS_DH_anon_WITH_AES_128_CBC_SHA256",
                "TLS_DH_anon_WITH_AES_128_GCM_SHA256",
                "TLS_DH_anon_WITH_AES_256_CBC_SHA",
                "TLS_DH_anon_WITH_AES_256_CBC_SHA256",
                "TLS_DH_anon_WITH_AES_256_GCM_SHA384",
                "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
                "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
                "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
                "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
                "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
                "TLS_ECDHE_ECDSA_WITH_NULL_SHA",
                "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
                "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
                "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
                "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
                "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
                "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
                "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
                "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
                "TLS_ECDHE_RSA_WITH_NULL_SHA",
                "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
                "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
                "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
                "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
                "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",
                "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384",
                "TLS_ECDH_ECDSA_WITH_NULL_SHA",
                "TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
                "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
                "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",
                "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
                "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",
                "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",
                "TLS_ECDH_RSA_WITH_NULL_SHA",
                "TLS_ECDH_RSA_WITH_RC4_128_SHA",
                "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",
                "TLS_ECDH_anon_WITH_AES_128_CBC_SHA",
                "TLS_ECDH_anon_WITH_AES_256_CBC_SHA",
                "TLS_ECDH_anon_WITH_NULL_SHA",
                "TLS_ECDH_anon_WITH_RC4_128_SHA",
                "TLS_EMPTY_RENEGOTIATION_INFO_SCSV",
                "TLS_FALLBACK_SCSV",
                "TLS_PSK_WITH_3DES_EDE_CBC_SHA",
                "TLS_PSK_WITH_AES_128_CBC_SHA",
                "TLS_PSK_WITH_AES_256_CBC_SHA",
                "TLS_PSK_WITH_RC4_128_SHA",
                "TLS_RSA_WITH_AES_128_CBC_SHA",
                "TLS_RSA_WITH_AES_128_CBC_SHA256",
                "TLS_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_RSA_WITH_AES_256_CBC_SHA",
                "TLS_RSA_WITH_AES_256_CBC_SHA256",
                "TLS_RSA_WITH_AES_256_GCM_SHA384",
                "TLS_RSA_WITH_NULL_SHA256")
                .where(new Cube.Selection<String>() {
                    @Override
                    public boolean predicate(String item, int index) {
                        return item.startsWith(type);
                    }
                });
    }

    Socket configCipherSuites(Socket socket) {
        if (!(socket instanceof SSLSocket)) return socket;
        SSLSocket sslsocket = (SSLSocket) socket;
        // 處理不合的cipher suite
        Set<String> suites = getCipherSuites().toSet();
        while (suites.size() > 0) {
            try {
                sslsocket.setEnabledCipherSuites(suites.toArray(new String[suites.size()]));
                break;
            } catch (Throwable e) {
                String message = e.getMessage();
                for (String cipher : suites) {
                    if (message.toLowerCase().contains(cipher.toLowerCase())) {
                        suites.remove(cipher);
                        System.out.printf("Cipher suite %s has been removed.%n", cipher);
                        break;
                    }
                }
            }
        }
        return socket;
    }
}
Gradle: error: unmappable character for encoding

Sometimes error occurs on gradle build cause of file encoding




Solved: add gradle vm option as below:

-Dfile.encoding=utf-8
Gradle: generate java source folder
task createSourceFolder {
    sourceSets*.java.srcDirs*.each { it.mkdirs() }
    sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}
Dynamic add classpath path
public void appendClasspath(String path) throws NoSuchMethodException, MalformedURLException, InvocationTargetException, IllegalAccessException {
    Path externalResourcesFolder = Paths.get(path);
    ClassLoader sysLoader = ClassLoader.getSystemClassLoader();
    if (sysLoader instanceof URLClassLoader) {
        Class<URLClassLoader> sysLoaderClass = URLClassLoader.class;

        // Use reflection to invoke the private addURL method
        Method method = sysLoaderClass.getDeclaredMethod("addURL", URL.class);
        method.setAccessible(true);
        method.invoke(sysLoader, externalResourcesFolder.toUri().toURL());

        System.out.printf("classpath: %s loaded%n", path);
    }
}
ASP.NET MVC 5 Attribute Routing
Enable attribute route
Global.asax
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Enable attribute route
        RouteTable.Routes.MapMvcAttributeRoutes();

        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
or
RouteConfig.cs
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            
        // Enable attribute route
        routes.MapMvcAttributeRoutes();

        AreaRegistration.RegisterAllAreas();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
Direct route
public class BookController : Controller {

    // Map to 'http://prhythm.com.tw/Pet/10'
    [Route("Pet/{id}")]
    public ActionResult Pet(int? id) {
        return View();
    }

}
Optional paramter
public class BookController : Controller {

    // Optional parameter id
    // Map to 'http://prhythm.com.tw/Pet'
    //     or 'http://prhythm.com.tw/Pet/5'
    [Route("Pet/{id?}")]
    public ActionResult Pet(int? id) {
        return View();
    }

}
Default parameter value
public class BookController : Controller {
    
    // Default value of id
    // Map to 'http://prhythm.com.tw/Pet'
    //     or 'http://prhythm.com.tw/Pet/10'
    [Route("Pet/{id=10}")]
    public ActionResult Pet(int? id) {
        return View();
    }

}
Paramter constrains
public class BookController : Controller {
    
    // Paramters constrains
    [Route("Pet/{id:int}")]
    public ActionResult Pet(int? id) {
        return View();
    }

}
ConstraintDescriptionExample
alpha Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) {x:alpha}
bool Matches a Boolean value. {x:bool}
datetime Matches a DateTime value. {x:datetime}
decimal Matches a decimal value. {x:decimal}
double Matches a 64-bit floating-point value. {x:double}
float Matches a 32-bit floating-point value. {x:float}
guid Matches a GUID value. {x:guid}
int Matches a 32-bit integer value. {x:int}
length Matches a string with the specified length or within a specified range of lengths. {x:length(6)}
{x:length(1,20)}
long Matches a 64-bit integer value. {x:long}
max Matches an integer with a maximum value. {x:max(10)}
maxlength Matches a string with a maximum length. {x:maxlength(10)}
min Matches an integer with a minimum value. {x:min(10)}
minlength Matches a string with a minimum length. {x:minlength(10)}
range Matches an integer within a range of values. {x:range(10,50)}
regex Matches a regular expression. {x:regex(^\d{3}-\d{3}-\d{4}$)}
Route prefix
[RoutePrefix("Booking")]
public class BookController : Controller {

    // Map to 'http://prhythm.com.tw/Booking'
    //     or 'http://prhythm.com.tw/Booking/Pet'
    [Route]    
    [Route("Pet")]
    public ActionResult Pet() {
        return View();
    }

    // Map to 'http://prhythm.com.tw/Booking/Edit'
    [Route("Edit")
    public ActionResult Edit() {
        return View();
    }
}
Override route prefix
[RoutePrefix("Booking")]
public class BookController : Controller {

    // Override route prefix
    // Map to 'http://prhythm.com.tw/Pet'
    [Route("~/Pet")]
    public ActionResult Pet() {
        return View();
    }
}
Default route
[RoutePrefix("Booking")]
[Route("action=pet")]
public class BookController : Controller {

    // Map to 'http://prhythm.com.tw/Booking'
    //     or 'http://prhythm.com.tw/Booking/Pet'
    public ActionResult Pet() {
        return View();
    }

    // Map to 'http://prhythm.com.tw/Booking/Edit'
    public ActionResult Edit() {
        return View();
    }
}
Route area
[RouteArea("Backend")]
[RoutePrefix("News")]
public class NewsController : Controller {

    // Map to 'http://prhythm.com.tw/backend/news'
    public ActionResult Index() {
        return View();
    }

}
[RouteArea("Backend", AreaPrefix = "Admin")]
[RoutePrefix("News")]
public class NewsController : Controller {

    // Map to 'http://prhythm.com.tw/admin/news'
    public ActionResult Index() {
        return View();
    }

}

Reference http://sampathloku.blogspot.tw/2013/11/attribute-routing-with-aspnet-mvc-5.html

Reference http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Asynchronous and deferred JavaScript execution explained
  • Normal execution <script>
    This is the default behavior of the <script> element. Parsing of the HTML code pauses while the script is executing. For slow servers and heavy scripts this means that displaying the webpage will be delayed.
  • Deferred execution <script defer>
    Simply put: delaying script execution until the HTML parser has finished. A positive effect of this attribute is that the DOM will be available for your script. However, since not every browser supports defer yet, don’t rely on it!
  • Asynchronous execution <script async>
    Don’t care when the script will be available? Asynchronous is the best of both worlds: HTML parsing may continue and the script will be executed as soon as it’s ready. I’d recommend this for scripts such as Google Analytics.

Reference : http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/

Reference : http://www.html5rocks.com/en/tutorials/speed/script-loading/

Integration config for spring & hibernate
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.prhythm.spring.web.controller"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:test"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.prhythm.spring.web.model"/>
        <!--<property name="annotatedClasses">-->
            <!--<list>-->
                <!--<value>com.prhythm.spring.web.model.Employee</value>-->
            <!--</list>-->
        <!--</property>-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>
Wrong text encoding while Jsoup parse document

While page encoding is different with content type encoding declaration. Jsoup will get wrong text decode content. To avoid this problem, Assign a correct text encoding will be required.

Connection connection = Jsoup.connect(requestUrl)
        .data("type", "1")
        .data("searchKeyUID", searchKeyUID)
        .timeout(timeout)
        .method(Connection.Method.GET);

Connection.Response response = connection.execute();
Document document = Jsoup.parse(new ByteArrayInputStream(response.bodyAsBytes()), "UTF-8", requestUrl);
Group data on SQLite

Schema

CREATE TABLE invoice
(
    Id INTEGER PRIMARY KEY,
    code TEXT,
    dropped INTEGER,
    due_date INTEGER,
    paid INTEGER,
    due_date2 TEXT
);

Initial data

INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (1, 'IMSS', 0, 1407384129647, 0, '2014-08-07 04:02:09');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (2, 'Deep Discovery family', 0, 1407346684736, 0, '2014-08-06 17:38:04');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (3, 'TMMS​', 1, 1407375568242, 0, '2014-08-07 01:39:28');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (4, 'TMS family​', 0, 1407374437084, 1, '2014-08-07 01:20:37');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (5, 'SafeSync', 0, 1407358168347, 1, '2014-08-06 20:49:28');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (6, 'TMVMS​', 0, 1407350693881, 0, '2014-08-06 18:44:53');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (7, 'TMS family​', 0, 1407372590354, 0, '2014-08-07 00:49:50');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (8, 'IMSVA', 0, 1407344495046, 0, '2014-08-06 17:01:35');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (9, 'Other', 0, 1407351210774, 0, '2014-08-06 18:53:30');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (10, 'Deep Discovery family', 0, 1407372667906, 0, '2014-08-07 00:51:07');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (11, 'IMSVA', 1, 1407365934950, 1, '2014-08-06 22:58:54');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (12, 'PSP', 1, 1407382557767, 1, '2014-08-07 03:35:57');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (13, 'SecureCloud​', 0, 1407371609679, 0, '2014-08-07 00:33:29');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (14, 'NVWE​', 0, 1407383088966, 0, '2014-08-07 03:44:48');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (15, 'ESE', 1, 1407360299869, 1, '2014-08-06 21:24:59');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (16, 'IMSVA', 0, 1407377397832, 0, '2014-08-07 02:09:57');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (17, 'IWSVA​', 0, 1407366067348, 1, '2014-08-06 23:01:07');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (18, 'TMS family​', 1, 1407351067728, 0, '2014-08-06 18:51:07');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (19, 'OSCE​', 0, 1407345046895, 0, '2014-08-06 17:10:46');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (20, 'TIM​', 0, 1407363640638, 1, '2014-08-06 22:20:40');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (21, 'CSS​', 1, 1407330238874, 0, '2014-08-06 13:03:58');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (22, 'TMPS​', 1, 1407321708684, 1, '2014-08-06 10:41:48');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (23, 'TMS family​', 1, 1407319881608, 0, '2014-08-06 10:11:21');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (24, 'SafeSync', 1, 1407306547713, 0, '2014-08-06 06:29:07');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (25, 'ESDP', 0, 1407298566126, 0, '2014-08-06 04:16:06');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (26, 'CSS​', 0, 1407282477671, 0, '2014-08-05 23:47:57');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (27, 'TMMS​', 1, 1407240200509, 1, '2014-08-05 12:03:20');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (28, 'Other', 0, 1407218499996, 0, '2014-08-05 06:01:39');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (29, 'ESE', 0, 1407210588362, 0, '2014-08-05 03:49:48');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (30, 'CSS​', 0, 1407207304034, 0, '2014-08-05 02:55:04');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (31, 'TMVMS​', 1, 1407188482248, 0, '2014-08-04 21:41:22');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (32, 'SecureCloud​', 0, 1407155296508, 0, '2014-08-04 12:28:16');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (33, 'TMS family​', 1, 1407136374493, 0, '2014-08-04 07:12:54');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (34, 'ESE', 1, 1407121543307, 1, '2014-08-04 03:05:43');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (35, 'ScanMail', 0, 1407118018107, 0, '2014-08-04 02:06:58');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (36, 'ScanMail', 0, 1407088856291, 0, '2014-08-03 18:00:56');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (37, 'IMSS', 0, 1407059314747, 1, '2014-08-03 09:48:34');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (38, 'OSCE​', 1, 1407027453954, 0, '2014-08-03 00:57:33');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (39, 'Deep Discovery family', 0, 1406995304204, 0, '2014-08-02 16:01:44');
INSERT INTO invoice (Id, code, dropped, due_date, paid, due_date2) VALUES (40, 'Worry-Free', 0, 1406968142441, 0, '2014-08-02 08:29:02');

Group select

select 
  Id, 
  code, 
  (dropped|paid) status, 
  (due_date < 1407200000000) expired, 
  due_date2 
from invoice 
order by 
  paid|dropped, 
  (due_date > 1407200000000), 
  due_date desc

result