[Library]: Adding Library Into Java[TM] Project

February 7, 2010 1 comment

“currently, i develop an application under Java platform, and i need to use a class which i’ve never used before, where can i get the library which contains the class?”

“how to add more library into my Java project [or program]?”

that questions rise when someone realize that his program needs an additional libraries. there are a sequence of problem people used to face on:

  1. what library does my program needs?
  2. i know the library but where can i get it [or download it]?
  3. i have the library but how to add it into my program?

most of people are getting stuck to find out what kind of library does his program requires to run, the easiest way to find it out is by forcing the program to run, then an exception will be thrown and you just need to see what is missing…? for example, see the following exception:

Exception [TOPLINK-4003] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Exception Description: Configuration error.  Class [com.mysql.jdbc.Driver] not found.
 at oracle.toplink.essentials.exceptions.DatabaseException.configurationErrorClassNotFound(DatabaseException.java:101)
 at oracle.toplink.essentials.sessions.DefaultConnector.loadDriver(DefaultConnector.java:183)
 at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:98)
 .....

that’s because of missing class com.mysql.jdbc.Driver, then check this one:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Message
 at javamail.Main.main(Main.java:8)
Caused by: java.lang.ClassNotFoundException: javax.mail.Message
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 .....

it’s caused by the missing of class javax.mail.Message, then “how to know the library [jar file] if i just know the required class?” simply open your browser and go to http://findjar.com/ to seach what jar file contains the class. download it.

now you have the jar, so how to connect the library [jar file] to the program? there are two possibilities, your program written with IDE or NOT at all.

if you use an IDE in develop your program you just need to add it on, in NetBeans IDE for example you just need to do these:

  1. right click on the project then select properties,
  2. go to ‘Libraries’ category,
  3. select ‘Add JAR/Folder’ to find you JAR file.

but if you don’t use any IDE, you have to link the JAR to the ‘Environtment Variables’, i will show how to add it in Windows operating system.

  1. first ensure the JAR file is in your local drive, then right click on the My Computer icon > select Properties
  2. select the Advanced tab > select Environtment Variables
  3. find the ‘Path’ variable and edit it to add your jar directory location
  4. finish. reopen your command prompt [if you use it].

have a good day,…

Categories: java, library, programming

[Database]: storage engine [part1]

February 5, 2010 Leave a comment

“have ever heard ‘storage engine’? what is that?”
“do you know what is MyISAM and InnoDB?”
“and what are the differences between them?”

before having a discussion about MyISAM and InnoDB let we talk about ‘database engine’ [or storage engine]. a storage engine is an underlying software [in Database Management System - DBMS] which takes control in managing how to connect, create, alter and remove database objects [tables, triggers, indexes, and others]. the storage engine also takes care of transaction.

“so what MyISAM is?”
MyISAM is one of popular storage engine, it’s a replacement of ISAM storage engine.
MyISAM developed for MySQL DBMS, MyISAM storage engine will create three type of file for every table creation, FRM file [store the table definition], MYI file [store all indexes for the table] and MYD [MY Data, store the records].

“then what about InnoDB?”
InnoDB is also a storage engine for MySQL, invented by Innobase Oy [Finland], an open source company. InnoDB is dual licensed, GNU GPL and as a proprietary software [owned by Oracle - Innobase Oy was acquired by Oracle in 2005].

these are some differences between InnoDB and MyISAM:

  • InnoDB uses row-level locking while MyISAM uses table-level locking, InnoDBB has a better performance in update action,
  • it store the table definition, indexes and all of the rows in one file, it’s unlike MyISAM,
  • a crashed table may be repaired by tracking the log when MyISAM table needs to be full scaned,
  • in the storage [physical disk], InnoDB places records in order of primary key [index] while MyISAM in order of their added time,
  • InnoDB supports transaction and better table relationship when MyISAM doesn’t support transaction.

