Archive

Archive for the ‘Java’ Category

Convert Java POJO object to XML String

September 6, 2012 Leave a comment

Here is the sample to convert Java POJO Object to XML String using JAXB utility and explained it detaily from Java pojo object creation from Schema to End.
 
1.Student.xsd :

<?xml version="1.0" encoding="windows-1252" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns="http://www.com.wordpress.rathinasaba.sample"
            targetNamespace="http://www.com.wordpress.rathinasaba.sample"
            elementFormDefault="qualified">
  <xsd:element name="students">
    <xsd:complexType>
      <xsd:sequence>
            <xsd:element name="student" type="studentType" minOccurs="0" maxOccurs="unbounded"/>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:key name="student-id">
      <xsd:selector xpath="student"/>
      <xsd:field xpath="@id"/>
    </xsd:key>
  </xsd:element>
  
  <xsd:complexType name="studentType">
    <xsd:sequence>
      <xsd:element name="name" type="xsd:string"/>
      <xsd:element name="age" type="xsd:integer"/>
      <xsd:element name="major" type="xsd:string" maxOccurs="unbounded"/>
      <xsd:element name="results">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="result" minOccurs="0" maxOccurs="unbounded">
              <xsd:complexType>
                <xsd:attribute name="course" type="xsd:string"/>
                <xsd:attribute name="grade" type="Grade"/>
              </xsd:complexType>
            </xsd:element>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
    <xsd:attribute name="id" type="xsd:string" use="required"/>
  </xsd:complexType>
  
  <xsd:simpleType name="Grade">
    <xsd:restriction base="xsd:string">
      <xsd:enumeration value="A"/>
      <xsd:enumeration value="A-"/>
      <xsd:enumeration value="B+"/>
      <xsd:enumeration value="B"/>
      <xsd:enumeration value="B-"/>
      <xsd:enumeration value="C+"/>
      <xsd:enumeration value="C"/>
      <xsd:enumeration value="C-"/>
      <xsd:enumeration value="D+"/>
      <xsd:enumeration value="D"/>
      <xsd:enumeration value="D-"/>
      <xsd:enumeration value="F"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>

 

2. Generate Java Objects from Schema ( Student.xsd ) :
1. Right Click Student.xsd , Select Generate –> JAXBClasses.
 

GenerateObjectUsingJAXB

GenerateObjectUsingJAXB


 

2. In this promt Choose package then Click Finish and the Java objects will be generated into the package you have selected.
 

Prompt

Prompt


 

GeneratedClasses

GeneratedClasses


 

3.Java class to convert Object to XML String using JAXB :
 

package com.wordpress.rathinasaba.sample.client;

import java.io.StringWriter;
import java.math.BigInteger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.wordpress.rathinasaba.sample.StudentType;
import com.wordpress.rathinasaba.sample.StudentType.Results;
import com.wordpress.rathinasaba.sample.StudentType.Results.Result;
import com.wordpress.rathinasaba.sample.Students;

public class SampleJava_PojoToXmlStr {

	/**
	 * JAXB Java Pojo objects location
	 */
	private static final String JAXB_PATH="com.wordpress.rathinasaba.sample";
	/**
	 * Main method
	 * @param args
	 */
	public static void main(String[] args) {
		String responseXMLStr=convertObjectToStr(prepareStudentObj());
		System.out.println("--- Response XML Str -:"+responseXMLStr);
	}
	/**
	 * This method is used to convert the POJO object to XML String using JAXB Utility
	 * @param pojoObject
	 * @return
	 */
	public static String convertObjectToStr(Object pojoObject){
		JAXBContext jaxbContext = null;
		Marshaller marshaller = null;
		StringWriter writer=null;
		try {
			jaxbContext=JAXBContext.newInstance(JAXB_PATH);
			marshaller = jaxbContext.createMarshaller();
			writer= new StringWriter();
			marshaller.marshal(pojoObject, writer);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return writer.toString();
	}
	
	/**
	 * Preparing Students Object
	 * @return Students
	 */
	private static Students prepareStudentObj(){
		Students students=new Students();
		
		StudentType student1=new StudentType();
		student1.setId("1000");
		student1.setName("Rathina");
		student1.setAge(new BigInteger("15"));
		
		Results results=new Results();
		Result result1=new Result();
		result1.setCourse("Maths");
		result1.setGrade("A");
		Result result2=new Result();
		result2.setCourse("Science");
		result2.setGrade("A-");
		
		results.getResult().add(result1);
		results.getResult().add(result2);
		student1.setResults(results);
	
		students.getStudent().add(student1);
		
		return students;
	}
}
Advertisements
Categories: Java Tags: , ,

Convert XML File To XMLElement

September 6, 2012 Leave a comment

Here is the Sample to convert XML File to oracle.xml.parser.v2.XMLElement .

package com.wordpress.rathinasaba.sample;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import oracle.xml.parser.v2.XMLDocument;
import oracle.xml.parser.v2.XMLElement;

public class SampleJava {

