Programming

basic programming

How to Inserting 0 To an AutoIncreament Field on MySql

Let say i have this table,

CREATE TABLE `refproductscale` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `scale` varchar(255) NOT NULL,
  `del` set('y','n') NOT NULL DEFAULT 'n',
  PRIMARY KEY (`id`)
)

I dont know why, but everytime im inserting ‘zero’ as its id, suddenly it changes into an increament number.
But with this script, im able to insert ‘zero’ as its id. This is my script,

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
insert into refproductscale values(0, 'none', 'n');

And this is the result,

All i have to do is use NO_AUTO_VALUE_ON_ZERO before i do insert query. 😉

How to Setup HTTPS Connection for NginX

I just bought a new SSL Certificate from an SSL providers, and now im trying to install it on my nginx webserver. Now im trying to share the steps needed to install my ssl certificate, in case someone need it.

But first, i need to generate a .key and .csr file using openssl’s command, i will need those files to become a “secret key” or my private key.

sudo openssl req -new -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr

Next is i send my .csr file to SSL providers to generate .crt files. In my case, the SSL Provider, gives me 2 .crt files. First is the “Intermediate Certificate” (my_intermediate_ca.crt) and another one is “SSL Certificate” files (domain.crt).

First, i need to join those 2 crt files,

cat domain.crt my_intermediate_ca.crt >> bundle.crt

It will look like this,

-----BEGIN CERTIFICATE-----
..... my domain.crt .......
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
..... my intermediate.crt .......
-----END CERTIFICATE-----

Next is registering my SSL on nginx, i just edit the ssl.conf here

sudo vi /etc/nginx/conf.d/ssl.conf

and add this lines

server {
    listen       443 default ssl;
    server_name  mydomain;

    server_tokens off;

    ssl_certificate      /crtlocation/bundle.crt;
    ssl_certificate_key  /crtlocation/domain.key;

    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout  5m;

    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers   on;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
	}
}

Restart nginx and check your ssl using openssl command,

openssl s_client -debug -connect localhost:443

A good SSL configuration will give this result,

Verify return code: 0 (ok)

While bad ones will create result like this,

Hope it would help others, have fun 😀

ps.
i had one weird condition on my previous ssl installation, somehow my website shows valid ssl on desktop browsers, but shows broken ssl when accessed from mobile devices and android browsers. I found out it’s due to i provide the wrong .crt file on nginx’s ssl.conf, i provide domain.crt instead of bundle.crt. 🙁

How to Log Log4J’s Message Logs Into Database

Today im going to do a simple log4j logging into mysql database, the only reason i want to log into database instead of into file is so that i could query the logs i have.

This is my java class that i use to do my testcase,

package com.edw.main;

import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class Main {

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

    private void doSomething() {
        logger.debug("im doing something");
        logger.error("im doing something - error -");
    }

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

and my simple table, to store all my log messages

CREATE TABLE `logs` (
  `thread_id` varchar(20) NOT NULL,
  `tanggal` datetime NOT NULL,
  `kelas` varchar(50) NOT NULL,
  `level` varchar(10) NOT NULL,
  `pesan` varchar(1000) NOT NULL,
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

This is my log4j.properties,

# Define the root logger with appender file
log4j.rootLogger = DEBUG, DB

# Define the DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender

# Set JDBC URL
log4j.appender.DB.URL=jdbc:mysql://localhost/test

# Set Database Driver
log4j.appender.DB.driver=com.mysql.jdbc.Driver

# Set database user name and password
log4j.appender.DB.user=root
log4j.appender.DB.password=password

# Set the SQL statement to be executed.
log4j.appender.DB.sql=INSERT INTO LOGS VALUES('%x',now(),'%C:%L','%p','%m', null)

# Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout

And this is what the contents of my database

This is my Netbeans; Project structure, as you can see, i only need 2 jars, mysql driver and log4j jar.

How to Log X-Forwarded-For HTTP Header on Glassfish Application Server

Yesterday i was talking with my friend, on how Glassfish Application Server able to log the http request’s original user ip. Because my Glassfish is behind Apache ModProxy, so what is logging om my Glassfish’s access log file is my proxy’s ip address.

My apache modproxy ip is 192.168.56.102, while my original ip is 192.168.56.101. So im planning to see “192.168.56.101” on my Glassfish access log instead of “192.168.56.102” which is my proxy’s ip.

This is my Access Logging screenshot,

But before you do that, please make sure, you checked the Access Logging checkbox

And this is the result of my Glassfish’s Access Log File, which is located at, <glassfish installation folder>/glassfish/domains/domain1/logs/access

"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:11 +0700" "GET // HTTP/1.1" 200 563
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:12 +0700" "GET // HTTP/1.1" 200 563
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:12 +0700" "GET // HTTP/1.1" 200 563
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:13 +0700" "GET // HTTP/1.1" 200 563
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:13 +0700" "GET // HTTP/1.1" 200 563
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:13 +0700" "GET // HTTP/1.1" 200 563
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:13 +0700" "GET // HTTP/1.1" 200 563
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:40:13 +0700" "GET // HTTP/1.1" 200 563

As you can see, what is written on my access log is my proxy ip address instead of my original address.

After spending some time researching, i found out that Apache ModProxy have an “X-Forwarded-For” http header which contain the original user’s ip address. So this is my new Access Logging Format, you can see me logging “X-Forwarded-For” header on the end of my new logging format.

%client.name% %auth-user-name% %datetime% %request% %status% %response.length% %header.X-Forwarded-For%

And this is my lates access log file, you can see my original ip at the end of every access log.

"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:51:56 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:51:56 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:51:56 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:51:56 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:51:56 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:51:57 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:51:57 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"
"192.168.56.102" "NULL-AUTH-USER" "20/Oct/2013:15:52:05 +0700" "GET // HTTP/1.1" 200 563 "192.168.56.101"

Hope it’d help others, have fun 😉

A Simple AES Encryption – Decryption Using Java

Several days ago, my friend asked me how to create a simple AES encryption – decryption using java. Well, here is your answer, hope it will helped you.

package com.edw.testing;

import java.security.AlgorithmParameters;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;

public class TestingAES {

    public TestingAES() {
    }

    private void execute() throws Exception {
        
        String password = "mypassword";
        String salt = "salt";
        String cipherText = "Hello, World!";
        
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        // encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] ciphertext = cipher.doFinal(cipherText.getBytes("UTF-8"));
        
        System.out.println("password : "+password);
        System.out.println("salt : "+salt);
        System.out.println("cipherText : "+cipherText);
        System.out.println("iv : "+new BASE64Encoder().encode(iv));
        System.out.println("ciphertext : "+new BASE64Encoder().encode(ciphertext));
        
        // decrypt
        Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipherDecrypt.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
        String plaintext = new String(cipherDecrypt.doFinal(ciphertext), "UTF-8");
        System.out.println("decrypted text : "+plaintext);
        
    }

    public static void main(String[] args) throws Exception {
        TestingAES testingAES = new TestingAES();
        testingAES.execute();
    }
}

And this is what is written on my netbeans console,

Oh and if you ever found this kind of error

Caused by: java.security.InvalidKeyException: Illegal key size or default parameters

it means that you need to install Java Cryptography Extension (JCE). You will find it here,

http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

Have fun 😀