util Posts

[Java] Create a Simple Http Get Request with GZip Compression Handling using Apache Httpclient

Previous Apache HttpClient use various class to handling compressed http response, such as DecompressingHttpClient and ContentEncodingHttpClient. But on the latest version, compression is handled automatically by using HttpClientBuilder class.

Here is my pom file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.edw</groupId>
    <artifactId>Edw</artifactId>
    <version>1</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    
    <dependencies>                
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>        
    </dependencies>
    
</project>

And this is my java class,

package com.edw.main;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Main {

    public static void main(String[] args) throws Exception {
        Main main = new Main();
        System.out.println(main.getContent("http://localhost:8085/"));
    }

    private String getContent(String urlToRead) throws Exception {
        HttpEntity resEntity = null;
        try {
            HttpClient httpclient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(urlToRead);

            HttpResponse response = httpclient.execute(httpGet);
            resEntity = response.getEntity();

            return EntityUtils.toString(resEntity);
        } finally {
            if (resEntity != null) {
                EntityUtils.consume(resEntity);
            }
        }
    }
}

[Weird Javascript Error] Leading Zero on Integer Variable Become Octal on Old Browser

Ive met a very weird error, that somehow never occurs to me on my browser. I found this error only happen on old mozilla browsers, and only happen on javascript’s parseInt method. Here is a simple example,

alert(parseInt("09")-1);

When im running it on my browser (Mozilla version 34), this is what happen,
mozillanew

But when running on old browsers (Mozilla version 3.6), this is what happen,
mozillaold

I finally found out that that on old browsers, leading zeros are treated as octal values instead of plain integers. So this is my workaround,

alert(parseInt("09".replace(/^[0]+/g,""))-1);

I removed the leading zero before parsing it into int.

Hope it can help others 🙂

A Simple Indonesian Geographic Coordinate Conversion Between Degrees to Degree-Minute-Second (DMS)

Recently i have a simple GIS project which force me to display an Indonesian DMS coordinate format, instead of the usual decimal format. This is a simple utility class i used to do convertion.

import java.text.DecimalFormat;

public class DegreeConverterTest {

    public static final String LONGITUDE = "longitude";
    public static final String LATITUDE = "latitude";

    public DegreeConverterTest(String testName) {
    }

    public static void main(String a[]) {
        System.out.println(degree2DMS(-8.857, LATITUDE));
        System.out.println(degree2DMS(10.645, LATITUDE));
        System.out.println(degree2DMS(135.696, LONGITUDE));
    }

    public static String degree2DMS(double coordinate, String mode) {
        String dms = "";

        char degree = '\u00B0';
        int degLong, minLongA;
        double minLong, secLong;
        DecimalFormat df = new DecimalFormat("#,###,####0.0000");

        if (LONGITUDE.equals(mode)) {
            // minus is BB (Bujur Barat or west longitude)
            // plus is BT (Bujur Timur of east longitude)
            degLong = (int) coordinate;
            minLong = (coordinate % 1) * 60;
            minLongA = (int) minLong;
            secLong = (minLong % 1) * 60;
            String secLongAs = String.valueOf(df.format(secLong));
            dms = degLong + degree + " " + minLongA + "' " + secLongAs + "\" BT";
        } else if (LATITUDE.equals(mode)) {
            // minus is LS (Lintang Selatan or south latitude)
            // plus is LU (Lintang Utara or north latitude)
            boolean isMinus = true;
            String minusDegree = "LS";
            degLong = (int) coordinate;
            String degLongS = String.valueOf(degLong);
            if (degLongS.contains("-")) {
                degLongS = degLongS.replace("-", "");
            } else {
                isMinus = false;
                minusDegree = "LU";
            }

            minLong = (coordinate % 1) * 60;
            minLongA = (int) minLong;
            String minLongAs = String.valueOf(minLongA);
            if (isMinus) {
                minLongAs = minLongAs.replace("-", "");
            }

            secLong = (minLong % 1) * 60;
            String secLongAs = String.valueOf(df.format(secLong));
            if (isMinus) {
                secLongAs = secLongAs.replace("-", "");
            }

            dms = degLongS + degree + " " + minLongAs + "' " + secLongAs + "\" " + minusDegree;
        }
        return dms;
    }
}

And this is the output i got on my netbeans’ console

8° 51' 25.2000" LS
10° 38' 42.0000" LU
311 41' 45.6000" BT

How To Simulate An Image Attachment HTTP Multipart POST

Below is the code i use for simulating an image attachment using apache http client.

package com.edw.postsimulator;

import java.io.File;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class PostTest {

    private static String url = "http://localhost:8083/RealsAppApi/images/add";

    public static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpContext localContext = new BasicHttpContext();
        
        Charset chars = Charset.forName("UTF-8");
        
        // http content
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("username", new StringBody("edwin", chars));
        entity.addPart("password", new StringBody("edwinpassword", chars));        
        
        // attach image
        File fileToUpload = new File("F:\\no.jpg");
        FileBody fileBody = new FileBody(fileToUpload, "application/octet-stream");
        entity.addPart("image", fileBody);
        httpPost.setEntity(entity);

        // fire and log the responses
        HttpResponse response = httpclient.execute(httpPost, localContext); 
        HttpEntity resEntity = response.getEntity();
        System.out.println(EntityUtils.toString(resEntity));
    }
}

These are the libraries i used for this project,
post simulator

Hope it would help others, have fun (Y)

Fixing Postgresql Error, “initdb: could not change permissions of directory, Permission denied”

Today im trying to install postgresql 9.3 on my windows server 2003 ( old server actually ), and i found a very weird error. Somehow im unable to complete the installation due to error “could not change permission of directory, permission denied”. Below is the complete error stacktrace,

fixing permissions on existing directory D:/PostgreSQL/9.1/data ... 
initdb: could not change permissions of directory 
"D:/PostgreSQL/9.1/data": Permission denied 

Called Die(Failed to initialise the database cluster with initdb)... 
Failed to initialise the database cluster with initdb 

Script stderr: 
  Program ended with an error exit code 

It happen even after i put the installation folder outside “Program Files” folder, due to windows’ Program Files permission folder setting.

After several hours trying, i found out that the workaround is actually simple. I just create a new folder, i named it “dodol” set the permission to “everyone” and install my postgresql into that folder.

postgresql folder installation

postgresql folder installation

And my postgresql is installed without any problem.