Monday, December 14, 2009

Graphical + Attachment java Email Client

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailClient {

private static final String SMTP_HOST_NAME = "";
private static final String SMTP_AUTH_USER =;
private static final String SMTP_AUTH_PWD = "xxx";

public static void main(String[] args) throws Exception {

new SimpleMailWithAttachment().test();


public void test() throws Exception {
Properties props = new Properties();

props.put("mail.transport.protocol", "smtp");
props.put("", SMTP_HOST_NAME);

Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing javamail with attachment");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent("<h1>Check attachment</h1>", "text/html");
MimeBodyPart attachFilePart = new MimeBodyPart();

FileDataSource fds =
new FileDataSource("d:\\");

attachFilePart.setDataHandler(new DataHandler(fds));
Multipart mp = new MimeMultipart();
new InternetAddress(""));
transport.connect(SMTP_HOST_NAME, SMTP_AUTH_USER,

Friday, December 11, 2009

Disable enter key using java script

Use the below code to disable enter key. You can also used this to disable un wanted keys,too. Just add more combination of keys after "evt.keyCode == 13".
<script language=javascript type=text/javascript>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = ( ? : ((evt.srcElement) ? evt.srcElement : null);
if (evt.keyCode == 13) {return false;}

document.onkeypress = stopRKey;

<textarea rows="5"></textarea>

Thursday, December 10, 2009

How to write & read cookie in java?

In this jsp page you can pass the value you want to set as your cookie.

<%@ page language="java" %>
<title>Cookie Input Form</title>

<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">


This page captures the cookie input value and set cookie in client hard disk.

<%@ page language="java" import="java.util.*"%>
String username=request.getParameter("username");
if(username==null) username="";

Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);

<title>Cookie Saved</title>
<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>


This is a page you can to use to see the cookie value later time.
<%@ page language="java" %>
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
for (int i = 0; i < cookies.length; i++)
if (cookies [i].getName().equals (cookieName))
myCookie = cookies[i];
<title>Show Saved Cookie</title>
if (myCookie == null) {
No Cookie found with the name <%=cookieName%>
} else {
<p>Welcome: <%=myCookie.getValue()%>.

Wednesday, December 2, 2009

Use keytool to generate keys in java

  1. keytool -genkey -alias weblogic -keyalg RSA -keystore server.keystore
  2. keytool -selfcert -export -alias weblogic -storepass changeit -file server.cer -keystore server.keystore
  3. keytool -genkey -alias client -keyalg RSA -keystore client.keystore
  4. keytool -selfcert -export -alias client -storepass changeit -file client.cer -keystore client.keystore
  5. keytool -import -v -trustcacerts -alias weblogic -file server.cer -keystore client.keystore -keypass changeit -storepass changeit
  6. keytool -keystore \jre\lib\security\cacerts -storepass changeit -file client.cer -import -alias client -trustcacerts
Here, i have created server.cer and client.cer certificates. Password used is "changeit".

Thursday, November 26, 2009

Use AXIS library to create web service and client

Download AXIS binary and extract it to your hard disk.
Set up AXIS2_HOME and path environment veriables.

Create service using WSDL file

1) Open terminal.

2) Go to the directory you want to create service.

3) Run the below command.

wsdl2java -uri "test.wsdl" -ss -sd -d xmlbeans -o service

4) This will create a folder called "service" and created the service using the .wsdl file.

5) Go to the "service" folder and run "ant" command to build the .aar file.

6) Go to AXIS bin and run "".

7) Put the created .aar file into AXIS repository\services folder.

8) It will auto deployed as a service.

9) You can access the service using "".

Create client using WSDL file

1) Open terminal.

2) Go to the directory you want to create client.

3) Run the below command.

wsdl2java -uri "test.wsdl" -d xmlbeans -o client

4) This will create a folder called "client" and created the client code using the .wsdl file.

Wednesday, November 18, 2009

DNS Mapping in windows

Go to "C:\Windows\System32\drivers\etc".

Edit hosts file in etc folder. Add your ip addres and the mapping name.

Ex :-

Now, you can access your ip address using DNS set above.

Ex :-

Thursday, October 29, 2009

Embed document in html

embed a HTML document
<object data="data/test.html" type="text/html" width="300" height="200">
alt : <a href="data/test.html">test.html</a>

