utility

Create New Trac Users on Windows

Trac is an interesting project management software, wiki and issue tracking system. Very light yet powerfull, thats why i use Trac to handle almost every project im involved with. One drawback is that you cannot manually add user account for accessing Trac, unless you installed Trac’s AccountManagerPlugin. Too bad im not able to installed it, thats why i need to find a workaround for handling users.

Trac is using web server authentication by default. To add new users, i need to add the new users in the Apache password file. In my Win32 environment it’s easy, just use htpasswd.exe application in my apache installation directory. Below here is my commands

C:\>cd C:\Program Files\BitNami Trac Stack\apache2\bin
C:\Program Files\BitNami Trac Stack\apache2\bin>htpasswd.exe -cs htpwd.txt edw

It will create a new file named htpwd.txt with user edw inside it. Next is just a simple copy paste from values created in htpwd.txt to my Trac’s htpasswd file. And just restart my Trac to apply my changes.

Another workaround for htpasswd.exe is using online htpasswd generator such as here or here. Just copy the generated output and paste it in your htpasswd file.
(B)

How to Fix Netbeans’ GroupLayout Incompatibility with Java 5.0 (and Less)

Netbeans has a very powerful feature for its Swing designer, but too bad the default swing designer generates soucecode using javax.swing.GroupLayout and it’s only available at Java 6. I found this problem early this morning, somehow i design the Swing UI using Netbeans but i have to deploy my application in a Java 5 environment. Btw, im using Netbeans 6.9.

Below is the screenshot for Netbeans’ free design layout.

And this is the generated sourcecode, it works well with java 6.0

But when im using Java 5, it generates lots of errors

So, the workarouds are whether i change all the UI layout designs from GroupLayout to NullLayout, or find a way so GroupLayout is compatible with Java 5.

Because the second workaround is much promising, so i googled a while and found out that it’s actually not to difficult to make GroupLayout is compatible with Java 5. This is how i do it.

Right click, and choose Properties

And choose Swing Layout Extension Library.

Suddenly all the javax.swing.GroupLayout changed into org.jdesktop.layout.GroupLayout. And dont forget to include swing-layout*.jar, because org.jdesktop.layout.GroupLayout located in it.

See, it’s not that hard right? (H)

How To Encrypt Properties File

Sometime i had to put sensitive informations such as database’s username and password on a properties file. In order make it safer, i had to encrypted all the information i had on these properties files. In this simple example, im trying to encrypt database username, password and connection url for iBatis connection, and i use Jasypt library for encryption.

As usual, a simple database,

CREATE DATABASE 'test'
USE 'test'

CREATE TABLE `contoh` (
  `nama` varchar(30) NOT NULL DEFAULT '',
  `alamat` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`nama`)
)

insert into contoh (nama, alamat) values ('edwin', 'singapore');
insert into contoh (nama, alamat) values ('kamplenk', 'ciledug');
insert into contoh (nama, alamat) values ('nugie', 'pamulang');
insert into contoh (nama, alamat) values ('samsu', 'dago');
insert into contoh (nama, alamat) values ('tebek', 'karawaci');

and a POJO

package com.edw.bean;

public class Contoh {
    private String nama;
    private String alamat;

    // other setter and getter

    @Override
    public String toString() {
        return "Contoh{" + "nama=" + nama + ", alamat=" + alamat + '}';
    }
}

A simple xml query, contoh.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="contoh" >

    <resultMap id="result" class="com.edw.bean.Contoh">
        <result property="nama" column="NAMA" columnIndex="1"/>
        <result property="alamat" column="ALAMAT" columnIndex="2"/>
    </resultMap>
   
    <select id="selectAllContoh" resultMap="result">
        select nama, alamat
        from contoh
    </select>

</sqlMap>

and a simple xml to load all my queries, i named it sqlmapconfig.xml. Please take a look at line 21 to 23, these are parameters from properties file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <settings
        useStatementNamespaces="true"
        lazyLoadingEnabled="true"
        enhancementEnabled="true"
        maxSessions="20"
        />

    <transactionManager type="JDBC" commitRequired="false">
        <dataSource type="SIMPLE">

            <property name="SetAutoCommitAllowed" value="false"/>
            <property name="DefaultAutoCommit" value="false"/>

            <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
            <property name="JDBC.ConnectionURL" value="${JDBC.ConnectionURL}"/>
            <property name="JDBC.Username" value="${JDBC.Username}"/>
            <property name="JDBC.Password" value="${JDBC.Password}"/>
   
        </dataSource>
    </transactionManager>

    <sqlMap resource="com/edw/sqlmap/contoh.xml"/>
