Saturday, August 15, 2015

Writing CSV File Using JAVA

We know how to read CSV file without using any API or external.JAR. Now we try to create CSV file with out using any API or external.JAR. Here we create CSV file using pure JAVA classes, for this we need to follow this steps.

Step 1:
  Create OutputStream object for file creation.
OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(filePath) 

Step 2: 
  We need to OutputStream to Writer object to get support for non english characterset .
Writer outStreamWriter = new OutputStreamWriter(fileStream,StandardCharsets.UTF_8);

Step 3: 
  We create a BufferedWriter object to get a better performance. 
BufferedWriter buffWriter = new BufferedWriter(outStreamWriter))

Step 4 :
   Now we write data using append("Data") method and then flush the buffer and close it.

            buffWriter.append("Data1");
            buffWriter.append(separator);
            buffWriter.append("Data2");
            buffWriter.newLine();
            buffWriter.flush();


Example Code : 
 
package csvfilehandling;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;


public class CSVWritingWithoutAPI {

    public static void main(String[] args) throws IOException{
        writeCSV("Our File Path", ",");
    }
    public static void writeCSV(String filePath, String separator) throws IOException {

        /**
         * We use try with resource so we don't need to call close
         * method or write finally block explicitly it will be called automatically. 
         */

        try (OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(filePath));
                Writer outStreamWriter = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8);
                BufferedWriter buffWriter = new BufferedWriter(outStreamWriter)) {
            buffWriter.append("Data1");
            buffWriter.append(separator);
            buffWriter.append("Data2");
            buffWriter.newLine();
            buffWriter.flush();
            buffWriter.append("1");
            buffWriter.append(separator);
            buffWriter.append("2");
            buffWriter.newLine();
            buffWriter.flush();
            buffWriter.append("11");
            buffWriter.append(separator);
            buffWriter.append("22");
            buffWriter.flush();
        }
    }
}

Sunday, August 9, 2015

Reading CSV File Using JAVA

Sometime we need to parse CSV(Comma Separated Values) file for data reading or writing .We use CSV file due to platform independence .There are lots of API available to parse a CSV file but here we use simple JAVA code, later we will learn how to use JAVA API for reading and writing a CSV file.

STEP 1 :
 Basically we need this lines to read a file.
try (InputStream fileStream = new BufferedInputStream(new FileInputStream(filePath));

STEP 2 :
 To read a file with different character set except English then we need to support for UTF-8 characters.So we use Reader class for that.
     Reader ir = new InputStreamReader(fileStream, "UTF-8");

STEP 3 :
  Now we create a BufferedReader object to read a file in a speedy way.
     BufferedReader buffReader = new BufferedReader(ir));

STEP 4 :
  We use readLine() method on BufferedReader object and loop will iterate until this object will be null.
              while ((line = buffReader.readLine()) != null) {
                csvData = line.split(separator);
                list.add(csvData);
            }  



 Example Code :

