Java

java

How to Send Emails With Java Using Gmail Accounts

It’s actually quite simple on how to send emails using java, only need several lines of codes. This is how i do it


import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;

public class MailTestSend {

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

    public static void main(String[] args) {
        try {

            // setup the mail server properties
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");

            // set up the message
            Session session = Session.getInstance(props);

            Message message = new MimeMessage(session);

            // add a TO address
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xxxxx@gmail.com"));

            // add a multiple CC addresses
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("yyyyy@gmail.com,zzzzzz@yahoo.com"));
            
            message.setSubject("Welcome to Java");
            message.setContent("Hi, im testing a new way to send emails via java.", "text/plain");

            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.gmail.com", 587, "yourgmailusername", "yourgmailpassword");
            transport.sendMessage(message, message.getAllRecipients());
            logger.error("successfully send email");
        } catch (Exception e) {            
            logger.error(e, e);
        }
    }
}

Please dont forget to include mail.jar into your project. This is the screenshot of my netbeans libraries and my email inbox.

:-[

LDAP Programming with Java

Today im trying to share on how to do a simple LDAP queries such as select, insert, edit and delete using java. Im using Apache Directory Server as LDAP server and JXplorer as LDAP explorer.

Enough chit-chat, here is my code.
First is a simple java bean,

package com.edw.bean;

/**
 *  com.edw.bean.Person
 *
 *  @author edw
 */
public class Person {
    
    private String name;
    private String address;    
    private String password;

	// other setter and getter
}

and here is my LDAP class controller

package com.edw.ldap.main;

import com.edw.bean.Person;
import java.security.MessageDigest;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;

/**
 *  com.edw.ldap.main.LDAPMain
 *
 *  @author edw
 */
public class LDAPMain {

    private Logger logger = Logger.getLogger(LDAPMain.class);
    private Hashtable<String, String> env = new Hashtable<String, String>();

    public LDAPMain() {
        try {
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
            env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
            env.put(Context.SECURITY_CREDENTIALS, "xxx");
        } catch (Exception e) {
            logger.error(e, e);
        }

    }

    private boolean insert(Person person) {
        try {

            DirContext dctx = new InitialDirContext(env);
            Attributes matchAttrs = new BasicAttributes(true);
            matchAttrs.put(new BasicAttribute("uid", person.getName()));
            matchAttrs.put(new BasicAttribute("cn", person.getName()));
            matchAttrs.put(new BasicAttribute("street", person.getAddress()));
            matchAttrs.put(new BasicAttribute("sn", person.getName()));
            matchAttrs.put(new BasicAttribute("userpassword", encryptLdapPassword("SHA", person.getPassword())));
            matchAttrs.put(new BasicAttribute("objectclass", "top"));
            matchAttrs.put(new BasicAttribute("objectclass", "person"));
            matchAttrs.put(new BasicAttribute("objectclass", "organizationalPerson"));
            matchAttrs.put(new BasicAttribute("objectclass", "inetorgperson"));
            String name = "uid=" + person.getName() + ",ou=users,ou=system";
            InitialDirContext iniDirContext = (InitialDirContext) dctx;
            iniDirContext.bind(name, dctx, matchAttrs);

            logger.debug("success inserting "+person.getName());
            return true;
        } catch (Exception e) {
            logger.error(e, e);
            return false;
        }
    }

    private boolean edit(Person person) {
        try {

            DirContext ctx = new InitialDirContext(env);
            ModificationItem[] mods = new ModificationItem[2];
            Attribute mod0 = new BasicAttribute("street", person.getAddress());
            Attribute mod1 = new BasicAttribute("userpassword", encryptLdapPassword("SHA", person.getPassword()));
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod1);

            ctx.modifyAttributes("uid=" + person.getName() + ",ou=users,ou=system", mods);

            logger.debug("success editing "+person.getName());
            return true;
        } catch (Exception e) {
            logger.error(e, e);
            return false;
        }
    }

    private boolean delete(Person person) {
        try {

            DirContext ctx = new InitialDirContext(env);
            ctx.destroySubcontext("uid=" + person.getName() + ",ou=users,ou=system");

            logger.debug("success deleting "+person.getName());
            return true;
        } catch (Exception e) {
            logger.error(e, e);
            return false;
        }
    }
    
    private boolean search(Person person) {
        try {

            DirContext ctx = new InitialDirContext(env);
            String base = "ou=users,ou=system";

            SearchControls sc = new SearchControls();
            sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

            String filter = "(&(objectclass=person)(uid="+person.getName()+"))";

            NamingEnumeration results = ctx.search(base, filter, sc);


            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                Attributes attrs = sr.getAttributes();

                Attribute attr = attrs.get("uid");
                if(attr != null)
                    logger.debug("record found "+attr.get());
            }
            ctx.close();
                        
            return true;
        } catch (Exception e) {
            logger.error(e, e);
            return false;
        }
    }

    private String encryptLdapPassword(String algorithm, String _password) {
        String sEncrypted = _password;
        if ((_password != null) && (_password.length() > 0)) {
            boolean bMD5 = algorithm.equalsIgnoreCase("MD5");
            boolean bSHA = algorithm.equalsIgnoreCase("SHA")
                    || algorithm.equalsIgnoreCase("SHA1")
                    || algorithm.equalsIgnoreCase("SHA-1");
            if (bSHA || bMD5) {
                String sAlgorithm = "MD5";
                if (bSHA) {
                    sAlgorithm = "SHA";
                }
                try {
                    MessageDigest md = MessageDigest.getInstance(sAlgorithm);
                    md.update(_password.getBytes("UTF-8"));
                    sEncrypted = "{" + sAlgorithm + "}" + (new BASE64Encoder()).encode(md.digest());
                } catch (Exception e) {
                    sEncrypted = null;
                    logger.error(e, e);
                }
            }
        }
        return sEncrypted;
    }

    public static void main(String[] args) {
        LDAPMain main = new LDAPMain();

        Person person = new Person();
        person.setAddress("kebayoran");
        person.setName("kamplenk");
        person.setPassword("pepe");

        // insert
        main.insert(person);
        
        // edit
        main.edit(person);
        
        // select
        main.search(person);
        
        // delete
        main.delete(person);
    }
}

