Trying to use XML SAX parser with JDK2 ...

Hi,
I'm pretty new to Java.
I'm trying to write and use java sample using XML SAX parser. I try with XP and XML4J.
Each time I compile it give me a error message like
"SAX01.java:23: unreported exception java.lang.Exception; must be caught or declared to be
thrown
(new SAX01()).countBooks();
^
Note: SAX01.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
1 error"
For what I found, it seems that "deprecated" mean usage of old classes or methods. What should I do ?
Wait for the XML parser to be rewrite ? ....
Thank's
Constant

"SAX01.java:23: unreported exception
java.lang.Exception; must be caught or declared to be
thrown
(new SAX01()).countBooks();
^Do this
public static void main(String[] args) throws Exception {
or do this
     try
                   first part of expression?(new SAX0()).countBooks();
     catch(Exception ex)     
          System.out.println("problem "+ ex);
Note: SAX01.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
1 error"deprecation is just a warning if there are no errors elsewhere in your program it should compile fine, but if you want to find out how to change it do this:
javac YourClassName.java -deprecation
then look in the docs for an alternative.

Similar Messages

  • Validating xml file against a specific schema using jaxp sax parser

    Hi,
    I would like to validate a soap xml given below
    <?xml version="1.0" encoding="UTF-8"?>
    <Envelope>
         <Body>
              <name>pavan</name>
              <number>123</number>
         </Body>
    </Envelope>
    to validate against the schema of soap from url "http://www.w3.org/2003/05/soap-envelope". I dont want to have this namespace in the xml. How can I validate against the specified schema using jaxp sax parser?
    Please help.
    Thanks,
    T.Pavan kumar

    Any one, please help.

  • Encoding error using Oracle SAX Parser, please help

    Hi, All,
    I have problem while I am trying to parse an XML file using Oracle SAX Parser.
    The following is from the trace file:
    java.io.UTFDataFormatException: Invalid UTF8 encoding.
    java.io.UTFDataFormatException: Invalid UTF8 encoding.
    at java.lang.Throwable.&lt;init&gt;(Compiled Code)
    at java.lang.Exception.&lt;init&gt;(Compiled Code)
    at java.io.IOException.&lt;init&gt;(Compiled Code)
    at java.io.UTFDataFormatException.&lt;init&gt;(Compiled Code)
    at oracle.xml.parser.v2.XMLUTF8Reader.checkUTF8Byte(Compiled Code)
    at oracle.xml.parser.v2.XMLUTF8Reader.readUTF8Char(Compiled Code)
    at oracle.xml.parser.v2.XMLUTF8Reader.fillBuffer(Compiled Code)
    at oracle.xml.parser.v2.XMLByteReader.saveBuffer(Compiled Code)
    at oracle.xml.parser.v2.XMLReader.fillBuffer(Compiled Code)
    at oracle.xml.parser.v2.XMLReader.tryRead(Compiled Code)
    at oracle.xml.parser.v2.XMLReader.scanXMLDecl(Compiled Code)
    at oracle.xml.parser.v2.XMLReader.pushXMLReader(Compiled Code)
    at oracle.xml.parser.v2.XMLReader.pushXMLReader(Compiled Code)
    at oracle.xml.parser.v2.XMLParser.parse(Compiled Code)
    at data_loader.main(Compiled Code)
    The XML file is a pure ascii text file, with encoding set to UTF-8.
    I can parse the file correctly on NT, but I got problem when I ran the code on a SUN solaris 2.6 machine.
    The parser version is 9.0.2.
    Thanks in advance.
    Peter

    You are right, I modified the codes and got it to work on Oracle
    But when I did your suggestion:
    <cftransaction>
      <cfstoredproc ...>
      <cfquery>
        SELECT ...
      </cfquery>
    </cftransaction>
    I got the same error as before which is:
    Error Executing Database Query.
    [Macromedia][Oracle JDBC Driver]Unhandled sql type
    But this time it points to the CF callling the str proc using cfprocparam
    Here is how I call the str. proc:
         <CFTRANSACTION>   
              <cfstoredproc procedure="MyReport" datasource="#Trim(application.dsn)#" returncode="True">  
                  <cfprocparam type="In" cfsqltype="CF_SQL_VARCHAR" variable="ins_name" value="#Trim(session.instname)#">
                  <cfprocparam type="In" cfsqltype="CF_SQL_VARCHAR" variable="aca_year" value="#Trim(ayr)#"> <------- POINT TO THIS LINE
              </cfstoredproc>
         </CFTRANSACTION>

  • XML SAX parser that support  LexicalHandler

    Hello,
    I'm looking for an XML SAX parser that support a LexicalHandler.
    I have xml files that are not well formed, ie: (&, <, >, etc...) characters within tags and I need to ignore them.
    Anyone have a link to some opensource library ??
    Thanks,
    Samir

    Don't waste your time. Using a LexicalHandler isn't going to help with parsing malformed XML. You should get the person who produced those files to replace them with correct XML.
    PC&#178;

  • Why are all the events in the XML SAX parser not activated?

    Hi everyone,
    I have written a mini server that parses XML files into SQL queries.
    Below is a segment of my code;
              try          {                                                       
                   Class.forName( JDBC_DRIVER );
                   myConnection = DriverManager.getConnection( DATABASE_URL, "username", "password");                                                  
                   EventXMLParser myEXP = new EventXMLParser(directory, myConnection);
                   File[] xmlFiles = directory.listFiles();
                   for (File xmlFile : xmlFiles)               {     
                        myEXP.XMLtoDB(xmlFile);
                        outWriter.println("File:" + xmlFile.getName() + " DONE");
              } catch (SQLException e)     {
                   System.err.println("SQLException for establishing connection");
                   e.printStackTrace();
              } catch (ClassNotFoundException e)     {
                   System.err.println("CLASS NOT FOUND EXCEPTION HERE");
                   e.printStackTrace();
              } catch (Exception e)     {
                   System.err.println(e);
                   e.printStackTrace();
              finally {
                   outWriter.println("PARSING COMPLETED");
                   outWriter.close();
         }Where the constructor EventXMLParser constructs the following:
         public EventXMLParser(File path, Connection connection)     {
              super();
              try     {
                   this.XMLpath = path;
                   this.db_connection = connection;
                   this.xr = XMLReaderFactory.createXMLReader();
                   this.XMLSAXhandler  = new DefaultHandler(); //create a new own handler
                   this.xr.setContentHandler(XMLSAXhandler);
                   this.xr.setErrorHandler(XMLSAXhandler);
                   //System.out.println("DEBUG: db_connection is " + db_connection.toString());
              catch (Exception e)     {
                   System.out.println("Constructor Error!");
                   e.printStackTrace();
         }Below are all my helper methods within EventXMLParser.java
         public void XMLtoDB(String XMLpath) throws Exception  {
              try     {
                   //Input
                   System.out.println("XMLpath is : " + XMLpath);
                   /*FileReader r = new FileReader(XMLpath); debug
                   InputSource in = new InputSource(r);
                   xr.parse(in);
                   xr.parse(XMLpath);
                   /* Note that while parsing, the end of each event, </event>
                    * will trigger sendSQL to execute the query on the database
              catch (Exception e)     {
                   throw new Exception("Error with XMLtoDB!! Exception: " + e);
         public void sendSQL(Event event, Connection sql_connection) throws SQLException     {
                   //JDBC part
                   try     {
                        System.err.println("DEBUG sendSQL");
                        Statement sql_statement = sql_connection.createStatement();
                        ResultSet resultSet = sql_statement.executeQuery( event.toSQL() );
                   catch (SQLException e)     {
                        e.printStackTrace();
         /* Parsing XML
          * From here onwards it's all designed for the SAX Parsing with different event calling methods
         public void startDocument()     {
              System.err.println("Start Document");
         public void endDocument()     {
              System.err.println("End Document");
         public void startElement(String uri, String name, String qName, Attributes atts)     {
              CurrentElement= name;
              System.out.println("This is parsing");
         public void characters(char ch[], int start, int length)     {
              SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
              StringBuffer sb = new StringBuffer();
              for (int i = start; i < start + length; i++)     
                   sb.append(ch);
              String content = sb.toString();
              if (CurrentElement.equals("eid"))
                   temp.setEventID( (Integer.valueOf(content)).intValue() ) ;
              else if (CurrentElement.equals("sd"))
                   temp.setShort_description(content);
              else if (CurrentElement.equals("ld"))
                   temp.setLong_description(content);
              else if ( (CurrentElement.equals("dt")))
                   temp.setDate_Time( formatter.parse(content, new ParsePosition(0)) );
              else if (CurrentElement.equals("repeat"))
                   temp.setRepeat_pattern( (Integer.valueOf(content)).intValue() );
              else if (CurrentElement.equals("valid"))
                   temp.setValid_period(content);
              else if (CurrentElement.equals("status"))     {
                   temp.setStatus( (Integer.valueOf(content)).intValue() );
              else {}
         public void endElement(String uri, String name, String qName)     {
              System.err.println("DEBUG" + temp.toString()); /*debug*/
              if (name.equals("event"))     {
                   try     {
                        /*debug*/ temp.setUserID(1);
                        /*debug*/ System.err.println("DEBUG: " + temp.toString());
                        sendSQL(temp, db_connection);
                        //temp = new Event();
                   catch (SQLException e)     {
                        System.err.println(e);
                   }//end catch
              }//end try
    Where event is a public class Event     {
         //fields
         private int userID = 1; // = 1 only applies for testing
         private int eventID;
         private String short_description;
         private String long_description;
         private Date date_time = null;
         private int repeat_pattern;
         private String valid_period;
         private int status;     //1 for new, 0 for modification and -1 for delete
         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
         //Constructors
         //every event requires the following: userID eventID and short_Description
         public Event(int uID, int eID, String shortDescrp)     {
              setUserID(uID);
              setEventID(eID);
              setShort_description(shortDescrp);
         public Event(int uid, int eid, String sd,
                                  String ld, Date d_t, int r_p, String v_p, int s)     {
              setUserID(uid);
              setEventID(eid);
              setShort_description(sd);
              setLong_description(ld);
              setDate_Time(d_t);
              setRepeat_pattern(r_p);
              setValid_period(v_p);
              setStatus(s);
         //set
         public void setUserID (int x)                         { this.userID = x ;}
         public void setEventID (int x)                         { this.eventID = x ;}
         public void setShort_description (String x)          { this.short_description = x ;}
         public void setLong_description (String x)          { this.long_description = x ;}
         public void setDate_Time(Date x)                    { this.date_time = x ;}
         public void setRepeat_pattern (int x)               { this.repeat_pattern = x ;}
         public void setValid_period (String x)               { this.valid_period = x ;}
         public void setStatus (int x)                         { this.status = x; }
         //get
         public int           getUserID()                              { return this.userID;}
         public int           getEventID()                         { return this.eventID;}
         public String      getShort_description()               { return this.short_description;}
         public String      getLong_description()               { return this.long_description;}
         public Date        getDate_Time()                         { return this.date_time;}
         public int         getRepeat_pattern()                    { return this.repeat_pattern;}
         public String      getValid_period()                    { return this.valid_period;}
         public int           getStatus()                              { return this.status; }
         //Event to SQL statements;
         public String toSQL()     {
              StringBuffer sb = new StringBuffer();
              ///if ( status == 1)     {
                   sb.append( "INSERT INTO events SET" );
                   sb.append( " userID = " + userID + ", ");
                   sb.append( "eventID = " + eventID + ", " );
                   sb.append( "short_description = " + "\'" + short_description + "\'" + ", "); //String
                   sb.append( "long_description = " + "\'" + long_description + "\'"  + ", "); //String
                   sb.append( "date_time = " + "\'" + formatter.format(date_time) + "\'" + ", ");
                   sb.append( "repeat_pattern = " + repeat_pattern + ", " );
                   sb.append( "valid_period = " + "\'" + valid_period + "\'" ); //String
                   sb.append( ";");
              //} else if ( status == 2)      {
              System.err.println(sb.toString());
              return sb.toString();
    }     My question is: I have taken my SQL query generated by toSQL() method in events and it worked.
    Here is the funny thing:
    Everything is correct syntax wise: No complaints what soever
    The mysql part works: Tested separately.
    So I tend to think that the problem lies within the SAX parser. I have written SAX2 parsers on this machine before and they have worked too. I tried inserting println statements all over startElement endElement etc etc only to find out that the SAX parser did not call any of the methods that I overided!! Why is that so?
    Can you guys spot where my SAX parser fails?

    I see.
    I try to correct this problem by removing super();
    so right now my code looks like this:
         static Event temp = new Event(0, 0, "null", "null", new Date(), 0, "null", 0);
         static String CurrentElement = null;
         static File XMLpath;
         static Connection db_connection;
         static XMLReader xr;
         static DefaultHandler XMLSAXhandler; 
         //Constructor,      Build the SAX Parser
         public EventXMLParser(File path, Connection connection)     {
              try     {
                   this.XMLpath = path;
                   this.db_connection = connection;
                   this.xr = XMLReaderFactory.createXMLReader();
                   this.XMLSAXhandler  = new DefaultHandler(); //create a new own handler
                   this.xr.setContentHandler(XMLSAXhandler);
                   this.xr.setErrorHandler(XMLSAXhandler);
                   //System.out.println("DEBUG: db_connection is " + db_connection.toString());
              catch (Exception e)     {
                   System.out.println("Constructor Error!");
                   e.printStackTrace();
         }This time, I created a new instance of default handler() which can be referenced by as the objects's XMLSAXhandler. However, that did not solve the problem, why does the problem still persist?
    Right now, there is only one instance of a default handler created. So why does all my parsing event functions still get ignored?

  • Using the SAX parser to split up a document to be processed by a DOMParser

    I need to process a potentially large document which could prove too large to be read into memory at once by the DOM parser. The document would look something like..
    (sorry about the formatting - can't use tabs!)
    <Root>
    <Parent>
    <Child>
    <Blah.....................
    </Blah>
    </Child>
    </Parent>
    <Parent>
    <Child.......
    </Child>
    </Parent>
    etc...
    etc...
    </Root>
    The number of Parent elements could potentially be in the thousands. What I would like to do would be to use the SAX parser to read the document and when a Parent element is encountered, write the parent element and all its children to a stream in order that an input source can be created. The input source can then be parsed by a DOM parser. Once complete, the next Parent element encountered by the SAX parser could be passed to the DOM parser and so on until all of the Parent elements have been processed.
    This way I can combine the ease of parsing the document using the DOM parser without having to worry about the overhead on memory.
    Does anyone have any ideas as to the best approach? I could use the SAX parser for the whole thing but the XML is quite complex and lends itself to DOM parsing much more conveniently.

    Can you read the file line by line:
    start the reading at <child>
    pause reading at </child>
    copy the string to a var
    wrap it with respective tags (<?xml<doctype etc...) and parse
    proceed to the next <child>xx</child>
    and repeat till you hit the closing of the file...
    - Ravi

  • I need help using a SAX parser

    Hello,
    I have a class that goes out to the web and retrieves an xml document w/o ever writing it to disk. I like to parse that object using SAX and a class that extends HandlerBase. Can any one show me how to parse an xml document that lives in memory rather than in a file? I've found many examples, but all of them assume you are reading from a file system. Any help is greatly appreciated.
    Here is the jist of my code :
    // Class 1 makes a request to another server based on some variable data. I've created a messenger object that handles all of the communications and returns the data in a DataInputStream
    XMLMessage xml = new XMLMessage();
    xml.createRequest(args[0],args[1],args[2]);
    XMLMessenger messenger = new XMLMessenger(xml.getDoc());
    DataInputStream dis = messenger.transferDocument();
    ResponseObj resp = new ResponseObj();
    resp.read(dis);
    System.out.println(resp.getvalue1() + "*" + resp.getvalue2()+ "*");
    // Class 2 is the ResponseObj and I want to use something similar to this read method, but
    // I can't get it to work with a data stream, instead of a string that represents a file.
    public void read(String filename) throws java.lang.Exception {
    Class c = Class.forName("com.ibm.xml.parser.SAXDriver");
         org.xml.sax.Parser parser = (org.xml.sax.Parser)c.newInstance();
         parser.setDocumentHandler(this);
         parser.parse(filename);

    Thanks for you help. I've modified my read() method to work like this :
    org.xml.sax.Parser parser = new com.ibm.xml.parser.SAXDriver();
    parser.setDocumentHandler(this);
    InputSource is = new InputSource(dis);
    parser.parse(is);
    This makes sense, but I'm still not getting any thing returned from the startElement(),characters(), or endElement() methods. It reports no errors, it just doesn't happen. Do you have any suggestions on how to debug this? I'm stumped, but really need to get this working.

  • Trying to use the JSSE library with Jrocket 7.0

    Hi All,
    I HAC who is trying to use the JSSE library with Jrocket 7.0.
    Sometimes the socket works and sometimes it does not. It throws the below
    exception,
    The exception stacktrace is given below:
    java.net.SocketException: SSL implementation not available
    at
    javax.net.ssl.DefaultSSLSocketFactory.createSocket(Ljava.lang.String;I)Ljava
    .net.Socket;(Unknown Source)
    at
    com.twister.transunion.TransUnionUtils.sendRequest(Ljava.lang.String;)Ljava.
    lang.String;(Unknown Source)
    at
    com.twister.transunion.TransUnionUtils.parseRequest(Lcom.twister.transunion.
    TransUnionRequest;)Z(Unknown Source)
    at
    com.twister.struts.signup.Signup5Action.button_apply_now(Lorg.apache.struts.
    action.ActionMapping;Lorg.apache.struts.action.ActionForm;Ljavax.servlet.htt
    p.HttpServletRequest;Ljavax.servlet.http.HttpServletResponse;)Lorg.apache.st
    ruts.action.ActionForward;(Unknown Source)
    at
    COM.jrockit.reflect.NativeMethodInvoker.invoke0(ILjava.lang.Object;[Ljava.la
    ng.Object;)Ljava.lang.Object;(Unknown Source)
    at
    COM.jrockit.reflect.NativeMethodInvoker.invoke(Ljava.lang.Object;[Ljava.lang
    .Object;)Ljava.lang.Object;(Unknown Sou
    the line of code causing the stack trace is:
    Socket socket =
    javax.net.ssl.SSLSocketFactory.getDefault().createSocket(HOST, PORT);
    He has added the following line to his jre/lib/security/java.security file:
    security.provider.3=com.sun.net.ssl.internal.ssl.Provider
    and he has added the JSSE jar files to the jre/lib/ext directory.
    The problem occurs when SSL is enabled in the config.xml file (e.g. <SSL
    Enabled="true" ...>). It does NOT occur when SSL is disabled.
    When SSL is disabled, the following code shows all three providers as
    defined in the java.security file. If SSL is enabled then he only sees the
    default 2 implementation and NOT the one he added above.
    java.security.Provider[] a = java.security.Security.getProviders();
    for (int i=0; i < a.length; i++)
    System.out.println("name: " + a.getName());
    System.out.println("ver: " + a[i].getVersion());
    System.out.println("info: " + a[i].getInfo());
    The problem is that client does not want to use WebLogic specific classes to
    create an SSL socket. As well he do NOT wish to dynamically register the
    SunJSSE provider. Since this setup works when SSL is disabled in WebLogic he
    believes he has configured everything properly.
    It appears to me that WebLogic is removing the JSSE as a security provider
    if SSL is enabled.
    Is it the expected behaviour? and Is it possible to statically register the
    JSSE provider in the jre/lib/security/java.security file ?
    Any pointers will be appreciated,
    Thanks in advance,
    Rubesh

    Hi Howard, just trawling through the Labview TE issues as I myself have started to work on a similar issue. I have now infact upgraded the Labview Test Executive to work in 7.1 ok (both development and Runtime).
    Using XP I had no issues upgrading in the development environment - creating the run-time version was not as easy but manged to do so with help from the Application Builder. I have also tested the SQL function (as i log to Oracle) and a basic audio test using a DSA4551 - again both seem to be upgraded with no issues.
    regards, paul.

  • HT201328 I'm trying to use an iphone 3 with t-mobile plan, itune say the phone is unlocked however i can't get a signal with the new sims card

    I'm trying to use an iphone 3 with t-mobile plan, itune say the phone is unlocked however i can't get a signal with the new sims card

    How is iTunes telling you it is unlocked? Did you go through an unlock procedure with your cell company and then Restore it in iTunes?

  • XML Sax Exception with 9.2.0.5 express*.jar files for Olap API

    I was using the olap_api_92.jar that
    came with jdeveloper for the olap api and having a coding problem.. In trying to see
    if I could resolve the previous problem, I set my classpath to use the jar files provided with the 9.2.0.5
    install for AiX.. all beginning with express*.jar
    I now get an XML parsing error that I can't fix..
    which jar is good, the olap_api_92.jar seems to work..
    Help!
    thanks,
    Lisa Cox
    OCLC Inc.
    java.lang.RuntimeException: org.xml.sax.SAXParseException: <Line 179, Column 18>: XML-0124: (Fatal Error) An attribute cannot appear more than once in the same start tag.
    at oracle.olapi.metadata.MetadataFetcher.processXML(MetadataFetcher.java:237)
    at oracle.olapi.metadata.MetadataFetcher.fetchBaseMetadataObjects(MetadataFetcher.java:180)
    at oracle.olapi.metadata.BaseMetadataProvider.fetchMetadataObject(BaseMetadataProvider.java:150)
    at oracle.olapi.metadata.BaseMetadataProvider.fetchMetadataObject(BaseMetadataProvider.java:107)
    at oracle.olapi.metadata.mdm.MdmMetadataProvider.getMetadataObject(MdmMetadataProvider.java:147)
    at oracle.olapi.metadata.mdm.MdmMetadataProvider.getRootSchema(MdmMetadataProvider.java:174)
    at oracle.express.mdm.MdmMetadataProvider.getRootSchema(MdmMetadataProvider.java:144)
    at org.oclc.xwc.olap.OlapClient.main(OlapClient.java:494)

    The OLAP component versions are empty.
    <Check key="OLAP Catalog version" value=""/>
    <Check key="OLAP AW Engine version" value=""/>
    <Check key="OLAP API Server version" value=""/>
    Please doublecheck that the catpatch.sql script ran without any errors.
    Aneel Shenker
    Senior Product Manager
    Oracle Corp.

  • Using the SAX Parser

    As I reported in this thread: Carriage Returns in XSLT output I am trying to produce a text output file with each line terminating in cr-lf (using the output from ViewObject.writeXML() passed through the XSLProcessor.processXSL() method to apply a XSLT stylesheet transformation to it), but the cr characters in the stylesheet are being converted to nl characters, so I am ending up with two nl characters at the end of each line.
    I found a 2002 query (here: http://www.xslt.com/html/xsl-list/2002-04/msg00193.html) by someone with the same problem, and a reply by Steve Muench explaining it and stating that the Oracle SAX parser does not have the same problem.
    So my question now is - does the SAX parser still retain cr characters (or is it too now converting them to nl) and if it does, how do I make XSLProcessor.processXSL() use it rather than the default XML parser? Can I do it from within my code, or does it need to be set in some sort of environment variable? We are on version 9.0.5.2 of JDeveloper(10g)

    Repost

  • Is there a SAX parser with PL/SQL??

    Hi All,
    I am a Oracle developer and generally want to do everything from PL/SQL.
    So, from a PL/SQL procedure I would like to parse a XML document. I have tried hard to find a PL/SQL package which can give me a PL/SQL SAX parser, but could not find one.
    All packages are based on DOM tree.
    Please convey if I am wrong and is there a SAX parser?
    I know that there is only one package DBMS_XMLSTORE which is C based and uses SAX parser, but it does not have procedures/functions like ".parse()".
    Thanks and regards

    Here's an example
    SQL> --
    SQL> define MODULE=SaxProcessor
    SQL> define CLASS=com/oracle/st/xmldb/pm/examples/SaxProcessor
    SQL> --
    SQL> set define off
    SQL> --
    SQL> var sourceFileName varchar2(32)
    SQL> var targetPath varchar2(1024)
    SQL> --
    SQL> begin
      2    :sourceFileName := 'JavaSource';
      3    :targetPath  := '/public/' || :sourceFileName || '.java';
      4  end;
      5  /
    PL/SQL procedure successfully completed.
    SQL> declare
      2    res boolean;
      3    javaSource clob :=
      4  'package com.oracle.st.xmldb.pm.examples;
      5
      6
      7  import java.io.IOException;
      8  import java.io.StringWriter;
      9
    10  import java.io.Writer;
    11
    12  import java.sql.DriverManager;
    13  import java.sql.SQLException;
    14
    15  import java.util.Enumeration;
    16  import java.util.Hashtable;
    17
    18  import oracle.jdbc.OracleConnection;
    19  import oracle.jdbc.OracleDriver;
    20
    21  import oracle.jdbc.OraclePreparedStatement;
    22
    23  import oracle.sql.BFILE;
    24
    25  import oracle.sql.CLOB;
    26
    27  import oracle.xml.parser.v2.SAXParser;
    28  import oracle.xml.parser.v2.XMLDocument;
    29  import oracle.xml.parser.v2.XMLElement;
    30
    31
    32  import org.w3c.dom.Attr;
    33  import org.w3c.dom.Element;
    34  import org.w3c.dom.Node;
    35
    36  import org.xml.sax.Attributes;
    37  import org.xml.sax.ContentHandler;
    38  import org.xml.sax.Locator;
    39  import org.xml.sax.SAXException;
    40
    41  public class SaxProcessor implements ContentHandler {
    42
    43      public static final boolean DEBUG = true;
    44
    45      private OracleConnection dbConnection;
    46
    47      private OraclePreparedStatement insertStatement;
    48      private OraclePreparedStatement errorStatement;
    49      private CLOB clob;
    50
    51      private Hashtable namespaceToPrefix = null;
    52      private Hashtable prefixToNamespace = null;
    53      private String targetElementName = null;
    54
    55      private XMLDocument currentDocument;
    56      private Node currentNode;
    57
    58      private int documentCount = 0;
    59
    60      public SaxProcessor() {
    61          this.namespaceToPrefix = new Hashtable();
    62          this.prefixToNamespace = new Hashtable();
    63      }
    64
    65      private boolean isTargetElement(String elementName) {
    66          return ((this.currentDocument == null) &&
    67                  (elementName.equals(this.targetElementName)));
    68      }
    69
    70      public void startDocument() throws SAXException {
    71      }
    72
    73      public void endDocument() throws SAXException {
    74      }
    75
    76      public void startElement(String namespaceURI, String localName, String elementName, Attributes attrs)
    77      throws SAXException
    78      {
    79          if (DEBUG) {
    80              System.out.println("startElement() : URI = " + namespaceURI + ", localName = " + localName + ", elementName = " + elementNa
    me);
    81          }
    82          if (this.currentDocument == null)
    83          {
    84              if (DEBUG) {
    85                  System.out.println("startElement() : Checking for start of Fragment.");
    86              }
    87              if (isTargetElement(localName))
    88              {
    89                  if (DEBUG) {
    90                      System.out.println("startElement() : Starting New Document");
    91                  }
    92                  this.currentDocument = new XMLDocument();
    93                  this.currentNode = this.currentDocument;
    94                  XMLElement rootElement = createNewElement(namespaceURI, localName, elementName, attrs);
    95                  this.currentDocument.appendChild(rootElement);
    96                  this.currentNode = rootElement;
    97              }
    98          }
    99          else
    100          {
    101             XMLElement nextElement = createNewElement(namespaceURI, localName, elementName, attrs);
    102             this.currentNode.appendChild(nextElement);
    103             this.currentNode = nextElement;
    104          }
    105      }
    106
    107      public void endElement(String namespaceURI, String localName, String qName)
    108      throws SAXException
    109      {
    110          if (this.currentDocument != null)
    111          {
    112              if (this.currentNode.equals(this.currentDocument.getDocumentElement()))
    113              {
    114                  try
    115                  {
    116                    insertDocument();
    117                    this.currentDocument = null;
    118                  }
    119                  catch (SQLException sqlE)
    120                  {
    121                      throw new SAXException(sqlE);
    122                  }
    123                  catch (IOException ioe)
    124                  {
    125                      throw new SAXException(ioe);
    126                  }
    127              }
    128              else
    129              {
    130                  this.currentNode = this.currentNode.getParentNode();
    131              }
    132          }
    133      }
    134
    135      private XMLElement createNewElement(String namespaceURI, String localName,
    136                                          String elementName, Attributes attrs) {
    137          XMLElement newElement = null;
    138          if (namespaceURI != null) {
    139              if (this.namespaceToPrefix.containsKey(namespaceURI)) {
    140                  /* Namespace in already in Scope - create Element from Qualified Name */
    141                  newElement =
    142                      (XMLElement)this.currentDocument.createElement(elementName);
    143              } else {
    144                  /* Namespace is not already in Scope - create Element with namespace */
    145                  newElement =
    146                      (XMLElement) this.currentDocument.createElementNS(namespaceURI,
    147                                                                                elementName);
    148                  newElement.setPrefix((String)this.namespaceToPrefix.get(namespaceURI));
    149              }
    150          } else {
    151              newElement =
    152                  (XMLElement)this.currentDocument.createElement(localName);
    153          }
    154          addAttributes(newElement, attrs);
    155          if (this.currentNode.equals(this.currentDocument)) {
    156              addNamespaceDeclarations(newElement);
    157          }
    158          return newElement;
    159      }
    160
    161      private void addAttributes(Element element, Attributes attrs) {
    162          for (int i = 0; i < attrs.getLength(); i++) {
    163              if (attrs.getURI(i).equals("http://www.w3.org/2000/xmlns/")) {
    164              } else {
    165                  element.setAttribute(attrs.getQName(i), attrs.getValue(i));
    166              }
    167          }
    168      }
    169
    170      private void addNamespaceDeclarations(Element element) {
    171          Enumeration keys = this.namespaceToPrefix.keys();
    172          while (keys.hasMoreElements()) {
    173              String namespace = (String)keys.nextElement();
    174              String prefix = (String)namespaceToPrefix.get(namespace);
    175              Attr attr = null;
    176              if (prefix.equals("")) {
    177                  attr = this.currentDocument.createAttribute("xmlns");
    178                  attr.setValue(namespace);
    179                  element.setAttributeNode(attr);
    180              } else {
    181                  if (!prefix.equals(element.getPrefix())) {
    182                      attr =
    183                          this.currentDocument.createAttribute("xmlns:" + prefix);
    184                      attr.setValue(namespace);
    185                      element.setAttributeNode(attr);
    186                  }
    187              }
    188          }
    189      }
    190
    191      public void characters(char[] p0, int p1, int p2) throws SAXException {
    192          if (this.currentDocument != null) {
    193              StringWriter sw = new StringWriter();
    194              sw.write(p0, p1, p2);
    195              String value = sw.toString();
    196              Node textNode = this.currentDocument.createTextNode(value);
    197              this.currentNode.appendChild(textNode);
    198          }
    199      }
    200
    201      public void startPrefixMapping(String prefix,
    202                                     String uri) throws SAXException {
    203          this.namespaceToPrefix.put(uri, prefix);
    204          this.prefixToNamespace.put(prefix, uri);
    205      }
    206
    207      public void endPrefixMapping(String prefix) throws SAXException {
    208          Enumeration e = prefixToNamespace.keys();
    209          while (e.hasMoreElements()) {
    210              String thisPrefix = (String)e.nextElement();
    211              if (thisPrefix.equals(prefix)) {
    212                  String namespace =
    213                      (String)prefixToNamespace.remove(thisPrefix);
    214                  namespaceToPrefix.remove(namespace);
    215              }
    216          }
    217      }
    218
    219      public void ignorableWhitespace(char[] p0, int p1,
    220                                      int p2) throws SAXException {
    221          // throw new SAXException ("Un-Implemented Method: ingnoreableWhitespace");
    222      }
    223
    224      public void processingInstruction(String p0,
    225                                        String p1) throws SAXException {
    226          throw new SAXException("Un-Implemented Method: processingInstruction");
    227      }
    228
    229      public void setDocumentLocator(Locator p0) {
    230          // throw new SAXException ("Un-Implemented Method: setDocumentLocator");
    231      }
    232
    233      public void skippedEntity(String p0) throws SAXException {
    234          throw new SAXException("Un-Implemented Method: skippedEntity");
    235      }
    236
    237      public void doParse(BFILE bfile, String targetElement,
    238                             String targetTable, String errorTable) throws Exception {
    239              this.targetElementName = targetElement;
    240              String insertStatementText =
    241                  "insert into " + targetTable + " values (xmlParse(DOCUMENT ? WELLFORMED))";
    242              String errorStatementText =
    243                  "insert into " + errorTable + " values (xmlParse(DOCUMENT ? WELLFORMED))";
    244
    245              DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    246              OracleDriver ora = new OracleDriver();
    247              this.dbConnection = (OracleConnection)ora.defaultConnection();
    248
    249              this.insertStatement =
    250                  (OraclePreparedStatement)this.dbConnection.prepareStatement(insertStatementText);
    251              this.errorStatement =
    252                  (OraclePreparedStatement)this.dbConnection.prepareStatement(errorStatementText);
    253
    254              this.clob =
    255                  CLOB.createTemporary(this.dbConnection, true, CLOB.DURATION_SESSION);
    256
    257              SAXParser parser = new SAXParser();
    258              parser.setAttribute(SAXParser.STANDALONE, Boolean.valueOf(true));
    259              parser.setValidationMode(SAXParser.NONVALIDATING);
    260              parser.setContentHandler(this);
    261              bfile.openFile();
    262              parser.parse(bfile.getBinaryStream());
    263              bfile.closeFile();
    264              this.insertStatement.close();
    265              this.errorStatement.close();
    266      }
    267
    268      private void insertDocument() throws SQLException, IOException {
    269          this.clob.truncate(0);
    270          Writer out = clob.setCharacterStream(0);
    271          this.currentDocument.print(out);
    272          out.close();
    273
    274          this.insertStatement.setClob(1, clob);
    275          this.insertStatement.execute();
    276
    277          this.documentCount++;
    278
    279          if (DEBUG) {
    280              System.out.println("insertDocument() : Document Inserted");
    281          }
    282      }
    283
    284      public static int parseBFile(BFILE bfile, String targetElement,
    285                             String targetTable, String errorTable) throws Exception {
    286          try {
    287            SaxProcessor processor = new SaxProcessor();
    288            processor.doParse(bfile,targetElement,targetTable,errorTable);
    289            return processor.documentCount;
    290          }
    291          catch (Exception e) {
    292            e.printStackTrace(System.out);
    293            throw e;
    294          }
    295
    296      }
    297  }
    298  ';
    299  begin
    300    if dbms_xdb.existsResource(:targetPath) then
    301      dbms_xdb.deleteResource(:targetPath);
    302    end if;
    303    res := dbms_xdb.createResource(:targetPath,javaSource);
    304  end;
    305  /
    Queuing DELETE Event
    PL/SQL procedure successfully completed.
    SQL> --
    SQL> set define on
    SQL> --
    SQL> create or replace and resolve java source
      2  named "&MODULE"
      3  using blob
      4  (
      5  select xdburiType('/public/JavaSource.java').getBlob(nls_charset_id('WE8ISO8859P1'))
      6  from dual
      7  )
      8  /
    old   2: named "&MODULE"
    new   2: named "SaxProcessor"
    Java created.
    SQL> show errors
    No errors.
    SQL> --
    SQL> declare
      2    shortname varchar2(128);
      3  begin
      4    shortname := dbms_java.shortname('&CLASS');
      5    execute immediate 'grant execute on "' || shortname || '" to public';
      6  end;
      7  /
    old   4:   shortname := dbms_java.shortname('&CLASS');
    new   4:   shortname := dbms_java.shortname('com/oracle/st/xmldb/pm/examples/SaxProcessor');
    PL/SQL procedure successfully completed.
    SQL> create or replace package SAX_PROCESSOR
      2  as
      3    procedure PARSE_BFILE(file BFILE, targetElement varchar2, targetTable varchar2, errorTable varchar2);
      4  end;
      5  /
    Package created.
    SQL> show errors
    No errors.
    SQL> --
    SQL> create or replace package body SAX_PROCESSOR
      2  as
      3  --
      4  procedure PARSE_BFILE(file BFILE, targetElement varchar2, targetTable varchar2, errorTable varchar2)
      5  AS LANGUAGE JAVA
      6     NAME 'com.oracle.st.xmldb.pm.examples.SaxProcessor.parseBFile( oracle.sql.BFILE, java.lang.String, java.lang.String, java.lang.Strin
    g)';
      7  end;
      8  /
    Package body created.
    SQL> show errors
    No errors.
    SQL> --
    SQL> drop table PO_TEST
      2  /
    Table dropped.
    SQL> create table PO_TEST of XMLTYPE
      2  /
    Table created.
    SQL> drop table PO_ERROR
      2  /
    Table dropped.
    SQL> create table PO_ERROR of XMLTYPE
      2  /
    Table created.
    SQL> create or replace directory xmldir as 'c:\temp'
      2  /
    Directory created.
    SQL> set serveroutput on
    SQL> --
    SQL> call SAX_PROCESSOR.PARSE_BFILE(bfilename('XMLDIR','testcase.xml'),'PurchaseOrder','PO_TEST','PO_ERROR')
      2  /
    call SAX_PROCESSOR.PARSE_BFILE(bfilename('XMLDIR','testcase.xml'),'PurchaseOrder','PO_TEST','PO_ERROR')
    ERROR at line 1:
    ORA-29549: class XFILES.com/oracle/st/xmldb/pm/examples/SaxProcessor has
    changed, Java session state cleared
    SQL> call SAX_PROCESSOR.PARSE_BFILE(bfilename('XMLDIR','testcase.xml'),'PurchaseOrder','PO_TEST','PO_ERROR')
      2  /
    Call completed.
    SQL> select count(*) from PO_TEST
      2  /
             3
    SQL> select * from PO_TEST
      2  /
    <PurchaseOrder xsi:noNamespaceSchemaLocation="http://xfiles:8080/home/SCOTT/poSo
    urce/xsd/purchaseOrder.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    ">
      <Reference>AMCEWEN-20030409123336271PDT</Reference>
      <Actions>
        <Action>
          <User>KPARTNER</User>
        </Action>
      </Actions>
      <Reject/>
      <Requestor>Allan D. McEwen</Requestor>
      <User>AMCEWEN</User>
    <PurchaseOrder xsi:noNamespaceSchemaLocation="http://xfiles:8080/home/SCOTT/poSo
    urce/xsd/purchaseOrder.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    ">
      <Reference>SKING-20030409123336321PDT</Reference>
      <Actions>
        <Action>
          <User>SKING</User>
        </Action>
      </Actions>
      <Reject/>
      <Requestor>Steven A. King</Requestor>
      <User>SKING</User>
    <PurchaseOrder xsi:noNamespaceSchemaLocation="http://xfiles:8080/home/SCOTT/poSo
    urce/xsd/purchaseOrder.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    ">
      <Reference>SMCCAIN-20030409120030451PDT</Reference>
      <Actions>
        <Action>
          <User>SVOLLMAN</User>
        </Action>
      </Actions>
      <Reject/>
      <Requestor>Samuel B. McCain</Requestor>
      <User>SMCCAIN</User>
    SQL>

  • Error java.lang.OutOfMemoryError using XML DOM parser

    Hi everyone,
    We are using Oracle 8.1.7 on Windows NT and trying to load XML into Oracle using the DOM API through PL/SQL. This is the method provided in the ORACLE_HOME\ora817\xdk\plsql\demo\domsample.sql which uses the XMLPARSER and XMLDOM PL/SQL packages.
    Now this works fine with small files (not sure about the exact file size). But for big files, it gives an error,
    ORA-29554: unhandled Java out of memory condition
    ORA-29532: Java call terminated by uncaught Java exception: java.lang.OutOfMemoryError
    We have increased the JAVA_POOL_SIZE from the default 20MB to 50MB. Not sure whether increasing this value will solve our problem and whether it is advisable to increase it to a higher value. Can anyone help, please ???
    Thanks.

    Steve,
    Thanks for the response. Now we are getting different error. In one of the questions earlier posted, someone (I think Jon) noted that following error (the one we are getting) can be resolved by using JDK 1.1.8, is there any specific JDK pre-req for XML Parser 0.9.8.6?
    Is it possible, to enhance release notes for 0.9.8.6 to include
    a) Tips mentioned in your mail (i.e. putting oracle xml parser 2.0.x before Apache/OJSP xmlparserv2.jar
    b) Dependencies on specific version of JDK
    Once again thanks for the responding to the mail and will appreciate a help to resolve this current error.
    Thanks,
    Shree
    Actual error :
    java.lang.IllegalArgumentException: sun.io.CharToB
    yteUTF-8
    at sun.io.CharToByteConverter.getConverterClass(Compiled Code)
    at sun.io.CharToByteConverter.getConverter(Compiled Code)
    at java.io.OutputStreamWriter.<init>(Compiled Code)
    at org.apache.jserv.JServConnection.getWriter(Compiled Code)
    at oracle.xml.xsql.XSQLServletPageRequest.setupWriter(Compiled Code)
    at oracle.xml.xsql.XSQLServletPageRequest.setContentType(Compiled Code)
    at oracle.xml.xsql.XSQLPageProcessor.process(Compiled Code)
    at oracle.xml.xsql.XSQLServlet.doGet(Compiled Code)
    at javax.servlet.http.HttpServlet.service(Compiled Code)
    at javax.servlet.http.HttpServlet.service(Compiled Code)
    at org.apache.jserv.JServConnection.processRequest(Compiled Code)
    at org.apache.jserv.JServConnection.run(Compiled Code)
    at java.lang.Thread.run(Compiled Code)
    null

  • Org.xml.sax.SAXParseException with XML Report Publish

    Anyone see the following error in XML Report Publisher? This happened after I ran Employee W2 XML Interface and ran XML Report Publisher for the output of the PDF output.
    --XDOException
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at oracle.apps.xdo.common.xml.XSLT10gR1.invokeParse(XSLT10gR1.java:570)
         at oracle.apps.xdo.common.xml.XSLT10gR1.transform(XSLT10gR1.java:235)
         at oracle.apps.xdo.common.xml.XSLTWrapper.transform(XSLTWrapper.java:182)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:1044)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:997)
         at oracle.apps.xdo.template.fo.util.FOUtility.generateFO(FOUtility.java:212)
         at oracle.apps.xdo.template.FOProcessor.createFO(FOProcessor.java:1665)
         at oracle.apps.xdo.template.FOProcessor.generate(FOProcessor.java:975)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.runProcessTemplate(TemplateHelper.java:5936)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3459)
         at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3548)
         at oracle.apps.xdo.oa.cp.JCP4XMLPublisher.runProgram(JCP4XMLPublisher.java:684)
         at oracle.apps.fnd.cp.request.Run.main(Run.java:157)
    Caused by: org.xml.sax.SAXParseException: <Line 268, Column 6>: XML-20109: (Fatal Error) PI with the name 'xml' can occur only in the beginning of the document.
         at oracle.xdo.parser.v2.XMLError.flushErrorHandler(XMLError.java:441)
         at oracle.xdo.parser.v2.XMLError.flushErrors1(XMLError.java:303)
         at oracle.xdo.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:305)
         at oracle.xdo.parser.v2.XMLParser.parse(XMLParser.java:289)
         ... 17 more
    Thanks.

    We are going to user Employee W-2 PDF.

  • XML - SAX Parsing Question

    Hi,
    I am parsing XML using SAX parser and fill the values into the HashTable ( like Key value pair ).. so i can get the vaues for a particular key using hash get function.
    For the following XML. There are 2 "subscriberNumber" attribute, one is under "sn:Subscriber" and the another is under "sn:SubscriberChange".
    I can able to put this values in hash table and when i print the Hash table it is printing as sn:subscriberNumber=[1234567890, 1234567890] .. But how will i know which one is from "sn:Subscriber" and which is from "sn:SubscriberChange"
    This is the XML :
    <sn:SubscriberNotification>
    <sn:notificationSubType>1120</sn:notificationSubType>
    <sn:Subscriber>
         <cng:PaymentType>PostPaid</cng:PaymentType>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:Subscriber>
    <sn:SubscriberChange>
         <sn:subscriberNumber>1234567890</sn:subscriberNumber>
    </sn:SubscriberChange>
    </sn:SubscriberNotification>
    Any suggestion and pointers are really helpful
    Thanks,
    -Raj..

    Try something like this:
    import java.util.Stack;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    class MyHandler extends DefaultHandler {
        Stack openTags = new Stack();
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if (qName.equals("sn:subscriberNumber")) {
                String parentTag = (String)openTags.peek();
                System.out.println("Parent tag of this <sn:subscriberNumber> is : <" + parentTag + ">");
            openTags.push(qName);
        public void endElement(String uri, String localName, String qName) throws SAXException {
            openTags.pop();
    }Regards

Maybe you are looking for

  • Date format of footer in pdf

    How to change the date format of footer from dd/mm/yyyy to Monday 09 August 2010 when we down load the report in pdf file

  • Report 6i rdf's and XML Publisher

    I'm trying to decide whether to implement Reports Developer 10g or XML Publishing as our reporting tool. Can I get some feedback from XML Publisher users who have also worked with the Oracle reporting tool Reports 6i? (I'm currently working with 6i)

  • Error in deploying JDBC driver

    Hi All while deploying JDBC driver i am following tthis guide https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/f04ce027-934d-2a10-5a8f-fa0b1ed4d88f while i run the command  C:>drivertool add aii_af_jmsproviderlib.sda msbase.jar mss

  • How long should migration assistant take to inspect computer for files to transfer

    just purchased a mac book pro. I'm attempting to migrate my pc files to the mac. I've successfully installed migration assistant on my pc. Migration assistant on the mac has been " inspecting your computer" for over 12 hours. Is this normal? I'm hesi

  • Share information from chip GPS to PC with USB or BLUETOOTH

    Hi! I want know if it's possible connect my iphone to my pc with USB or BLUETOOTH, to share information from the gps chip as a tethering mode.