package csvfilehandling;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CSVReadingWithOutAPI {

    public static void main(String[] args) {
        try {
            //System.out.println((getCSVInList("
Our CSV File Path", ",").get(0))[1]);
            for (String[] csvDataRow : getCSVInList("Our CSV File Path", ",")) {
                for (String csvDataOnColumn : csvDataRow) {
                    System.out.println(csvDataOnColumn);
                }
            }
            //System.out.println(getCSVInMap("
Our CSV File Path", ",").get(0).get(1));
            for (Map.Entry<Integer, List<String>> csvDataSet : getCSVInMap("
Our CSV File Path", ",").entrySet()) {
                for (String csvData: csvDataSet.getValue()) {
                    System.out.println(csvData);
                }
            }
            //System.out.println(getCSVFromColumn("
Our CSV File Path", ",", "DATACOLUMN1"));
            for (String columndata : getCSVFromColumn("
Our CSV File Path", ",", "DATACOLUMN1")) {
                System.out.println(columndata);
            }

        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public static List<String[]> getCSVInList(String filePath, String separator) throws IOException {
        List<String[]> list = new ArrayList<>();
        /**
         * We use try-with-resources Statement for close the resource and
         * release it .
         */

try (InputStream fileStream = new BufferedInputStream(new FileInputStream(filePath));
                Reader ir = new InputStreamReader(fileStream, "UTF-8");
                BufferedReader buffReader = new BufferedReader(ir)) {
            String line;
            String[] csvData;
            while ((line = buffReader.readLine()) != null) {
                csvData = line.split(separator);
                list.add(csvData);
            }
        }
        return list;
    }

    public static Map<Integer, List<String>> getCSVInMap(String filePath, String separator) throws IOException {
        Map<Integer, List<String>> map = new HashMap<>();
        /**
         * We use try-with-resources Statement for close the resource and
         * release it .
         */

try (InputStream fileStream = new BufferedInputStream(new FileInputStream(filePath));
                Reader ir = new InputStreamReader(fileStream, "UTF-8");
                BufferedReader buffReader = new BufferedReader(ir)) {
            String line;
            String[] csvData;
            int lineNumber = 0;
            while ((line = buffReader.readLine()) != null) {
                csvData = line.split(separator);
                map.put(lineNumber, Arrays.asList(csvData));
                lineNumber++;
            }
        }
        return map;
    }

    public static List<String> getCSVFromColumn(String filePath, String separator, String columnName) throws IOException {
        List<String> columnList = new ArrayList<>();
        /**
         * We use try-with-resources Statement for close the resource and
         * release it .
         */

try (InputStream fileStream = new BufferedInputStream(new FileInputStream(filePath));
                Reader ir = new InputStreamReader(fileStream, "UTF-8");
                BufferedReader buffReader = new BufferedReader(ir)) {
            String line;
            String[] csvDataInCurrentLine;
            int lineNumber = 0;
            int columnNumber = 0;
            while ((line = buffReader.readLine()) != null) {
                csvDataInCurrentLine = line.split(separator);
                /**
                 * This is a one time checking for First Line Reading .
                 */

                if (lineNumber == 0) {
                    /**
                     * Use binarySearch to find the column name from String
                     * Array String[] csvDataInCurrentLine; .
                     */

                    if (Arrays.binarySearch(csvDataInCurrentLine, columnName) < 0) {
                        break;
                    }
                    columnNumber = Arrays.asList(csvDataInCurrentLine).indexOf(columnName);
                } else {
                    columnList.add(csvDataInCurrentLine[columnNumber]);
                }
                lineNumber++;
            }
        }
        return columnList;
    }
}

 

Saturday, August 1, 2015

FileDownload Using Firefox Profile

We know how to create Firefox profile using Selenium WebDriver code and what it is. We also download a file using using AutoIt tool. Now here we try to learn how to download file using using Firefox profile.

For downloading a file using Selenium WebDriver we need to set some properties in Firefox profile.In below we know what is the meaning of that properties.

Step 1.

        FirefoxProfile profile = new FirefoxProfile();
This is required to create a Firefox profile form Selenium WebDriver,

Step 2.
        profile.setPreference("browser.download.folderList", 2); 
Default Value of  browser.download.folderList is 1. We can set it as 0, 1, or 2.
          0  =  Firefox will save all files downloaded via the browser on the user's Desktop.
          1  =  Downloads are stored in the Downloads folder.
          2  =  Location specified for the most recent download is utilized again . 

Step 3.
        profile.setPreference("browser.download.manager.showWhenStarting", false); 
Default Value of browser.download.manager.showWhenStarting is true. This option means whether or not the Download Manager window is displayed when a file download is initiated or not. If we make it as false then Window should not be appeared.

Step 4.
        profile.setPreference("browser.download.dir", downloadLocation); 
browser. download. dir properties is required for last directory used for saving a file from the "What should (browser) do with this file?"

Step 5.
        profile.setPreference("browser.helperApps.neverAsk.openFile",
                "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
 


This property browser. helperApps. neverAsk. openFile A comma-separated list of MIME types to open directly without asking for confirmation. Default value is an empty string.

Step 6. 
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");


This property browser. helperApps. neverAsk. saveToDisk A comma-separated list of MIME types to save to disk without asking what to use to open the file. Default value is an empty string.

Step 7.
        profile.setPreference("browser.helperApps.alwaysAsk.force", false);
This property browser. helperApps. alwaysAsk. force True: Always ask what to do with an unknown MIME type,and disable option to remember what to open it with False (default): Opposite of above.

Step 8.
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
This Property browser.download.manager.alertOnEXEOpen True (default): When it is true then warn the user attempting to open an executable from the Download Manager False: display no warning and allow executable to be run Note: In Firefox, this can be changed by checking the "Don't ask me this again" box when you encounter the alert.

Step 9.
        profile.setPreference("browser.download.manager.focusWhenStarting", false);
        profile.setPreference("browser.download.manager.useWindow", false);
        profile.setPreference("browser.download.manager.showAlertOnComplete", false);

This Properties browser. download. manager. focusWhenStarting True: Set the Download Manager window as active when starting a download False (default): Leave the window in the background when starting a download.

Step 10.
        profile.setPreference("browser.download.manager.closeWhenDone", false);
This Property browser. download. manager. closeWhenDone True: Close the Download Manager when all downloads are complete False (default): Opposite of the.

N.B  For detail list of MIME Type is available here
  1. http://www.freeformatter.com/mime-types-list.html
  2. http://www.sitepoint.com/web-foundations/mime-types-complete-list/
Complete Example :


package filedownload;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;


public class FileDownload {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver(new FirefoxBinary(new File("G:/Program Files/Mozilla Firefox/firefox.exe")),
getFireFoxProfile("G:\\Test"));
        driver.get("http://www.google.com");
    }

    public static FirefoxProfile getFireFoxProfile(String downloadLocation) {
        FirefoxProfile profile = new FirefoxProfile();
        /**
         * Default Value: 1 The value of browser.download.folderList
         * can be set to either 0, 1, or 2.
         * 0 = Firefox will save all files downloaded via the browser on the user's desktop.
         * 1 = these downloads are stored in the Downloads folder.
         * 2 = location specified for the most recent download is utilized again .
         */

        profile.setPreference("browser.download.folderList", 2);
        /**
         * Default Value: true The browser.download.manager.showWhenStarting Preference in Firefox's
         *about:config interface allows the user to specify
         * whether or not the Download Manager window is displayed when a file download is initiated.
         */

        profile.setPreference("browser.download.manager.showWhenStarting", false);
        /**
         * browser. download. dir The last directory used for saving a file from the
         * "What should (browser) do with this file?" dialog.
         */

        profile.setPreference("browser.download.dir", downloadLocation);
        /**
         * browser. helperApps. neverAsk. openFile A comma-separated list of MIME types to
         * open directly without asking for confirmation. Default value is an empty string.
         */

        profile.setPreference("browser.helperApps.neverAsk.openFile",
                "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
         /**
         * browser. helperApps. neverAsk. saveToDisk A comma-separated list of MIME types
         * to save to disk without asking what to use to open the file. Default value
         * is an empty string.
         */

        profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
        /**
         * browser. helperApps. alwaysAsk. force True: Always ask what to do with an unknown MIME type,
         * and disable option to remember what to open it with False (default): Opposite of above
         */

        profile.setPreference("browser.helperApps.alwaysAsk.force", false);
        /**
         * browser.download.manager.alertOnEXEOpen True (default):
         * warn the user attempting to open an executable from the
         * Download Manager False: display no warning and allow
         * executable to be run Note: In Firefox, this can be changed
         * by checking the "Don't ask me this again" box when you
         * encounter the alert.
         */

        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        /**
         * browser. download. manager. focusWhenStarting
         * True: Set the Download Manager window as active when starting a download
         * False (default): Leave the window in the background when starting a download
         */

        profile.setPreference("browser.download.manager.focusWhenStarting", false);
        profile.setPreference("browser.download.manager.useWindow", false);
        profile.setPreference("browser.download.manager.showAlertOnComplete", false);       profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
        profile.setPreference("pdfjs.disabled", true);
        /**
         * browser. download. manager. closeWhenDone
         * True: Close the Download Manager when all downloads are complete
         * False (default): Opposite of the
         */

        profile.setPreference("browser.download.manager.closeWhenDone", false);
        return profile;
    }
}

 

Friday, July 31, 2015

Working With Chrome Profile With Selenium WebDriver

Previously we learn how to create Firefox Profile and how to access this profile using Selenium WebDriver.
Here We learn how to create Chrome profile and use this profile from Selenium WebDriver.

1. Create Chrome Profile :
  •  Open Chrome Browser and click on Setting option.
  • Scroll down the page and click on Add person option.Give a name and click on Add button. If we check this option"Create a desktop shortcut for the user" then we can find a chrome shortcut for this profile.
  • After creation this profile we can find that a folder created under "Documents and Settings\Administrator\Local Settings\Application Data\Google\Chrome\User Data"
     
2. Accessing Chrome Profile Using Selenium WebDriver :
  • Download Chrome Driver from here .
  • Extact the .exe file from downloaded zip and put this file(.exe) in our project folder.
  • Add this .exe to System property using 
    System.setProperty("webdriver.chrome.driver", "./chromedriver.exe");
                                                         Or

    Using ChromeDriverService class for this.
    ChromeDriverService chSvc = new ChromeDriverService.Builder()
              .usingDriverExecutable(new File("./chromedriver.exe")).usingAnyFreePort().build();

  • Create ChromeOption object and add use addArguments() method to set the user profile.
         ChromeOptions chOption = new ChromeOptions();
         chOption.addArguments("user-data-dir=ChromeProfile Location");

  • Now pass ChromeDriverService and ChromeOption object during ChromeDriver object creation.
            WebDriver driver = new ChromeDriver(chSvc,chOption); 
Example Code: 

package chromeprofile;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;

public class LoadChromeProfile {

    public static void main(String[] args) {
        //System.setProperty("webdriver.chrome.driver", "./chromedriver.exe");

        ChromeDriverService chSvc = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File("./chromedriver.exe")).usingAnyFreePort().build();

        ChromeOptions chOption = new ChromeOptions();

        /**
         * "user-data-dir = profilepath" --to open profile
         * "--start-maximized" for maximize the browser
         */

        chOption.addArguments("user-data-dir = Our Profile Path");
        chOption.addArguments("--start-maximized");        WebDriver driver = new ChromeDriver(chSvc, chOption);
        driver.quit();
    }
}

 

Sunday, June 21, 2015

Validate XML With Referenced XSD File Using SAX Parser

Previously we learn how to validated a XML file with reference or internal schema using DOM parser. Here we do the same thing but using SAX parser.

Step 1:

  Create a  SAXParserFactory object.
      SAXParserFactory saxFactory = SAXParserFactory.newInstance();  

Step 2:
  Set SAXParserFactory object as NameSpaceAware true.
      saxFactory.setNamespaceAware(true);

Step 3:
  Set SAXParserFactory object as Validating true.
      saxFactory.setValidating(true);

Step 4:
   Set SAXParser Property.
      parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");


Step 5:
  Set ErrorHandler to XMLReader object.
                xmlReader.setErrorHandler(
                    new ErrorHandler() {
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                            System.out.println("WARNING: " + e.getMessage()); // do nothing
                        }
                       
                        @Override
                        public void error(SAXParseException e) throws SAXException {
                            System.out.println("ERROR: " + e.getMessage());
                            throw e;
                        }
                       
                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                            System.out.println("FATAL: " + e.getMessage());
                            throw e;
                        }
                    });


Step 6:
  Parse XML file .
    xmlReader.parse("file.xml");

Our complete code looks like that:

package SAXParser;

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;


public class SAXParserValidation {

    public static void main(String[] args) {
        try {
            SAXParserFactory saxFactory = SAXParserFactory.newInstance();
            saxFactory.setValidating(true);
            saxFactory.setNamespaceAware(true);
            SAXParser parser = saxFactory.newSAXParser();
            parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
           
            XMLReader xmlReader = parser.getXMLReader();
            xmlReader.setErrorHandler(
                    new ErrorHandler() {
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                            System.out.println("WARNING: " + e.getMessage()); // do nothing
                        }
                       
                        @Override
                        public void error(SAXParseException e) throws SAXException {
                            System.out.println("ERROR: " + e.getMessage());
                            throw e;
                        }
                       
                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                            System.out.println("FATAL: " + e.getMessage());
                            throw e;
                        }
                    });
            xmlReader.parse("file.xml");
        } catch (ParserConfigurationException | SAXException | IOException e) {
            System.out.println("!!!!!!!!!!!!!!!Error!!!!!!!!!!!!" + e.getMessage());
        }
    }
   
} 


 XML File :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students  xsi:noNamespaceSchemaLocation="file.xsd"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <student id="1">
    <fname>TestFirstName</fname>
    <lname>TestLastName</lname>
    <sectionname rollno="1">A</sectionname>
  </student>
