Sunday, August 3, 2014

Program for creation of XML document using DOM4J

DOM4J is an open-source java library for programming XML in java. 

I used Eclipse as the IDE and Java SE 7 Update 25 for developing the program. 

One have to download the DOM4J jars to start with. It can be downloaded from here DOM4J archive Download link

Once downloaded Unrar the rar file and consolidate all the jars from the folders and browse them into the build path of the Eclipse that you're using. Click ALT+ENTER on the project and properties window will open up, navigate to the Java Build Path section, in the Libraries tab click the button Add external jars and browse all the consolidated jars.


 The Eclipse project can be a simple java project.

DOM4J Program:
You can use this program to create the xml document using DOM4J. 

 package com.dom4j.xml;  
 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 import java.io.StringReader;  
 import java.io.StringWriter;  
 import javax.xml.transform.OutputKeys;  
 import javax.xml.transform.Source;  
 import javax.xml.transform.Transformer;  
 import javax.xml.transform.TransformerConfigurationException;  
 import javax.xml.transform.TransformerException;  
 import javax.xml.transform.TransformerFactory;  
 import javax.xml.transform.stream.StreamResult;  
 import javax.xml.transform.stream.StreamSource;  
 import org.dom4j.Document;  
 import org.dom4j.DocumentHelper;  
 import org.dom4j.Element;  
 public class XMLCreation {  
      /**  
       * This method creates XML document upon calling.  
       */  
      private void createXML() {  
           Document document = DocumentHelper.createDocument();  
           Element root = document.addElement("Root");  
           Element child1 = root.addElement("Child1")  
                     .addAttribute("attr1", "attr1val")  
                     .addAttribute("loopNode", "no");  
           Element child2 = child1.addElement("Child2").addAttribute("loopNode",  
                     "no");  
           {  
                for (int i = 0; i < 3; i++) {  
                     Element loopNode = child2.addElement("Loop" + i);  
                     loopNode.addAttribute("loopNode", "yes");  
                     loopNode.addText("Loop Child " + i);  
                }  
           }  
           Source source = new StreamSource(new StringReader(document.asXML()));  
           StringWriter stringWriter = new StringWriter();  
           StreamResult streamResult = new StreamResult(stringWriter);  
           File file = null;  
           BufferedWriter bufferedWriter = null;  
           try {  
                file = new File("C:/DemoXMLFile1.xml");  
                file.createNewFile();  
                TransformerFactory transformerFactory = TransformerFactory  
                          .newInstance();  
                Transformer transformer = transformerFactory.newTransformer();  
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
                transformer.setOutputProperty(  
                          "{http://xml.apache.org/xslt}indent-amount", "9");  
                transformer.transform(source, streamResult);  
                bufferedWriter = new BufferedWriter(new FileWriter(  
                          file.getAbsoluteFile()));  
                bufferedWriter.write(streamResult.getWriter().toString());  
                bufferedWriter.flush();  
                bufferedWriter.close();  
           } catch (FileNotFoundException f) {  
                f.printStackTrace();  
           } catch (TransformerConfigurationException t) {  
                t.printStackTrace();  
           } catch (IOException i) {  
                i.printStackTrace();  
           } catch (TransformerException t) {  
                t.printStackTrace();  
           }  
      }  
      /**  
       * Main method  
       *   
       * @param args  
       */  
      public static void main(String args[]) {  
           new XMLCreation().createXML();  
      }  
 }  

1. The process is pretty straight forward. I used Document interface and created an instance to it. 
2. I used this instance to create a root element using Element interface. I added attributes to the node. 
3. Further I created another Element instance and added node as child to the above root element and attributes.
4. I created a loop and every time loop iterates it creates child node to the sub child node and adds text to the loop node. 
5. I made use of TransformerFactory and Transformer to format the xml document. 
6. The normal BufferedWriter to write the xml to the document. 
7. The interface Source stores the document xml details in StringReader, the StringReader creates characterstream. 
8. I created an object to StringWriter class and passed the instance to the StreamResult interface. 
9. The StringWriter converts character stream to the buffered stream. 
10. To the transformer we have included output properties to provide indent to the xml file using setOutputProperty.

One can also use the Scanner class to provide file paths and file names as dynamic parameters.

The output file I got with Indent 9:



Suggestions are welcome. Please feel free to comment.

Saturday, July 5, 2014

Creating a simple java servlet

For creating a simple servlet, all we need is a HTML/JSP file and a java class.

Below is the Eclipse project structure for the Dynamic Web Project I created:

Below is the web.xml config I used:
I used two child elements in xml under web-app namely:
1. servlet
2. servlet-mapping

