Wednesday, November 20, 2013

Java XML




XML is widely used technology to transport or store data. Java Provides various API’s for processing XML; for example DOMSAXStAXJAXB. There are other APIs available for XML Processing, for exampleJDOM. Aimed to explore different kinds of XML Processing API’s and to learn some common tasks we need to perform with XML.
DOM XML Parser
DOM Parser is the easiest parser to learn, it loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.
  • Read XML File
  • Write XML File
  • Edit XML File

SAX XML Parser

Java SAX Parser provides API to parse XML documents. SAX Parsers are different than DOM parser because it doesn’t load complete XML into memory and read xml document sequentially. It’s an event based parser and we need to implement our Handler class with callback methods to parse XML file. It’s more efficient than DOM Parser for large XML files in terms of time and memory usage.
  • Read XML File

StAX XML Parser

Java Streaming API for XML (Java StAX) provides implementation for processing XML in java. StAX consists of two sets of API – cursor based API and iterator based API.
  • Read XML File Using StAX Iterator API
  • Write XML File Using StAX Iterator API
  • Read XML File Using StAX Cursor API
  • Write XML File Using StAX Cursor API

JDOM XML Parser

JDOM provides a great Java XML API to read, edit and write XML documents easily. JDOM provides wrapper classes to chose your underlying implementation from SAX Parser, DOM Parser, STAX Event Parser and STAX Stream Parser.
Benefit of using JDOM is that you can switch from SAX to DOM to STAX Parser easily, you can provide factory methods to let client application chose the implementation.
  • JDOM Read XML File
  • JDOM Write XML File
  • JDOM Edit XML File

JAXB

Java Architecture for XML Binding (JAXB) provides API for converting Object to XML and XML to Object easily. JAXB was developed as a separate project but it was used widely and finally became part of JDK in Java 6.
  • JAXB Tutorial
    Using JAXB is very easy and it uses annotations. We need to annotate Java Object to provide instructions for XML creation and then we have to create Marshaller to convert Object to XML.Unmarshaller is used to convert XML to java Object. It is most widely used JAXB annotations and how to convert a Java Object to XML (Marshalling) and XML to Java Object (Unmarhsalling).

XPath

XPath provides syntax to define part of an XML document. XPath Expression is a query language to select part of the XML document based on the query String. Using XPath Expressions, we can find nodes in any xml document satisfying the query string.
  • XPath Tutorial
    javax.xml.xpath package provides XPath support in Java. To create XPathExpression, XPath API provide factory methods. XPath query language to find out elements satisfying given criteria.

JiBX

JiBX is a very powerful framework for converting XML data to java object and vice versa. It is very useful in applications integration where XML is the format for data transfer, for example, Web Services and Legacy Systems Integration based on Message Oriented Model (MOM).
  • JiBX Tutorial
    There are many frameworks available for XML transformation such as JAXB and XMLBeans but JiBX differs in the approach for XML binding and transformation process. JiBX performs these tasks via utility classes generated at compile time via ant scripts. This approach reduces the processing time by moving away from the traditional two-step process with other parsers to a single step.

Different XML Tasks

  • Generate Sample XML from XSD in Eclipse
    If you work on webservices, you must have been using XSD’s and to test the webservice, you need to generate XML from XSD file. Eclipse provide a very easy way to generate XML from XSD.
  • Validate XML against XSD
    Java XML Validation API can be used to validate XML against an XSD. javax.xml.validation.Validatorclass is used to validate xml file against xsd file.
  • Java XML Property File
    Usually we store configurations parameters for java applications in a property file. In java property file can be a normal property file with key-value pairs or it can be an XML file also.
    In this example, we will learn how to write property XML file and then read properties from XML property files.
  • SOAP XML
    Soap is an Xml based transport protocol. Soap stands for Simple Object Access Protocol. Soap is a lightweight mechanism for exchanging structured and typed information. As it is XML based so it is language and platform independent.
    SOAP XML and how can we create it using Liquid XML Studio software.
  • Format XML Document
    A utility class with methods for pretty printing XML and converting XML Document to String and String to XML document.
  • Convert Document to String and String to Document
    Sometimes while programming in java, we get String which is actually an XML and to process it, we need to convert it to XML Document (org.w3c.dom.Document). Also for debugging purpose or to send to some other function, we might need to convert Document object to String. Two utility methods to convert String to XML Document and XML Document to String.

