Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Generating Java objects from XML files

I found a great tool called XStream that can generate Java objects directly from the XML. Previously, I used XMLBeans but this requires the XMLSchema to be generated. Moreover, installation process is bit hard. But with XStream, its pretty easy to create java objects from XMLs and getting XMLs from objects. Here I provide complete example, which is the extension of the code given in XStream's official site.

Requirements: 
Three Files:  XstreamTest.java , Person.java, PhoneNumber.java
Library: xstream-1.4.3.jar
 JDK: 1.6xxx

1. XstreamTest.java 
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XstreamTest {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Person joe = new Person("Joe", "Walnes");
        joe.setPhone(new PhoneNumber(123, "1234-456"));
        joe.setFax(new PhoneNumber(123, "9999-999"));
        XStream xstream = new XStream(new StaxDriver());
        String xml = xstream.toXML(joe);

        System.out.println(xml);
        Person p1 = (Person)xstream.fromXML(xml);
        System.out.println("Phone no:"+p1.getPhone().getNumber());
    }

}



2. Person.java
public class Person {
      private String firstname;
      private String lastname;
      private PhoneNumber phone;
      private PhoneNumber fax;
        public Person(String fname,String lname){
            this.firstname=fname;
            this.lastname=lname;
        }
        public String getFirstname() {
            return firstname;
        }
        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }
        public String getLastname() {
            return lastname;
        }
        public void setLastname(String lastname) {
            this.lastname = lastname;
        }
        public PhoneNumber getPhone() {
            return phone;
        }
        public void setPhone(PhoneNumber phone) {
            this.phone = phone;
        }
        public PhoneNumber getFax() {
            return fax;
        }
        public void setFax(PhoneNumber fax) {
            this.fax = fax;
        }  
}

3. PhoneNumber.java
public class PhoneNumber {
    private int code;
    private String number

    public PhoneNumber(int i, String string) {
        this.code=i;
        this.number=string;
    }
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
   
}

OUTPUT: 
JoeWalnes1231234-4561239999-999
Phone no:1234-456

Generate XSD from XML

Sometimes we need to generate XML-Schema (e.g. XSD) from a given XML document. There are many tools but the one I use is called trang. Here are simple steps to generate xsd of a xml file (input.xml):

1. Download and Unzip trang-20030619.zip
2. Go to trang-20030619 folder and use following command:
java -jar trang.jar -I xml -O xsd input.xml output.xsd

Creating a RSS Feed using ROME

Creating a RSS Feed using Java is straightforward. You just need to know how to use ROME API. The website presents some sample codes too. Following code, copied from Codeidol.com, will be useful.

Scanner Class in Java

When I started learning Java around 8 years ago, I had a  problem. Because I'd already known C and C++, it was very hard for me to get input from console using Java code. C and C++ need just a line to get input whereas for Java we'd required a lot. Now it's more easier using Scanner class :

Reading From Keyboard :
import java.util.Scanner;

public class ScannerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//
// Read string input for username
//
System.out.print("Username: ");
String username = scanner.nextLine();
//
// Read string input for password
//
System.out.print("Password: ");
String password = scanner.nextLine();
//
// Read an integer input for another challenge
//
System.out.print("What is 2 + 2: ");
int result = scanner.nextInt();
if (username.equals("admin") && password.equals("secret") && result == 4) {
System.out.println("Welcome to Java Application");
} else {
System.out.println("Invalid username or password, access denied!");
}
}
}

Note: Code is taken from this URL.

Reading From File:
import java.util.Scanner;
import java.io.*;
class HelpFile
{
    public static void main(String[] args) throws IOException
    {
        Scanner scanner = new Scanner(new File("test.txt"));
        while (scanner.hasNextLine())
         System.out.println(scanner.nextLine());
    }
}


Reading From Socket:
Scanner remote = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
 //read line from keyboard
line = keyboard.nextLine();
 //send line to remote node
 out.println(line);
 //wait for a line from remote node
line = remote.nextLine();       

Text Normalizer - Dealing with ascents

I had to sort French texts in alphabetical order. It was not as simple as we compare English strings because we must deal with the French ascents such as é and à.
If we don't process anything and use the simple string comparison function, we get équipement after zebra. However, we need équipement between words starting from 'd' and 'f' i.e. we want  équipement as if it were equipement. In order to solve the problem, we must compare strings after we normalize and remove Diacritic:

String normalizedStr1=Normalizer.normalize(Text1, Normalizer.Form.NFD).replaceAll("[\u0300-\u036F]", "");

String normalizedStr2=Normalizer.normalize(Text2, Normalizer.Form.NFD).replaceAll("[\u0300-\u036F]", "");

Now we make comparison between normalizedStr1 and normalizedStr2 instead of Text1 and Text2.

TPTP - A Java Profiling Tool

In software engineering, program profiling, software profiling or simply profiling, a form of dynamic program analysis (as opposed to static code analysis), is the investigation of a program's behavior using information gathered as the program executes. The usual purpose of this analysis is to determine which sections of a program to optimize - to increase its overall speed, decrease its memory requirement or sometimes both.

The set of profiling tools provides software developers or testers with the ability to analyze the performance of a Java program or to gain a comprehensive understanding of the overall performance of an application. Eclipse Test and Performance Tools Platform (TPTP) is such a tool used for profiling. A good tutorial is here: Tutorial.

Finding 'a word' using Regular Expression

We frequently need to test where a word (rather than pattern) exists in other string or not. To illustrate more, consider the following two strings:

String1: This fact is very important to understand.
String2: port

Now  two interesting cases arise:
  • Find whether pattern "port" appears in String1: In this case the regular expression would be: String regExp=".*"+ String2 +".*"; Clearly, we don't care what comes before and after the pattern. It would be true because port pattern in there in String1 (the word important contains it)
  • Find whether a word "port" appears in String1. Regular expression in this case is : String regExp=".*\\b"+ String2 +"\\b.*"; Following Java code is used to test this:
String regExp=".*\\b"+String2+"\\b.*";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(String1);
if( m.matches())
{

}
It fails here because "port" as a word doesn't appear in String1. It just appears as a pattern. If String1="The port was far" then the pattern matches because port appears as a word.

Key role is played by the \b of regular expression which is used to find word in a string.

Java Reflection

Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

References:
  1. Tutorials at jenkov.com

Properties in Java

Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values. The key identifies, and is used to retrieve, the value, much as a variable name is used to retrieve the variable's value. For example, an application capable of downloading files might use a property named "download.lastDirectory" to keep track of the directory used for the last download.
To manage properties, create instances of java.util.Properties. This class provides methods for the following:
  • loading key/value pairs into a Properties object from a stream,
  • retrieving a value from its key,
  • listing the keys and their values,
  • enumerating over the keys, and
  • saving the properties to a stream.

References:
  1. Properties in JAVA