The element servlet contains two child elements further namely:
1. servlet-name - to specify the name of the servlet (name can be anything)
2. servlet-class - to specify the name of java class including package name.

The element servlet-mapping contains two child elements further namely:
1. servlet-name: to specify name of the servlet (the name should be same as one specified in the child element servlet-name of element servlet).
2. url-pattern: to specify the url-pattern of the servlet.

 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <servlet>  
  <servlet-name>Servlet1</servlet-name>  
  <servlet-class>com.servlets.ServletClass1</servlet-class>  
  </servlet>  
  <servlet-mapping>  
  <servlet-name>Servlet1</servlet-name>  
  <url-pattern>/Servlet1</url-pattern>  
  </servlet-mapping>  
 </web-app>  

Sample JSP code:
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Insert title here</title>  
 </head>  
 <h1 align="center">Enter your details down below:</h1>  
 <body bgcolor="yellow">  
 <form method="post" action="ServletClass1">  
 <center>  
 <table border="1" bordercolor="red" bgcolor="lime" cellspacing="20" style="font-size: 20px;font-family:inherit;" cellpadding="3">  
 <tr bgcolor="yellow">  
 <td>Name: <input type="text" name="name"><br/></td>  
 </tr>  
 <tr bgcolor="yellow"><td>  
 Profession: <br/>  
 Developer: <input type="radio" name="Developer"/><br/>  
 Architect: <input type="radio" name="Architect"/><br/>  
 </td>  
 </tr>  
 <tr bgcolor="yellow">  
 <td>  
 Skills:<br/>  
 <select name="skills">  
 <option value="J2EE" label="J2EE"></option>  
 <option value="J2SE" label="J2SE"></option>  
 <option value="J2ME" label="J2ME"></option>  
 </select></td></tr>  
 </table>  
 <input type="submit" value="Submit" style="font-size:20px;font-family:inherit;"/>  
 </center>  
 </form>  
 </body>  
 </html>  

You can use above code either in a JSP file or HTML file. I created three types of fields - text, radio buttons, drop down fields.
In the html elements I used form fields and have given the servlet name in action tag and POST method in method tag which means when the servlet is called it invokes POST method.

I am trying to retrieve the values that comes out when certain fields are containing values or selected from a servlet.

Servlet:
 A servlet is a simple java file that communicates with the server. A java file that extends HttpServlet class is said to be a servlet.

Below is the  sample java code that I have used:
 package com.servlets;  
 import java.io.IOException;  
 import java.io.PrintWriter;  
 import javax.servlet.ServletException;  
 import javax.servlet.annotation.WebServlet;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 /**  
  * Servlet implementation class ServletClass1  
  */  
 @WebServlet("/ServletClass1")  
 public class ServletClass1 extends HttpServlet {  
      private static final long serialVersionUID = 1L;  
      /**  
       * @see HttpServlet#HttpServlet()  
       */  
      public ServletClass1() {  
           super();  
      }  
      /**  
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse  
       *   response)  
       */  
      protected void doGet(HttpServletRequest request,  
                HttpServletResponse response) throws ServletException, IOException {  
      }  
      /**  
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse  
       *   response)  
       */  
      protected void doPost(HttpServletRequest request,  
                HttpServletResponse response) throws ServletException, IOException {  
           PrintWriter out = response.getWriter();  
           out.println("<p style='font-size:20px'> Name: "  
                     + request.getParameter("name") + "</p><br/>");  
           out.println("<p style='font-size:20px'> Developer: "  
                     + request.getParameter("Developer") + "</p><br/>");  
           out.println("<p style='font-size:20px'> Architect: "  
                     + request.getParameter("Architect") + "</p><br/>");  
           out.println("<p style='font-size:20px'> Skills: "  
                     + request.getParameter("skills") + "</ps>");  
      }  
 }  

In the above code, I have used PrintWriter to enable logging into response file that will be returned by the server. If you use System.out.println (SOP), we get outputs in log files of the server. I used tomcat server version 7. Once I ran the JSP/HTML file on the server, I got the form as below:



I filled the above from as below:
 
 and I clicked the submit button and the server returns the below response: 
Since I didn't select Architect radio button it is coming as null and the rest are as selected.

Any suggestions are welcome. Please feel free to comment.

Sunday, May 11, 2014