</students>




XML Schema :

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xs:element name="students" type="studentsType"/>
  <xs:complexType name="sectionnameType">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute type="xs:byte" name="rollno"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="studentType">
    <xs:sequence>
      <xs:element type="xs:string" name="fname"/>
      <xs:element type="xs:string" name="lname"/>
      <xs:element type="sectionnameType" name="sectionname"/>
    </xs:sequence>
    <xs:attribute type="xs:byte" name="id"/>
  </xs:complexType>
  <xs:complexType name="studentsType">
    <xs:sequence>
      <xs:element type="studentType" name="student"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Validate XML With Referenced XSD File Using DOM Parser

On the last post we learn how to validated a XML file against an external XML schema file. Now we try to learn how to validate a XML file against referenced or internal schema definition.

Step 1 :

Create DocumentBuilderFactory object as given below.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 

Step 2 :

Set DocumentBuilderFactory object as NameSpace Aware true.
     docFactory.setNamespaceAware(true);

Step 3:

Set DocumentBuilderFactory object as Validating true.
     docFactory.setValidating(true);

Until we set docFactory as NameSpaceAware it will not validate the XML file with referenced Schema if we only set the Validating as true.

Step 4:

Set Attribute on DocumentBuilderFactory.

 If schemalocation specified in the XML Document using the schemaLocation or  noNamespaceSchemaLocation attributes then use
    docFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
              "http://www.w3.org/2001/XMLSchema");