	public static void main(String[] args) {
		String filePath="C:/Saba/workspace/java/RequestXML/Fault.xml";
		XMLElement xmlElement=getXMLElement(filePath);
		printXML(xmlElement.getDocument());
	}
/**
 * This method will convert the XML file into oracle.xml.parser.v2.XMLElement by accepting the filePath
 * @param filePath
 * @return oracle.xml.parser.v2.XMLElement
 */
	private static XMLElement getXMLElement(String filePath) {
		XMLDocument xmlDoc = null;
		try {
			DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
			domFactory.setNamespaceAware(true);
			DocumentBuilder builder = domFactory.newDocumentBuilder();
			Document doc = builder.parse(new File(filePath));
			xmlDoc = new XMLDocument();
			xmlDoc.appendChild(xmlDoc.importNode(doc.getDocumentElement(), true));
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return (XMLElement) xmlDoc.getDocumentElement();
	}
	/**
	 * This method is to Print org.w3c.dom.Document 
	 * @param doc
	 */
	private static void printXML(Document doc)  {
		try {
			TransformerFactory tfactory = TransformerFactory.newInstance();
			Transformer xform = tfactory.newTransformer();
			javax.xml.transform.Source src=new DOMSource(doc);
			java.io.StringWriter writer = new StringWriter();
			Result result = new javax.xml.transform.stream.StreamResult(writer);
			xform.transform(src, result);
			System.out.println("-- payload --:"+writer.toString());
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
}

XPath sample with namespace in Java

August 1, 2012 Leave a comment

Here is the simple example to show the element values of xml file using XPath APIs.

1. Person.xml needs to be parsed using XPath APIs:

<?xml version="1.0" encoding="UTF-8"?>
<pn:Person xmlns:pn="http://www.com.room.xpath.sample">
	<pn:name>
		<pn:firstName>Raja</pn:firstName>
		<pn:middlName>Kumar</pn:middlName>
		<pn:lastName>Robot</pn:lastName>
	</pn:name>
	<pn:title>MR</pn:title>
	<pn:address>
		<pn:streetNo>No.19</pn:streetNo>
		<pn:streetName>Rose St</pn:streetName>
		<pn:city>Sydney</pn:city>
		<pn:state>NSW</pn:state>
		<pn:postalCode>2067</pn:postalCode>
	</pn:address>
</pn:Person>

2. NamespaceContextMap.java

package com.room.xpath.sample;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;

public final class NamespaceContextMap implements
    NamespaceContext {

  private final Map<String, String> prefixMap;
  private final Map<String, Set<String>> nsMap;

  /**
   * Constructor that takes a map of XML prefix-namespaceURI values. A defensive
   * copy is made of the map. An IllegalArgumentException will be thrown if the
   * map attempts to remap the standard prefixes defined in the NamespaceContext
   * contract.
   * 
   * @param prefixMappings
   *          a map of prefix:namespaceURI values
   */
  public NamespaceContextMap(
      Map<String, String> prefixMappings) {
    prefixMap = createPrefixMap(prefixMappings);
    nsMap = createNamespaceMap(prefixMap);
  }

  /**
   * Convenience constructor.
   * 
   * @param mappingPairs
   *          pairs of prefix-namespaceURI values
   */
  public NamespaceContextMap(String... mappingPairs) {
    this(toMap(mappingPairs));
  }

  private static Map<String, String> toMap(
      String... mappingPairs) {
    Map<String, String> prefixMappings = new HashMap<String, String>(
        mappingPairs.length / 2);
    for (int i = 0; i < mappingPairs.length; i++) {
      prefixMappings.put(mappingPairs[i], mappingPairs[++i]);
    }
    return prefixMappings;
  }

  private Map<String, String> createPrefixMap(
      Map<String, String> prefixMappings) {
    Map<String, String> prefixMap = new HashMap<String, String>( prefixMappings);
    addConstant(prefixMap, XMLConstants.XML_NS_PREFIX,XMLConstants.XML_NS_URI);
    addConstant(prefixMap, XMLConstants.XMLNS_ATTRIBUTE,XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    return Collections.unmodifiableMap(prefixMap);
  }

  private void addConstant(Map<String, String> prefixMap,
      String prefix, String nsURI) {
    String previous = prefixMap.put(prefix, nsURI);
    if (previous != null && !previous.equals(nsURI)) {
      throw new IllegalArgumentException(prefix + " -> "
          + previous + "; see NamespaceContext contract");
    }
  }

  private Map<String, Set<String>> createNamespaceMap(
      Map<String, String> prefixMap) {
    Map<String, Set<String>> nsMap = new HashMap<String, Set<String>>();
    for (Map.Entry<String, String> entry : prefixMap
        .entrySet()) {
      String nsURI = entry.getValue();
      Set<String> prefixes = nsMap.get(nsURI);
      if (prefixes == null) {
        prefixes = new HashSet<String>();
        nsMap.put(nsURI, prefixes);
      }
      prefixes.add(entry.getKey());
    }
    for (Map.Entry<String, Set<String>> entry : nsMap
        .entrySet()) {
      Set<String> readOnly = Collections
          .unmodifiableSet(entry.getValue());
      entry.setValue(readOnly);
    }
    return nsMap;
  }

  @Override
  public String getNamespaceURI(String prefix) {
    checkNotNull(prefix);
    String nsURI = prefixMap.get(prefix);
    return nsURI == null ? XMLConstants.NULL_NS_URI : nsURI;
  }

  @Override
  public String getPrefix(String namespaceURI) {
    checkNotNull(namespaceURI);
    Set<String> set = nsMap.get(namespaceURI);
    return set == null ? null : set.iterator().next();
  }

  @Override
  public Iterator<String> getPrefixes(String namespaceURI) {
    checkNotNull(namespaceURI);
    Set<String> set = nsMap.get(namespaceURI);
    return set.iterator();
  }

  private void checkNotNull(String value) {
    if (value == null) {
      throw new IllegalArgumentException("null");
    }
  }

  /**
   * @return an unmodifiable map of the mappings in the form prefix-namespaceURI
   */
  public Map<String, String> getMap() {
    return prefixMap;
  }

}

3. XPathTest.java

package com.room.xpath.sample;

import java.io.IOException;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathTest {
	public static void main(String[] args) {
		try {
			Document doc=getDoc("Person.xml");
			XPath xpath=getXPath();
			xpath.setNamespaceContext(getNamespaceContext());
			XPathExpression expr = xpath.compile("//pn:name/*/text()");
			Object result = expr.evaluate(doc, XPathConstants.NODESET);
			NodeList nodes = (NodeList) result;
			for (int i = 0; i < nodes.getLength(); i++) {
				System.out.println(nodes.item(i).getNodeValue());
			}
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		} catch (DOMException e) {
			e.printStackTrace();
		}
	}

	private static Document getDoc(String fileName) {
		Document doc=null;;
		try {
			DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
			domFactory.setNamespaceAware(true);
			DocumentBuilder builder = domFactory.newDocumentBuilder();
			doc = builder.parse("Person.xml");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}

	private static XPath getXPath() {
		return XPathFactory.newInstance().newXPath();
	}

	private static NamespaceContext getNamespaceContext() {
		NamespaceContext context = new NamespaceContextMap("pn","http://www.com.room.xpath.sample");
		return context;
	}
}

Change default port 8080 in Oracle XE

April 22, 2011 24 comments

When two services in system running with the same port, example “8080”, you cant able to get access to those services. For this we have to change the listening port number of any services to other than “8080” port.

Here I have given how to change the listening port number of Oracle XE Database.

1. To get the current HTTP Listener Port number and FTP Port number, use the below query

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\Room>sqlplus

SQL*Plus: Release 10.2.0.1.0 - Production on Fri Apr 22 19:05:48 2011

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Enter user-name: system
Enter password:

Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

SQL> select dbms_xdb.gethttpport as "HTTP-Port",dbms_xdb.getftpport as "FTP-Port
" from dual;

 HTTP-Port   FTP-Port
---------- ----------
      8090          0

SQL>

2. To change the HTTP Listener Port number, use the below single command in SQL window.


SQL> begin
  2  dbms_xdb.sethttpport('80');
  3  end;
  4  /

Categories: sql Tags: , ,

Connecting to an Oracle database using Java

January 4, 2011 1 comment

This example uses JDBC Driver to connect to an Oracle database instance located in localhost.

sample connection string for Oracle DB

                     jdbc:oracle:thin:@localhost:1521:oracle

Find the connection string details from tnsnames.ora file located in Oracle Database installation directory

ORACLE_HOME\product\11.2.0\dbhome_1\NETWORK\ADMIN
ORACLE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = oracle)
    )
  )

Here the Sample code to connect with Oracle Database.

package com.room.db.connection;

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

public class DBConnectionTest {

	/**
	 * This method is to get the Database connection
	 * @return
	 */
	public static Connection getConnection(){
		Connection connection=null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oracle", "system", "password");
			System.out.println("--- java.sql.Connection created ----");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
	/**
	 * This method is for closing the connection resources
	 * @param rs
	 * @param stmt
	 * @param conn
	 */
	public static void closeConnection(ResultSet rs,Statement stmt,Connection conn){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				rs=null;
			}
		}
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				stmt=null;
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				conn=null;
			}
		}
	}
	