Simple java program to copy files on any OS.


  • This is a simple java program to copy files from anywhere to anywhere in the file system and on any operating system.
  • Scanner in util package to make inputs dynamic.
  • Using the program you just have to enter source of input file with file name and destination where it has to be placed.
  • The code calculates the time taken for the processing too.

 package com.objectStream;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.util.Scanner;  
 public class DemoObjectStreamRead {  
      static long startTime = System.currentTimeMillis();  
      static Scanner scanner = new Scanner(System.in);  
      static final String FORWARD_SLASH = "/";  
      static final String COLON = ":";  
      public static void main(String[] args) throws IOException {  
           System.out.println("Enter source: ");  
           String inputFile = scanner.next();  
           String file = "";  
           file = inputFile.split(COLON)[1];  
           System.out.println("Enter destination folder(s)");  
           String outputFile = scanner.next();  
           if (!new File(outputFile).exists()) {  
                new File(outputFile).mkdirs();  
           }  
           outputFile = outputFile.concat(FORWARD_SLASH + file);  
           File ipFile = new File(inputFile);  
           File opFile = new File(outputFile);  
           InputStream is = new FileInputStream(ipFile);  
           int read = 0;  
           byte[] bytes = new byte[1024];  
           FileOutputStream os = new FileOutputStream(opFile);  
           while ((read = is.read(bytes)) != -1) {  
                os.write(bytes, 0, read);  
           }  
           is.close();  
           os.flush();  
           os.close();  
           long endTime = System.currentTimeMillis();  
           long time = endTime - startTime;  
           System.out.println("time taken: " + (double) time / 100 / 60 + " mins");  
      }  
 }  

Feel free to comment. Suggestions and comments are appreciated.

Saturday, February 15, 2014

Top 10 basic UNIX/Linux commands

Hi everyone,  here are the basic UNIX commands that will be useful for the daily usage in the UNIX or Linux operating systems...

1. cd - Change directory

This command will be used very frequently when you're in an UNIX/Linux terminal to change from one directory to another.


Syntax: cd directory_name
            cd .. gives directory above the current directory
            cd / there is root directory above all directories, which is /, this command will navigate you to that directory.
             cd ~ Tilde key refers to the home directory of the current user, this command will navigate one to that directory.             

2. pwd - Print working directory

This command will be helpful when you want to know which directory you're currently working in.

Syntax: pwd

3. whoami & who

   i.) whoami: Prints the effective user. This command will let you know the current user.
       Syntax: whoami
   ii.) who: Prints the logged users for the current session.
       Syntax: who

4.) ls

This command will list the current directory contents. This is a very useful command.

Syntax: ls: lists directories
            ls -a: lists all directories.

5. cat - concatenate command

This command  can concatenate the files and print the output on console. It basically can combine contents of files, it can help us view the contents on console.

Syntax: consider we have two files file1 and file2, cat command can be used like this:
cat file1 file2
the combined output will be shown on screen.
One can also view the output of a single file using the command like this:
cat file1

6. clear - clear command

This command helps the user to clear the screen.

Syntax:  clear

7. less - less command

Some files may have contents that exceed the screen view, one can use less command and view the contents of a file without missing the content of the file from the screen, clicking enter one can view the contents of the file moving line by line or one can also use up and down arrows on keyboard to view the whole contents of the file.

Syntax: less fileName

8. head - head command

This command helps one to view the first 10 lines of a file by default. One can modify the command to view more or less than 10 lines.

Syntax: head fileName - gives the first 10 lines of the file.
           head -20 fileName - gives the first 20 lines of the file.

9. tail - tail command

This command helps one to view the last 10 lines of a file by default. One can modify the command to view more or less than 10 lines.

Syntax: tail fileName - gives the last 10 lines of the file.
            tail -20 fileName - gives the last 20 lines of the file.

10. ps - Snapshot of the current processes

This command is very useful, this shows the processes currently running.

Syntax: ps -e : This command shows the process ID (PID) and the process associated with the PID. This command is identical to another command ps -A (shows all processes).
            ps -ef : This command shows the user ID (UID), Process ID (PID), start time, and process.

Bonus: chmod - command that changes file permissions.

This command helps one to change file permissions for different users. Users are differentiated as Users, Groups and all others.

Users:
u - users
g - groups
a- all

Permissions:
r - read
w - write
x - execute

one can change the file permissions as follows:

chmod uga+rwx fileName - this command gives read, write and execute permissions to all the users (u,g,a).
chmod u+rw fileName - this command gives read and write permissions to user.

Octal notations for chmod:
r - 4
w - 2
x - 1

One can use the combination of the above permissions adding digits, for example user wants read and write permission, then 4+2 (r+w) gives 6, user wants full permission, then 4+2+1 (r+w+x) gives 7, for example you want to give user full permissions, groups read and write permissions and all others only read permissions, then the command is used like this:

chmod 764 fileName - here first digit is 7 combination of 4+2+1 (r+w+x) for user, 6 combination of 4+2 (r+w) for groups, 4 read permission for all.

Note: All the above commands are case sensitive.

Comments

blog comments powered by Disqus