Tuesday, November 19, 2013

Eclipse Java Debugging


Watch Point

This is one nice feature I love. When a chosen attribute is accessed or modified program execution will halt and allow to debug. Select a class variable in Outline view and from its context menu select Toggle Watchpoint. This will create a watch point for that attribute and it will be listed in Breakpoints view.

Exception Breakpoint

In Breakpoints view there is a button labeled as J! We can use that button to add a java exception based breakpoint. For example we want the program to halt and allow to debug when a NullPointerException is thrown we can add a breakpoint using this.

Conditional Breakpoint

Hope we know how to add a breakpoint. If not, just click on the left pane (just before the line number) and a breakpoint will be created. In debug perspective, ‘Breakpoints’ view will list the breakpoint created. We can add a boolean condition to it. That is, the breakpoint will be activated and execution will hold only if the boolean condition is met otherwise this breakpoint will be skipped.

Evaluation (Display or Inspect or Watch)

Ctrl+Shift+d or Ctrl+Shift+i on a selected variable or expression will show the value. We can also add a permanent watch on an expression/variable which will be shown in Expressions view when debug is on.

Change Variable Values

We can change the value of a variable on the fly during debug. Choose a variable and go to Variables view and select the value, type and enter.

Stop in Main

In Run/Debug Settings, Edit Configuration we can enable a check box that says Stop in main. If enabled when we debug a java program that launches with a main method, the execution halts at first line of main method.

Environment Variables

Instead of going to System properties to add an environment variable, we can conveniently add it through Edit Configuration dialog box.

Drop to Frame

This is the second best feature I love. We can just return the control to any frame in the call stack during debug. Changes made to variables will not be reset. Choose the stack level which you want to go back and restart debug from there and click the drop to frame button from debug toolbar. Eclipse is cool!

Step Into, Over and Return

I kept this as the last point as this is the first thing to learn in debugging :-)
  • F5 – Step Into: moves to next step and if the current line has a method call the control will go into the first line of the called method.
  • F6 – Step Over: moves the control to next line. If there is a method call in the current line, it executes the method call internally and just moves the control to next line.
  • F7 – Step Return: When done from inside a method the control will move to the calling line from where the current method is invoked.
  • F8 – Move to next breakpoint.

Step Filter

When we Step Into (F5) a method we may go into external libraries (like java) and we may not need it. We can add a filter in preferences and exclude packages.



Wednesday, November 6, 2013

Attach JDK Source Code



In Eclipse, select Windows -> Preferences -> Java -> Installed JREs , expands rt.jar, select “Source attachment” and find the src.zip from your disk drive.

e.g C:\Program Files\Java\jdk1.7.0\src.zip

Similarly we can add the web source file like servlet or JSP.

Tuesday, November 5, 2013

Windows Host file



The hosts file is a computer file used by an operating system to map hostnames to IP addresses

One of the lesser known, but important files included with Windows is the hosts file. It's a simple text file without a file extension that was designed to map or override IP addresses before accessing a domain name server. Recently, it's taken a more protective role in ad blocking and stopping spyware.