there are still many storage engines out there like Memory, Federated, and others…
for further information about MySQL’s storage engine, you can find here: http://dev.mysql.com/doc/refman/5.1/en/storage-engines.html

have a good day…

Categories: databases, mysql

[Exception]: a java mail exception

February 4, 2010 Leave a comment

do you get this exception stack:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Message
 at javamail.Main.main(Main.java:8)
Caused by: java.lang.ClassNotFoundException: javax.mail.Message
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
 at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
 ... 1 more
Java Result: 1

the exception thrown because you miss the Mail API.
You can download it here: http://java.sun.com/products/javamail/downloads/index.html
to fix it up, just add the required Mail API.
[see here to see how to link an external library]

have a good day

Categories: exception, java, programming

[Exception]: a database exception [part 1]

February 4, 2010 Leave a comment

do you get this exception stack:


Exception in thread "main" Local Exception Stack:
Exception [TOPLINK-4003] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Exception Description: Configuration error.  Class [com.mysql.jdbc.Driver] not found.
at oracle.toplink.essentials.exceptions.DatabaseException.configurationErrorClassNotFound(DatabaseException.java:101)
at oracle.toplink.essentials.sessions.DefaultConnector.loadDriver(DefaultConnector.java:183)
at oracle.toplink.essentials.sessions.DefaultConnector.connect(DefaultConnector.java:98)
at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:184)
at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:582)
at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:280)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:229)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:93)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:126)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:120)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:91)
at simplejpa.entities.manager.DBManager.refreshEntityManager(DBManager.java:17)
at simplejpa.entities.manager.DBManager.addNewAccount(DBManager.java:28)
at simplejpa.Main.main(Main.java:13)
Java Result: 1

the exception thrown because you miss the Database Driver, exception above occurs if you forget to link the MySQL Database Driver [sometimes called with MySQL Connector]. for MySQL, you can get the Driver here: http://dev.mysql.com/downloads/connector/j/
to fix it up, just add the required JDBC Driver.
[see here to see how to link an external library]

have a good day

Categories: exception, java, programming

Sending Email using Java[TM] Mail API

February 4, 2010 Leave a comment

“can somebody help me to send email using java?”

a year ago, i had a project which requires mail functionality. the most required function was to send email. then we decided to design a class which exploit Java Mail API to fulfill the requirement.
actually we designed only one class, but for improvement, i break it into two classes, these are the classes and the codes:
MailSender

package javamail;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class MailSender {

 private String SMTPHost;
 private String SMTPPort;
 private String username;
 private String password;

 public MailSender() {
 SMTPHost = "";
 SMTPPort = "";
 username = "";
 password = "";
 }

 public MailSender(String _SMTPHost, String _SMTPPort,
 String _username, String _password) {
 SMTPHost = _SMTPHost;
 SMTPPort = _SMTPPort;
 username = _username;
 password = _password;
 }

 public void setPassword(String _password) {
 password = _password;
 }

 public void setUsername(String _username) {
 username = _username;
 }

 public String getSMTPHost() {
 return SMTPHost;
 }

 public void setSMTPHost(String _SMTPHost) {
 SMTPHost = _SMTPHost;
 }

 public String getSMTPPort() {
 return SMTPPort;
 }

 public void setSMTPPort(String _SMTPPort) {
 SMTPPort = _SMTPPort;
 }

 public void sendMail(List<String> _to, List<String> _toCC,
 List<String> _toBCC, String _subject, String _content)
 throws Exception {
 if (IMAPAuthenticator.getIMAPAuthentication(SMTPHost, username, password)) {
 Properties props = System.getProperties();

 props.put("mail.smtp.host", SMTPHost);
 props.put("mail.debug", "true");
 props.put("mail.smtp.port", "25");
 props.put("mail.smtp.localhost", SMTPPort);
 props.put("mail.smtp.auth", "false");

 Session session = Session.getInstance(props);
 Message message = new MimeMessage(session);

 try {
 message.setFrom(new InternetAddress(username +
 "@" + SMTPHost));

 for (int counter = 0; counter < _to.size(); ++counter) {
 message.setRecipient(Message.RecipientType.TO, new InternetAddress(_to.get(counter)));
 }

 if (_toCC != null) {
 for (int counterCC = 0; counterCC < _toCC.size(); ++counterCC) {
 message.setRecipient(Message.RecipientType.CC, new InternetAddress(_toCC.get(counterCC)));
 }
 }

 if (_toBCC != null) {
 for (int counterBCC = 0; counterBCC < _toBCC.size(); ++counterBCC) {
 message.setRecipient(Message.RecipientType.BCC, new InternetAddress(_toBCC.get(counterBCC)));
 }
 }

 message.setSubject(_subject);
 message.setText(_content);
 message.setSentDate(new Date());

 Transport.send(message);

 } catch (Exception e) {
 e.printStackTrace();
 throw e;
 }
 } else {
 throw new AuthenticationFailedException("invalid user");
 }
 }
}

