Java

java

How to Set %JAVA_HOME% Variable on Apache Tomcat’s Catalina Script

Usually im using Apache Tomcat’s catalina script to launch and start Apache Tomcat, but sometimes the script wont run because of not having JAVA_HOME variables on your OS environment variables or you cant add new environment variables due to lack of privileges.

So instead of adding JAVA_HOME variable into my OS, i set the JAVA_HOME on my catalina scripts. This is how i do it, i add this script on the top of catalina.bat file.

set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.7.0_07

Note, there is no space before and after “=” sign.

Easy isnt it 😉

Integrating BCrypt Hashing With Hibernate Framework

In this example, im trying to simulate a simple login to MySQL database. Usually i hash password value using MD5, but now im trying to do hashing using BCrypt Algorithm. Im using a simple java BCrypt class downloaded from here.

First as always, a simple table and row.

CREATE TABLE `users` (
  `username` varchar(20) NOT NULL DEFAULT '',
  `pwd` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`username`)
)

insert into `users`(`username`,`pwd`) values ('edwin','$2a$12$bUwElzXYO116G6x.fLm5FOAJNB46R0974sAh2TQumJei4ia.x0YPy');

Next is creating a simple java class and xml to represent database tables.

package com.edw.bean;

public class Users  implements java.io.Serializable {

     private String username;
     private String pwd;

    public Users() {
    }

	// other setter and getter
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.edw.bean.Users" table="users" catalog="test">
        <id name="username" type="string">
            <column name="username" length="20" />
            <generator class="assigned" />
        </id>
        <property name="pwd" type="string">
            <column name="pwd" length="80" />
        </property>
    </class>
</hibernate-mapping>

Next is my hibernate.cfg.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">****</property>
    <mapping resource="com/edw/bean/Users.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

And my java class to load hibernate.cfg.xml

package com.edw.util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {           
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {            
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

And this is my Main java class,

package com.edw.main;

import com.edw.bean.Users;
import com.edw.util.BCrypt;
import com.edw.util.HibernateUtil;
import org.apache.log4j.Logger;
import org.hibernate.Session;

public class Main {
    
    private static Logger logger = Logger.getLogger(Main.class );
    
    private Boolean startApp(String username, String password) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            Users user = (Users)session.createQuery("from Users where username = :username")
                    .setString("username", username)
                    .uniqueResult();      
            // compare password with database's encrypted password
            if(BCrypt.checkpw(password, user.getPwd()))
                return true;
            return false;
        } catch (Exception e) {
            logger.error(e,e);
        } finally {            
            session.close();
        }
        return false;
    }
    
    private String hashPassword(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt(12));
    }
    
    public static void main(String[] args) {
        Main main = new Main();
        boolean success = main.startApp("edwin", "12345");
        if(success)
            logger.debug("Password is Right");
        else
            logger.debug("Password is Wrong");
        
        // simulate 10 hashed string password
        for (int i = 0; i < 10; i++) {
            logger.debug(main.hashPassword("12345"));
        }        
    }
}

This is my Netbeans project structure,

And this is my Netbean’s console

Random String Generator Using Java

This is a simple method to create a random string result, the first method is create string between A-Z and 0-9 while the second one only provide hexadecimal characters.

package com.edw.main;

import java.util.UUID;
import org.apache.commons.lang.RandomStringUtils;

public class Main {
    public static void main(String[] args) {
        // one
        System.out.println(RandomStringUtils.randomAlphanumeric(32).toUpperCase());
        
        // two
        System.out.println(UUID.randomUUID().toString().replace("-", "").toUpperCase());
    }
}

This is the screenshot of my Netbeans Project.

and this is the result,

Hope it helped others, good luck.

How to Fix WebSphere’s Failed to Start Service

Today im trying to start my IBM WebSphere from Windows Service, but it keeps showing error. And i cant even starting WebSphere from Command Prompt. This is the error on my WebSphere error log file.

[18/10/12 18:59:12:760 ICT] 00000000 WindowsServic 3   Timed out waiting for service to respond to command, after 60 seconds. Failed to start service, or timed out while waiting for start to complete. Check the logs for details.
[18/10/12 18:59:12:760 ICT] 00000000 AdminTool     A   ADMU7704E: Failed while trying to start the Windows Service associated with server: server1; 
probable error executing WASService.exe: Starting Service: XNode01
Timed out waiting for service to respond to command, after 60 seconds. Failed to start service, or timed out while waiting for start to complete. Check the logs for details.

How to fix it is actually not too hard, i just delete server1.pid which located under my WebSphere logs folder and start my WebSphere again. Somehow WebSphere wont start if server1.pid exists.

This is the location for my logs folder

C:\Program Files\IBM\WebSphere\AppServer\profiles\AppSrv01\logs\server1

Have fun (F)