Another way to think of a hosts file is as an address translator and redirector. If you went to New York City and asked to go to the New York Times Company, someone would translate your request into 229 West 43rd Street. A similar process happens on the web. Your browser first checks your hosts file to see if it has an IP address for sdfgsdfg.com. If the hosts file has an entry it is used, otherwise a domain name server is queried to get the IP address of 199.239.136.200. (Yes, technically, you can enter that IP address into your browser's address bar and get to www.asdfg.com.)

One benefit of using the hosts file is precedence. Most systems access this file first because it's loaded into the computer's memory at start up. There are some exceptions such as people who use proxy servers.
When various types of Internet advertisements became invasive, some people used the hosts file as a means to bypass the ads. People would add an entry to their hosts file that redirected an ad server away from the intended destination. Or, using our analogy from above we could redirect the New York Times traffic to your home address.

This redirection can be accomplished by adding a line such as the following to the hosts file:

127.0.0.1 www.dgdfgdfg.com # ad server for XYZ company

In the above example, when your web browser encounters a request for www.xdfgdfgyz.com, it would look in the hosts file and find the entry 127.0.0.1. This IP address is a universal address assigned to the localhost that is your PC. So, rather than going to the true IP address for the XYZ ad server, the request would stop at your PC and the ad wouldn't appear. You can also add a # sign and comment to identify the site.
While this ad blocking method works, there are consequences. The web page may not format correctly depending on the ad. Moreover, many small specialty sites and blogs rely on ad income to offset their costs.

Alternate Uses of Hosts File
This same process is also used by some anti-spyware and ad-blocking packages. Instead of redirecting ad servers, they protect you by preventing access to various sites. Typically, these are sites that have spyware, malware or adult-orientated material. Some of these programs also lock the hosts file or alert you if there have been changes.
Because the file can redirect traffic, some malicious programs have tried to insert entries into this file for their purposes. One morning, you type http://www.nytidgdfgdmes.com/ and you're now staring at some adult site in Eastern Europe. Sorry, the hosts file doesn't do any site verification. If there is an entry for the New York Times that maps to an IP address in Eastern Europe, well that's where your browser will go. As this example illustrates, you can be hijacked as you can use any IP address and not just 127.0.0.1.

Location of the Windows Hosts File
The good news is you control the hosts file. You can easily add, edit or delete entries using a text editor such as Windows Notepad. The exception is Windows Vista. Microsoft support has provided a knowledge base article on modifying the hosts or lmhosts file.

It's probably worth 5 minutes to look at the file in case you ever need to change the contents. The hardest part, is probably finding the file as the location differs based on which Windows operating system you are using.

Windows 95 - C:windows
Windows 98 - C:\windows
Windows Me - C:\windows
Windows 2000 - C:windows\system32\drivers\etc
Windows XP - C:\windows\system32\drivers\etc
Windows NT - C:\winnt\system32\drivers\etc
Windows Vista - C:\windows\system32\drivers\etc
Windows 7 - C:\windows\system32\drivers\etc

If you want to find out more about hosts file, there are plenty of articles and resources. Some people have compiled their own lists that you can download. Others have programs that make editing the file easier. And if you do decide to change your hosts file, please remember to make a backup first. You'll also need to reboot your computer to have the changes work.



Windows 7

To access the hosts file in Windows 7 you can use the following command in the Run Line to open notepad and the file.
notepad c:\windows\system32\drivers\etc\hosts
sshot-2010-08-31-[19-41-19]
Once notepad is open you can edit the file. In this example we will block Facebook. To do this just enter in the following after the # mark.
0.0.0.0    www.facebook.com
Now that you have edited your Hosts file make sure to save it.
Now notice if we try to access Facebook in IE we can’t get to the page.

Windows 7

  1. Open Notepad in Run as Administrator mode.
  2. Now you can see these lines...
    # localhost name resolution is handled within DNS itself.
    #    127.0.0.1           localhost
    #    ::1                 localhost
    
  3. Add new line for your domain.
  4. After the change it will be like this...
    # localhost name resolution is handled within DNS itself.
    #      127.0.0.1             localhost
    #      ::1                   localhost
           10.40.0.9             xxx.com  
           10.40.0.10            yyy.com
    
  5. Now save the hosts file. If it prompts to save it elsewhere then you forgot to open Notepad as administartor.
  6. Go to Windows' command promt and run this command ipconfig /flushdns
  7. Open your browser and try to browse xxx.com and yyy.com etc. Should work fine.