IMAPAuthenticator

package javamail;

import com.sun.mail.imap.IMAPStore;
import java.util.Properties;
import javax.mail.Session;

public class IMAPAuthenticator {

 public static boolean getIMAPAuthentication(String _IMAPHost,
 String _username, String _password) throws Exception {
 boolean isAuthenticated = false;

 try {
 Properties properties = System.getProperties();
 Session session = Session.getDefaultInstance(properties);
 IMAPStore store = (IMAPStore) session.getStore("imap");

 store.connect(_IMAPHost, _username, _password);
 store.close();
 isAuthenticated = true;

 } catch (Exception ex) {
 ex.printStackTrace();
 isAuthenticated = false;
 }

 return isAuthenticated;
 }
}

to test it, write this code in your Main class then run it.

package javamail;

import java.util.ArrayList;

public class Main {

 public static void main(String[] args) throws Exception {
 MailSender ms = new MailSender();
 ms.setUsername("myusername");
 ms.setPassword("myPASSwORD");
 ms.setSMTPHost("mail.myhosting.ac.id");
 ms.setSMTPPort("25");

 ArrayList<String> to = new ArrayList();
 ArrayList<String> toCC = new ArrayList();
 String subject = "[JavaMail]: subject";
 String content = "[JavaMail]: content";
 to.add("mr@mail.hishost.com");
 toCC.add("ms@herhost.co.id");
 toCC.add("bthr@mail.somewhere.net");

 ms.sendMail(to, toCC, toCC, subject, content);
 }
}

check your inbox and have a good day…

Categories: java, programming

serialize [object] and deserialize in Java[TM]

February 3, 2010 Leave a comment

“can i store my object into file?”
“how to transmit an object over the network”

in java programming, you can write or transmit your object over the network, how come? java provides an object serialization which ‘converts’ an object into a streaming bits, then you can do many things with the stream.
“could you give me some example?”, okay, in this session i will show you how to serialize objects and deserialize it back.
this are term people used to know:
object -> serialize / deflate / marshalling -> streaming bits
streaming bits -> deserialize / inflate / unmarshalling – > objects
one thing you have to remember is when you want to make a serializable class, make sure that you ‘flag’ it by implements java.io.Serializable interface.
the scenario of the sample is like this:
there are three classes:
SerializableObject: the class which object will be serialized
ObjectDeflater: object to streaming bit ‘converter’
ObjectInflater: streaming bit to object ‘converter’

this is very simple, just create a new project [i use JDK 1.6 update 10 and NetBeans 6.5 IDE] then create the three required classes. after that, write down these codes:

code for SerializableObject:

package javaserialization;
import java.io.Serializable;

public class SerializableObject implements Serializable {