       /**
	 * Main method to test the DB Connection and querying the DB              version
	 * @param args
	 */
	public static void main(String[] args) {
//		System.out.println(DBConnectionTest.getConnection());
		Connection conn=null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
			conn=getConnection();
			stmt=conn.createStatement();
			final String query="select BANNER from SYS.V_$VERSION";
			rs=stmt.executeQuery(query);
			while(rs.next()){
				System.out.println (rs.getString(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeConnection(rs, stmt, conn);
		}
		
	}
}
Categories: Java, sql

Coverting String to Date and vise versa

December 30, 2010 Leave a comment

Here I have given the sample for converting String to Date object and vice versa using java.text.SimpleDateFormat class.

package com.room.date.sample;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCoversion {

	private static final String DDMMYYYY_FMT = "dd/MM/yyyy";
	private static final DateFormat df = new SimpleDateFormat(DDMMYYYY_FMT);

	public static Date convertStringToDate(String dateStr) {
		try {
			return df.parse(dateStr);
		} catch (ParseException exc) {
			exc.printStackTrace();
			return null;
		} catch (Exception exc) {
			exc.printStackTrace();
			return null;
		}
	}

	public static String convertDateToString(Date date) {
		try {
			return df.format(date);
		} catch (Exception exc) {
			return null;
		}
	}

	public static void main(String[] args) {
		System.out.println("StringToDate ----:" + convertStringToDate(null));
		System.out.println("DateToString ----:"	+ convertDateToString(new Date()));
	}
}

Categories: Java

Converting InputStream to String and vise versa

December 29, 2010 Leave a comment

Here I have given the simple sample to convert InputStream object into String .

Create one file under the source folder.

package com.room.inputstreamtostring.sample;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class InputStreamToString {

	public static String convertInputStreamToString(InputStream inputStream){
		Writer writer=new StringWriter();
		char[] buffer=new char[1024];
		try {
			BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			int n;
			while((n=reader.read(buffer)) != -1){
				writer.write(buffer,0,n);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return writer.toString();
	}
	
	public static boolean isEmpty(String payload){
		return payload==null || "".equals(payload.trim());
	}
	
	public static InputStream convertStringToInputStream(String payload){
		InputStream is=null;
		try {
			if(!isEmpty(payload)){
				is=new ByteArrayInputStream(payload.getBytes("UTF-8"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}	
		return is;
	}
	
	public static String readFile(String filename){
		File file=new File(filename);
		StringBuffer buffer=new StringBuffer();
		BufferedReader bufferReader=null;
		try {
			bufferReader=new BufferedReader(new FileReader(file));
			String text;
			while((text=bufferReader.readLine())!=null){
				buffer.append(text).append(System.getProperty("line.separator"));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	
	public static void main(String[] args) {
		// Converting InputStream to String
		InputStreamToString instance=new InputStreamToString();
		InputStream stream=instance.getClass().getResourceAsStream("/struts.xml");
		System.out.println(convertInputStreamToString(stream));
		
		//Converting String to InputStream
		String text=readFile("./struts.xml");
		System.out.println("read file --:"+text);
		System.out.println(convertStringToInputStream(text));
	}
}