embed a pdf document
<object data="data/test.pdf" type="application/pdf" width="300" height="200">
alt : <a href="data/test.pdf">test.pdf</a>

embed a wav document
<object type="audio/x-wav" data="data/test.wav" width="200" height="20">
<param name="src" value="data/test.wav">
<param name="autoplay" value="false">
<param name="autoStart" value="0">
alt : <a href="data/test.wav">test.wav</a>

Tuesday, October 20, 2009

Clear clipboad using java script

Call this java script method to clear your clipboard in IE6. Sorry, it doesn't work in Mozilla and other browsers.

function clsClipsBrd(){

Thursday, October 15, 2009

Create web service clients in java

There is a tool to create web service clients called as "cxf". This is a free tool. You must have the wsdl file to create java clients.

Download URL :-
User guide :-
Reference :-

  • Extract cxf zip file and change directory to /din in your terminal
  • use the follwing command to create java clients
wsdl2java HelloWorld.wsdl

Namespace error in JAX-WS

Here is the error, i got when i am going to creat my web service client.

oracle.jdeveloper.webservices.model.WebServiceException: Error creating model from wsdl "": undefined element declaration 's:schema'

I tried many ways to create my client using jdeveloper, but failed.

After that, i used axis web service for client implementation. It works fine in eclipse.

Create XML file in java

This is a simple example of creating standard XML file in java.

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("root");

This code segment creates a root element of the XML file.

Now, use this code to create child nodes to XML document.

Element em = document.createElement("element");

Thursday, September 17, 2009

How to find informix cost factor

Cost factor of a table is used to measure the performance of the sql executions. When your table cost factor is high, it will decrease the sql exection . That means it will get some times to generate resultsets of the sql.
Here is the way to measure informix cost factor.
Example :-
set explain on;
select * from table
  • Use set explain on; before your sql stetement in telnet client in dbaccess mode in informix.
  • Then exit dbaccess mode and type "ls -ltrh" in your home directory.
  • This will list all the files. Go to end. You will find a file called as "sqexplain.out".
  • Vi the file. Then press "shift+g" to end of the file to see your table cost factor details.

Friday, September 11, 2009

sql for monthly,yearly report

select year(added_on),month(added_on),count(*) from table_name
group by 1,2
order by 2

This will produce a resultset for monthly yearly reports.

Ex :-

Year Month Records
------ ------ --------
2009 5 14416
2009 6 788
2009 7 15413
2009 8 16091

Wednesday, September 2, 2009

Mysql today in where clause

select * from table where added_on=date(now());

To use this sql you must have used "date" datatype for your table column.
select * from table where added_at=now();

This works fine for "time" columns too .

Monday, August 31, 2009

Get radio button value in js

Suppose your radio button grop is "radiogroup".
function getradioSelection() {
var group=document.getElementsByName("radiogroup");
var grp='';
for(var k=0;k<group.length;k++){
return grp;

This method will return the selected radio button value.

Tuesday, August 25, 2009

Insert data into mysql from text file

Unload data into a text file.
Import data into a excel sheet. Then save the file again as .txt(Tab delimited) file.
Export file to your mysql server. vi the .txt file in linux. Then save the file using following command.
  • :%s/tab/|/g ---------->Then enter.
  • :wq!  ------------->Save the file
  • LOAD DATA INFILE "table.txt" INTO TABLE table
    ----> Load data to mysql server

Unload/load data from informix

unload to "table.txt" select * from table

This will unload data to your user login in database server. Suppose you logged as "test" user, it will unload data to folder "test".

load data from "table.txt" insert into table

Use this sql to load data from "table.txt" to a table.

Thursday, August 20, 2009

String qur="select a from table a";
Query q = em.createQuery(qur);

This will return the resultset limited to 10 in ejb.

Friday, August 7, 2009

How to log exceptions in dwr?

Add the following jar files to your project library.


Tuesday, August 4, 2009

Remove time in java.sql.Date using sql


Here "disconnected_on" is the field in the table. If you use to_char() method it will remove time values and formate the date as "YYYY-MM-DD".

Ex :-
before use :- 2009-10-10 12:09
after usage :- 2009-10-10

Monday, August 3, 2009

Meta tag to refesh the page

This is the meta tag that is used to refresh the page.

<META HTTP-EQUIV=Refresh CONTENT='100; URL=index.php'>
Here, CONTENT='100 means time interval for a refresh.
URL is the page/url must be refreshed.

Friday, July 31, 2009

One to Many Relational Mapping in ejb ( usage of jpa)

In this example, i use customer / order scenario. One customer can have many orders.
There is a one to many realtionship between customer and order entity classes.
The two tables are CUSTOMER and ORDER_TABLE.
Here is the schemas of the tables.
create table CUSTOMER (

create table ORDER_TABLE (



There is a primary key and foreign key mappings between tables.
Here is the entity classes.
import javax.persistence.*;
import static javax.persistence.CascadeType.*;
import java.util.Collection;
import java.util.ArrayList;


public class Customer implements Serializable {
private int id;
private String name;
private Collection<Order> orders = new ArrayList<Order>();

public int getId() {
return id;

public void setId(int id) { = id;

public String getName() {
return name;

public void setName(String name) { = name;

@OneToMany(cascade = ALL, mappedBy = "customer")
public Collection<Order> getOrders() {
return orders;

public void setOrders(Collection<Order> newValue) {
this.orders = newValue;

import javax.persistence.*;
@Table(name = "ORDER_TABLE")
public class Order {

private int id;
private String address;
private Customer customer;

@Column(name = "ORDER_ID")
public int getId() {
return id;

public void setId(int id) { = id;

@Column(name = "SHIPPING_ADDRESS")
public String getAddress() {
return address;

public void setAddress(String address) {
this.address = address;

@JoinColumn(name = "CUSTOMER_ID")
public Customer getCustomer() {
return customer;

public void setCustomer(Customer customer) {
this.customer = customer;

Suppose you are going to insert two orders for a customer, here is the insert(); This is a method that should be in your session bean.
public void insert() {

Customer cust = new Customer();
cust.setName("sujith nishantha");

Order order1 = new Order();
order1.setAddress("123 Main St. Anytown, Sri Lanka");

Order order2 = new Order();
order2.setAddress("567 1st St. Random City, Sri Lanka");



This will insert 2 orders for a cutomer.
Here is the select a customer. This method will return a customer object that consists of 2 orders.
public void select() {
Query q =
em.createQuery("select c from Customer c where = :name");
q.setParameter("name", "sujith nishantha");
Collection col = q.getResultList();
System.out.println("size ..... "+col.size());

Sunday, July 19, 2009

sql of no of count in a value

select mobile,count(mobile) from table group by mobile

This will return no of counts for a mobile number.

Friday, July 17, 2009

Date comparison in sql

Here is the sql for date comparison.

select * from table where active_until > added_on

Wednesday, July 15, 2009

jsp session

Add this code to the top of the jsp page.

<%@ page import="java.util.*" session="true"%>

Then you can get the session id of the browser and the server.

This id is unique for a browser window.

<% String sessionId=session.getId(); %>

And, you can aloso set your own variable for session. There is a method as "setAttribute".

Use this to set your own attribute for a session.


Tuesday, June 30, 2009

how to add an external weblogic server to jdeveloper

add "Oracle\Middleware\wlserver_10.3\server\lib\weblogic.jar" file to "Oracle\Middleware\jdeveloper\jdev\lib\ext" and restart the jdeveloper.

1) In jdevepoler view menu choose "Application Server Navigator".

2) Then right click on the "Application Servers" and select "New Application Server".

3) Enter weblogic server ip , port, username, password.

4) Enter the weblogic domain as "WLS_Domain";

5)Test your cnnection.

6) Right click on your project select Deploy --> to your weblogic server.

get integer value of a char

int x = str.charAt(1)

This return the integer values of the char.


A = 97

Friday, June 26, 2009

Disable back button in IE using js

use this code in your page onload method.


Sunday, June 14, 2009

remove unwanted chars (new line,tab) in java

String truncated = originalString.replaceAll("\\p{Cntrl}", "");

Monday, June 8, 2009

mysal data load and unload



Friday, May 15, 2009

Autoboxing and Unboxing in java example

Java is an Object Oriented programming language. We have to deal with primitive types and objects together.

Here autoboxing comes to play the role. It wraps the primitive data type into a object. There are wrapper classes for it.

For Example : -

 public class FormatPrint {

     public static void main(String[] args) {

       System.out.printf("There is only %d thing.", 1);



The signature of the printf() is

printf(String format, Object... args)

But, inthe above example i have printed a integer value. This is called as autoboxing. This can be used in Generics,too.

Here is java normal java generic example : -

 import java.util.ArrayList;

   public class ManualBoxing {

     public static void main(String[] args) {

        ArrayList list = new ArrayList();

        for(int i = 0; i < 10; i++){

            list.add(new Integer(i));




But we don't need to "new Integer(i)". We can use autoboxing and simply the code as follow.

import java.util.ArrayList;

    public class Autoboxing {

      public static void main(String[] args) {

          ArrayList<Integer> list = new ArrayList<Integer>();

          for(int i = 0; i < 10; i++){





For further details : -

Wednesday, May 13, 2009

Delete non empty directory in java


class DeleteDir {

public static void main(String args[]) {

deleteDirectory(new File(args[0]));


static public boolean deleteDirectory(File path) {

if( path.exists() ) {

File[] files = path.listFiles();

for(int i=0; i<files.length; i++) {

if(files[i].isDirectory()) {



else {





return( path.delete() );



Monday, April 27, 2009

How to log records to log file? Using log4j

This piece of code will explain the usage of the log4j. In java development, you may have faced for error logging situation. Here is the solution.

Make a log configuration file with follwoing details in your project. Here log configuration file name is "logconfig.txt"






log4j.appender.debugl.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm:ss}|%m %n


There must be a file called "data_usage_log.txt" in C directory. Then it will upgrade with logs.

Add the following methods to your class constructors.

Logger preLogger



preLogger = Logger.getLogger("debugl");


you can add your error report as follows“Logging ”);

Sunday, April 19, 2009

Combine two pdf files using itext

Here is a simple way to combine two pdf files into one.
I have used iText-2.1.5.jar

This is the sample code


import com.lowagie.text.pdf.PdfCopyFields;

import com.lowagie.text.pdf.PdfReader;

public class PDFTest {

public static void main(String[] args) throws Exception {

System.out.println("Concatenate Two PDF");

PdfReader reader1 = new PdfReader("D:/upload/first.pdf");

PdfReader reader2 = new PdfReader("D:/upload/second.pdf");

PdfCopyFields copy = new PdfCopyFields(new FileOutputStream("D:/upload/concatenatedPDF.pdf"));






Thursday, April 16, 2009

Formatting text on Textarea/ Remove unwanted chars in Textarea

function escapeVal(textarea,replaceWith){

textarea.value = escape(textarea.value);

for(i=0; i<textarea.value.length; i++){

if(textarea.value.indexOf("%0D%0A") > -1){



else if(textarea.value.indexOf("%0A") > -1){



else if(textarea.value.indexOf("%0D") > -1){




return unescape(textarea.value);


If you need to remove un wanted chars in a textarea you can use the above java script.


set the textarea object as the 1st parameter and 2nd paramter is the replaceable char with unwanted ones.

Monday, April 6, 2009

Direct file access in weblogic server

In weblogic, you can keep a directory for all images,pdfs,....

how to do ...


you have to create a "weblogic.xml" file in WEB-INF in your application. This weblogic.xml should be like this.

<?xml version="1.0" encoding="UTF-8"?>







suppose you have a directory called as images in path /apps/test/images. You can give users to direct access those files as follows.


This is called as Virtual directory mapping in weblogic.

Connection pool/jndi

In normal java development, we use jdbc database connections. It takes several mili seconds to make connection between database server and your application.

In connection pool concept, there are several connections are built with the application server startup. This make web applications more fast.

As i mentioned, it makes several connection at the app sever startup. Developers can access those connections using jndi. There is a jndi for a conncetion pool. All the jndi are in the java jvm.

Developers has to look up for the jndi names and use the database connection.

Suppose your connection pool is "dbtest" . And you have mapped this pool with jndi name "jdbc/dbtest".

your lookup mathod will be like this in netbeans.

private DataSource getDbtest() throws NamingException {
Context c = new InitialContext();
return (DataSource) c.lookup("java:comp/env/dbtest");

The above method returns a sql data source. You can get a connection using it.