If schemalocation specified by the 'http://java.sun.com/xml/jaxp/properties/schemaSource' property then use
    docFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
              "http://www.w3.org/2001/XMLSchema");


    docFactory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", "file:test2.xsd");


Step 5:

Set ErrorHandler to DocumentBuilderFactory object. It is optional,  it is required if we try to catch different level of parsing error like warning, error, fatal error etc.

We can set this on DocumentBuilder Object like this.
      docBuilder.setErrorHandler(new DefaultErrorHandler());

Or if we want to implement our own then it looks like this.
            docBuilder.setErrorHandler(
                    new ErrorHandler() {
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                            System.out.println("WARNING: " + e.getMessage()); // do nothing
                        }

                        @Override
                        public void error(SAXParseException e) throws SAXException {
                            System.out.println("ERROR: " + e.getMessage());
                            throw e;
                        }

                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                            System.out.println("FATAL: " + e.getMessage());
                            throw e;
                        }
                    });


Step 6 :

Now parse the XML file.
    docBuilder.parse(new File("file.xml"));

Our complete code looks like that:

package domparsing;

import com.sun.org.apache.xml.internal.utils.DefaultErrorHandler;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class DOMValidation {

    /**
     * @param args the command line arguments
     * @throws javax.xml.parsers.ParserConfigurationException
     * @throws org.xml.sax.SAXException
     * @throws java.io.IOException
     */
    public static void main(String[] args) {
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            docFactory.setNamespaceAware(true);
            docFactory.setValidating(true);
            /**
             * This line is required if We setValidating as true
             * but no noNamespaceSchemaLocation defined in XML file.
             */

            //docFactory.setFeature("http://apache.org/xml/features/validation/dynamic", true);
            docFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
              "http://www.w3.org/2001/XMLSchema");
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            //docBuilder.setErrorHandler(new DefaultErrorHandler());

            docBuilder.setErrorHandler(
                    new ErrorHandler() {
                        @Override
                        public void warning(SAXParseException e) throws SAXException {
                            System.out.println("WARNING: " + e.getMessage()); // do nothing
                        }

                        @Override
                        public void error(SAXParseException e) throws SAXException {
                            System.out.println("ERROR: " + e.getMessage());
                            throw e;
                        }

                        @Override
                        public void fatalError(SAXParseException e) throws SAXException {
                            System.out.println("FATAL: " + e.getMessage());
                            throw e;
                        }
                    });
            /**
             * Commented line required if we want to
             * show the output after parsing it.One is
             * for using DOM and another is one using STAX.
             */

            //TransformerFactory.newInstance().newTransformer().transform(new StreamSource("file.xml"), new StreamResult(System.out));
            //TransformerFactory.newInstance().newTransformer().transform(new DOMSource(docBuilder.parse(new File("file.xml"))),new StreamResult(System.out));
            docBuilder.parse(new File("file.xml"));
        } catch (IOException | SAXException | ParserConfigurationException | IllegalArgumentException e) {
            System.out.println("!!!!!!!!!!!!!!!Error!!!!!!!!!!!!" + e.getMessage());
        }
    }
}