 private final int DEFAULT_ID = 0;
 private final String DEFAULT_NAME = "DEFAULT_NAME";
 private final String DEFAULT_MESSAGE = "DEFAULT_MESSAGE";
 private int objectId;
 private String objectName;
 private String objectMessage;

 public SerializableObject() {
 objectId = DEFAULT_ID;
 objectName = DEFAULT_NAME;
 objectMessage = DEFAULT_MESSAGE;
 }

 public SerializableObject(
 int _objectId,
 String _objectName,
 String _objectMessage) {
 objectId = _objectId;
 objectName = _objectName;
 objectMessage = _objectMessage;
 }

 public int getObjectId() {
 return objectId;
 }

 public void setObjectId(int objectId) {
 this.objectId = objectId;
 }

 public String getObjectMessage() {
 return objectMessage;
 }

 public void setObjectMessage(String objectMessage) {
 this.objectMessage = objectMessage;
 }

 public String getObjectName() {
 return objectName;
 }

 public void setObjectName(String objectName) {
 this.objectName = objectName;
 }

 public void printInfo() {
 System.out.println(
 objectId + "\n" +
 objectName + "\n" +
 objectMessage + "\n");
 }
}

code for ObjectDeflater:

package javaserialization;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectDeflater {

 private String filePath;
 private File file;
 private FileOutputStream fos;
 private ObjectOutputStream oos;

 public ObjectDeflater(String _filePath) {
 filePath = _filePath;
 }

 private void allocate() throws IOException {
 file = new File(filePath);
 fos = new FileOutputStream(file);
 oos = new ObjectOutputStream(fos);
 }

 private void dealocate() {
 try {
 oos.close();
 } catch (IOException ioe) {
 ioe.printStackTrace();
 }
 }

 public void deflateObject(int _numberOfObject) throws IOException {
 allocate();

 SerializableObject so = null;
 for (int objCounter = 0; objCounter < _numberOfObject; ++objCounter) {
 so = new SerializableObject(objCounter, "my name is: " + objCounter, "my message is: " + objCounter);
 oos.writeObject(so);
 }

 dealocate();
 }
}

code for ObjectInflater:

package javaserialization;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInflater {

 private String filePath;
 private File file;
 private FileInputStream fis;
 private ObjectInputStream ois;

 public ObjectInflater(String _filePath) {
 filePath = _filePath;
 }

 private void allocate() throws IOException {
 file = new File(filePath);
 fis = new FileInputStream(file);
 ois = new ObjectInputStream(fis);
 }

 private void dealocate() {
 try {
 ois.close();
 } catch (IOException ioe) {
 ioe.printStackTrace();
 }
 }

 public void inflateObject() throws IOException, ClassNotFoundException {
 allocate();

 SerializableObject so = null;
 try {
 while ((so = (SerializableObject) ois.readObject()) != null) {
 so.printInfo();
 }
 } catch (EOFException eofe) {
 // reaches end of file
 // no action required
 // leave it blank
 }

 dealocate();
 }
}

to test the project, write this code in the Main class:

package javaserialization;

public class Main {

 public static void main(String[] args) {
 // your file path, it must be exists
 String filePath = "D:\\tutorials\\JavaSerialization\\objectschest.txt";
 ObjectDeflater od = null;
 ObjectInflater oi = null;

 try {
 od = new ObjectDeflater(filePath);
 od.deflateObject(5);
 } catch (Exception ex) {
 ex.printStackTrace();
 }

 try {
 oi = new ObjectInflater(filePath);
 oi.inflateObject();
 } catch (Exception ex) {
 ex.printStackTrace();
 }
 }
}

run the project then discover what is happening…
have a good day,

Categories: java, programming

Using Java Persistence API [JPA] – Sample [2]

February 3, 2010 Leave a comment

well, in this section you will try to update and remove a record in a database through Java Persistence API.

hum,… this part is a continued part of the provious section actually, so you need to do the previous [about record insertion] before continuing to this one.

