Why XMLReader.parse() throws NullPointerException ? [ sax  xerces ]

Hi, I have a thread that get xml text from a document and parse it. When i type *<?xml* or i delete *<?xml version="1.0" encoding="UTF-16"?>* until *<?xml version="1.0 >* i get this Nullexception:
Exception in thread "Thread-5" java.lang.NullPointerException
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.scanChar(XMLEntityScanner.java:533)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:219)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:772)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
at TA.S$C7.run(S.java:94)
Here is the code:
@Override public void run()
{while(true)
{while((doc.getLength()==0)||(ao1==false))
{try {this.sleep(500);}
catch (InterruptedException ex){}
try
{try
{if(ao1) {text=this.doc.getText(0,doc.getLength()); reader = new StringReader(text); source = new InputSource(reader); source.setSystemId("StringReader"); }
} catch (BadLocationException ex){}
if(ao1) xmlReader.parse(source); //*THIS GENERATE java.lang.NullPointerException*
}//error here
catch (IOException ex) {}
catch (SAXException ex){System.out.println("Error: "+ex.toString());}
try {this.sleep(2000);}catch (InterruptedException ex) {}
Thanks

I can't understand what typing or deleting has to do with anything; the parser is parsing a document, isn't it? Unless it's parsing from System.in and you're typing the document into the console, which doesn't seem likely based on what you posted.
However this
<?xml version="1.0 >{code}
isn't a well-formed prolog. There's a missing closing quote on the version attribute. I still wouldn't have expected a NPE, but then you haven't posted much of an example. There's some unformatted code (try posting it inside {code} tags to make it readable) and you don't show an example of a document which causes the exception. Just some stuff about typing and deleting.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • SAX Parser throws NullPointerException

    Hi.
    I'm using WLS6.1 SP1 built-in XML SAX parser. The code is like,
    SAXParserFactory factory = SAXParserFactory.newInstance();
    XMLReader parser = factory.newSAXParser().getXMLReader();
    // Add a error handler
    eh = new MyErrorHandler();
    parser.setErrorHandler(eh);
    parser.setContentHandler(this);
    // Enable namespace
    parser.setFeature("http://xml.org/sax/features/namespaces", true);
    // Enable validation
    parser.setFeature("http://xml.org/sax/features/validation", false);
    parser.parse(new InputSource(in));
    The NullPointerException is thrown at -
    org.apache.xerces.framework.XMLParser.parse(XMLParser.java:965)
    after the end element of (</eb:MessageHeader>) before the start element of <SOAP-ENV:Header>.
    The XML file is attached.
    =====================================
    However, I tried to parse this document on xerces parser 131.
    It worked fine.
    =====================================
    Did I miss any thing? It seems like a bug to me.
    Thanks!
    [header.xml]

    SAX should mask the fact that some content is specified inside of a CDATA section.. It is just characters.
    The safest way to process characters is to setup a StringBuffer or equivalent in the startElement method. There is a variation of the StringBuffer append method that has the same three parameters (char[], int, int) as the characters signature. The characters method may be called many times before you are given all of the content of the string. How it decides when to call you depends on the parser and is subject to change over time. But, if you accumulate the contents in each call of characters and do the toString() in the endElement method you are going to get the right content. Lots of people over the last year or so that I've been involved in this forum have had other ways they thought were better than this, but most of them have eventually tried and accepted this way because it works and their "better" way did not.
    It looks like you got the content for the CDATA section (Please refer...).I'm not sure what your problem is.
    Dave Patterson

  • XML parsing -  org.xml.sax.driver not specified

    I am attempmtping to parse my first XML document and get the following excpetion when running my prog.
    org.xml.sax.SAXException: System property org.xml.sax.driver not specified.
    I am following the examples in the O'Reilly Java and XML book but suspect I am missing something obvious.
    This is the offending line of code:
    XMLReader xr = XMLReaderFactory.createXMLReader();
    Any help will be appreciated.

    You need to set a property for your class that invokes your SAX handler. This is the property you need to set
    org.xml.sax.driver=???
    Where ??? is the name of the package where your SAXparser lives.
    for example, my sax driver is in:
    org.xml.sax.driver=org.apache.xerces.parsers.SAXParser
    (see code below)
    Also, a sweet reference is Elliot Rusty Harold's "XML processing with Java", which answered all the practical questions I had -- really! And is free, online.
    http://www.ibiblio.org/xml/books/xmljava/chapters/index.html
    This is the code for main() where my xml handler is invoked
    try
    {  SpiderHandler spiderHandler = new SpiderHandler(testSpider);
       XMLReader reader = XMLReaderFactory.createXMLReader();
       reader.setContentHandler(spiderHandler);
       for (int i=4; i<args.length; i++)
       {   FileReader xmlScript = new FileReader(args);
    System.out.println("Input file number "+i+" named "+args[i]);
    // org.xml.sax.XMLReader.parse(InputSource) interface
    // see org.xml.sax.InputSource class      
    reader.parse(new InputSource(xmlScript));
    catch(Exception e)
    {   System.out.println("Error encountered in parsing from main(). \n");
    e.printStackTrace();
    Luck to you! XML is a joy.

  • Why it is throwing null at last  whenever i am running this program

    public static void main(String args[])
              String str;                    
              try     
              FileReader fis = new FileReader(C:\\src\\vinaysingh\\xmlreq.xml");
              BufferedReader br= new BufferedReader(fis);
              do
                   str=br.readLine();
                   System.out.println(str);
              while(!str.equals(null));
    why it is throwing null on last if i am reading any xml file

    get the value of string as the value which u
    had collected from the string instead of nullWhat? That just doesn't make any sense. At all.
    I presume what you're asking is:
    How do I read lines from a text file, ignoring empty lines. Especially how do I know when I've reached the end of the file so that I can stop trying to read more lines.
    this might help some ...
    package krc.utilz.io;
    import java.util.Collection;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.io.File;
    import java.io.Reader;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.InputStream;
    import java.io.FileInputStream;
    import java.io.Closeable;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    * @class: krc.utilz.io.Filez
    * A collection of static "file handling" helper methods.
    public abstract class Filez
      public static final int BFRSIZE = 4096;
       * reads the given file into one big string.<p>
       * Warning: don't use this on big files. It uses too much RAM!
       * @param String filename - the name of the file to read
       * @return the contents filename
      public static String read(String filename)
        throws FileNotFoundException
        return Filez.read(new FileReader(filename));
       * Reads the contents of the given reader into one big string, and closes
       * the reader.
       * Warning: don't use this on big files. It uses too much RAM!
       * @param java.io.Reader reader - a subclass of Reader to read from.
       * @return the whole contents of the given reader.
      public static String read(Reader in)
        try {
          StringBuffer out = new StringBuffer();
          try {
            char[] bfr = new char[BFRSIZE];
            int n = 0;
            while( (n=in.read(bfr,0,BFRSIZE)) > 0 ) {
              out.append(bfr,0,n);
          } finally {
            if(in!=null)in.close();
          return out.toString();
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
       * (re)writes the given content to the given filename
       * @param String content - the new contents of the fil
       * @param String filename - the name of the file to write.
      public static void write(String content, String filename) {
        try {
          PrintWriter out = null;
          try {
            out = new PrintWriter(new FileWriter(filename));
            out.write(content);
          } finally {
            if(out!=null)out.close();
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
       * Appends the given content to the given filename.
       * @param String content - the string to write to the file.
       * @param String filename - the name of the file to write to.
      public static void append(String content, String filename) {
        try {
          PrintWriter out = null;
          try {
            out = new PrintWriter(new FileWriter(filename, true)); //true=append
            out.write(content);
          } finally {
            if(out!=null)out.close();
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
       * reads each line of the given file into an array of strings.
       * @param String filename - the name of the file to read
       * @return a fixed length array of strings containing file contents.
      public  static String[] readArray(String filename)
        throws FileNotFoundException
        return readList(filename).toArray(new String[0]);
       * reads each line of the given file into an ArrayList of strings.
       * @param String filename - the name of the file to read
       * @return an ArrayList of strings containing file contents.
      public static ArrayList<String> readArrayList(String filename)
        throws FileNotFoundException
        return (ArrayList<String>)readList(filename);
       * reads each line of the given file into a List of strings.
       * @param String filename - the name of the file to read
       * @return an List handle ArrayList of strings containing file contents.
      public static List<String> readList(String filename)
        throws FileNotFoundException
        try {
          BufferedReader in = null;
          List<String> out = new ArrayList<String>();
          try {
            in = new BufferedReader(new FileReader(filename));
            String line = null;
            while ( (line = in.readLine()) != null ) {
              out.add(line);
          } finally {
            if(in!=null)in.close();
          return out;
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
       * reads the whole of the given file into an array of bytes.
       * @param String filename - the name of the file to read
       * @return an array of bytes containing the file contents.
      public static byte[] readBytes(String filename)
        throws FileNotFoundException
        return( readBytes(new File(filename)) );
       * reads the whole of the given file into an array of bytes.
       * @param File file - the file to read
       * @return an array of bytes containing the file contents.
      public static byte[] readBytes(File file)
        throws FileNotFoundException
        try {
          byte[] out = null;
          InputStream in = null;
          try {
            in = new FileInputStream(file);
            out = new byte[(int)file.length()];
            int size = in.read(out);
          } finally {
            if(in!=null)in.close();
          return out;
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
       * do files A & B have the same contents
       * @param String filenameA - the first file to compare
       * @param String filenameA - the second file to compare
       * @return boolean do-these-two-files-have-the-same-contents?
      public static boolean isSame(String filenameA, String filenameB)
        throws FileNotFoundException
        try {
          File fileA = new File(filenameA);
          File fileB = new File(filenameB);
          //check for same physical file
          if( fileA.equals(fileB) ) return(true);
          //compare sizes
          if( fileA.length() != fileB.length() ) return(false);
          //compare contents (buffer by buffer)
          boolean same=true;
          InputStream inA = null;
          InputStream inB = null;
          try {
            inA = new FileInputStream(fileA);
            inB = new FileInputStream(fileB);
            byte[] bfrA = new byte[BFRSIZE];
            byte[] bfrB = new byte[BFRSIZE];
            int sizeA=0, sizeB=0;
            do {
              sizeA = inA.read(bfrA);
              sizeB = inA.read(bfrB);
              if ( sizeA != sizeB ) {
                same = false;
              } else if ( sizeA == 0 ) {
                //do nothing
              } else if ( !Arrays.equals(bfrA,bfrB) ) {
                same = false;
            } while (same && sizeA != -1);
          } finally {
            Clozer.close(inA, inB);
          return(same);
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
       * checks the given filename exists and is readable
       * @param String filename = the name of the file to "open".
       * @param OPTIONAL String type = a short name for the file used to identify
       *  the file in any exception messages.
       *  For example: "input", "input data", "DTD", "XML", or whatever.
       * @return a File object for the given filename.
       * @throw FileNotFoundException if the given file does not exist.
       * @throw IOException if the given file is unreadable (usually permits).
      public static File open(String filename)
        throws FileNotFoundException
        return(open(filename,"input"));
      public static File open(String filename, String type)
        throws FileNotFoundException
        try {
          File file = new File(filename);
          String fullname = file.getCanonicalPath();
          if(!file.exists()) throw new FileNotFoundException(type+" file does not exist: "+fullname);
          if(!file.canRead()) throw new RuntimeIOException(type+" file is not readable: "+fullname);
          return(file);
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
       * gets the filename-only portion of a canonical-filename, with or without
       * the extension.
       * @param String path - the full name of the file.
       * OPTIONAL @param boolean cutExtension - if true then remove any .ext
       * @return String the filename-only (with or without extension)
      public static String basename(String path) {
        return(basename(path,false));
      public static String basename(String path, boolean cutExtension)
        String fname = (new File(path)).getName();
        if (cutExtension) {
          int i = fname.lastIndexOf(".");
          if(i>0) fname = fname.substring(0,i);
        return(fname);
    }You'll probably want to remove all references to RuntimeIOException... just throw the standard checked IOException instead.

  • Private Room throws NullPointerException

    Hi,
    I have created a private room and it was sucessfull. i am able to see the room without any problem. but when others(non-members) go to their rooms directory, it throws NullPointerException. This problem is only for private rooms only.
    we are using SP 17
    The exception is
    java.lang.NullPointerException
         at com.sap.ip.collaboration.roomui.api.util.properties.RoomResourceProperties.getPropertyValueAsString(RoomResourceProperties.java:53)
         at com.sap.ip.collaboration.roomui.api.util.properties.RoomResourceProperties.getRoomPrivacy(RoomResourceProperties.java:33)
         at com.sap.netweaver.coll.roomui.api.uicommands.UIRequestMembershipCommand.isExecutable(UIRequestMembershipCommand.java:67)
         at com.sapportals.wcm.rendering.uicommand.UIGroupCommand.getResourceCommands(UIGroupCommand.java:78)
         at  ..............
    can anyone reply what might be the reason be?
    Thank you.
    Saravana.
    Edited by: Saravana Parthiban Palaniswamy on Feb 4, 2009 1:22 PM
    Edited by: Saravana Parthiban Palaniswamy on Feb 4, 2009 1:26 PM

    Hi,
    If u goes to room directory in collaboration, there is a tab called Restricted Rooms. End of the room name there is context menu if u click that, it will show the menu there you can see the option called “Request Membership”. If you click that, corresponding room owner will receive the mail if he/she enabled the mail properties.
    If the answer helps your Question, provide the points.
    Regards,
    Kathiresan R

  • CreateEntityManagerFactory throws NullPointerException for ejb3 jse client

    This question has been posted to the Toplink/jpa forum without any reply.
    Dear experts!
    I am trying to create a java standard edition client, to test outside the weblogic server, my ejb 3 entities, declared as shown in the following persistence.xml.
    The java code follows also. I have read about some relevant bugs in eclipselink back in 2006, or 7 or 8 and mostly unanswered threads :
    CreateEntityManagerFactory null pointer exception and
    Returned null to createEntityManagerFactory about tomcat and oc4j.
    Persistence.createEntityManagerFactory() throw NullPointerException in oc4j
    I am using JDeveloper 11g Studio Edition Version 11.1.1.3.0, Build JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660.
    Any helping hand available?
    Thank you very much in advance!
    NA
    package chapter12javaseclient;
    import actionbazaar.buslogic.BidException;
    import actionbazaar.persistence.Bid;
    import actionbazaar.persistence.Bidder;
    import actionbazaar.persistence.Item;
    import java.util.HashMap;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import org.eclipse.persistence.config.EntityManagerProperties;
    public class PlaceBidBeanJavaSE {
    private static EntityManagerFactory emf;
    private static EntityManager em;
    public static void main(String[] args) {
    String userId= "idiot";
    Long itemId = new Long (1);
    Double bidPrice = 2001.50;
    try {
    if (emf == null){
    emf = Persistence.createEntityManagerFactory("actionBazaar");
    System.out.println("EntityManagerFactory created!");
    getEntityManager();
    System.out.println("EntityManager created!");
    addBid(userId,itemId,bidPrice);
    commitTransaction();
    } finally {
    // close the EntityManager when done
    em.close();
    emf.close();
    private static void getEntityManager() {
    HashMap emProps = new HashMap();
    emProps.put(EntityManagerProperties.JDBC_USER, "ab");
    emProps.put(EntityManagerProperties.JDBC_PASSWORD, "ab");
    System.out.println("Creating entity manager");
    em = emf.createEntityManager(emProps);
    em.getTransaction().begin();
    private static void commitTransaction() {
    em.getTransaction().commit();
    private static Long addBid(String userId, Long itemId, Double bidPrice) throws BidException {
    Item item = em.find(Item.class,itemId);
    if (item == null)
    throw new BidException("Invalid Item Id");
    Bidder bidder = em.find(Bidder.class,userId);
    if (bidder == null)
    throw new BidException("Invalid Bidder Id");
    Bid bid = new Bid();
    bid.setItem(item);
    bid.setBidBidder(bidder);
    bid.setBidPrice(bidPrice);
    em.persist(bid);
    return bid.getBidId();
    <?xml version="1.0" encoding="UTF-8" ?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="actionBazaar" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>actionbazaar.persistence.Bid</class>
    <class>actionbazaar.persistence.Item</class>
    <class>actionbazaar.persistence.User</class>
    <class>actionbazaar.persistence.Bidder</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    <property name="eclipselink.target-server" value="WebLogic_10"/>
    <property name="eclipselink.target-database" value="Oracle11"/>
    <property name="javax.persistence.jdbc.driver"
    value="oracle.jdbc.OracleDriver"/>
    <property name="javax.persistence.jdbc.password"
    value="ab"/>
    <property name="javax.persistence.jdbc.url"
    value="jdbc:oracle:thin:@hera:1521:orcl"/>
    <property name="javax.persistence.jdbc.user" value="ab"/>
    <property name="eclipselink.logging.level" value="ALL"/>
    </properties>
    </persistence-unit>
    </persistence>

    A solution might be found here:
    Re: createEntityManagerFactory() throws NullPointerException for ejb jse client
    Re: createEntityManagerFactory() throws NullPointerException for ejb jse client
    NA
    [http://nickaiva.blogspot.com/]

  • CreateEntityManagerFactory() throws NullPointerException for ejb jse client

    Dear experts!
    I am trying to create a java standard edition client, to test outside the weblogic server, my ejb 3 entities, declared as shown in the following persistence.xml.
    The java code, and stacktrace follows also. I have read about some relevant bugs in eclipselink back in 2006, or 7 or 8 and mostly unanswered threads :
    CreateEntityManagerFactory null pointer exception and
    Returned null to createEntityManagerFactory about tomcat and oc4j.
    Persistence.createEntityManagerFactory() throw NullPointerException in oc4j
    I am using JDeveloper 11g Studio Edition Version 11.1.1.3.0, Build JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660.
    Any helping hand available?
    Thank you very much in advance!
    NA
    package chapter12javaseclient;
    import actionbazaar.buslogic.BidException;
    import actionbazaar.persistence.Bid;
    import actionbazaar.persistence.Bidder;
    import actionbazaar.persistence.Item;
    import java.util.HashMap;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import org.eclipse.persistence.config.EntityManagerProperties;
    public class PlaceBidBeanJavaSE {
    private static EntityManagerFactory emf;
    private static EntityManager em;
    public static void main(String[] args) {
    String userId= "idiot";
    Long itemId = new Long (1);
    Double bidPrice = 2001.50;
    try {
    if (emf == null){
    emf = Persistence.createEntityManagerFactory("actionBazaar");
    System.out.println("EntityManagerFactory created!");
    getEntityManager();
    System.out.println("EntityManager created!");
    addBid(userId,itemId,bidPrice);
    commitTransaction();
    } finally {       
    // close the EntityManager when done
    em.close();
    emf.close();
    private static void getEntityManager() {
    HashMap emProps = new HashMap();
    emProps.put(EntityManagerProperties.JDBC_USER, "ab");
    emProps.put(EntityManagerProperties.JDBC_PASSWORD, "ab");
    System.out.println("Creating entity manager");
    em = emf.createEntityManager(emProps);
    em.getTransaction().begin();
    private static void commitTransaction() {
    em.getTransaction().commit();
    private static Long addBid(String userId, Long itemId, Double bidPrice) throws BidException {
    Item item = em.find(Item.class,itemId);
    if (item == null)
    throw new BidException("Invalid Item Id");
    Bidder bidder = em.find(Bidder.class,userId);
    if (bidder == null)
    throw new BidException("Invalid Bidder Id");
    Bid bid = new Bid();
    bid.setItem(item);
    bid.setBidBidder(bidder);
    bid.setBidPrice(bidPrice);
    em.persist(bid);
    return bid.getBidId();
    <?xml version="1.0" encoding="UTF-8" ?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="actionBazaar" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>actionbazaar.persistence.Bid</class>
    <class>actionbazaar.persistence.Item</class>
    <class>actionbazaar.persistence.User</class>
    <class>actionbazaar.persistence.Bidder</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    <property name="eclipselink.target-server" value="WebLogic_10"/>
    <property name="eclipselink.target-database" value="Oracle11"/>
    <property name="javax.persistence.jdbc.driver"
    value="oracle.jdbc.OracleDriver"/>
    <property name="javax.persistence.jdbc.password"
    value="ab"/>
    <property name="javax.persistence.jdbc.url"
    value="jdbc:oracle:thin:@hera:1521:orcl"/>
    <property name="javax.persistence.jdbc.user" value="ab"/>
    <property name="eclipselink.logging.level" value="ALL"/>
    </properties>
    </persistence-unit>
    </persistence>
    The log output follows:
    C:\Oracle\Middleware\jdev_11gR1\jdk160_18\bin\javaw.exe -client -classpath C:\MyWork\11g\ejb3inaction\.adf;C:\MyWork\11g\ejb3inaction\Chapter12JavaSEClient\classes;C:\MyWork\11g\ejb3inaction\Chapter12\classes;C:\Oracle\Middleware\jdev_11gR1\modules\javax.ejb_3.0.1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\com.oracle.toplink_1.0.0.0_11-1-1-3-0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\org.eclipse.persistence_1.0.0.0_2-0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\com.bea.core.antlr.runtime_2.7.7.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.toplink_11.1.1\javax.persistence_2.0_preview.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.xdk_11.1.0\xmlparserv2.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.xdk_11.1.0\xml.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.jsf_1.0.0.0_1-2.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.enterprise.deploy_1.2.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.interceptor_1.0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.jms_1.1.1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.jsp_1.1.0.0_2-1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.jws_2.0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.activation_1.1.0.0_1-1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.mail_1.1.0.0_1-4-1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.xml.soap_1.3.1.0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.xml.rpc_1.2.1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.xml.ws_2.1.1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.management.j2ee_1.0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.resource_1.5.1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.servlet_1.0.0.0_2-5.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.transaction_1.0.0.0_1-1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.xml.stream_1.1.1.0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.security.jacc_1.0.0.0_1-1.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.xml.registry_1.0.0.0_1-0.jar;C:\Oracle\Middleware\jdev_11gR1\modules\javax.persistence_1.0.0.0_1-0-2.jar;C:\Oracle\Middleware\jdev_11gR1\wlserver_10.3\server\lib\weblogic.jar;C:\Oracle\Middleware\jdev_11gR1\wlserver_10.3\server\ext\jdbc\oracle\11g\ojdbc6.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.nlsrtl_11.1.0\orai18n-collation.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.nlsrtl_11.1.0\orai18n-lcsd.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.nlsrtl_11.1.0\orai18n-mapping.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.nlsrtl_11.1.0\orai18n-servlet.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.nlsrtl_11.1.0\orai18n-translation.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.nlsrtl_11.1.0\orai18n-utility.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.nlsrtl_11.1.0\orai18n.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.odl_11.1.1\ojdl.jar;C:\Oracle\Middleware\jdev_11gR1\oracle_common\modules\oracle.dms_11.1.1\dms.jar -Djavax.net.ssl.trustStore=C:\Oracle\Middleware\jdev_11gR1\wlserver_10.3\server\lib\DemoTrust.jks chapter12javaseclient.PlaceBidBeanJavaSE
    [EL Finest]: 2010-06-25 09:23:10.495--ServerSession(229902)--Thread(Thread[main,5,main])--Begin predeploying Persistence Unit actionBazaar; session file:/C:/MyWork/11g/ejb3inaction/Chapter12JavaSEClient/classes/_actionBazaar; state Initial; factoryCount 0
    [EL Finest]: 2010-06-25 09:23:10.518--ServerSession(229902)--Thread(Thread[main,5,main])--property=eclipselink.orm.throw.exceptions; default value=true
    [EL Finer]: 2010-06-25 09:23:10.532--ServerSession(229902)--Thread(Thread[main,5,main])--Searching for default mapping file in file:/C:/MyWork/11g/ejb3inaction/Chapter12JavaSEClient/classes/
    [EL Finer]: 2010-06-25 09:23:10.537--ServerSession(229902)--Thread(Thread[main,5,main])--Searching for default mapping file in file:/C:/MyWork/11g/ejb3inaction/Chapter12JavaSEClient/classes/
    [EL Config]: 2010-06-25 09:23:10.652--ServerSession(229902)--Thread(Thread[main,5,main])--The access type for the persistent class [class actionbazaar.persistence.Item] is set to [PROPERTY].
    [EL Config]: 2010-06-25 09:23:10.696--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the many to many mapping element [method getCategorySet] is being defaulted to: class actionbazaar.persistence.Category.
    [EL Config]: 2010-06-25 09:23:10.702--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the one to many mapping element [method getBids] is being defaulted to: class actionbazaar.persistence.Bid.
    [EL Config]: 2010-06-25 09:23:10.71--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the many to one mapping element [method getSeller] is being defaulted to: class actionbazaar.persistence.Seller.
    [EL Config]: 2010-06-25 09:23:10.71--ServerSession(229902)--Thread(Thread[main,5,main])--The access type for the persistent class [class actionbazaar.persistence.User] is set to [PROPERTY].
    [EL Config]: 2010-06-25 09:23:10.711--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the one to many mapping element [method getCategories] is being defaulted to: class actionbazaar.persistence.Category.
    [EL Config]: 2010-06-25 09:23:10.716--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the one to one mapping element [method getBillingInfo] is being defaulted to: class actionbazaar.persistence.BillingInfo.
    [EL Config]: 2010-06-25 09:23:10.717--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the one to one mapping element [method getContactInfo] is being defaulted to: class actionbazaar.persistence.ContactInfo.
    [EL Config]: 2010-06-25 09:23:10.718--ServerSession(229902)--Thread(Thread[main,5,main])--The access type for the persistent class [class actionbazaar.persistence.Bidder] is set to [PROPERTY].
    [EL Config]: 2010-06-25 09:23:10.72--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the one to many mapping element [method getBids] is being defaulted to: class actionbazaar.persistence.Bid.
    [EL Config]: 2010-06-25 09:23:10.721--ServerSession(229902)--Thread(Thread[main,5,main])--The access type for the persistent class [class actionbazaar.persistence.Bid] is set to [PROPERTY].
    [EL Config]: 2010-06-25 09:23:10.721--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the many to one mapping element [method getBidBidder] is being defaulted to: class actionbazaar.persistence.Bidder.
    [EL Config]: 2010-06-25 09:23:10.721--ServerSession(229902)--Thread(Thread[main,5,main])--The target entity (reference) class for the many to one mapping element [method getItem] is being defaulted to: class actionbazaar.persistence.Item.
    [EL Config]: 2010-06-25 09:23:10.722--ServerSession(229902)--Thread(Thread[main,5,main])--The alias name for the entity class [class actionbazaar.persistence.Item] is being defaulted to: Item.
    [EL Config]: 2010-06-25 09:23:10.746--ServerSession(229902)--Thread(Thread[main,5,main])--The alias name for the entity class [class actionbazaar.persistence.Bidder] is being defaulted to: Bidder.
    [EL Config]: 2010-06-25 09:23:10.746--ServerSession(229902)--Thread(Thread[main,5,main])--The alias name for the entity class [class actionbazaar.persistence.User] is being defaulted to: User.
    [EL Config]: 2010-06-25 09:23:10.753--ServerSession(229902)--Thread(Thread[main,5,main])--The table name for entity [class actionbazaar.persistence.Bidder] is being defaulted to: USERS.
    [EL Config]: 2010-06-25 09:23:10.753--ServerSession(229902)--Thread(Thread[main,5,main])--The discriminator column name for the root inheritance class [class actionbazaar.persistence.Bidder] is being defaulted to: DTYPE.
    [EL Config]: 2010-06-25 09:23:10.755--ServerSession(229902)--Thread(Thread[main,5,main])--The primary key column name for the inheritance class [class actionbazaar.persistence.Bidder] is being defaulted to: USER_ID.
    [EL Config]: 2010-06-25 09:23:10.755--ServerSession(229902)--Thread(Thread[main,5,main])--The foreign key column name for the inheritance class [class actionbazaar.persistence.Bidder] is being defaulted to: USER_ID.
    [EL Config]: 2010-06-25 09:23:10.758--ServerSession(229902)--Thread(Thread[main,5,main])--The alias name for the entity class [class actionbazaar.persistence.Bid] is being defaulted to: Bid.
    Exception in thread "main" java.lang.NullPointerException
         at chapter12javaseclient.PlaceBidBeanJavaSE.main(PlaceBidBeanJavaSE.java:43)
    Process exited with exit code 1.

    Thank you for your reply!
    The client now works correctly. It seems that the line
    em = emf.createEntityManager(emProps);//
    throws an exception when no argument is given for em = emf.createEntityManager();// emProps missing!
    There was also a warning in jdev editor, about the line you mentioned:
    <property name="eclipselink.target-server" value="WebLogic 10"/>
    Carry on with your good work!
    The updated persistence.xml and java source code shown below:
    <?xml version="1.0" encoding="UTF-8" ?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="actionBazaar" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>actionbazaar.persistence.Bid</class>
    <class>actionbazaar.persistence.Item</class>
    <class>actionbazaar.persistence.User</class>
    <class>actionbazaar.persistence.Bidder</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    <property name="eclipselink.target-database" value="Oracle11"/>
    <property name="javax.persistence.jdbc.driver"
    value="oracle.jdbc.OracleDriver"/>
    <property name="javax.persistence.jdbc.password"
    value="29E8BD11B89A62E3862F19C4F84B7DB0"/>
    <property name="javax.persistence.jdbc.user" value="ab"/>
    <property name="eclipselink.logging.level" value="ALL"/>
    <property name="eclipselink.orm.validate.schema" value="true"/>
    <property name="javax.persistence.jdbc.url"
    value="jdbc:oracle:thin:@hera:1521:orcl"/>
    </properties>
    </persistence-unit>
    </persistence>
    package chapter12javaseclient;
    import actionbazaar.buslogic.BidException;
    import actionbazaar.persistence.Bid;
    import actionbazaar.persistence.Bidder;
    import actionbazaar.persistence.Item;
    import java.util.HashMap;
    import java.util.Hashtable;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    import org.eclipse.persistence.config.EntityManagerProperties;
    public class PlaceBidBeanJavaSE {
    private static EntityManagerFactory emf;
    private static EntityManager em;
    private static Hashtable emProps = new Hashtable();
    public static void main(String[] args) {
    String userId= "idiot";
    Long itemId = new Long (2);
    Double bidPrice = 2002.50;
    try {
    if (emf == null){
    emf = Persistence.createEntityManagerFactory("actionBazaar");
    System.out.println("EntityManagerFactory created!");
    getEntityManager();
    System.out.println("EntityManager created!");
    addBid(userId,itemId,bidPrice);
    commitTransaction();
    } finally {       
    // close the EntityManager when done
    em.close();
    emf.close();
    private static void getEntityManager() {
    try {
    System.out.println("Creating entity manager");
    em = emf.createEntityManager(emProps);// if argument is missing exception is thrown!
    em.getTransaction().begin();
    } catch (Exception ne) {
    // TODO: Add catch code
    ne.printStackTrace();
    private static void commitTransaction() {
    em.getTransaction().commit();
    private static Long addBid(String userId, Long itemId, Double bidPrice) throws BidException {
    Item item = em.find(Item.class,itemId);
    if (item == null)
    throw new BidException("Invalid Item Id");
    Bidder bidder = em.find(Bidder.class,userId);
    if (bidder == null)
    throw new BidException("Invalid Bidder Id");
    Bid bid = new Bid();
    bid.setItem(item);
    bid.setBidBidder(bidder);
    bid.setBidPrice(bidPrice);
    em.persist(bid);
    return bid.getBidId();
    NA
    [http://nickaiva.blogspot.com/]

  • XMLReader throws NullPointerException

    have developed a CSV to XML parser using a JAXP with SAX Events to parse the CSV file into a DOM tree.
    Well inside the parse() method I have the following code":
    public void parse(InputSource input) throws IOException, SAXException
    BufferedReader br = null;
    if( input.getCharacterStream() != null )
    br = new BufferedReader( input.getCharacterStream() );
    else if( input.getByteStream() != null )
    br = new BufferedReader( new InputStreamReader( input.getByteStream() ) );
    else if( input.getSystemId() != null )
    URL url = new URL( input.getSystemId() );
    br = new BufferedReader( new InputStreamReader( url.openStream() ) );
    else
    throw new SAXException( "Objeto InputSource invalido" );
    ContentHandler ch = getContentHandler();
    ch.startDocument();
    ch.startElement( "", "", "file", new AttributesImpl() );
    this.parseInput( br );
    ch.endElement( "", "", "file" );
    ch.endDocument();
    Problem is that whenever the app gets to the ch.startDocument() statement it throws an java.lang.NullPointerExecption. I have no idea why this is happening, I have tested the very same code with Xalan 2 and Xercer 2 parsers and it works without problems. But using the oracle xml parser v2 throws the Exception.
    Is this a bug? should I set tome of the Transformer's attributes to an specifica value to avoid this? Where could I find more info on processing SAX events?
    Thanks,
    Fedro

    have developed a CSV to XML parser using a JAXP with SAX Events to parse the CSV file into a DOM tree.
    Well inside the parse() method I have the following code":
    public void parse(InputSource input) throws IOException, SAXException
    BufferedReader br = null;
    if( input.getCharacterStream() != null )
    br = new BufferedReader( input.getCharacterStream() );
    else if( input.getByteStream() != null )
    br = new BufferedReader( new InputStreamReader( input.getByteStream() ) );
    else if( input.getSystemId() != null )
    URL url = new URL( input.getSystemId() );
    br = new BufferedReader( new InputStreamReader( url.openStream() ) );
    else
    throw new SAXException( "Objeto InputSource invalido" );
    ContentHandler ch = getContentHandler();
    ch.startDocument();
    ch.startElement( "", "", "file", new AttributesImpl() );
    this.parseInput( br );
    ch.endElement( "", "", "file" );
    ch.endDocument();
    Problem is that whenever the app gets to the ch.startDocument() statement it throws an java.lang.NullPointerExecption. I have no idea why this is happening, I have tested the very same code with Xalan 2 and Xercer 2 parsers and it works without problems. But using the oracle xml parser v2 throws the Exception.
    Is this a bug? should I set tome of the Transformer's attributes to an specifica value to avoid this? Where could I find more info on processing SAX events?
    Thanks,
    Fedro

  • SAX (xerces) problem

    I have a big problem with Apache Xerces2 Java.
    I have to parse and get data from very large xml files (100 MB to 20 GB). Because the files are very large I have to use SAX parser.
    If I use internal xerces in any update of jdk/jre 1.6 then whole document gets into memory. I have found a bug report related at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6536111 . I am not sure that fix will solve my problem and fix has not delivered yet. According to the bug report it is going to be delivered with jdk6 update 14 in the mid May 2009.
    I thougt maybe the problem is with the internal SAX parser. So I started to use source of xerces. (I use the last version - 2.9.1). At this point I have discovered that parse takes more time and need 24 byte for each node. Sometimes xml files have 80.000.000 nodes. It will take 1,5 - 2 GB of RAM which I don't have. Even if I have RAM that size I can not use it at windows 32 platform. (OS limits)
    Has anyone got idea, solution?
    Thanks..

    Thank you both Toll and DrClap for your help. I'll take a look at Saxon, but I'm still intrigued why nobody is complaining about a tool (SAX) that's almost a standard for stream parsing... and yet not working for XSLT transformations! Maybe you were right after all when you said stream processing might not be possible for my XSLT file but I doubt it because the XML is representing "sort of" a table and therefore it's made up of thousands of structurally identical <row> elements which can be individually transformed...I can't think of anything more suitable for streaming transformation.
    Thanks again for your time.
    Edited: at the end I've decided to parse the document using SAX (which in my tests uses almost no memory at all and performs lightning-fast) and then applying a XSL transformation for each parsed node (I can do it in my case). But transforming a document will still be a huge problem -in terms of memory usage- for those who don't have a repeating pattern on their XML's, although I guess 99% of the times there'll probably be one for big/huge documents.
    I think this will be very useful for other programmers facing the same problem I had. This code divides a xml file into several different files according to a repeating pattern (in this case InsurancePolicyData/Record) using SAX and then processes each chunk of xml separately, optimizing the use of memory:
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.Writer;
    import org.dom4j.io.SAXReader;
    public class SingleThreadSplitXSLT
      public static void main(String[] args)
        throws Exception
        if (args.length != 3)
          System.err.println(
            "Error: Please provide 3 inputs:” +
            “ inputXML XSLT outputXML");
          System.exit(-1);
        long startTimeMs = System.currentTimeMillis();
        File xmlFile = new File(args[0]);
        File xsltFile = new File(args[1]);
        BufferedWriter outputWriter = new
          BufferedWriter(new FileWriter(args[2]));
        styleDocument(xmlFile, xsltFile, outputWriter);
        outputWriter.close();
        long executionTime =
          System.currentTimeMillis() - startTimeMs;
        System.err.println("Successful transformation took "
          + executionTime);
      public static void styleDocument(File xmlFile,
        File xsltFile, Writer outputWriter)
        throws Exception
        // start the output file
        outputWriter.write(
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        outputWriter.write("<InsurancePolicyData>");
        // read the input file incrementally
        SAXReader reader = new SAXReader();
        reader.addHandler( "/InsurancePolicyData/Record",
          new SplitFileElementHandler(
            xsltFile, outputWriter));
        reader.read(xmlFile);
        // finish output file
        outputWriter.write("</InsurancePolicyData>");
    }(I found it at http://www.devx.com/xml/Article/34677/1954)
    That's exactly what I was looking for, hope it helps others as well :)
    Edited by: Isana on Jun 4, 2009 7:56 AM

  • Xml Parse throws SaxParseException.Encoding is UTF-8 insteadof ISO-8859-1 ?

    Hi All,
    I'm having some korean characters in my xml. when i tried to parse the xml i'm getting SaxParseException .
    <?xml version="1.0" encoding="UTF-8"?> --- Throwing Exception
    <?xml version="1.0" encoding="ISO-8859-1"?> --- No Exception, successfully parsed
    I'm not sure why UTF-8 is failing and ISO is passing. But I'm always getting xml with UTF-8 format? Can anyone know the reason?
    I also like to know the differences between UTF-8 and ISO, i don't find any good article/document for this.
    Thanks,
    J.Kathir

    When SAX throws an exception when the encoding is set to UTF-8, then the XML contains something that is not a valid UTF-8 code (i.e. your source file is not encoded using UTF-8). Also: whenever you ask about an exception you should definitely post the entire exception, including message and stack trace.
    If it doesn't throw an exception when it is set to ISO-8859-1, then it does not mean that this is the correct choice. ISO-8859-1 is defined from 0 up to 255, so any byte stream is correct in that encoding ('though not necessarily meaninful).
    You absolutely have to find out which encoding the file really is, before you can parse it. If it should contain Korean characters then it is definitely not ISO-8859-1 (or any other encoding from the ISO-8859 family), as those only support latin, cyrillic and similar scripts.

  • StartElement throws NullPointerException

    hi
    The code below throws a NullPointerException at startElement method ... Can someone help figure out how to fix it ...?
    xmlSt value is set from another method which is NOT NULL.....
    public class xmlResHandler extends HandlerBase
    public void validateXml (String xmlSt) throws Exception
    String xmlString = xmlSt;
    java.io.InputStream input=null;
    input=new java.io.ByteArrayInputStream(xmlString.getBytes());
    out = new OutputStreamWriter (System.out, "UTF8");
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.newSAXParser().parse( input, new xmlResHandler());
    System.out.println("validation success in validateXml");
    public Writer out;
    public xmlResHandler(){}
    public void error (SAXParseException e) throws SAXParseException
    throw e;
    public void warning (SAXParseException err) throws SAXParseException
    System.out.println("** Warning" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
    public void startDocument () throws SAXException
    showData ("<?xml version='1.0' encoding='UTF-8'?>");
    newLine();
    public void endDocument () throws SAXException
    try {
    newLine();
    out.flush ();
    } catch (IOException e) {
    throw new SAXException ("I/O error", e);
    public void startElement (String name, AttributeList attrs) throws SAXException
    showData ("<"+name);
    if (attrs != null) {
    for (int i = 0; i < attrs.getLength (); i++) {
    showData (" ");
    showData (attrs.getName(i)+"=\""+attrs.getValue (i)+"\"");
    showData (">");
    public void endElement (String name) throws SAXException
    showData ("</"+name+">");
    public void characters (char buf [], int offset, int len) throws SAXException
    String s = new String(buf, offset, len);
    showData (s);
    private void showData (String s) throws SAXException
    try {
    System.out.println (s);
    out.flush ();
    } catch (IOException e) {
    throw new SAXException ("I/O error", e);
    private void newLine () throws SAXException
    String lineEnd = System.getProperty("line.separator");
    try {
    System.out.println (lineEnd);
    out.flush ();
    } catch (IOException e) {
    throw new SAXException ("I/O error", e);
    Spent a lot of time ....no luck where i am going wrong ... Thanks for the help in advance
    prabhu

    Tested this with JDK 1.4 and it works with the following changes:
    Make these static:
    static public Writer out;
    static public void validateXml (String xmlSt)
    and, of course adding:
    import java.io.*;
    import org.xml.sax.*;
    import javax.xml.parsers.SAXParserFactory;
    Then here is what I used to test it:
    public class Test2 {
         static public void main(String args[]){
              System.out.println("Hi there");
              String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> <html> <head> <title> Ho there </title> </head> <body> <h1> Hi there </h1> </body> </html>";
              try {
                   xmlResHandler.validateXml(s);
              }catch (Exception ex){
                   ex.printStackTrace();
    }I think you problem make have to do with your management of the "out" Writer.

  • Why not parsing using JDOM?

    Please see the xml file & my java code. The code seems ok..but not parsing right! Please advise, where the problem is?? Also, how do I extract the Supplier tag in this example file??? Any help is really appreciated!!!
    <POOutbound_schema PurchaseOrder="P415704423" OrderDate="2003-06-05"><DocRouting/><Supplier Account="152625001" CompanyName="REP " Address1="ATTENTION SALES " Address2="XXXXXXXXXX " City="XXXXX " Address4=" " Address5=" " Address6=" " State="KA" CountryCode=" " ZipCode="67223 " Phone="833-555-5555" Fax="333-670-3324" OrderStatus="CLOSED AND PRINTED" Comments="DO NOT SHIP TEST PO " TransmissionDate="2003-06-05" TransmissionTime="17:14:54"/><Buyer CompanyName="XXXXXXXXX" Phone="222-577-3708" Fax=" " BuyerNumber="101000" BuyerName="1IM " Email="[email protected]"/><DeliveryAddress CompanyName=" ENSEN COMPANY " Address1="C/O SHIPPING " Address2="221900 SHI BLVD " City="SCHG " Address4=" " Address5=" " Address6="SCHAUMBURG " State="IL" ZipCode="65693 " Phone="800-444-4448" ShipDeptContactName="HHHHN "/><PaymentTerms DueDays="30" DiscountDays="10" DiscountPercent="0"/><DeliveryTerms PrePaid="Prepaid" Transport="TO BE DETERMINED " Fob="ORIGIN "/><OrderLine TransmissionID="-2147482947" ItemNo="506280 " BranchNumber="00423" Description="3-3/4 RD X 20' R/L " QuantityUnitOfMeasure="Pound" PriceUnitOfMeasure="Pound" UnitPrice1="1.0000" UnitPrice2="71.0000" ForeignCurrencyCode="USD" BaseCurrencyCode="USD" DueDate="2003-06-05" POLineNumber="1" Qty="1.0000" SizeDescription="140/41 HR ANN ASTM A322 " LineStatus="Open"><LineNotes OrderLineNote="440/414 HR BAR - LP ANLED - LATT REV ASTM A32, A304 "/><LineNotes OrderLineNote="- AIM .025 MAP AN S - CERT/R RD - 410/412H HABILITY "/><LineNotes OrderLineNote="REQD - STAMP HEAT NUMBER ONE END ON SIZES 2-1/2" AND OVER - "/><LineNotes OrderLineNote="GRAIN SIZE 5 OR FINER - REPORT NI,CU,V AND HARDNESS "/></OrderLine><OrderLine TransmissionID="-2147482946" ItemNo="502327 " BranchNumber="00423" Description="3/4 SQ X 12' R/L " QuantityUnitOfMeasure="Pound" PriceUnitOfMeasure="Pound" UnitPrice1="1.0000" UnitPrice2="1.0000" ForeignCurrencyCode="USD" BaseCurrencyCode="USD" DueDate="2003-06-05" POLineNumber="2" Qty="1.0000" SizeDescription="1018 CF ASTM A108 " LineStatus="Open"><LineNotes OrderLineNote="1018 CF BAR - LATEST REV: ASTM A108 - CERT T/R REQD "/><LineNotes OrderLineNote=" "/></OrderLine><OrderLine TransmissionID="-2147482945" ItemNo="507027 " BranchNumber="00423" Description="5-3/4 RD X 20' R/L " QuantityUnitOfMeasure="Pound" PriceUnitOfMeasure="Pound" UnitPrice1="1.0000" UnitPrice2="1.0000" ForeignCurrencyCode="USD" BaseCurrencyCode="USD" DueDate="2003-06-05" POLineNumber="3" Qty="1.0000" SizeDescription="86/80H HR ASTM A322 ASTM A304 " LineStatus="Open"><LineNotes OrderLineNote="8/86H HOT RO BA - LAST REVASTM A32AND ATM A304 - AIM "/><LineNotes OrderLineNote=".025 MAX P AND S - STAMUMBER ON ONE END SIZES 2-1/2" AND OVER "/><LineNotes OrderLineNote="GRA SIZE OR FINER - HARDEILITY TO BE REPORTED - CET /R REQD "/></OrderLine></POOutbound_schema>
    import java.io.File;
    import java.io.FilenameFilter;
    import java.io.*;
    import java.lang.*;
    import org.jdom.*;
    import org.jdom.input.*;
    import org.jdom.output.*;
    import java.util.*;
    public class EmjPO
    public static void main (String args[]) {
    String[] outarray=new String[1000];
    String pono=null;
    int j=0;
    try {
    /* Build the document with SAX and Xerces, no validation */
    SAXBuilder builder = new SAXBuilder();
    /* Create the document */
    Document doc = builder.build(new File("c:/emjdata/PO.xml"));
    /* To get the DocType from in xml file. Reads the Doctype. */
    DocType docType = doc.getDocType();
    /* Get the root element. */
    Element root = doc.getRootElement();
    /* Get Children */     
    List rtiloadoutbound = root.getChildren("POOutbound_schema");
    Iterator i = rtiloadoutbound.iterator();
    while (i.hasNext()) {
    Element rti_load_outbound = (Element) i.next();
    /* Parses each tag to output string */
    String PurchaseOrder = rti_load_outbound.getAttributeValue("PurchaseOrder");
    String OrderDate = rti_load_outbound.getAttributeValue("OrderDate");     
    System.out.println(" Purchase Order : " + PurchaseOrder + " " + OrderDate);
    } /* while ends here */
    } /* try ends here */
    catch (Exception ex) {
    ex.printStackTrace();     
    System.out.println("Exception Occured " + ex);

    The stack trace should tell you the line number and the filename where the exception happened.
    This is just a guess:
    List rtiloadoutbound = root.getChildren("POOutbound_schema"); //this returns null because root iself the element 'POOutbound_schema'
    Iterator i = rtiloadoutbound.iterator(); //calling .iterator() on a null gives the NullPointerExceptionso try
    String PurchaseOrder = root.getAttributeValue("PurchaseOrder");
    String OrderDate = root.getAttributeValue("OrderDate");

  • How to Parse XML with SAX and Retrieving the Information?

    Hiya!
    I have written this code in one of my classes:
    /**Parse XML File**/
              SAXParserFactory factory = SAXParserFactory.newInstance();
              GameContentHandler gameCH = new GameContentHandler();
              try
                   SAXParser saxParser = factory.newSAXParser();
                   saxParser.parse(recentFiles[0], gameCH);
              catch(javax.xml.parsers.ParserConfigurationException e)
                   e.printStackTrace();
              catch(java.io.IOException e)
                   e.printStackTrace();
              catch(org.xml.sax.SAXException e)
                   e.printStackTrace();
              /**Parse XML File**/
              games = gameCH.getGames();And here is the content handler:
    import java.util.ArrayList;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    class GameContentHandler extends DefaultHandler
         private ArrayList<Game> games = new ArrayList<Game>();
         public void startDocument()
              System.out.println("Start document.");
         public void endDocument()
              System.out.println("End document.");
         public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
         public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
         public void characters(char[] ch, int start, int length) throws SAXException
              /**for (int i = start; i < start+length; i++)
                   System.out.print(ch);
         public ArrayList<Game> getGames()
              return games;
    }And here is the xml i am trying to parse:<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
    <Database>
         <Name></Name>
         <Description></Description>
         <CurrentGameID></CurrentGameID>
         <Game>
              <gameID></gameID>
              <name></name>
              <publisher></publisher>
              <platform></platform>
              <type></type>
              <subtype></subtype>
              <genre></genre>
              <serial></serial>
              <prodReg></prodReg>
              <expantionFor></expantionFor>
              <relYear></relYear>
              <expantion></expantion>
              <picPath></picPath>
              <notes></notes>
              <discType></discType>
              <owner></owner>
              <location></location>
              <borrower></borrower>
              <numDiscs></numDiscs>
              <discSize></discSize>
              <locFrom></locFrom>
              <locTo></locTo>
              <onLoan></onLoan>
              <borrowed></borrowed>
              <manual></manual>
              <update></update>
              <mods></mods>
              <guide></guide>
              <walkthrough></walkthrough>
              <cheats></cheats>
              <savegame></savegame>
              <completed></completed>
         </Game>
    </Database>I have been trying for ages and just can't get the content handler class to extract a gameID and instantiate a Game to add to my ArrayList! How do I extract the information from my file?
    I have tried so many things in the startElement() method that I can't actually remember what I've tried and what I haven't! If you need to know, the Game class instantiates with asnew Game(int gameID)and the rest of the variables are public.
    Please help someone...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    OK, how's this?
    public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException
              current = "";
         public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException
              try
                   if(qualifiedName.equals("Game") || qualifiedName.equals("Database"))
                        {return;}
                   else if(qualifiedName.equals("gameID"))
                        {games.add(new Game(Integer.parseInt(current)));}
                   else if(qualifiedName.equals("name"))
                        {games.get(games.size()-1).name = current;}
                   else if(qualifiedName.equals("publisher"))
                        {games.get(games.size()-1).publisher = current;}
                   etc...
                   else
                        {System.out.println("ERROR - Qualified Name found in xml that does not exist as databse field: " + qualifiedName);}
              catch (Exception e) {} //Ignore
         public void characters(char[] ch, int start, int length) throws SAXException
              current += new String(ch, start, length);
         }

  • How to ignore white space when parse xml document using xerces 2.4.0

    When I run the program with the xml given below the following error comes.
    Problem parsing the file.java.lang.NullPointerExceptionjava.lang.NullPointerExce
    ption
    at SchemaTest.main(SchemaTest.java:25)
    ============================================================
    My expectation is "RECEIPT". Pls send me the solution.
    import org.apache.xerces.parsers.DOMParser;
    import org.xml.sax.InputSource;
    import java.io.*;
    import org.xml.sax.ErrorHandler;
    import org.w3c.dom.*;
    public class SchemaTest {
    public static void main (String args[])
    try
    FileInputStream is = new FileInputStream(new File("C:\\ADL\\imsmanifest.xml"));
    InputSource in = new InputSource(is);
    DOMParser parser = new DOMParser();
    //parser.setFeature("http://xml.org/sax/features/validation", false);
    //parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "memory.xsd");
    //ErrorHandler errors = new ErrorHandler();
    //parser.setErrorHandler(errors);
    parser.parse(in);
    Document manifest = parser.getDocument();
    manifest.normalize();
    NodeList nl = manifest.getElementsByTagName("organization");
    System.out.println((((nl.item(0)).getChildNodes()).item(0)).getFirstChild().getNodeValue());
    catch (Exception e)
    System.out.print("Problem parsing the file."+e.toString());
    e.printStackTrace();
    <?xml version = '1.0'?>
    <organizations default="detail">
    <organization identifier="detail" isvisible="true">
    <title>RECEIPT</title>
    <item identifier="S100000" identifierref="R100000" isvisible="true">
    <title>Basic Module</title>
    <item identifier="S100001" identifierref="R100001" isvisible="true">
    <title>Objectives</title>
    <metadata/>
    </item>
    </item>
    <metadata/>
    </organization>
    </organizations>
    Is there a white space problem? How do I get rid from this problem.

    ok now i really wrote the whole code, a bit scrolling in the API is to hard?
                DocumentBuilderFactory dbf = new DocumentBuilderFactory();
                DocumentBuilder db = dbf.newDocumentBuilder();
                dbf.setNamespaceAware(true); //or set false
                Document d = db.parse(inputstream);

  • HttpConnection throws NullPointerException

    Hi everybody !
    I'm faceing an odd problem here. I have developed an J2ME (MIDP1.0) application that, among other things, needs to comunicate with my server. The application woks fine on the emulator, it even works great on my phone (Nokia 2650) and on my partners phone (Nokia 6610), but when tested on other phones (SonyErricson, Sagem, Motorola, even an smartphone from Nokia, a 7610 i think) it throws a NullPointerException. I've run out of ideeas regading how to solve this. Here's the piece of code that bugs me:
    public void run(){
            Pachet raspuns = null;               
            display.setCurrent(forma);
            progress.setLabel("Trying to connect");       
            try {
                conn = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
                conn.setRequestMethod( HttpConnection.POST );
                conn.setRequestProperty("Content-Type", "application/vnd.wap.wmlc");
                byte[] dataForSend = deTrimis.getRawData();
                conn.setRequestProperty("Content-Length", ""+dataForSend.length);
                progress.setLabel("Sending request");
                progress.setValue(25);                      
                forma.append("Opening outputstream\n");
                os = conn.openOutputStream();
                forma.append("Sending data\n");           
                os.write( dataForSend );
                forma.append("Flushing data\n");           
                os.flush();      // this throws the exception
                forma.append("Closing stream\n");           
                os.close();    // if i remove the "os.flush()", the exception is thrown here
                forma.append("Getting response code\n");
                int code = conn.getResponseCode(); // if i remove both os.flush() and os.close() the exception is thrown here !!!
                forma.append("Response code = "+code+"\n");                          
                progress.setLabel("Checking response");
                progress.setValue(50);
                if (code != HttpConnection.HTTP_OK){
                     throw new Exception (conn.getResponseMessage()+"("+code+")");
                progress.setLabel("Reading data");
                progress.setValue(75);           
                if (!aborted){
                    dIn = conn.openDataInputStream();               
                    raspuns = new Pachet();
                    raspuns.readPackage(dIn);
                if (!aborted)
                    listener.packageReceived(raspuns);           
            } catch (Exception e) {
                forma.append("Connection failed. Reason: "+e.getMessage());           
                e.printStackTrace();
            } finally{
                cleanUp();
        }I really need to get this working, so could please someone give me a hint.
    Thank you,
    Daniel Comsa.

    Hi
    I solved this problem.
    There is nothing wrong with the device but the connection that we use.
    Our service provider does not provide the pure HTTP connection rather it goes over WAP and thats where the problem comes.
    Cause we attach our header for the server and WAP sticks his header in between , thats why server does not handle the request and consider it as bad request.
    I have commented the following lines for my code to work
    connection.setRequestProperty("User-Agent",
    System.getProperty("microedition.profiles"));
    connection.setRequestProperty("Content-Type",
    "application/octet-stream");
    Regards,
    Sushil

Maybe you are looking for

  • Service Interfaces not Parsed in SPROXY

    Hi Everyone, I have a namespace http://sap.com/xi/Global2/testing which is imported with the standard SWCV from SAP Market Place. I recently made some changes to this namespace by importing few 'External Definitions' and then created 'Message Mapping

  • Dynamic text and rollovers

    I've got a dynamic, scrolling text field and the text is being rendered as HTML. How can I create a rollover state for the text? Thanks.

  • Error during migration of ADF project from Jdev 12 to jdev 11.1.1.7

    Hi all,    I have created a ADF project in Jdeveloper 12c.during migration from 12c to jdev11g everything was normal.but when i tried to deploy it over integrated weblogic 11g of jdeveloper,it created error- 9 Sep, 2014 8:56:39 PM IST> <Error> <J2EE>

  • Importing Language Problem

    Hi, I tried to import a new Language (AR) to ECC6 , when I run the job from SMLT it gets me an error, when I see the log file display a message like that: Could not create cofile Message no. STRALAN_MSAG076 No entry found in control table (PAT03) Wha

  • Windows 2000 connected to Mac OS X 10.4 Server

    We are in the process of installing a digital press with a workflow front end running Windows 2000 Server. We would like to connect this to our XServe running 10.4 Server. Are there any issues with connecting an older Windows operating system to newe