</sqlMapConfig>

this is my db.properties file, always make sure you had this “ENC( )” on your encrypted values.

JDBC.ConnectionURL=ENC(Q29EXRzvWOsaXiT3YcYjlEN7W4OBU2YulDTnfrHq8LtVL3nyr7ATpQ==)
JDBC.Username=ENC(sM7XAh9750ZUzguilF6kmw==)
JDBC.Password=ENC(GTr5QT97wgVcLNclT8NjClNYKOLeP6c1)

This is my java file, i use it to load db.properties and connecting it to fit parameters on sqlmapconfig.xml.

package com.edw.config;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.Reader;
import java.util.Properties;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.properties.EncryptableProperties;


/**
 *
 * @author edw
 */
public class SqlMapConfig {

    protected static final SqlMapClient sqlMap;

    private static final String PWD = "SDHLKSHUWEHDKSLKLJKSALJDLKA00IUAY98273492JLKASJDLKASJDKLAJSD";
    

    static {
        try {
            StandardPBEStringEncryptor  encryptor = new StandardPBEStringEncryptor();
            encryptor.setAlgorithm("PBEWithMD5AndDES");
            encryptor.setPassword(PWD);
            Properties properties = new EncryptableProperties(encryptor);
            properties.load(new FileInputStream(new File("db.properties")));

            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/sqlmapconfig.xml");
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader,properties);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlMapClient getSqlMap() {
        return sqlMap;
    }
}

this is my Main class,

package com.edw.main;

import com.edw.bean.Contoh;
import com.edw.config.SqlMapConfig;
import java.util.List;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class Main {

    private Logger logger = Logger.getLogger(Main.class);

    public Main() {        
    }

    private void execute(){
        try {
            List<Contoh> contohs = SqlMapConfig.getSqlMap().queryForList("contoh.selectAllContoh");
            for (Contoh contoh : contohs) {
                logger.debug(contoh);
            }            
        } catch (Exception ex) {
            logger.error(ex.getMessage(),ex);
        }

    }

    public static void main(String[] args) {
        Main main = new Main();
        main.execute();
    }

}

this is what happen on my log window when im running this app

run:
2011-02-06 00:10:27,808 [SimpleDataSource] DEBUG com.ibatis.common.jdbc.SimpleDataSource:26 - Created connection 29524641.
2011-02-06 00:10:27,812 [Connection] DEBUG java.sql.Connection:26 - {conn-100000} Connection
2011-02-06 00:10:27,815 [Connection] DEBUG java.sql.Connection:26 - {conn-100000} Preparing Statement:          select nama, alamat         from contoh     
2011-02-06 00:10:27,855 [PreparedStatement] DEBUG java.sql.PreparedStatement:26 - {pstm-100001} Executing Statement:          select nama, alamat         from contoh     
2011-02-06 00:10:27,855 [PreparedStatement] DEBUG java.sql.PreparedStatement:26 - {pstm-100001} Parameters: []
2011-02-06 00:10:27,855 [PreparedStatement] DEBUG java.sql.PreparedStatement:26 - {pstm-100001} Types: []
2011-02-06 00:10:27,857 [ResultSet] DEBUG java.sql.ResultSet:26 - {rset-100002} ResultSet
2011-02-06 00:10:27,873 [ResultSet] DEBUG java.sql.ResultSet:26 - {rset-100002} Header: [NAMA, ALAMAT]
2011-02-06 00:10:27,874 [ResultSet] DEBUG java.sql.ResultSet:26 - {rset-100002} Result: [edwin, singapore]
2011-02-06 00:10:27,874 [ResultSet] DEBUG java.sql.ResultSet:26 - {rset-100002} Result: [kamplenk, ciledug]
2011-02-06 00:10:27,874 [ResultSet] DEBUG java.sql.ResultSet:26 - {rset-100002} Result: [nugie, pamulang]
2011-02-06 00:10:27,874 [ResultSet] DEBUG java.sql.ResultSet:26 - {rset-100002} Result: [samsu, dago]
2011-02-06 00:10:27,875 [ResultSet] DEBUG java.sql.ResultSet:26 - {rset-100002} Result: [tebek, karawaci]
2011-02-06 00:10:27,876 [SimpleDataSource] DEBUG com.ibatis.common.jdbc.SimpleDataSource:26 - Returned connection 29524641 to pool.
2011-02-06 00:10:27,876 [Main] DEBUG com.edw.main.Main:27 - Contoh{nama=edwin, alamat=singapore}
2011-02-06 00:10:27,876 [Main] DEBUG com.edw.main.Main:27 - Contoh{nama=kamplenk, alamat=ciledug}
2011-02-06 00:10:27,876 [Main] DEBUG com.edw.main.Main:27 - Contoh{nama=nugie, alamat=pamulang}
2011-02-06 00:10:27,876 [Main] DEBUG com.edw.main.Main:27 - Contoh{nama=samsu, alamat=dago}
2011-02-06 00:10:27,878 [Main] DEBUG com.edw.main.Main:27 - Contoh{nama=tebek, alamat=karawaci}
BUILD SUCCESSFUL (total time: 0 seconds)

Btw, im using this test class to generate my encrypted values,

package com.edw.test;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author edw
 */
public class TestEncryption {

