Monday, September 24, 2012

XML Parsing in java

This sample code reads the XML file using DOM parser. DOM parser loads the XML file into the memory and makes an object model of it. This Object modal can be traversed to get its elements.


This code will parse the following MyXMLFile.xml file and print its elements to the console.


XML file: MyXMLFile.xml
<?xml version="1.0"?> 
  <company>
     <employee>
       <firstname>Tom</firstname> 
       <lastname>Cruise</lastname> 
     </employee> 
     <employee> 
           <firstname>Paul</firstname> 
           <lastname>Enderson</lastname> 
     </employee> 
     <employee>
           <firstname>George</firstname>
          <lastname>Bush</lastname>
     </employee>
  </company> 


import java.io.File;
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;

public class XMLReader {

public static void main(String argv[]) {

try {
File file = new File("c:\\MyXMLFile.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("employee");
System.out.println("Information of all employees");

for (int s = 0; s < nodeLst.getLength(); s++) {

Node fstNode = nodeLst.item(s);

if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
}

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

@SRC: http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html

Tuesday, January 3, 2012

What is OData and How to test OData calls




The Open Data Protocol (OData) is an open web protocol for querying and updating data. The protocol allows for a consumer to query a datasource over the HTTP protocol and get the result back in formats like Atom, JSON or plain XML, including pagination, ordering or filtering of the data.


Many of the building blocks that make up OData are standardized via Atom and AtomPub. The OData specification is available under the Microsoft Open Specification Promise (OSP). Microsoft has released an OData software development kit (SDK) consisting of libraries for .NET, PHP, Java, JavaScript, webOS, and the iPhone.

How to test?

Firefox plugin called "Rest Client" is available to test OData calls.

Ways to test various CRUD operations:

1. CREATE:

    Set Method = POST
    content-type = application/atom+xml
    Enter payload in "Request Body" and execute.

2. UPDATE:
    We can use Method = PUT, but this is kind of outdated instead user Merge. To use MERGE set header
    X-HTTP-METHOD = MERGE.
    URI = http://mysite.com/services/odata/user('user_id')
    Enter valid payload and execute the operation.

3. DELETE:
    Method = DELETE
    URI = http://mysite.com/services/odata/user('user_id')
    execute the operation.

Wednesday, December 14, 2011

How to enable remote access to MySQL server on Windows


1. Open a DOS command prompt on the server.
2. Run the following command from the mysql\bin directory:
mysql -u root --password=
or type "mysql -uROOT -pPASSWORD" directly in command prompt, if you added mysql\bin to PATH environment variable.
3. A mysql> prompt should be displayed.
4. To create a remote user account with root privileges, run the following commands:
GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'IP' IDENTIFIED BY 'PASSWORD';

'USERNAME' is the username to be created.
'IP' is the public IP address of the remote connection.
'PASSWORD' is the password to be assigned for this username.
(IP can be replaced with % to allow this user to logon from any host or IP)

mysql> FLUSH PRIVILEGES;
mysql> exit;

Thursday, December 1, 2011

Reading Property Files in java


Load property files via static blocks and retrieve them file those block when ever you want to read a property. This way we don't have to open file stream when we want to read a property.

private static Properties prop = null;
static{
java.io.InputStream inst = MyClass.class.getClassLoader().getResourceAsStream("com/../../Resources/PropFile.properties");
prop=new Properties();
try {
prop.load(inst);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

//Retrieving value of a key
prop.getProperty("Key")

Friday, October 14, 2011

Using Logger in Java

Logger is very important in many applications, using logger we can log message in a program/project.
Steps to use logger:
1. Download "logging-log4j.X.X.X" from apache website and extract it to your favorite place.
2. Add "logging-log4j.X.X.X\dist\lib" to your "classpath" environment variable.
Note: Download and adding "xercesImpl.jar", "xmlParserAPIs.jar" to classpath if you have any issues.
3. Add "log4j.jar" to "Referenced Libraries" folder of your Java project.
4. create "log4j.properties" file in "/src" folder with below content
#-----Content start

log4j.rootCategory=INFO, S, R

log4j.logger.com.dappit.Dapper.parser=ERROR
log4j.logger.org.w3c.tidy=FATAL

log4j.appender.S = org.apache.log4j.ConsoleAppender
log4j.appender.S.layout = org.apache.log4j.PatternLayout
log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n

log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File = ./logs/MyLog.log
log4j.appender.R.Append = true
log4j.appender.R.DatePattern = '.'yyy-MM-dd
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
#---Content end

4. Create your class file, add import statement like "import org.apache.log4j.*;"
5. Instantiate logger "Logger log = Logger.getLogger(LoggerUsage.class);"
Note: Here "LoggerUsage" will be your class where you are using logger.
6. Start logging various incidents like

log.info("Logging info");
log.error("Logging Error...");
7. This will log print message to console and also to a file "/logs/MyLog.log" because we added below entry in log4j.properties file.
log4j.appender.R.File = ./logs/MyLog.log


If log4j.jar is not found in classpath then we get error saying
"log4j:WARN Please initialize the log4j system properly."