Friday, August 21, 2009

Upload a file to a server-Java Source Code [JSP]



The below code will give you the idea how to upload a file to a server location. We are using a specific folder “uploadedFile” in the server current directory for the uploaded files.

To implement upload functionality, we will be using FileUpload and IO packages under common packages of Apache. This will ease out our job of coding this.

Links to download the jar files for the above.

http://commons.apache.org/fileupload/
http://commons.apache.org/io/

We will be creating two JSPs one of which will be the first page which will be asking for the files to browse and upload. After submitting the file, it will give us the details of the file which we have uploaded.

Below are the sample JSPs:
uploadfileToServer.jsp



fileUpload.jsp

















Thursday, August 20, 2009

Java Source Code to lock a file

Below source code is the simple example of how to lock a file. The below program will not allow you to delete the created file or to edit the created file for 1 min. I will use FileChannel and FileLock class to achieve that.

API Source:

http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html
http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
*
* @author Snehanshu
*/
public class FileLockDemo {

/** Creates a new instance of FileLockDemo */
FileLockDemo() {
}

private void doLockFile() {
try{
File file = new File("./FileLockDemo.txt");
FileLock lock = null;
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("File is being locked");
bufferedWriter.close();

FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
System.out.println("Locking the file");
lock = channel.lock(0, Long.MAX_VALUE, true); // Create a shared lock on the file.

// This section of code will lock the file for 1 mins [60 secs = 60000 milliseconds].
//For those 60 secs, you will not be able to delete or save the file after editing.
System.out.println("Wait for 60 secs for the program to unlock the file");
try {
Thread.sleep(60000);
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Releasing the lock of the file");
if (lock != null && lock.isValid()) {
lock.release(); // Lock is being released
}
} catch(FileNotFoundException fNFE) {
fNFE.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
FileLockDemo fileLockDemo = new FileLockDemo();
fileLockDemo.doLockFile();
}

}

Delete a file only when it is closed

Hi, below is the code which will create and open a file using window resources and if the file is already created then it will open the file.

try {
Process pc = Runtime.getRuntime().exec("C:/WINDOWS/ServicePackFiles/i386/notepad.exe C:/CheckDemo.txt");
} catch (IOException ex) {
ex.printStackTrace();
}

However I was wondering, if we need to open the file in temporary mode; meaning when the file is closed, it should be automatically deleted.

The waitFor() method of the Process class will do the trick.

The API describes the method like below:

causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

[Source: http://java.sun.com/javase/6/docs/api/java/lang/Process.html]

The code is like below:

import java.io.File;
import java.io.IOException;

public class Test {
public static void main(String[] args) throws Exception {
try {
Process pc = Runtime.getRuntime().exec("C:/WINDOWS/ServicePackFiles/i386/notepad.exe C:/CheckDemo.txt");
try {
pc.waitFor();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
File file = new File("C:/CheckDemo.txt");
file.delete();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Sunday, August 16, 2009

JcheckBox – Select Any of the checkbox

Below is the java source code which selects any of the JcheckBox – which is basically acting as Radio Button.

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingCheckBoxDemo implements ActionListener {

JCheckBox FZYamaha;
JCheckBox XCD135Bajaj;
JCheckBox StunnerHero;
JCheckBox Avenger;

public SwingCheckBoxDemo() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingCheckBoxDemo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FZYamaha = new JCheckBox("FZ Yamaha");
FZYamaha.setMnemonic(KeyEvent.VK_C);
FZYamaha.setSelected(true);

XCD135Bajaj = new JCheckBox("XCD 135 Bajaj");
XCD135Bajaj.setMnemonic(KeyEvent.VK_G);
XCD135Bajaj.setSelected(false);

StunnerHero = new JCheckBox("Stunner");
StunnerHero.setMnemonic(KeyEvent.VK_H);
StunnerHero.setSelected(false);

Avenger = new JCheckBox("Avenger");
Avenger.setMnemonic(KeyEvent.VK_T);
Avenger.setSelected(false);

/*Put the check boxes in a column in a panel*/

JPanel checkPanel = new JPanel(new GridLayout(0, 1));
checkPanel.add(FZYamaha);
checkPanel.add(XCD135Bajaj);
checkPanel.add(StunnerHero);
checkPanel.add(Avenger);

frame.add(checkPanel, BorderLayout.LINE_START);

frame.pack();
frame.setSize(300,100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

FZYamaha.addActionListener(this);
XCD135Bajaj.addActionListener(this);
StunnerHero.addActionListener(this);
Avenger.addActionListener(this);
}


public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == FZYamaha) {
System.out.println("Yamaha");
FZYamaha.setSelected(true);
XCD135Bajaj.setSelected(false);
StunnerHero.setSelected(false);
Avenger.setSelected(false);
}

if(ae.getSource() == XCD135Bajaj) {
System.out.println("XCD135Bajaj");
FZYamaha.setSelected(false);
XCD135Bajaj.setSelected(true);
StunnerHero.setSelected(false);
Avenger.setSelected(false);
}

if(ae.getSource() == StunnerHero) {
System.out.println("StunnerHero");
FZYamaha.setSelected(false);
XCD135Bajaj.setSelected(false);
StunnerHero.setSelected(true);
Avenger.setSelected(false);
}

if(ae.getSource() == Avenger) {
System.out.println("Avenger");
FZYamaha.setSelected(false);
XCD135Bajaj.setSelected(false);
StunnerHero.setSelected(false);
Avenger.setSelected(true);
}
}

public static void main(String[] args) {
SwingCheckBoxDemo swingCheckBoxDemo = new SwingCheckBoxDemo();
}
}



Thursday, August 13, 2009

JCheckBox - Java Source Code

Below source code is simple example of JCheckBox in Swings.


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JCheckBoxDemo {

JCheckBox FZYamaha;
JCheckBox XCD135Bajaj;
JCheckBox StunnerHero;
JCheckBox Avenger;

JCheckBoxDemo() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingCheckBoxDemo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

FZYamaha = new JCheckBox("FZ Yamaha");
FZYamaha.setMnemonic(KeyEvent.VK_C);
FZYamaha.setSelected(true);

XCD135Bajaj = new JCheckBox("XCD 135 Bajaj");
XCD135Bajaj.setMnemonic(KeyEvent.VK_G);
XCD135Bajaj.setSelected(true);

StunnerHero = new JCheckBox("Stunner");
StunnerHero.setMnemonic(KeyEvent.VK_H);
StunnerHero.setSelected(true);

Avenger = new JCheckBox("Avenger");
Avenger.setMnemonic(KeyEvent.VK_T);
Avenger.setSelected(true);

/*Put the check boxes in a column in a panel*/

JPanel checkPanel = new JPanel(new GridLayout(0, 1));
checkPanel.add(FZYamaha);
checkPanel.add(XCD135Bajaj);
checkPanel.add(StunnerHero);
checkPanel.add(Avenger);

frame.add(checkPanel, BorderLayout.LINE_START);

frame.pack();
frame.setSize(300,100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}


public static void main(String[] args) {
JCheckBoxDemo checkBoxDemo = new JCheckBoxDemo();
}
}









Tuesday, August 11, 2009

Include an addition Tag in XML – Java Source Code

The below simple source code will append a node [address] before a specfic node [telephone] and under specific parent node [employee] of a specific XML.

Company.xml [Input]





/*
* AppendChild.java
*/

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;



/**
*
* @author Snehanshu Chatterjee
*/
public class AppendChild {

/** Creates a new instance of AppendChild */
public AppendChild() {
}

private void appendChildIntoXML(){

}

public static void main(String[] args) {
try{
File xmlDocument = new File("Company.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlDocument);
insertNode(document,xmlDocument);
}catch(Exception e){
e.printStackTrace();
}
}


private static void insertNode(Document doc,File fileDoc){
Node parentNode = doc.getParentNode();
Node officeNode = doc.getElementsByTagName("employee").item(0);
Node telChild = doc.getElementsByTagName("telephone").item(0);
Node addressNode = (Node) doc.createElement("Address");
Node newChild = officeNode.appendChild(addressNode);
officeNode.insertBefore(newChild,telChild);

try {
// create DOMSource for source XML document
Source xmlSource = new DOMSource(doc);
// create StreamResult for transformation result
Result result = new StreamResult(new FileOutputStream(fileDoc));
// create TransformerFactory
TransformerFactory transformerFactory = TransformerFactory.newInstance();
// create Transformer for transformation
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
// transform and deliver content to client
transformer.transform(xmlSource, result);
} catch (TransformerFactoryConfigurationError factoryError) {
// handle exception creating TransformerFactory
System.err.println("Error creating " + "TransformerFactory");
factoryError.printStackTrace();
}catch (TransformerException transformerError) {
System.err.println("Error transforming document");
transformerError.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}

}

}

Run:
set classpath=.
javac AppendChild.java
java AppendChild
pause


Company.XML [Output]:

JMenu – Java Source Code

Below is the simple source code to implement JMenu, JMenuItem and JMenuBar.


Source Code



import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

public class ExploreMenu implements ActionListener {

ExploreMenu() {
JFrame frame = new JFrame("Explore Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setResizable(false);
frame.setLocationRelativeTo(null);

// Create the menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu menu = new JMenu("File");
menuBar.add(menu);
// Create a menu item
JMenuItem item = new JMenuItem("Windows");
menu.add(item);
// Install the menu bar in the frame
frame.setJMenuBar(menuBar);
frame.setVisible(true);
item.addActionListener(this);
}


public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Windows")) {
try {
Runtime.getRuntime().exec("explorer C:\\WINDOWS");
}catch(IOException ie){
ie.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}


public static void main(String[] args) {
ExploreMenu exploreMenu = new ExploreMenu();
}

}



Putting the message into IBM Websphere MQ

Like pervious article, we are going to take a look onto the source code to put the message into the MQ.

Entries in the properties file [ProducerProperties.properties]:

host=hostname where MQ is installed; localhost if installed locally
port=port on to which connection is established to the channedl
channel=SYSTEM.DEF.SVRCONN
queueManagerName=Queue Manager Name
destinationName=Queue Name where the message will go
isTopic=false
samplefilelocation=./Company.xml

Source Code

import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import java.io.*;
import java.io.FileInputStream;
import java.util.Properties;
import javax.jms.*;

public class MQProducer {

public MQProducer() {
}

private void putMessageIntoMQ() {
String propertiesFile = "./ProducerProperties.properties";
this.readPropertyFile(propertiesFile);
Connection connection = null;
Session session = null;
javax.jms.Destination destination = null;
MessageProducer producer = null;
try {
JmsFactoryFactory ff = JmsFactoryFactory.getInstance("com.ibm.msg.client.wmq");
JmsConnectionFactory cf = ff.createConnectionFactory();
cf.setStringProperty("XMSC_WMQ_HOST_NAME", host);
cf.setIntProperty("XMSC_WMQ_PORT", port);
cf.setStringProperty("XMSC_WMQ_CHANNEL", channel);
cf.setIntProperty("XMSC_WMQ_CONNECTION_MODE", 1);
cf.setStringProperty("XMSC_WMQ_QUEUE_MANAGER", queueManagerName);
cf.setStringProperty("XMSC_USERID","username"); //username to connect to MQ
cf.setStringProperty("XMSC_PASSWORD","password"); // password to connect to MQ
connection = cf.createConnection();
session = connection.createSession(false, 1);
if(isTopic)
destination = session.createTopic(destinationName);
else
destination = session.createQueue(destinationName);
producer = session.createProducer(destination);
long uniqueNumber = System.currentTimeMillis() % 1000L;
TextMessage message = session.createTextMessage();
message.setText(sampleFile);
connection.start();
producer.send(message);
System.out.println((new StringBuilder()).append("Sent message:\n").append(message).toString());
recordSuccess();
} catch(JMSException jmsex) {
recordFailure(jmsex);
} finally {
if(producer != null)
try {
producer.close();
} catch(JMSException jmsex) {
System.out.println("Producer could not be closed.");
recordFailure(jmsex);
}
if(session != null)
try {
session.close();
} catch(JMSException jmsex) {
System.out.println("Session could not be closed.");
recordFailure(jmsex);
}
if(connection != null)
try {
connection.close();
} catch(JMSException jmsex) {
System.out.println("Connection could not be closed.");
recordFailure(jmsex);
}
}
System.exit(status);
}

private static void processJMSException(JMSException jmsex) {
System.out.println(jmsex);
Throwable innerException = jmsex.getLinkedException();
if(innerException != null)
System.out.println("Inner exception(s):");
for(; innerException != null; innerException = innerException.getCause())
System.out.println(innerException);

}

private static void recordSuccess() {
System.out.println("SUCCESS");
status = 0;
}

private static void recordFailure(Exception ex) {
if(ex != null)
if(ex instanceof JMSException)
processJMSException((JMSException)ex);
else
System.out.println(ex);
System.out.println("FAILURE");
status = -1;
}

private static String host;
private static int port;
private static String channel;
private static String queueManagerName;
private static String destinationName;
private static boolean isTopic;
private static int status = 1;
private static String sampleFile;





private void readPropertyFile(String fileName) { // reading from the property file
try {
Properties mqProperties = new Properties();
FileInputStream fileInputStream = new FileInputStream(fileName);
mqProperties.load(fileInputStream);
host = mqProperties.getProperty("host");
port = Integer.parseInt(mqProperties.getProperty("port"));
channel = mqProperties.getProperty("channel");
queueManagerName = mqProperties.getProperty("queueManagerName");
destinationName = mqProperties.getProperty("destinationName");
isTopic = Boolean.parseBoolean(mqProperties.getProperty("isTopic"));
sampleFile = mqProperties.getProperty("samplefilelocation");
fileInputStream.close();
} catch (Exception exp) {
exp.printStackTrace();
}
}


public static void main(String args[]) {
MQProducer mqProducer = new MQProducer();
mqProducer.putMessageIntoMQ();
}
}






Below is the output in console after run:




Getting the Message from MQ – Source Code Java

Today I want to share something new with you which I have learnt few days back.

I was asked to build an application which will consume messages from a messaging queue from remote machine and save into the local machine.

When I saw the MQ, it was IBM websphere MQ in which can manually put the message and test whether our code of getting the message is working or not.

Before walking through the code, it is important to go through the basic terminologies. So please google it and find some useful stuff.

If you happen to install IBM websphere MQ, you will find some of parameters of MQ which we will require to connect to MQ. We will put those parameters into a properties file (ConsumerProperties.properties), so that we can change it without changing the source code.

We assume that the message in the queue will be of XML type and we store the message into an XML file only.

The entries in the properties file will be like the following:

hostName=The host where the MQ server exists; localhost, if locally MQ server is set
qmgrName=Queue Manager Name where channels and the queues are established
port=the port with which the channel is connected
channel=SYSTEM.DEF.SVRCONN
msgFileName=./ConsumedXMLFile
msgDir=./
qName=Queue Name where the message actually comes


Source Code


import com.ibm.mq.*;
import java.util.*;
import java.io.*;
import java.text.SimpleDateFormat;

public class JConsumer {
private MQQueueManager mqQueueManager; // QMGR object
private MQQueue queue; // Queue object
private int openOptionInquire; // Open options
private String hostName; // host name
private String channel; // server connection channel
private String port; // port number on which the QMGR is running
private String qmgrName; // queue manager name
private String qName; // queue name
private String msgFileName; // message file name
private String msgDir;
private static String dateStringPre = new String();
private static String dateStringPost = new String();
private static String dateStringPreTemp = new String();
private static String dateStringPostTemp = new String();
private static boolean statusFlag = false;



private void startDownloading() {

try{
JConsumer MQBrowse = new JConsumer();
MQBrowse.init();
} catch( Exception e) {
e.printStackTrace();
}
}

public void init() {

try{
String fileName = "./ConsumerProperties.properties";
this.readPropertyFile(fileName);
this.mqInit( );
System.out.println("Mq initializing started "+new Date());
} catch( Exception e) {
e.printStackTrace();
}
}


private void mqInit( ) { // Initiation of the MQ parameter
try {

System.out.println("host name : " + hostName+"\n"
+"QMGR name : " + qmgrName+"\n"
+"port number : " + port+"\n"
+"channel : " + channel+"\n"
+"file name : " + msgFileName+"\n"
+"queue name : " + qName+"\n"
+"\n");

mqOperations();
} catch (Exception e) {
e.printStackTrace();
}

}

public void mqOperations() throws Exception { // connect, open, browse, close & disconnects

try {
mqConnect(); // queue manager connection
mqOpen(); // pens the queue & browse
mqClose(); // close the queue
mqDisconnect(); // disconects the queue manager
}

catch (Exception exp) {
exp.printStackTrace();
}


} //mqOperations ends here


private void mqConnect() throws Exception { // Connection to the queue manager
try {
MQEnvironment.hostname = hostName;
MQEnvironment.channel = channel;
MQEnvironment.port = Integer.parseInt(port);

System.out.println("Connecting to ---------- "+hostName + " ---------- " + channel + " ----------- " + port);

mqQueueManager = new MQQueueManager(qmgrName);
System.out.println("Qmgr ---------- " + qmgrName + " connection successfull ");
}

catch ( MQException mqExp) {
System.out.println("Error in connecting to queue manager -- "+qmgrName+" with CC : " + mqExp.completionCode +" RC : " + mqExp.reasonCode);
mqClose();
mqDisconnect();
}
}



private void mqDisconnect() { // disconnect to queue manager
try {
mqQueueManager.disconnect();
System.out.println("Qmgr : " + qmgrName + " disconnect successfull ");
}

catch ( MQException mqExp) {
System.out.println("Error in queue manager disconnect...."+"QMGR Name : " + qmgrName+"CC : " + mqExp.completionCode+"RC : " + mqExp.reasonCode);
}
} // end of mqDisconnect


private void mqOpen() throws MQException {
try {
int openOption = 0;

openOption = MQC.MQOO_BROWSE MQC.MQOO_INPUT_SHARED; // open options for browse & share

queue = mqQueueManager.accessQueue(qName, openOption,qmgrName,null,null);

MQGetMessageOptions getMessageOptions = new MQGetMessageOptions();
getMessageOptions.options = MQC.MQOO_INPUT_AS_Q_DEF;
//MQC.MQGMO_BROWSE_FIRST MQC.MQGMO_WAIT ; //for browsing
getMessageOptions.waitInterval = MQC.MQWI_UNLIMITED;
//MQC.MQWI_UNLIMITED;
// for waiting unlimted times
// waits unlimited
MQMessage message = new MQMessage();
BufferedWriter writer ;
String strMsg;

try {
System.out.println( "waiting for message ... ");
queue.get(message, getMessageOptions);
System.out.println( "Get message sucessfull... ");
byte[] b = new byte[message.getMessageLength()];
message.readFully(b);
strMsg = new String(b);
System.out.println("\n"+strMsg);
// if empty message, close the queue...
if ( strMsg.trim().equals("") ) {
System.out.println("empty message, closing the queue ..." + qName);
}
message.clearMessage();
writer = new BufferedWriter(new FileWriter(msgFileName+"_"+new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())+".xml", true));
writer.write("\n");
writer.write(new String(b));
writer.write("\n");
writer.close();
getMessageOptions.options = MQC.MQOO_INPUT_AS_Q_DEF;
//MQC.MQGMO_BROWSE_NEXT MQC.MQGMO_WAIT ;
} catch (IOException e) {
System.out.println("IOException during GET in mqOpen: " + e.getMessage());
}
} catch ( MQException mqExp) {
System.out.println("Error in opening queue ...."+"Queue Name : " + qName+" CC : " + mqExp.completionCode+" RC : " + mqExp.reasonCode);
mqClose();
mqDisconnect();
}

} //end of mqOpen

private void mqClose() { // close the queue
try {
queue.close();
} catch (MQException mqExp) {
System.out.println("Error in closing queue ...."+"Queue Name : " + qName+" CC : " + mqExp.completionCode+" RC : " + mqExp.reasonCode);
}

}

private void readPropertyFile(String fileName) throws Exception { // reading from the property file
try {
Properties mqProperties = new Properties();
FileInputStream fileInputStream = new FileInputStream(fileName);
mqProperties.load(fileInputStream);
hostName = mqProperties.getProperty("hostName");
qmgrName = mqProperties.getProperty("qmgrName");
port = mqProperties.getProperty("port");
channel = mqProperties.getProperty("channel");
msgFileName = mqProperties.getProperty("msgFileName");
qName = mqProperties.getProperty("qName");
msgDir = mqProperties.getProperty("msgDir");
fileInputStream.close();
} catch (Exception exp) {
exp.printStackTrace();
}
}

public static void main(String args[]){
JConsumer consumer = new JConsumer();
consumer.startDownloading();
}

}

Source Code to log messages in Java Applications

This article will highlight the source code of logger functionality of Java. Whenever you build any application using Java, you need to log the certain details or any exceptions happened while execution of the program.
For that we use built in logger jar [log4j-1.2.9.jar - http://www.findjar.com/jar/log4j/jars/log4j-1.2.9.jar.html] which contains all the relevant class of the Logger functionalities. The below simple code logs the information messages, debug messages and the error messages.

Logger API: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html

There is one log4jconfig.properties which contains the logger file properties. So we will use another java class to access the properties file.

The entries which I have used in the log4jconfig.properties file are:

log4j.rootLogger=DEBUG,file
log4j.appender.file.layout=org.apache.log4j.HTMLLayout
log4j.appender.file.File=logger.html
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=2000KB



Log4Logger.java

/*
* Log4Logger.java
* Snehanshu Chatterjee
*/

import java.util.Properties;
import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;

public class Log4Logger extends org.apache.log4j.Logger {
private static Category l=null;
/** Creates a new instance of Log4Logger */
public Log4Logger(String name) {
super(name);
}
static{
try{
Properties logProp=new Properties();
String fName=new String("./log4jconfig.properties");
PropertyConfigurator.configure(fName);
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* This method gets category object and it is static method.
* @param name String.
* @return Category Object with the l field.
*/
public static Category returnLogger(String name) {
l= Log4Logger.getLogger(name);
return l;
}
}


The below code which actually logs any information.

LoggerDemo.java

/*
LoggerDemo.java
Snehanshu Chatterjee
*/
import org.apache.log4j.Category;

public class LoggerDemo {

private static Category OutputCtrl = Log4Logger.returnLogger(LoggerDemo.class.getName());

LoggerDemo() {
}

private void doLog() {
OutputCtrl.info("Info Message");
OutputCtrl.debug("Debug the Program");
OutputCtrl.error("Error Message");
}

public static void main(String args[]) {
LoggerDemo loggerDemo = new LoggerDemo();
loggerDemo.doLog();
}

}

Run the File [Putting java file and jar file in one folder]
set classpath=.;./log4j-1.2.9.jar/
javac LoggerDemo.java
java LoggerDemo
pause

Monday, August 3, 2009

Source code to connect to a Oracle Database – Java

This is sample source code to connect to Oracle Database.
You need to have Oracle Driver [Can be downloaded from http://www.findjar.com/jar/mule/dependencies/maven1/oracle-jdbc/jars/ojdbc14.jar.html], the ip address of the machine where database exists and service identifier of the database. We use 1521 as a default ip address to connect to the database.



/*
* DBConnection.java
*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DBConnection {

Connection con;
DBConnection() {
}

private void dbInitiateConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch(NullPointerException npe) {
npe.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}

try {
con = DriverManager.getConnection("jdbc:oracle:thin:@ipaddress:1521:serviceidentifierofdatabase","username","password");
con.setAutoCommit(false);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


private void getDataFromTable() {
try {
PreparedStatement psd = con.prepareStatement("select empno from emp");
ResultSet rst = psd.executeQuery();
System.out.println("Employee Nos are ");
while(rst.next()){
int empNo = rst.getInt(1);
System.out.println(empNo);
}
rst.close();
psd.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}




private void dbCloseConnection() {
try {
con.close();
} catch(SQLException ex) {
ex.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String args[]) {
DBConnection dbConnect = new DBConnection();
dbConnect.dbInitiateConnection();
dbConnect.getDataFromTable();
dbConnect.dbCloseConnection();
}

}

TabbedPane – Java Source Code

The below code is the simple source code to create TabbedPane in Swings.


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class TabbedPaneDemo {

TabbedPaneDemo() {
JFrame frame = new JFrame("TabbedPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,100);
frame.setResizable(false);
frame.setLocationRelativeTo(null);

JPanel p = new JPanel();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JTabbedPane tb = new JTabbedPane();

tb.addTab("Index",null,p,"This is enabled");
tb.addTab("Index",null,p1,"This is disabled");
tb.addTab("Index",null,p2,"This is enabled");
tb.addTab("Index",null,p3,"This is disabled");
tb.addTab("Index",null,p4,"This is enabled");

tb.setEnabledAt(1,false);
tb.setEnabledAt(3,false);

frame.add(tb);

frame.setVisible(true);
}



public static void main(String[] args) {
TabbedPaneDemo tabbedPaneDemo = new TabbedPaneDemo();
}

}


Java - why public static void main

public: The public method can be accessed outside the class or package.

static: To access the static method, there is no need to create object and you need not have an instance of the class to access the method.

void: There is no need by application to return value. JVM launcher do this with it exists.

main(): It is the entry point for the java application.

String args[] : args is an array of string which holds the optional arguments to the class.

Total Pageviews