utility Posts

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
Google+

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)

Google+

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.

Google+

Logging HTTP Request Parameters using HTTP Servlet

This is a servlet filter that i use if i want to log what parameters fired by my REST client, basically it’s just a simple http servlet filter.

package com.edw;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

public class LoggingFilter implements Filter {

    private Logger logger = Logger.getLogger(this.getClass());
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            
            String uri = req.getRequestURI();
            logger.debug("Requested Resource::"+uri);
            
            Enumeration<String> enumeration = req.getParameterNames();
            
            while(enumeration.hasMoreElements()) {
                String parametername = enumeration.nextElement();
                logger.debug(parametername + " : " +req.getParameter(parametername));
            }
        } catch (Exception e) {
            logger.error(e,e);
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}

Add your servlet filer to your web.xml and listen for a specific url request, on this example i listen for requests to /services/ url.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">    
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <filter>
	<filter-name>LogFilter</filter-name>
	<filter-class>
		com.edw.LoggingFilter
	</filter-class>
    </filter>
    <filter-mapping>
            <filter-name>LogFilter</filter-name>
            <url-pattern>/services/*</url-pattern>
    </filter-mapping>    
</web-app>
Google+

Create and Exporting A Web-Based Excel Report Using JXLS and SpringMVC

Today im trying to create a simple excel exporter report using SpringMVC. Im integrating JXLS library with SpringMVC framework. I prefer using JXLS compared to JasperReport or other java-to-excel-library due to its easy templating, so i dont need to create excel formatting from java code.

I start with my pom.xml

<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>JXLSSpringMVC</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <name>JXLSSpringMVC</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency> 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
        
        <!-- jxls -->
        <dependency>
            <groupId>net.sf.jxls</groupId>
            <artifactId>jxls-core</artifactId>
            <version>0.9.9</version>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>6.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

And a simple web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

And 2 SpringMVC configuration file, applicationContext.xml,

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:annotation-config/>
    
    <tx:annotation-driven/>
    
    <context:component-scan base-package="com.edw.jxlsspringmvc"/>
    
</beans>

and dispatcher-servlet.xml,

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.edw.jxlsspringmvc.controller" />
	
    <mvc:annotation-driven />

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
</beans>

And a simple excel file,
jxls excel template

A java controller file,

package com.edw.jxlsspringmvc.controller;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author edwin < edwinkun at gmail dot com >
 */
@Controller
public class IndexController {

    @Autowired
    private ServletContext context;
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }
    
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public String export(HttpServletRequest request, HttpServletResponse response) {
        try {
            // set output header
            ServletOutputStream os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=\"myexcel.xls\"");
            
            String reportLocation = context.getRealPath("WEB-INF");

            Map beans = new HashMap();
            beans.put("name", "Edwin");
            beans.put("address", "Jakarta, Indonesia");
            XLSTransformer transformer = new XLSTransformer();

            Workbook workbook = transformer.transformXLS(new FileInputStream(reportLocation + "/myexcel.xls"), beans);
            workbook.write(os);
            os.flush();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }    
}

And my index.jsp file

<html>
    <head>
        <title>Download Excel</title>
    </head>
    <body>
        <a href="${pageContext.request.contextPath}/export">download excel</a>
    </body>
</html>

My Netbeans project structure is like this,
jxls netbeans project

And this is the result when im clicking on the website’s download url,
jxls download result

Have fun with JXLS :)

Google+