XML File :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students  xsi:noNamespaceSchemaLocation="file.xsd"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <student id="1">
    <fname>TestFirstName</fname>
    <lname>TestLastName</lname>
    <sectionname rollno="1">A</sectionname>
  </student>
</students>




XML Schema :

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xs:element name="students" type="studentsType"/>
  <xs:complexType name="sectionnameType">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute type="xs:byte" name="rollno"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="studentType">
    <xs:sequence>
      <xs:element type="xs:string" name="fname"/>
      <xs:element type="xs:string" name="lname"/>
      <xs:element type="sectionnameType" name="sectionname"/>
    </xs:sequence>
    <xs:attribute type="xs:byte" name="id"/>
  </xs:complexType>
  <xs:complexType name="studentsType">
    <xs:sequence>
      <xs:element type="studentType" name="student"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Saturday, June 13, 2015

XML Validation And WellFormedNess Checking In Java

Previously we learn how to read and write a XML with different parser. Now we will concentrate how to check the wellformedness and validity of a XML file.

Now question is what is wellformedness and what is the validation of a XML file.

  1. WellFormedNess  : It is related with XML syntax of an XML document for an example : XML document must have a single root element, the elements must be properly nested, tag names cannot begin with a number or contain certain characters, and so on.
  2. Valid : A valid XML document means that the document complies with the rules of a particular document specification.This can be done with DTD(Document Type Definition) or Schema. Before a document can be valid to a standard, it must start by being well-formed. An XML document cannot be valid until it is well-formed

