Tuesday, September 26, 2017

XML Parsing - DOM / SAX /StAX


Reference links:
https://examples.javacodegeeks.com/core-java/xml/java-xml-parser-tutorial/
https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/


The code : https://github.com/dianaplazar10/JAVAproject.git

An XML document consists of elements. Each element has a start tag, its content and an end tag. Also, an XML document must have exactly one root element.

In java, there are 3 ways of parsing an XML:

1) DOM parser : 

The DOM(Document Object Model) parser parses the entire XML document and loads the XML content into a Tree structureUsing the Node and NodeList classes, we can retrieve and modify the content of an XML file.

Inside the main method, we 

  • create a DocumentBuilder from the DocumentBuilderFactory and then, 
  • parse and store the XML file in an instance of the Document class. 
  • Then, we parse that document and when we find a node of type Node.ELEMENT_NODE
  • we retrieve all its information and store them in an instance of the Employee class. 
  • Finally, we print the information of all stored employees.
  • APIs used: DocumentBuilder, Document, NodeList, Node, Element


2) SAX parser : 

SAX(event-based Sequential Access parser API) parser only needs to report each parsing event as it happens and the minimum memory required for a SAX parser is proportional to the maximum depth of the XML file.



  • APIs used: SAXParserFactory, SAXParser,
  • extends the DefaultHandler class, in order to provide the following callbacks:



  • startElement: this event is triggered when a start tag is encountered.


  • endElement: – this event is triggered when an end tag is encountered.


  • characters: – this event is triggered when some text data is encountered.


  • 3) StAX parser : 

    StAX(Streaming API for XML)parser is able to process tree-like structured data as the data gets streamed-in. StAX was designed as a median between DOM and SAX parsers. In this parsing, the entry point is a cursor that represents a point within the XML document. The application moves the cursor forward, in order to pull the information from the parser. In contrast, a SAX parser pushes data to the application, instead of pulling.

    Examples:
    1) DOM parser 
    ___________________
    package com.soap.xmlParse;

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;

    public class DomParserExample {

         public static void main(String[] args) throws ParserConfigurationException,
              SAXException, IOException {

              if(args.length != 1)
                   throw new RuntimeException("The name of the XML file is required!");

              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              DocumentBuilder builder = factory.newDocumentBuilder();

              // Load the input XML document, parse it and return an instance of the
              // Document class.
              Document document = builder.parse(new File(args[0]));

              List<Employee> employees = new ArrayList<Employee>();
              NodeList nodeList = document.getDocumentElement().getChildNodes();
              for (int i = 0; i < nodeList.getLength(); i++) {
                   Node node = nodeList.item(i);
                   if (node.getNodeType() == Node.ELEMENT_NODE) {
                        Element elem = (Element) node;
                        String ID = node.getAttributes().getNamedItem("ID").getNodeValue(); // Get the value of the ID attribute.

                        // Get the value of all sub-elements.
                        String firstname = elem.getElementsByTagName("Firstname").item(0).getChildNodes().item(0).getNodeValue();
                        String lastname = elem.getElementsByTagName("Lastname").item(0).getChildNodes().item(0).getNodeValue();

                        Integer age = Integer.parseInt(elem.getElementsByTagName("Age").item(0).getChildNodes().item(0).getNodeValue());
                        Double salary = Double.parseDouble(elem.getElementsByTagName("Salary").item(0).getChildNodes().item(0).getNodeValue());

                        employees.add(new Employee(ID, firstname, lastname, age, salary));
                   }
              }
              // Print all employees.
              for (Employee empl : employees)
                   System.out.println(empl.toString());
         }

    }
    ___________________

    2) SAX parser
    ___________________
    package com.soap.xmlParse;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;

    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;

    public class SAXParserExample extends DefaultHandler {

         private static List<Employee> employees = new ArrayList<Employee>();
         private static Employee empl = null;
         private static String text = null;

         @Override
         // A start tag is encountered.
         public void startElement(String uri, String localName, String qName, Attributes attributes)
              throws SAXException {

              switch (qName) {
                   // Create a new Employee.
                   case "Employee": {
                    empl = new Employee();//attributes.getValue("ID"), "Firstname", "Lastname", 33, 4000);
                    empl.setID(attributes.getValue("ID"));
                        break;
                   }
              }
         }

         @Override
         public void endElement(String uri, String localName, String qName) throws SAXException {
              switch (qName) {
                   case "Employee": {
                        // The end tag of an employee was encountered, so add the employee to the list.
                        employees.add(empl);
                        break;
                   }
                   case "Firstname": {
                        empl.setFirstname(text);
                        break;
                   }
                   case "Lastname": {
                        empl.setLastname(text);
                        break;
                   }
                   case "Age": {
                        empl.setAge(Integer.parseInt(text));
                        break;
                   }
                   case "Salary": {
                        empl.setSalary(Double.parseDouble(text));
                        break;
                   }
              }
         }

         @Override
         public void characters(char[] ch, int start, int length) throws SAXException {
              text = String.copyValueOf(ch, start, length).trim();
              System.out.println(text + ":" + ch.toString() + ":" + start + ":" + length);
         }

         public static void main(String[] args) throws ParserConfigurationException,
              SAXException, IOException {

              if (args.length != 1)
                   throw new RuntimeException("The name of the XML file is required!");

              SAXParserFactory parserFactor = SAXParserFactory.newInstance();
              SAXParser parser = parserFactor.newSAXParser();
              SAXParserExample handler = new SAXParserExample();

              parser.parse(new File(args[0]), handler);

              // Print all employees.
              for (Employee empl : employees)
                   System.out.println(empl.toString());
         }

    }
    ___________________

    3) StAX parser
    ___________________
    package com.soap.xmlParse;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.xml.stream.XMLInputFactory;
    import javax.xml.stream.XMLStreamConstants;
    import javax.xml.stream.XMLStreamException;
    import javax.xml.stream.XMLStreamReader;

    public class StaxParserExample {

         public static void main(String[] args) throws FileNotFoundException,
              XMLStreamException {

              if (args.length != 1)
                   throw new RuntimeException("The name of the XML file is required!");

              List<Employee> employees = null;
              Employee empl = null;
              String text = null;

              XMLInputFactory factory = XMLInputFactory.newInstance();
              XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream(
                                                      new File(args[0])));

              while (reader.hasNext()) {
                   int Event = reader.next();

                   switch (Event) {
                        case XMLStreamConstants.START_ELEMENT: {
                             if ("Employee".equals(reader.getLocalName())) {
                                  empl = new Employee();
                                  empl.setID(reader.getAttributeValue(0));
                             }
                             if ("Employees".equals(reader.getLocalName()))
                                  employees = new ArrayList<>();

                             break;
                        }
                        case XMLStreamConstants.CHARACTERS: {
                             text = reader.getText().trim();
                             break;
                        }
                        case XMLStreamConstants.END_ELEMENT: {
                             switch (reader.getLocalName()) {
                                  case "Employee": {
                                       employees.add(empl);
                                       break;
                                  }
                                  case "Firstname": {
                                       empl.setFirstname(text);
                                       break;
                                  }
                                  case "Lastname": {
                                       empl.setLastname(text);
                                       break;
                                  }
                                  case "Age": {
                                       empl.setAge(Integer.parseInt(text));
                                       break;
                                  }
                                  case "Salary": {
                                       empl.setSalary(Double.parseDouble(text));
                                       break;
                                  }
                             }
                             break;
                        }
                   }
              }

              // Print all employees.
              for (Employee employee : employees)
                   System.out.println(employee.toString());
         }

    }

    ___________________

    Thursday, February 23, 2017

    Lambdas in Java(1.8) - 5 - Streams API - iterations simplified / MethodReference

    Collection.stream()

    import java.util.Arrays;
    import java.util.List;
    import java.util.function.Consumer;

    public class Java8StreamsToPrintList {

    public static void main(String[] args) {
    List<Person> people = Arrays.asList(
    new Person("Gallen","Burchhill"),
    new Person("Allen","churchhill"),
    new Person("Alex","garten"),
    new Person("Sam","Batley"));

    people.stream()
    .filter(person-> person.firstName.startsWith("A"))
    .forEach(person->System.out.println(person));

    System.out.println("---------------------------------");

    int numberOfPplStartsWithA = 
    (int) people.stream()
    .filter(person-> person.firstName.startsWith("A"))
    .count();
    System.out.println(numberOfPplStartsWithA);

    System.out.println("--------METHOD REFERENCE, equivalent-----------");
    //Using Method reference to print all values in List
    printAllPeople(people,System.out::println);
                   //System.out::println is same as person->System.out.println(person)
    }

    private static void printAllPeople(List<Person> people, Consumer<Person> consumer) {
    for (Person person: people) {
    consumer.accept(person);
    }

    }

    }


    ______________________________________________________________________________

    Lambdas in Java(1.8) - 4 - Simplified List operations using Lambdas

    Simplified List operations using Lambdas

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    import java.util.function.Consumer;
    import java.util.function.Predicate;

    public class Lambdas_ListOperations {

    public static void main(String[] args) {
    List<Person> people = Arrays.asList(
    new Person("Gallen","Burchhill"),
    new Person("Allen","churchhill"),
    new Person("Alex","garten"),
    new Person("Sam","Batley"));

    //Sorting List the usual way
    // Collections.sort(people,new Comparator<Person>(){
    // @Override
    // public int compare(Person person1, Person person2) {
    // return person1.firstName.compareTo(person2.firstName);
    // };
    // });
    //(OR)
    //Sorting List the Lambda way
    Collections.sort(people, 
                                           (person1,person2)-> person1.firstName.compareTo(person2.firstName));


                   //PRINT all using regular method
    // for(Person person : people){
    // System.out.println(person.firstName);
    // }
    //(OR)
    //PRINT all the Lambda way
    printAllFromListUsingLambdas(people,
                                                                       (person1)->System.out.println(person1.firstName));

     //PRINT all users with firstNames starting with "A"
    //               printConditionally(people);
    //(OR)
                    //PRINT all users with firstNames starting with "A" the Lambda way
    printConditionallyUsingLambdas(people,
    person1->person1.firstName.startsWith("A"),
    person1->System.out.println(person1.firstName));
    }

    private static void printConditionallyUsingLambdas(List<Person> people, Predicate<Person> predicate, Consumer<Person> consumer) {
    for(Person person1 : people){
    if(predicate.test(person1)) consumer.accept(person1);
    }
    }

    private static void printAllFromListUsingLambdas(List<Person> people, Consumer<Person> consumer) {
    for(Person person : people)
    {
    consumer.accept(person);
    }
    }

    private static void printConditionally(List<Person> people) {
    for(Person person : people){
    if(person.firstName.startsWith("A")) System.out.println(person.firstName);
    }
    }
    }

    class Person{
    String firstName;
    String lastName;

    public Person(String firstName,String lastName) {
    this.firstName = firstName;
    this.lastName=lastName;
    }

    @Override
    public String toString() {
    return this.firstName+" "+this.lastName;
    }
    }


    Note:
     Important out-of-the-box APIs provided in java 8(java.util.Function.Predicate)
    • Consumer<Object>..Its a functional method with a single method called accept(Object). This method takes in an object but returns nothing.. instead it s accept method can be implemented in printing or performing some logic as in the above example.
    • Predicate<Object>..Its a functional Interface with a single method called test(Object) and returns a boolean. This method takes in an object and returns boolean.. Its test method can be implemented in checking a certain condition as in the example above
    • BiCosumer<Object1, Object2>..This Functional interface is very similar to Consumer interface.. the only difference is that it takes 2 objects and returns nothing as in Consumer.

    1. There are many more OOTB interfaces provided in java 8 for Lambda usage.
    2. @FunctionaInterface is the annotation that can you used above an interface that is intended for Lambda functions. This way, the developers can be informed of the interfaces that are used in code by Lambda declarations; which in turn will disable them from altering it.
    ________________________________________________________________________

    Lambdas in Java(1.8) - 3 - Anonymous InnerClass replaced with Lambda



    Replace Anonymous inner classes with Lambdas.

    A classic situation of using Lambda to replace an anonymous class, with Only one method(a must condition) is the Thread declaration that implements an inner Runnable interface as below:


    public class ReplaceAnonymousWithLambda {
    public static void main(String[] args) {
    //Using Runnable anonymour inner class
    Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
    System.out.println("run() executed from Runnable Anonymous inner class");
    }
    });
    //-----------------(A)
    thread.run();

    //Using Lambda function as a replacement for the Runnable anoynymous class
    thread = new Thread(()->System.out.println("contents as in run() using Lambda exp"));
    //-----------------(B)
    thread.run();
    }

    }

    Lambdas in Java(1.8) - 2 - Lambda Passed as method argument Example

    LambdaInterface 
    (or) 
    Lambda Expression as Method Argument

    public class PassingLambdaAsMethodArgument {

    void printGreeting(GreetingLambdaInterface greetingLambdaInterface){
    System.out.println(greetingLambdaInterface.printGreetingStrLength("hallo") );//print the length of string "hallo"
    }

    public static void main(String[] args) {
    PassingLambdaAsMethodArgument plafp = new PassingLambdaAsMethodArgument();

    //Pass lambda Interface object as method argument
    GreetingLambdaInterface gli = s->s.length();
    plafp.printGreeting( gli );

    //(OR) 

                   //pass the lambda expression as method argument
    plafp.printGreeting(s->s.length());
    }
    }

    interface GreetingLambdaInterface {
    int printGreetingStrLength(String s);
    }

    Lambdas in Java(1.8) - 1


    Lambdas

    reference :https://www.youtube.com/watch?v=gpIUfj3KaOc

    They are a concept of passing a method definition itself in a very short form over passing and argument using a method definition.
    In other words, A piece of code gets assigned to a method itself (a block of code) .
    Something like :

    • aBlockofCode = public void perform(){System.out.print("Hello");}... All Lambda expressions are in orange text below:
    However, with the right syntax:
    • Ex 1: aBlockofCode= () -> {System.out.print("Hello");}
    • the bolded expression is a lambda expression.
    • //note that  ";" is within the curly braces
    • The braces is not requires if the block of code contains only one statement.
    • Ex 2: aBlockofCode= (int a) -> a*2;//here, the functions takes a param int a, and returns (a*2). The statement "return" is ignored here, since blocking(using curly braces for multiple statments) is not required. However, if block of code, return needs to be defnied wenevr required.
    • Ex 3: aBlockofCode=  (int a,int b) -> { 
    if(b==0) return 0; 
      return a/b;
        };
        • Ex 4: aBlockofCode= (String s) -> s.length();

        While the orange text is referring a lambda expression, a lambda expression can be defined as a interface. Refer the examples below for more understanding:

        public class Lambdas {
        public static void main(String[] args) {
        PrintHalloLambdaInterface halloVarLambda = ()->System.out.println("hello");// --(A)
        halloVarLambda.PrintHalloMethod();
        AddParamsLambdaInterface addParams = (int a, int b)->a+b;// --(B)
        System.out.println(addParams.PrintSum(2, 3));
        StringLengthLambdaInterface strLenLambda =(String s)->s.length();// --(C)
        System.out.println(strLenLambda.PrintStrLength("StringLength"));
        }

        interface PrintHalloLambdaInterface{
         void PrintHalloMethod(); //param not taken or returns- implemented body in//  --(A)
        }
        interface AddParamsLambdaInterface{
         int PrintSum(int a, int b);//2 int params taken and returns an int- implemented body in // --(B)
        }
        interface StringLengthLambdaInterface{
         int PrintStrLength(String str);
        }
        }


        Note:
        • TYPE INFERENCE - Replacing "String s" with just "s" is valid in --(C)
          • StringLengthLambdaInterface strLenLambda = s ->s.length();// --(C)
        • A LambdaInterface can have only one abstract method(Functional Interface) that matches the lambda 



        Wednesday, February 8, 2017

        7-java.lang.Math (javaSE-1.8)

        java.lang.Math (javaSE-1.8)


        Math.E :2.718281828459045   //returns number closer to another other natural logs
        --------------------------------------------------------------
        Math.PI :3.141592653589793
        --------------------------------------------------------------
        Math.addExact(3, -790) :-4 //adds arguments
        Math.subtractExact(3,-7) :10 //subtracts arguments
        Math.decrementExact(4) :3 //decrement argument by 1
        Math.incrementExact(4) :5: //increments argument by 1
        Math.multiplyExact(3,4) :12
        Math.negateExact(3) :-3
        --------------------------------------------------------------
        Math.cbrt(8) :2.0
        Math.sqrt(4) :2.0
        Math.abs(-32.54536) :32.54536 //removes negation
        Math.max(34, 34.2) :34.2
        Math.min(34, 34.2) :34.0
        Math.nextAfter(3, 5) :3.0000002 ://returns closed of the first towards teh second
        Math.pow(2, 3) :8.0
        Math.random() :0.9903858200332046
        Math.round(3.569) :4
        Math.rint(5.6) :6.0
        --------------------------------------------------------------
        Math.ceil(3.4) :4.0
        Math.floor(3.4) :3.0
        Math.floorDiv(4, 3) :1  //returns [Math.floor(4/3)].. applies to int /long
        Math.floorMod(4, 3) :1  //returns [ 4 - (floorDiv(4,3) * 4) ]
        --------------------------------------------------------------
        Math.copySign(30.34, -89.1) :-30.34   //returns 1st argument with sign of 2nd
        --------------------------------------------------------------
        Math.exp(1) :2.718281828459045   //returns Eulers number(2.7182...Math.E) raised to power of argument
        Math.expm1(1) :1.718281828459045  //returns (Math.exp(argument) -1).. so, above.. returns (2.718...-1)
        --------------------------------------------------------------
        Math.hypot(3, 4) :5.0 //returns [ sqroot (3^2 + 4^2) ]
        --------------------------------------------------------------
        Math.getExponent(3) :1
        --------------------------------------------------------------
        Math.log10(1) :0.0
        Math.log(2) : Math.log(1)      0.6931471805599453:0.0
        --------------------------------------------------------------

        Tuesday, January 31, 2017

        6-Collections operational APIs in common

        Sorting

        • Already sorted Collections are as below. 
          • TreeSet
          • TreeMap
        However for the rest, a comparator needs to be implemented in 3 following ways:
        • sort() method for sorting List:
          • List l = new ArrayList(Arrays.asList(3, 5, 4, 2, 3, 2, 1, 3));
          • Collections.sort(l); //increasing order
          • System.out.println("Increasing order:"+l);
          • O/p: Increasing order: [1, 2, 2, 3, 3, 3, 4, 5]
          • .
          • However, The element’s class must implement Comparable interface. This is mandatory since this version of sort() uses element’s compareTo() method to compare them. Otherwise a ClassCastException will be thrown.


        • custom Sort method for sorting List:Steps to create custom Comparator are below:
          • create a custom comparator class that implements Comparator interface, and implement its compare() method as below:
            • class IntegerComparator implements Comparator {
            •     public int compare(Object o1, Object o2) {
            •       return (Integer)o2 - (Integer)o1;
            •     }
            • }
          • Note that the Object that is compared(Integer in this case) needs to implement Comparable interface in order to be use a comparator(IntegerComparator  in this case) for comparison.
            • This customComparator(IntegerComparator) then used as in below code:
              • Collections.sort(l, new IntegerComparator());//decreasing order
              • System.out.println("Decreasing order\n"+l);
          • Using unnamed Comparator class(within sort() call)
            • Collections.sort(l, new Comparator() {
                    • public int compare(Object o1, Object o2) {
                    • return (Integer)o2 - (Integer)o1;
                    • }}
                  • ); //decreasing order
          _______________________________________________________________________


          Shuffling

          • The opposite of sort is shuffle which arranges list elements arbitrarily.
          • Two versions of shuffle() are :
            1. One operates on a List using a default source of randomness.
              • Collections.shuffle(l);
            2. Another requires a Random object to be specified explicitly.
              • Collections.shuffle(l, new Random());

          _______________________________________________________________________

          Manipulation

          • Reversing Collections.reverse(list);
          • Swapping : swaps elements of two specified positions of a specified list
            • Collections.swap(list,2, 4);
          • Copying : Copy all the elements on lists1 into list2
            • Collections.copy(list1, list2);
          • Filling : fill all elements of list1 with "0", wrt to example below
            • Collections.fill(list,0);
          • Adding: Collections.addAll(l1, -1, -2, -3);//Adds three integers to the list l1.
          _______________________________________________________________________

          Search

          • binarySearch(): It is common to use sort() method to sort the List before a call to binarySearch().
            • Collections.sort(list); //list=[1, 2, 2, 3, 3, 3, 4, 5]
            • int in = Collections.binarySearch(l, 4); //in = 6
            • in = Collections.binarySearch(list, 2); //in = 1
            • in = Collections.binarySearch(list, 3); //in = 3
          • For unsuccessful search, it returns a value (-(insertion point) - 1),
            • in = Collections.binarySearch(list, 0); //in = -1
          _______________________________________________________________________

          min()/max()

          • int min = (int)Collections.min(list); //min = 0
          • int max = (int)Collections.max(list); //max = 6
          _______________________________________________________________________

          frequency()
          • int fre = Collections.frequency(list,2); //fre = 2
          • fre = Collections.frequency(list,3); //fre = 3


          _______________________________________________________________________