    private static final String PWD = "SDHLKSHUWEHDKSLKLJKSALJDLKA00IUAY98273492JLKASJDLKASJDKLAJSD";

    public TestEncryption() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Test
    public void test() {

        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setAlgorithm("PBEWithMD5AndDES");
        encryptor.setPassword(PWD);

        System.out.println(encryptor.encrypt("jdbc:mysql://localhost/test"));
        System.out.println(encryptor.encrypt("root"));
        System.out.println(encryptor.encrypt("password"));

    }
}

and this is my NetBeans project structure

Well, i hope it can help others. Cheers (B)

[Tutorial] Upload File atau Image Dengan JSP

Beberapa hari terakhir di forum programmer Kaskus lagi rame pertanyaan tentang caranya upload file pakek JSP. Daripada pusing-pusing mendingan gw pake library bawaan apache, yaitu Apache Commons FileUpload.

Aplikasi sederhana ini terdiri dari 1 buah JSP sebagai presentation layer dan 1 Servlet buat handle uploading file-nya. Konsep-nya sederhana, semua file yang keupload akan disimpan didalam folder /image yang terletak 1 folder dengan file index.jsp.

Oke, langsung kita mulai kalo gitu. Ini file index.jsp gw,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form action="upload" method="POST" enctype="multipart/form-data">
            Select file : <input type="file" name="fileSelect" />
            <br />
            <input type="submit" />
        </form>
    </body>
</html>

dan ini servlet buat handle upload file ataupun image,

package com.baculsoft.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // get your absolute path
        String uploadTo = getServletContext().getRealPath("/") + "image/";

        try {

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            // no multipart form
            if (!isMultipart) {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet UploadServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>No Multipart Files</h1>");
                out.println("</body>");
                out.println("</html>");
            }
            // multipart form
            else {
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

                // parse requests
                List<FileItem> fileItems = upload.parseRequest(request);

                // Process the uploaded items
                for (FileItem fileItem : fileItems) {
                    // a regular form field
                    if (fileItem.isFormField()) {
                        
                    }
                    // upload field
                    else {
                        String fileName = fileItem.getName();
                        File fileTo = new File(uploadTo + fileName);
                        fileItem.write(fileTo);

                        out.println("<html>");
                        out.println("<head>");
                        out.println("<title>Servlet UploadServlet</title>");
                        out.println("</head>");
                        out.println("<body>");
                        out.println("<h1> success write to " + fileTo.getAbsolutePath() + "</h1>");
                        out.println("</body>");
                        out.println("</html>");

                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

abis itu gw register servlet gw di web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
    <servlet>
        <servlet-name>upload</servlet-name>
        <servlet-class>com.baculsoft.servlet.UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>upload</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

ini struktur project gw di Netbeans.

Nah gampang kan 😉

nb.
untuk tutorial lebih lengkapnya bisa dicek disini