Here is screenshot of my LDAP explorer, after i’ve insert my latest ldap record.

hope it can help others, have fun with LDAP 😉

A Simple JSon Requestor using Java

In my latest project, i found the needed to simulate a json request from my local computer. After do some research, i created a simple java class to simulate json request to my servlet. Im using GSon to format my java class to json string, and Apache HttpComponents.

Im trying to do json request to my servlet, to do an invoice payment. First, as always, is an Incoice javabean.

package com.edw.bean;

/**
 *  com.edw.bean.Invoice
 *
 *  @author edw
 *
 */
public class Invoice {
    private String username;
    private String po_number;
    private int bill;

    // other setter and getter
}

and this is my main java class, it will do a simple Request to my servlet

package com.edw.json;

import com.edw.bean.Invoice;
import com.google.gson.Gson;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 *  com.edw.json.JSonRequestor
 *
 *  @author edw
 *
 */
public class JSonRequestor {

    public JSonRequestor() {
    }

    private void doRequest() {
        URL serverURL = null;
        try {
            
            Invoice invoice = new Invoice();
            invoice.setBill(2000);
            invoice.setPo_number("2000");
            invoice.setUsername("edw");
            
            Gson g = new Gson();
            String json = g.toJson(invoice);
            
            System.out.println(json);

            HttpClient httpclient = new DefaultHttpClient();
            
            HttpPost httppost = new HttpPost("http://localhost:18000/EPay/CreateInvoice");
            StringEntity stringEntity = new StringEntity(json);
            stringEntity.setContentType("application/json");
            httppost.setEntity(stringEntity);
            
            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }
            EntityUtils.consume(resEntity);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        JSonRequestor jSonRequestor = new JSonRequestor();
        jSonRequestor.doRequest();
    }
}

and this is how my request will looks like

this is libraries that i used

I hope it would help others,
have fun and dont forget to visit Indonesia 🙂

Create a Pascal Triangle using Java

On my last job interview, i was asked to create a very simple Pascal Triangle using java. What is a Pascal Triangle (indonesian people called it “Segitiga Pascal”) ?? According to Wikipedia, it is a triangular array of the binomial coefficients in a triangle. Okay this is how i do it.