WellFormedNess checked in java when parse() method called. So we don't need to do any extra thing for that.

Now we go to find the way how to validate the xml file.

There are two way because some time schema definition is defined into the XML file then we need to use internal XML Validation and some time we need to validate the XML file with external schema file when schema definition is not defined into the XML file.

Here we will try to learn how to validate a XML file against an external XML Schema file.

Step 1: 
    
     Set Schema Language
        String schemaLanguage=XMLConstants.W3C_XML_SCHEMA_NS_URI;
        

Step 2:

     Create SchemaFactory Object
        SchemaFactory schemaFactory=SchemaFactory.newInstance(schemaLanguage);
        

Step 3:

      Create Schema Object
          Schema schema=schemaFactory.newSchema(new File("XSD FilePath"));
       
      If we have multiple schema file then use Source Object array

         Schema schema=schemaFactory.newSchema(new StreamSource[]{new StreamSource(new File("XSD FilePath"))});


Step 4:


     Create Validator object
        Validator xmlValidator= schema.newValidator();

Step 5:


     Now call validate method and pass XML file as a parameter to validate. 
        xmlValidator.validate(new StreamSource(new File("XML FilePath")));

Complete Code Example :


import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;

public class SchemaValidationExample {

    public static void main(String[] args) {
        try {
            /**
             * Define Schema Language.
             */

            String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
           
            /**
             * Create SchemaFactory Object.
             */

            SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
           
            /**
             * Create Schema Object,here we pass Schema File
             * If we require multiple Schema File then use
             * StreamSource object array.
             */

            Schema schema = schemaFactory.newSchema(new File("file.xsd"));
           
            //To valide XML against multiple xchema file.
            //Schema schema=schemaFactory.newSchema(new StreamSource[]{new StreamSource(new File("file.xsd"))});
           
            /**
             * Create Validator Object.
             */
            Validator xmlValidator = schema.newValidator();

           
            /**
             * Validate XML File.
             */

            xmlValidator.validate(new StreamSource(new File("file.xml")));
           
        } catch (SAXException |IOException ex) {
            Logger.getLogger(SchemaValidationExample.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 

 
XSD File :
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xs:element name="students" type="studentsType"/>
  <xs:complexType name="sectionnameType">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute type="xs:byte" name="rollno"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="studentType">
    <xs:sequence>
      <xs:element type="xs:string" name="fname"/>
      <xs:element type="xs:string" name="lname"/>
      <xs:element type="sectionnameType" name="sectionname"/>
    </xs:sequence>
    <xs:attribute type="xs:byte" name="id"/>
  </xs:complexType>
  <xs:complexType name="studentsType">
    <xs:sequence>
      <xs:element type="studentType" name="student"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>
        

XML File :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students xsi:noNamespaceSchemaLocation="file.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <student id="1">
    <fname>TestFirstName</fname>
    <lname>TestLastName</lname>
    <sectionname rollno="1">A</sectionname>
  </student>
</students>

 
     

Saturday, June 6, 2015

Writing XML File With STAX Stream Parser

Here we try to learn how to use STAX Stream Parser in XML writing. We know that STAX stream parser is consuming lower memory and more efficient than STAX Event Parser . Now we follow this steps to create a XML file using STAX Stream Parser.

Step : 1
       Create XMLOutputFactory object.
          XMLOutputFactory xof = XMLOutputFactory.newFactory();

Step : 2 
        Create XMLStreamWriter object.

           XMLStreamWriter writer = xof.createXMLStreamWriter(new FileWriter("C:\\file.xml"));

 Step : 3
         Start Document
            writer.writeStartDocument();

         Start Element
           writer.writeStartElement("students");

         Add Attribute
            writer.writeAttribute("id", "1");

         Add Character in XML Node
            writer.writeCharacters("TestLaststName");

        End Element
             writer.writeEndElement();

        End Document
             writer.writeEndDocument();

Step : 4
      Flush XMLStreamWriter object and close this object.
        
          writer.flush();
          writer.close();


Complete Code Is Given Below :


package STAXParser;

import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;

public class STAXStreamWriter {

    public static void main(String[] args) throws IOException, XMLStreamException, TransformerConfigurationException, TransformerException {
        /**
         * Create XMLOutputFactory Object.
         */

        XMLOutputFactory xof = XMLOutputFactory.newFactory();

        /**
         * Create XMLStreamWriter Object.
         */

        XMLStreamWriter writer = xof.createXMLStreamWriter(new FileWriter("C:\\file.xml"));
//        XMLStreamWriter writer = xof.createXMLStreamWriter(new StreamResult(System.out));
        /**
         * This is created for formatting.
         */

        writer = new IndentingXMLStreamWriter(writer);

        /**
         * Handling Start Document,Start Element,Add Attribute,
         * Add Character,EndDocument and EndElement.
         */

        writer.writeStartDocument();
       
        writer.writeStartElement("students");
       
        writer.writeStartElement("student");
        writer.writeAttribute("id", "1");

        writer.writeStartElement("fname");
        writer.writeCharacters("TestFirstName");
        writer.writeEndElement();

        writer.writeStartElement("lname");
        writer.writeCharacters("TestLaststName");
        writer.writeEndElement();

        writer.writeStartElement("section");
        writer.writeAttribute("rollno", "1");
        writer.writeCharacters("A");
        writer.writeEndElement();
       
        writer.writeEndElement();
        writer.writeEndElement();
        writer.writeEndDocument();

        /**
         * Flush XMLStreamWriter Object and Close.
         */

        writer.flush();
        writer.close();
    }
}


OutPut :
 

<?xml version="1.0" encoding="UTF-8"?>
<studens>
    <student id="1">
        <fname>TestFirstName</fname>
        <lname>TestLastName</lname>
        <section rollno="1">A</section>
    </student>
</studens>

Writing XML File Using STAX Event Parser

Using STAX parser is another way to write XML file. As we know STAX have two type of parsing technique one is Event or Iterator and another one is Stream or Cursor type,here STAX have same two types to write XML file.

Here we take a look on STAX event Parser, later we will know the another one.

Step 1 : 
      Create XMLOutputFactory object.
        XMLOutputFactory outFactory=XMLOutputFactory.newFactory();


Step 2 :
      Create XMLEventWriter object.
         XMLEventWriter xew=outFactory.createXMLEventWriter(new FileWriter("File Name"));

Step 3:
      Create XMLEventFactoryobject.
         XMLEventFactory evntFactory=XMLEventFactory.newFactory();

Step 4 :
      Start Document
         xew.add(evntFactory.createStartDocument());
     
      StartElement
        xew.add(evntFactory.createStartElement("", "", "Element Name"));   

      Add Attribute
        xew.add(evntFactory.createAttribute("Attribute Name", "Attribute Value"));

      Add Character
        xew.add(evntFactory.createCharacters("XML Node Character Value"));
 
     Close Element
        xew.add(evntFactory.createEndElement("", "", "Element Name Which we want to close"));
     
     Close Document 
        xew.add(evntFactory.createEndDocument());

Step 5 :
     Flush the writer object.
        xew.flush();

Step 6 :
     Close writer object.
        xew.close();
       

Complete Code Given Below :

package STAXParser;

import java.io.FileWriter;
import java.io.IOException;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;

public class STAXEventWriter {

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

        /**
         * Create XMLOutputFactory object.
         */

 
        XMLOutputFactory outFactory=XMLOutputFactory.newFactory();
        

        /**
         * Create XMLEventWriter object.
         */

 
        XMLEventWriter xew=outFactory.createXMLEventWriter(new FileWriter("C:\\file.xml"));
        //XMLEventWriter xew=outFactory.createXMLEventWriter(System.out);


        /**
         * Create XMLEventFactory object.
         */

        XMLEventFactory evntFactory=XMLEventFactory.newFactory();
       
        /**
         * This are created to decorate XML file.
         */

 
        XMLEvent end = evntFactory.createDTD("\n");
        XMLEvent tab = evntFactory.createDTD("\t");
       
        /**
         * Handling Stat Document, CreateElement, Add Attribute
         * Create Characters, Close Element and close Document.
         */

        xew.add(evntFactory.createStartDocument());
        xew.add(end);
       
        xew.add(evntFactory.createStartElement("", "", "studens"));
        xew.add(end);
        xew.add(tab);
       
        xew.add(evntFactory.createStartElement("", "", "student"));
        xew.add(evntFactory.createAttribute("id", "1"));
        xew.add(end);
        xew.add(tab);
        xew.add(tab);
       
        xew.add(evntFactory.createStartElement("", "", "fname"));
        xew.add(evntFactory.createCharacters("TestFirstName"));
        xew.add(evntFactory.createEndElement("", "", "fname"));
        xew.add(end);
        xew.add(tab);
        xew.add(tab);
       
        xew.add(evntFactory.createStartElement("", "", "lname"));
        xew.add(evntFactory.createCharacters("TestLastName"));
        xew.add(evntFactory.createEndElement("", "", "lname"));
        xew.add(end);
        xew.add(tab);
        xew.add(tab);
       
        xew.add(evntFactory.createStartElement("", "", "section"));
        xew.add(evntFactory.createAttribute("rollno", "1"));
        xew.add(evntFactory.createCharacters("A"));
        xew.add(evntFactory.createEndElement("", "", "section"));
        xew.add(end);
        xew.add(tab);
       
        xew.add(evntFactory.createEndElement("", "", "student"));
        xew.add(end);
       
        xew.add(evntFactory.createEndElement("", "", "students"));
        xew.add(evntFactory.createEndDocument());
       
        /**
         * Flush writer object and Close this object.
         */

        xew.flush();
        xew.close();
    }
}


OutPut :
 

<?xml version="1.0" encoding="UTF-8"?>
<studens>
    <student id="1">
        <fname>TestFirstName</fname>
        <lname>TestLastName</lname>
        <section rollno="1">A</section>
    </student>
</studens>


Saturday, May 23, 2015

Writing XML File Using DOM Parser

Still now we learn how to read XMLfile using DOM, SAX and STAX parser and we know that only DOM and STAX have the ability to write XML file.Here we learn how to write XML file using DOM and later we know how to write XML File using STAX parser.

Step 1:
    Create DocumentBuilderFactory object .
      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

Step 2:

    Create DocumentBuilder object .
      DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

Step 3:
    Create Document object .
      Document dom = domBuilder.newDocument();

Step 4:
    Create Element object .
      Element rootStart = dom.createElement("elementName")

Step 5:
   Add this object to dom .
      dom.appendChild(rootStart);

  If  this node is under any node then add this under any element object  
      rootStart.appendChild(rootStart)

Step 6: 
    Create Attribute Object and set value 
        Attr attribte = dom.createAttribute("attributeName");
        attribte.setValue("attributeValue");

    Add Attribute object with appropriate node
        root.setAttributeNode(attribte);

 

Step 7:
   Create TransformerFactory object. 
       TransformerFactory transFactory = TransformerFactory.newInstance();

Step 8:
    Create Transformer object.
        Transformer transformer = transFactory.newTransformer();

Step 9:
    Create DOMSource Object .
        DOMSource domSource = new DOMSource(dom);

Step 10:
    Create  StreamResult object and show the file into the console or save in file.

        //Show the file in console
        StreamResult console = new StreamResult(System.out);
        transformer.transform(domSource, console);


         //Save the XML File
        StreamResult xmlFile = new StreamResult(new File("File Path"));
        transformer.transform(domSource, xmlFile);

   
Example Code Given Below :


package domparsing;

import java.io.File;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class DOMWriterExample {

    public static void main(String[] args) throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
        /**
         * Create DocumentBuilderFactory Object.
         */

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        /**
         * Create DocumentBuilder object.
         */

        DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
        /**
         * Create Document object.
         */

        Document dom = domBuilder.newDocument();
        /**
         * Create root element students and add to DOM .
         */

        Element rootStart = dom.createElement("students");
        dom.appendChild(rootStart);

        /**
         * Add student node under students node.
         */

        Element root = dom.createElement("student");
        rootStart.appendChild(root);

        /**
         * Adding Attribute in student node.
         */

        Attr attribte = dom.createAttribute("id");
        attribte.setValue("1");
        root.setAttributeNode(attribte);

        /**
         * Add fname,lname and section under student node and attribute also.
         */

        Element childNodeFirstName = dom.createElement("fname");
        childNodeFirstName.setTextContent("TestFirstName");
        root.appendChild(childNodeFirstName);

        Element childNodeLastName = dom.createElement("lname");
        childNodeLastName.setTextContent("TestLastName");
        root.appendChild(childNodeLastName);

        Element childNodeSectionName = dom.createElement("sectionname");
        childNodeSectionName.setAttribute("rollno", "1");
        childNodeSectionName.setTextContent("A");
        root.appendChild(childNodeSectionName);
        /**
         * Create TransformerFactory and set property.
         */

        TransformerFactory transFactory = TransformerFactory.newInstance();
        //transFactory.setAttribute("indent-number", 4);
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        /**
         * Create DOMSource object and pass DOM object as a parameter.
         */

        DOMSource domSource = new DOMSource(dom);

        /**
         * Showing output on Console.
         */

        StreamResult console = new StreamResult(System.out);
        transformer.transform(domSource, console);
        /*
         StreamResult result = new StreamResult(new StringWriter());
         transformer.transform(domSource, result);
         String xmlString = result.getWriter().toString();
         System.out.println(xmlString);
         */


        /**
         * Storing XML into the file.
         */

        StreamResult xmlFile = new StreamResult(new File("C:\\file.xml"));
        transformer.transform(domSource, xmlFile);
    }
}