updating and removing record by using JPA is so easy. in this session you just need to modify two classes that we have made before [in the previous part].

  1. first is modifying DBManager class by adding four more methods, the class will be like this:
    package simplejpa.entities.manager;
    import javax.persistence.Query;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import simplejpa.entities.Account;
    
    public class DBManager {
    
     private EntityManager em;
     private EntityManagerFactory emf;
    
     private EntityManager refreshEntityManager() {
     emf = Persistence.createEntityManagerFactory("SimpleJPAPU");
     if (em == null) {
     em = emf.createEntityManager();
     }
    
     return em;
     }
    
     public void addNewAccount(
     String _accountName,
     String _accountEmail,
     String _accountPhone,
     String _accountAddress) {
     refreshEntityManager();
     try {
     em.getTransaction().begin();
     Account account = new Account();
     account.setAccountName(_accountName);
     account.setAccountEmail(_accountEmail);
     account.setAccountPhone(_accountPhone);
     account.setAccountAddress(_accountAddress);
    
     em.persist(account);
     em.getTransaction().commit();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     }
    
     public Account getAccountWithID(Long _accountId) {
     refreshEntityManager();
     Account account = null;
     Query query = em.createQuery("SELECT A FROM Account A WHERE A.accountId=:ACCOUNTID");
     query.setParameter("ACCOUNTID", _accountId);
    
     try {
     account = (Account) query.getSingleResult();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
    
     return (account);
     }
    
     public Account getAccountWithName(String _accountName) {
     refreshEntityManager();
     Account account = null;
     Query query = em.createQuery("SELECT A FROM Account A WHERE A.accountName=:ACCOUNTNAME");
     query.setParameter("ACCOUNTNAME", _accountName);
    
     try {
     account = (Account) query.getSingleResult();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
    
     return (account);
     }
    
     public void updateAccountWithID(
     Long _accountId,
     String _newAccountName,
     String _newAccountEmail,
     String _newAccountPhone,
     String _newAccountAddress) {
     refreshEntityManager();
     try {
     em.getTransaction().begin();
     Account account = getAccountWithID(_accountId);
     account.setAccountName(_newAccountName);
     account.setAccountEmail(_newAccountEmail);
     account.setAccountPhone(_newAccountPhone);
     account.setAccountAddress(_newAccountAddress);
    
     em.merge(account);
     em.getTransaction().commit();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     }
    
     public void removeAccountWithID(
     Long _accountId) {
     refreshEntityManager();
     try {
     em.getTransaction().begin();
     Account account = getAccountWithID(_accountId);
    
     em.remove(account);
     em.getTransaction().commit();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     }
    }
    
  2. the next is to modifying Main class, just like this:
    package simplejpa;
    import simplejpa.entities.Account;
    import simplejpa.entities.manager.DBManager;
    
    public class Main {
    
     public static void main(String[] args) {
     // instantiate DBManager
     DBManager dbm = new DBManager();
    
     // try to add some new accounts
     dbm.addNewAccount("mario", "mariosimaremare@yahoo.co.id", "0123456789", "Sitoluama");
     dbm.addNewAccount("mario elyezer", "mariosimaremare@gmail.com", "081081081081", "Laguboti");
     dbm.addNewAccount("mario simaremare", "mariosimaremare@hotmail.com", "085208520852", "North Sumatera");
    
     // retrieve some registered accounts
     Account mario = dbm.getAccountWithName("mario");
     Account marioelyezer = dbm.getAccountWithName("mario elyezer");
    
     // try to remove account
     dbm.removeAccountWithID(mario.getAccountId());
     // try to update account
     dbm.updateAccountWithID(marioelyezer.getAccountId(), "mario elyezer subekti", "me@mycampus.com", "065506550655", "campus");
     }
    }
    
  3. ok, finish! you can run it to see what will happens…

have a good day,

Categories: java, programming
Follow

Get every new post delivered to your Inbox.