package com.edw.test;

/**
 *  com.edw.test.PascalTriangle
 *
 *  @author edw
 */
public class PascalTriangle {

    public static void main(String[] args) {
        // initiate
        int numberOfRows = 8;
        int[][] pascal = new int[numberOfRows][numberOfRows];
         
        // fill my triangle
        for (int i = 0; i &lt; numberOfRows; i++) {
            pascal[i][0] = 1;                        
            for (int j = 1; j &lt;= i; j++) {
                pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
            }
        }

        // print it
        for (int i = 0; i &lt; numberOfRows; i++) {
            for (int j = 0; j &lt;= i; j++) {
                System.out.print(pascal[i][j] + &quot; &quot;);
            }
            System.out.println();
        }
    }
}

this is the result on my Netbeans’ console

hope it can help others
cheers :-[

How to Create A Java Class Performance Test Using JMeters AbstractJavaSamplerClient

JMeter is a very powerfull tools to do performance testing. In this tutorial, im going to simulate a heavy load on a java object to test its strength and performance testing. My java class is very simple, only an ordinary java class to do inserts into mysql database using Hibernate framework.

first is a sample database and a table

CREATE DATABASE test;
USE test;
CREATE
    TABLE student
    (
        id INT NOT NULL AUTO_INCREMENT,
        studentname VARCHAR(60) NOT NULL,
        PRIMARY KEY (id)
    );

a java class and xml as representation for database’s table

package com.edw.bean;

public class Student implements java.io.Serializable {

    private Integer id;
    private String studentname;

    public Student() {
    }

    public Student(String studentname) {
       this.studentname = studentname;
    }
	
	// 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.Student" table="student" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="studentname" type="string">
            <column name="studentname" length="60" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

this is my Hibernate main configuration xml

<?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">xxxxxx</property>
    <property name="hibernate.connection.autocommit">true</property>
    <mapping resource="com/edw/bean/Student.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

and my java class to load Hibernate’s configuration

package com.edw.hbm;

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

/**
 * @author edw
 */
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;
    }
}

This is my tested java class, it has to extends AbstractJavaSamplerClient so the jmeter application can test it

package com.edw.test;

import com.edw.bean.Student;
import com.edw.hbm.HibernateUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *  com.edw.test.StudentStressTest
 *
 *  @author edw
 */
public class StudentStressTest extends AbstractJavaSamplerClient {

    private Map<String, String> mapParams = new HashMap<String, String>();
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public StudentStressTest() {
        super();
    }

    @Override
    public void setupTest(JavaSamplerContext context) {
        for (Iterator<String> it = context.getParameterNamesIterator(); it.hasNext();) {
            String paramName =  it.next();
            mapParams.put(paramName, context.getParameter(paramName));
        }
    }

    public SampleResult runTest(JavaSamplerContext context) {
        SampleResult result = new SampleResult();

        try {

            JMeterVariables vars = JMeterContextService.getContext().getVariables();
            vars.put("demo", "demoVariableContent");

            result.sampleStart();

            Student student = new Student();
            student.setStudentname(mapParams.get("name")+" "+new Date().getTime());
            Session session = sessionFactory.openSession();
            session.save(student);
            session.flush();
            session.close();

            result.sampleEnd();

            
            result.setSuccessful(true);
            result.setSampleLabel("SUCCESS: " + student.getStudentname());

        } catch (Throwable e) {
            result.sampleEnd();
            result.setSampleLabel("FAILED: '" + e.getMessage() + "' || " + e.toString());
            result.setSuccessful(false);

            e.printStackTrace();
            System.out.println("\n\n\n");
        }

        return result;
    }

    @Override
    public Arguments getDefaultParameters() {

        Arguments params = new Arguments();

        params.addArgument("name", "edw");

        return params;
    }
}

Next is build your project into jar and put it into jmeter’s path ( \lib\ext ), dont forget to copy your application library such as hibernate3.jar.
If you open your JMeter ui, you can see your java class on Add > Sampler > Java Request. You can see the results sumamry on tab summary report.

This is my Netbeans project structure, and my jmeter configuration.

Have fun working with JMeter 🙂