DocumentBuilderFactory.newInstance().newDocumentBuilder() error

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
public class FrameRecorder extends Thread {
     public Document dmt;
     public FrameRecorder() {
          DocumentBuilderFactory fctry = DocumentBuilderFactory.newInstance();
          fctry.setValidating(true);
          fctry.setNamespaceAware(true);
          fctry.setIgnoringElementContentWhitespace(true);
//the error is on the next line.
          DocumentBuilder bldr = fctry.newDocumentBuilder();
When I run it, I get an error saying:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
     Unhandled exception type ParserConfigurationException
     at FrameRecorder.<init>(FrameRecorder.java:11)
     at BaseFrame.<init>(BaseFrame.java:17)
     at Base.createGUI(Base.java:10)
     at Base$1.run(Base.java:7)
     at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:226)
     at java.awt.EventQueue.dispatchEvent(EventQueue.java:602)
     at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
     at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
     at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
     at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
I don't know what to do to fix this.
I'm running 64-bit Ubuntu 10.4 so could it be a compatibility problem? The only headway I could make was that .newDocumentBuilder() throws a ParserConfigurationException (that's the error I'm getting), and the docs tell me that .newDocumentBuilder() throws this when it "DocumentBuilder cannot be created which satisfies the configuration requested".
Any help?

Yes, somewhere in your code you have a compile error. I'm guessing you're using Eclipse and running your code from within it (or at least, running the Eclipse compiled classes from the command line).
You need to go and fix the compiler error. You already have all the information you need. You know where it is, you know what it is, and the documentation confirms it.

Similar Messages

  • DocumentBuilderFactory.newInstance() only works after garbage collection

    Hi all,
    I am stucked with a strange behaviour of "DocumentBuilderFactory.newInstance()".
    I use the DocumentBuilderFactory in an applet
    to parse an xml-file.
    My applet starts ok until the line 5 (newInstance) gets called.
    At this time it seems that nothing happens anymore and that
    the applet fails to continue.
    But when I open up the java console and hit
    g (garbage collection) the xml parsing continues immediatly
    and my applet completes loading and runs ok.
    1 private void genarteDomNodes() {
    2 try {
    3 // ---- Parse XML file ----
    4 DocumentBuilderFactory factory =
    5 DocumentBuilderFactory.newInstance();
    6 DocumentBuilder builder =
    7 factory.newDocumentBuilder();
    8 Document document = builder.parse(
    9 new URL(this.myModules_xml).openStream() );
    10 // ---- Get list of nodes to given element tag name ----
    11 NodeList ndList =
    12 document.getElementsByTagName("meter-group");
    13 printNodesFromList( ndList );
    14 } catch( SAXParseException spe ) {
    15 ...
    16 } catch( SAXException sxe ) {
    17 ...
    18 } catch( ParserConfigurationException pce ) {
    19 ...
    20 } catch( IOException ioe ) {
    21 ...
    22 }
    23 }

    I am still stucked with this problem. But I found out how to enable JAXP debug output for applets (setting system properties isn't allowed for applets).
    This puts somemore output to the java console. It might help someone to understand my problem. I also printed some debug messages to track down my problem.
    Following is the console output of my applet:
    URL of XML to parse = "http://10.110.132.195/c8000-modules.xml"
    entering "genarteDomNodes"
    just before calling "DocumentBuilderFactory.newInstance()"
    JAXP: find factoryId =javax.xml.parsers.DocumentBuilderFactory
    !!! at this time the applet "hangs" and nothing happens;
    until I hit the "g" button. Then applet continues immediatly and prints:
    JAXP: loaded from fallback value: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
    JAXP: created new instance of class com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl using ClassLoader: sun.plugin.security.PluginClassLoader@32060c
    After invoking the garbage collector the applet continue to parse the xml file and runs as expected.
    Can someone help me please.

  • Weird DocumentBuilderFactory.newInstance() behaviour

    problem summary
    ==============
    jvm breaks when I call DocumentBuilderFactory.newInstance(). I suspect its something to do with security but no exception is caught in the try...catch block where DocumentBuilderFactory.newInstance() is called.
    Other info about the problem
    ======================
    I'm working on an application that use 'presence service' and message queue service. When I use Sun's message queue service, jvm doesn't break. But when I use a SKype client (jskype) jvm always fail even though jskype doesn't reference DocumentBuilderFactory.newInstance() at all. Anyone?

    That's great thinking Fred.
    I've working on a much cut down and simplified version with just program changes to find out the cause of the behaviour.
    I tried your note off suggestion without success, but your comment on the original multi being "blocked" led me to route the final events to a second copy of the multi instrument rather than the original, and it works - the custom bank changes are correctly output!
    Maybe there's some kind of internal message validation or something, I'm not quite sure. But using a second copy of the multi instrument - though not ideal - is a perfectly acceptible workaround.
    So thanks for the pointer - you really helped me out..!

  • DocumentBuilderFactory.newInstance(); OR TransformerFactory.newInstance();

    Usually when we create a reference to an class, we'll do:
    Test tst = new Test();
    But when we create a DocumentBuilderFactory or a TransformerFactory, we use:
    DocumentBuilderFactory.newInstance();
    or
    TransformerFactory.newInstance();
    Why use the newInstance() instead?
    Thanks
    Scott

    Those are "factory" classes (as you might guess from their names). The DocumentBuilderFactory's newInstance() method returns an object that is an instance of DocumentBuilderFactory. If you read the documentation for the method, you will see the logic it goes through to decide which class it will produce an instance of.
    This allows the user to configure the choice of DocumentBuilderFactory by changing the environment, rather than by having to modify source code and recompile.

  • DocumentBuilderFactory.newInstance()

    Hi Guys,
    I am writing a utility that does access a database table and an xml file, like the following.
    public void reads(){
    tableMap = readTable(tableName); // here I am making a DB connection.
    xmlMap = readXML(tableName); //
    public Map readXML(){
         docFact=DocumentBuilderFactory.newInstance();
         //��creates an xml document
    Here the problem is while I am using that readTable function the application exits by the line �docFact=DocumentBuilderFactory.newInstance()�. and if the readTable function is not called it works fine!.
    Biju.

    Did you run if from GUI of from console? One of the possibilities is that your JRE is crashed (in that case it usually create a log file).

  • WSIFServiceFactory.newInstance() gives error but in WSAD itis ok

    Hi,
    on calling
    WSIFServiceFactory.newInstance() gives error
    java.lang.NoClassDefFoundError: oracle/j2ee/ws/wsdl/extensions/wsif/schema/Schema2Java
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
         at org.apache.wsif.util.WSIFUtils.createSimpleTypesMap(WSIFUtils.java:704)
         at org.apache.wsif.WSIFServiceFactory.newInstance(WSIFServiceFactory.java:84)
    with regards
    Siddharth singh

    Hi,
    the line
    java.lang.NoClassDefFoundError: oracle/j2ee/ws/wsdl/extensions/wsif/schema/Schema2Java
    points to a missing library class.Make sure Schema2Java is accessible from your project
    Frank

  • Problem with JAXBContext.newInstance  internal error

    Hey!
    I am working on an upgrade of the JAXB version in our Enterprise application. Class generation and build apparently works fine. From the class that invokes the webservice I try to create a JAXBContext using the newInstance method. Like this:
    JAXBContext.newInstance("com.myapp.myschema.packagename");This worked fine with JAXB1.0, but now I get the following stacktrace. I suspect that this error occurs due to som package problems, but I have no idea how to fix it. Can anyone help me??
    Heres the stacktrace:
    java.lang.InternalError
         at com.sun.xml.bind.v2.model.annotation.RuntimeInlineAnnotationReader.getClassValue(RuntimeInlineAnnotationReader.java:99)
         at com.sun.xml.bind.v2.model.annotation.RuntimeInlineAnnotationReader.getClassValue(RuntimeInlineAnnotationReader.java:17)
         at com.sun.xml.bind.v2.model.core.Adapter.<init>(Adapter.java:43)
         at com.sun.xml.bind.v2.model.impl.PropertyInfoImpl.<init>(PropertyInfoImpl.java:88)
         at com.sun.xml.bind.v2.model.impl.SingleTypePropertyInfoImpl.<init>(SingleTypePropertyInfoImpl.java:35)
         at com.sun.xml.bind.v2.model.impl.AttributePropertyInfoImpl.<init>(AttributePropertyInfoImpl.java:23)
         at com.sun.xml.bind.v2.model.impl.RuntimeAttributePropertyInfoImpl.<init>(RuntimeAttributePropertyInfoImpl.java:18)
         at com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl.createAttributeProperty(RuntimeClassInfoImpl.java:68)
         at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.addProperty(ClassInfoImpl.java:747)
         at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.getProperties(ClassInfoImpl.java:257)
         at com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl.getProperties(RuntimeClassInfoImpl.java:89)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:127)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.calcRef(TypeRefImpl.java:56)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.getTarget(TypeRefImpl.java:33)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:22)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:15)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:38)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:41)
         at java.util.AbstractList$Itr.next(AbstractList.java:422)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:139)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.calcRef(TypeRefImpl.java:56)
         at com.sun.xml.bind.v2.model.impl.TypeRefImpl.getTarget(TypeRefImpl.java:33)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:22)
         at com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:15)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:38)
         at com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:41)
         at java.util.AbstractList$Itr.next(AbstractList.java:422)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:139)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:49)
         at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:41)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:189)
         at com.sun.xml.bind.v2.model.impl.RegistryInfoImpl.<init>(RegistryInfoImpl.java:63)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.addRegistry(ModelBuilder.java:232)
         at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:201)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:352)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:350)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:349)
         at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:215)
         at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:76)
         at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:55)
         at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:124)
         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:585)
         at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:132)
         at javax.xml.bind.ContextFinder.find(ContextFinder.java:286)
         at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
         at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
         at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:244)

    I did have the same problem and it took me several hours to figure it out. Here is what I did, it might be useful for others later.
    I have a number of opened projects and needed to reference them in my ant build.xml
    The program runs fine from eclipse, but dies when I run the created jar file from command line.
    The line of code where it stopped was
    JAXBContext context = JAXBContext.newInstance(jaxbPackage);
    with the above InternalError printstack printed. Which was not really informative.
    Apparently, one of the referenced projects indirectly required other projects which I did not mention in my build.xml It was obviously the packaging problem.
    You can also check the version of you jvm in your terminal and in your eclipse; check the class path in eclipse and temporarily add all the missing lines to your CLASSPATH. If the problem goes away, you can easily figure out which class path was missing.

  • Java Error in RFC Lookup in XSLT Mapping usinf Java helper class

    Hi All,
    I am doing RFC Lookup in XSLT Mapping using Java Helper class.
    The Lookup works fine when called one RFC at a time However my requirement is I want to do 2 Lookups.
    Both Lookups works when done individually however when I call both lookups in one mapping I get following error "javax.xml.transform.TransformerException: DOMSource whose Node is null."
    Following is the code I have written in XSLT for the lookup:
         <xsl:template name="Lookup_1">
              <xsl:param name="STDPN"/>
                   <rfc:RFC_READ_TABLE>
                        <QUERY_TABLE>KNA1</QUERY_TABLE>
                        <OPTIONS><item><TEXT>
                                  <xsl:value-of select="$STDPN"/>
                             </TEXT></item>
                        </OPTIONS>
                        <FIELDS>
                             <item>
                                  <FIELDNAME>KUNNR</FIELDNAME>
                             </item>
                        </FIELDS>
                   </rfc:RFC_READ_TABLE>
              </xsl:variable>
              <xsl:variable name="response" xmlns:lookup="java:urn.mt.pi" select="lookup:execute($request, 'BS_D, 'cc_RfcLookup', $inputparam)"/>
              <xsl:element name="STDPN">
                   <xsl:value-of select="$response//DATA/item/WA"/>
              </xsl:element>
         </xsl:template>
         <xsl:template name="Lookup_2">
              <xsl:param name="BELNR"/>
                   <xsl:variable name="Query">AGMNT = '<xsl:value-of select="$BELNR"/>'</xsl:variable>
                   <xsl:variable name="request1">
                        <rfc:RFC_READ_TABLE>
                             <QUERY_TABLE>ZTABLE</QUERY_TABLE>
                             <OPTIONS><item><TEXT>
                                  <xsl:value-of select="$Query"/>
                                  </TEXT></item>
                             </OPTIONS>
                             <FIELDS>
                                  <item>
                                       <FIELDNAME>KUNAG</FIELDNAME>
                                  </item>
                             </FIELDS>
                        </rfc:RFC_READ_TABLE>
                   </xsl:variable>
                   <xsl:variable name="response1" xmlns:lookup="java:urn.mt.pi" select="lookup:execute($request1, 'BS_D','cc_RfcLookup', $inputparam)"/>
                   <xsl:element name="BELNR">
                        <xsl:value-of select="$response1//DATA/item/WA"/>
                   </xsl:element>
         </xsl:template>
    My Question: Am I doing anything wrong? Or Is it possible to call multiple lookups in one XSLT?
    Thanks and Regards,
    Atul

    Hi Atul,
    I had the same problem like you had.
    The main Problem is that with the example code the request variable is created as NodeList object. In XSLT a variable is somekind of a constant and can't be changed. As the request object is empty after the first request the programm fails at the following line:
    Source source = new DOMSource(request.item(0));
    So I've created a workaround for this problem.
    In the call of the template I've put the request as a parameter object at the template call:
    <xsl:with-param name="req">
    <rfc:PLM_EXPLORE_BILL_OF_MATERIAL xmlns:rfc="urn:sap-com:document:sap:rfc:functions">
      <APPLICATION>Z001</APPLICATION>
      <FLAG_NEW_EXPLOSION>X</FLAG_NEW_EXPLOSION>
      <MATERIALNUMBER><xsl:value-of select="value"/></MATERIALNUMBER>
      <PLANT>FSD0</PLANT>
      <VALIDFROM><xsl:value-of select="//Recordset/Row[name='DTM-031']/value"/></VALIDFROM>
      <BOMITEM_DATA/>
    </rfc:PLM_EXPLORE_BILL_OF_MATERIAL>
    </xsl:with-param>
    With this change the request will be provided as a String object and not as a NodeList object.
    Afterwards the RfcLookup.java has to be changed to the following:
    package com.franke.mappings;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.lookup.Channel;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import com.sap.aii.mapping.api.AbstractTrace;
    import com.sap.aii.mapping.lookup.RfcAccessor;
    import com.sap.aii.mapping.lookup.LookupService;
    import com.sap.aii.mapping.lookup.XmlPayload;
    * @author Thorsten Nordholm Søbirk, AppliCon A/S
    * Helper class for using the XI Lookup API with XSLT mappings for calling RFCs.
    * The class is generic in that it can be used to call any remote-enabled
    * function module in R/3. Generation of the XML request document and parsing of
    * the XML response is left to the stylesheet, where this can be done in a very
    * natural manner.
    * TD:
    * Changed the class that request is sent as String, because of IndexOutOfBound-exception
    * When sending multiple requests in one XSLT mapping.
    public class RfcLookup {
         * Execute RFC lookup.
         * @param request RFC request - TD: changed to String
         * @param service name of service
         * @param channelName name of communication channel
         * @param inputParam mapping parameters
         * @return Node containing RFC response
         public static Node execute( String request,
                 String service,
                 String channelName,
                 Map inputParam)
              AbstractTrace trace = (AbstractTrace) inputParam.get(StreamTransformationConstants.MAPPING_TRACE);
              Node responseNode = null;
              try {
                  // Get channel and accessor
                  Channel channel = LookupService.getChannel(service, channelName);
                  RfcAccessor accessor = LookupService.getRfcAccessor(channel);
                   // Serialise request NodeList - TD: Not needed anymore as request is String
                   /*TransformerFactory factory = TransformerFactory.newInstance();
                   Transformer transformer = factory.newTransformer();
                   Source source = new DOMSource(request.item(0));
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   StreamResult streamResult = new StreamResult(baos);
                   transformer.transform(source, streamResult);*/
                    // TD: Add xml header and remove linefeeds for the request string
                    request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+request.replaceAll("[\r\n]+", ""); 
                    // TD: Get byte Array from request String to send afterwards
                    byte[] requestBytes = request.getBytes();
                   // TD: Not used anymore as request is String
                    //byte[] requestBytes = baos.toByteArray();
                    trace.addDebugMessage("RFC Request: " + new String(requestBytes));
                    // Create input stream representing the function module request message
                    InputStream inputStream = new ByteArrayInputStream(requestBytes);
                    // Create XmlPayload
                    XmlPayload requestPayload =LookupService.getXmlPayload(inputStream);
                    // Execute lookup
                    XmlPayload responsePayload = accessor.call(requestPayload);
                    InputStream responseStream = responsePayload.getContent();
                    TeeInputStream tee = new TeeInputStream(responseStream);
                    // Create DOM tree for response
                    DocumentBuilder docBuilder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    Document document = docBuilder.parse(tee);
                    trace.addDebugMessage("RFC Response: " + tee.getStringContent());
                    responseNode = document.getFirstChild();
              } catch (Throwable t) {
                   StringWriter sw = new StringWriter();
                   t.printStackTrace(new PrintWriter(sw));
                   trace.addWarning(sw.toString());
              return responseNode;
         * Helper class which collects stream input while reading.
         static class TeeInputStream extends InputStream {
               private ByteArrayOutputStream baos;
               private InputStream wrappedInputStream;
               TeeInputStream(InputStream inputStream) {
                    baos = new ByteArrayOutputStream();
                    wrappedInputStream = inputStream;
               * @return stream content as String
               String getStringContent() {
                    return baos.toString();
              /* (non-Javadoc)
              * @see java.io.InputStream#read()
              public int read() throws IOException {
                   int r = wrappedInputStream.read();
                   baos.write(r);
                   return r;
    Then you need to compile and upload this class and it should work.
    I hope that this helps you.
    Best regards
    Till

  • Question about removing a node.. getting 'not found in this context'  error

    hi, i have the following code:
         public boolean deleteRunType(String runTypeName){
              //in this function we
              NodeList nl = Doc.getElementsByTagName("Run-Type");
              int numberOfNodes = nl.getLength();
              String attribute;
              NamedNodeMap attributes;
              for(int i=0;i<numberOfNodes;i++){
                   attributes = nl.item(i).getAttributes();
                   if(attributes!=null){
                        Node attributeNode = attributes.getNamedItem("name");
                        if(attributeNode!=null){
                             attribute = attributeNode.getNodeValue();
                             System.out.println("Comparing:  attribute = " + attribute + "   to runTypeName = " + runTypeName);
                             if(attribute.compareTo(runTypeName) == 0){
                                  System.out.println("Match!");
                                  Doc.removeChild(nl.item(i));
                        }//end if
                   }//end if
              }//end for
              return true;
    //definition of Doc:
                        DocumentBuilder DB  = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                        Doc           = DB.parse(xmlFile);anyways, i am getting an error:
    org.apache.crimson.tree.DomEx: NOT_FOUND_ERR: That node does not exist in this context.
         at org.apache.crimson.tree.ParentNode.removeChild(Unknown Source)
         at RunType.RunTypeXMLWriter.deleteRunType(RunTypeXMLWriter.java:58)
         at RunType.RunTypeXMLWriter.main(RunTypeXMLWriter.java:81)when i run it. it crashes on the Doc.removeChild(nl.item(0)); line.
    why is this? I grabbed the child directly from the list, so it should exist in this
    context. Maybe i don't understand the context.
    Any ideas or suggestions? Thank you SO much for all the help. i am finally
    starting to get the hang of XML, but i still have some hangups!

    This is not an uncommon problem.
    When you do getElementsByTagName() on a document, you get all elements by that name that anywhere in the tree of the document.
    When you do a removeChild, you need to be pointing to the parent of the element you are removing.
    If you change the removeChild line to :
    Node parent =  nl.item(i).getParentNode();
    parent.removeChild( nl.item(i) );Also, it is generally not done to use a capital letter to start the name of an instance, such as "Doc". Initial capital letters are usually reserved for class names.
    Dave Patterson

  • Why parser error

    Hi guys,
    I am using
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    xml = builder.parse(DocuContent.getInputStream());
    But I got
    com.sap.engine.lib.xml.parser.NestedSAXParserException: Fatal Error: com.sap.engine.lib.xml.parser.ParserException: Unsupported character: 6e(:main:, row:1, col:1682)(:main:, row=1, col=1682) -> com.sap.engine.lib.xml.parser.ParserException: Unsupported character: 6e(:main:, row:1, col:1682)
    What would be the problem, is something wrong with my XML data?
    Thanks for ur hint!
    Reg.
    Liying

    Hi Praveen ,
    here is my XML:
    I can not open it online: I got the error:
    Die XML-Seite kann nicht angezeigt werden
    Die XML-Eingabe kann nicht angezeigt werden, wenn Stylesheet XSL verwendet wird. Beheben Sie den Fehler und klicken Sie dann auf Aktualisieren, oder wiederholen Sie den Vorgang später.
    Im Textinhalt wurde ein ungültiges Zeichen gefunden. Fehler beim Bearbeiten der Ressource 'http://mira03.iv.brnet.int:50100...
    <?xml version="1.0" encoding="utf-8"?><templateConfig templateId="br_project_template" rootpath="/room_extensions/c...

  • Xml validation error, pls help

    I try to use the following way to validate my xml file with one schema.
    // parse an XML document into a DOM tree
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = parser.parse(new File("instance.xml"));
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(new File("mySchema.xsd"));
    Schema schema = factory.newSchema(schemaFile);
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    try {
    validator.validate(new DOMSource(document));
    } catch (SAXException e) {
    // instance document is invalid!
    got the error message like SAXException: http://www.w3.org/TR/xml-schema-1#cvc-type.3.1.1?
    i am very confused. what can be the problem?
    Thanks very much.

    <?xml version="1.0" encoding="UTF-8"?>
    <dataset xmlns="xx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="xx yy.xsd">
    <heading xsi:type="PW_Heading" datasetId="PW_2005-08-22_18-34-58.pts" generationDate="2005-08-22T16:35:00Z" providerId="PW"/>
    <eventCommands>
    <DEFINE>
    <siEvent xsi:type="KRIMI_SiEventDefinition" eventId="KRIMI_0000177732121_SI" serviceId="KRIMI" programId="KRIMI_0000177732121"
    startTime="2005-08-23T03:52:15Z" duration="00 00:48:54.000" title="SOKO Leipzig" comment="#SG:1" triggerType="TIMED">
    </siEvent>
    </DEFINE>
    </eventCommands>
    </dataset>
    This should be output xml which can be validated.
    the schema for heading and siEvent is:
    <xs:complexType name="Heading" abstract="true">
              <xs:attribute name="generationDate" type="xs:dateTime" use="required"/>
              <xs:attribute name="datasetId" type="Token30" use="required"/>
              <xs:attribute name="providerId" type="Token10" use="required"/>
         </xs:complexType>
    <xs:complexType name="SiEventDefinition" abstract="true">
              <xs:choice>
                   <xs:element name="siStandard" type="SiStandardDefinition"/>
                   <xs:element name="siReference" type="SiReferenceDefinition"/>
                   <xs:element name="siTimeshift" type="SiTimeshiftDefinition"/>
              </xs:choice>
              <xs:attributeGroup ref="EventPropertyDefinition"/>
         </xs:complexType>
    now my output xml is:
    <?xml version="1.0" encoding="UTF-8"?>
    <dataset >
    <heading datasetId="PW_2005-08-22_18-34-58.pts" generationDate="2005-08-22T16:35:00Z" providerId="PW"/>
    <eventCommands>
    <DEFINE>
    <siEvent eventId="KRIMI_0000177732121_SI" serviceId="KRIMI" programId="KRIMI_0000177732121"
    startTime="2005-08-23T03:52:15Z" duration="00 00:48:54.000" title="SOKO Leipzig" comment="#SG:1" triggerType="TIMED">
    </siEvent>
    </DEFINE>
    </eventCommands>
    </dataset>
    my problem is: i dont know how to generate these attributes in dataset, and how to generate the xsi:type attribute in heading and siEvent.
    Thanks in advance.

  • ClassCastException in DocumentBuilderFactory on DB-Server

    Hi,
    I've deployed an application, that recieves a xml-String to parse.
    It's running fine in JDeveloper but when I deploy it to the Database
    I recieve the ClassCastException.
    I figured out that it's thrown when I do:
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Whats the problem with the DocumentBuilderFactory?
    Any Suggestions?
    THX
    Selim Keser

    Have you loaded the same version of the Oracle XDK for Java into the database account where you're trying to run this?

  • How to retrieve information from XML using servlets

    Hi
    I have a scenario like this
    File-->XI-->J2ee application(HTTP Receiver adapter)
    I want to know how XI sends xml file as a query string file name?
    What ever may be the case i just need to retrieve the information from Request object and display the same in browser(JSP).How to do that, I am totally confused, please anyone help me!
    Code help is highly rewarded.
    Thanx

    Hi Rajesh!
    I have tried your code. But some where i went wrong. Please correct me: I am using NWDS2.0.9
    my web.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                             "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
        <display-name>WEB APP</display-name>
        <description>WEB APP description</description>
        <servlet>
            <servlet-name>DisplayRes</servlet-name>
            <servlet-class>com.quinnox.DisplayRes</servlet-class>
        </servlet>
        <servlet-mapping>
              <servlet-name>DisplayRes</servlet-name>
              <url-pattern>/DisplayRes/*</url-pattern>
         </servlet-mapping>
    </web-app>
    my application.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
                                 "http://java.sun.com/dtd/application_1_3.dtd">
    <application>
        <display-name>ReceiverEntpr</display-name>
        <description>EAR description</description>
        <module>
            <web>
                <web-uri>HttpReceiver.war</web-uri>
                <context-root>/HttpReceiver</context-root>
            </web>
        </module>
    </application>
    and my servlet code:
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.Writer;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Result;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.xml.sax.EntityResolver;
    import org.xml.sax.SAXException;
    import com.sun.java_cup.internal.parser;
    import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
    public class DisplayRes extends HttpServlet {
         public void doGet(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException
              doWork(requset, response);
         public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
              doWork(req, resp);
         private void doWork(HttpServletRequest req, HttpServletResponse resp) throws IOException
              String path = null;
              PrintWriter out = null;
              PrintWriter p2=resp.getWriter();     
              try
                   resp.setContentType("text/xml");
                   out = resp.getWriter();
                   out.println("hi");
                   path = req.getPathInfo();
                   if(req.getContentLength() != -1){
                   outputURI(req.getInputStream(), out);
              } catch (IOException ioe) {     return;     
         //private void outputURI(InputStream resultStream, Writer out) {
              private void outputURI(InputStream resultStream, PrintWriter out) {
              if (resultStream == null) {
    //             no default file
    //            logger.error("No File to return");
              return;
              try {
              DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    //            Class clazz = loader.loadClass("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
    //            DocumentBuilderFactoryImpl factory = (DocumentBuilderFactoryImpl) clazz.newInstance();
    //            DocumentBuilder parser = factory.newDocumentBuilder();
              parser.setEntityResolver(new ClassPathEntityResolver());
              printXML(parser.parse(resultStream), out);
              resultStream.close();
              } catch (Exception e) {
    //            logger.error("Trying to parse the output " , e);
         //private void printXML(Document document, Writer writer) throws Exception {
              private void printXML(Document document, PrintWriter writer) throws Exception {
              Transformer transformer = TransformerFactory.newInstance().newTransformer();
              Source source = new DOMSource(document);
              Result output = new StreamResult(System.out);
              transformer.transform(source, output);
    //             Write as XML so that entity references can be resolved.
              if (writer != null) {
              transformer.transform(source, new StreamResult(writer));
    Please tell me how to display in servlet.
    If it is better to display in a browser. Please send me the code.
    Thanks

  • Why do I need to catch this exception?

    Hello all
    This is a question about exception handling. I have to build a diary application that lets you save reminders on particular dates using xml. Just to make it a little tougher, I was not allowed to use the Calendar class. This is the code I wrote:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*; 
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;     
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;                                                                                                                                                                                                                         
    import static java.lang.Math.*;
    public class CalendarAssignment extends JFrame implements ActionListener
         int MonthLength [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
         public JButton [] days = new JButton[43];
         private JLabel lbl, reminderlbl;
         private JPanel top, grid, remindercenter, reminderbottom;
         private JFrame reminderframe;
         private JTextField year1, reminderinput, dayno;
         private JComboBox months;
         private Container container;
         private JButton fetch, save, cancel;
         private Document doc;
         private File file;
         private Node node;
         private String year, month, day;
              public static void main( String[] args ) {
                   CalendarAssignment c = new CalendarAssignment( );
                   c.setSize( 400, 300 );
                   c.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                   c.show( );
              public CalendarAssignment( ) {
                   int CurrentYear, CurrentMonth;
                   String YearString, MonthString, Now;
                   Date today;
                   container = getContentPane( );
                   container.setLayout( new BorderLayout( ) );
                   SimpleDateFormat DateFormatter;
                   DateFormatter = new SimpleDateFormat( "MM.yyyy" );
                   today = new Date( );
                   Now = DateFormatter.format( today );
                   MonthString = Now.substring( 0,2 );
                   YearString = Now.substring( 3,7 );
                   CurrentMonth = Integer.valueOf( MonthString );
                   CurrentYear = Integer.valueOf( YearString );
                   top = new JPanel( );
                        String [] items = { "January", "February", "March", "April", "May", "June",
                                      "July", "August", "September", "October", "November",
                                      "December" };
                        months = new JComboBox( items );
                        months.setEditable( false );
                        months.setSelectedIndex( CurrentMonth - 1 );          
                        year1 = new JTextField( );
                        year1.setText( YearString );
                        year1.setEditable( true );
                        year1.setHorizontalAlignment( year1.CENTER );
                        fetch = new JButton( "Fetch Month" );
                        fetch.addActionListener( this );
                        top.setLayout( new GridLayout( 1, 3, 20, 0 ) );
                        top.add( months );
                        top.add( year1 );
                        top.add( fetch );
                   grid = new JPanel( );
                        grid.setLayout( new GridLayout( 7, 7, 0, 0 ) );
                        String [] week = { "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun" };
                        for ( int a = 0; a < 7; a ++ ) {
                                  JLabel lbl = new JLabel( week[a], JLabel.CENTER );
                                  grid.add( lbl );
                        for ( int i = 0; i < 42; i ++ ) {
                                  days[i] = new JButton( );
                                  grid.add( days[i] );
                                  days.addActionListener( this );
                        DrawCalendar( CurrentMonth, CurrentYear );
                        container.add( top, BorderLayout.NORTH );
                        container.add( grid, BorderLayout.CENTER );
              private void DrawCalendar( int SelectMonth, int SelectYear ) {
                        int DisplayMonthLength, Buttons;
                        String ButtonID = "";
                        int OffSet = MonthStart( SelectMonth, SelectYear );
                        DisplayMonthLength = MonthLength [SelectMonth - 1];
                        if ( SelectMonth == 2 )
                             DisplayMonthLength += LeapYear( SelectYear );
                        for ( Buttons = 1; Buttons < 43; Buttons ++ ) {
                             if ( ( Buttons <= OffSet ) || ( Buttons > ( DisplayMonthLength + OffSet ) ) ) {
                                  ButtonID = "";
                                  days[Buttons-1].setEnabled( false );
                             else {
                                  ButtonID = Integer.toString( Buttons - OffSet );
                                  days[Buttons-1].setEnabled( true );
                        days[Buttons-1].setLabel( ButtonID );
                        grid.add( days[Buttons-1] );
              private int LeapYear( int year ) {
                        int FourHundred, OneHundred, Fourth;
                        FourHundred = year % 400;
                        OneHundred = year % 100;
                        Fourth = year % 4;
                        if( ( ( FourHundred == 0 ) ) || ( ( OneHundred != 0 ) && ( Fourth == 0 ) ) )
                             return ( 1 );
                        else
                             return ( 0 );
              private int MonthStart( int Month, int Year ) {
                        int OffSet, LastMonths, BeforeOrAfter, Years;
                        int AllDays = 0;
                        int YearDays = 365;
                        int YearMonths = 12;
                        BeforeOrAfter = Year - 2006;
                        Years = abs( BeforeOrAfter );
                        if( BeforeOrAfter != 0 )
                             BeforeOrAfter = BeforeOrAfter / Years;
                        switch( BeforeOrAfter ) {
                             case 1:
                                  for( int a = 2006; a < Year; a ++ ) {
                                       AllDays += YearDays + LeapYear( a );
                                  AllDays += LastMonthsCalc( Month, Year );
                             break;
                             case -1:
                                  for( int a = 2005; a > Year; a -- ) {
                                       AllDays += YearDays + LeapYear( a );
                                  for( LastMonths = YearMonths; LastMonths >= Month; LastMonths -- ) {
                                       AllDays += MonthLength[LastMonths - 1];
                                       if( LastMonths == 2 )
                                            AllDays += LeapYear( Year );
                             break;
                             default:
                                  if( Month > 1 )
                                       AllDays += ( LastMonthsCalc( Month, Year ) );
                        OffSet = AllDays % 7;
                        if( BeforeOrAfter ==( -1 ) )
                             return( 6 - OffSet );
                        else if( OffSet > 0 )
                             return( OffSet - 1 );
                        else
                             return( 6 );
              private int LastMonthsCalc( int Month, int Year ) {
                        int Counter;
                        int days = 0;
                        for( Counter = 1; Counter < Month; Counter ++ ) {
                             days += MonthLength[Counter - 1];
                             if( Counter == 2 )
                                  days += LeapYear( Year );
                        return( days );
              public void CreateReminder( String buttonID, String yearID, String monthID ) {
                        reminderframe = new JFrame( );
                        reminderlbl = new JLabel( );
                        reminderframe.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                        remindercenter = new JPanel( );
                             reminderlbl = new JLabel( "Please type in reminder to be saved for " + buttonID + " " + monthID + " " + yearID + ":", JLabel.CENTER );
                             reminderinput = new JTextField( 30 );
                             reminderinput.setHorizontalAlignment( reminderinput.CENTER );
                             reminderinput.setEditable( true );
                             remindercenter.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                             remindercenter.add( reminderlbl );
                             remindercenter.add( reminderinput );
                        reminderbottom = new JPanel( );
                             save = new JButton( "Save" );
                             save.addActionListener( this );
                             cancel = new JButton( "Cancel" );
                             cancel.addActionListener( this );
                             dayno = new JTextField( buttonID );
                             dayno.setEditable( false );
                             dayno.setEnabled( false );
                             dayno.show( false );
                             reminderbottom.setLayout( new FlowLayout( ) );
                             reminderbottom.add( save );
                             reminderbottom.add( cancel );
                             reminderbottom.add( dayno );
                        reminderframe.setSize( 500, 75 );
                        reminderframe.add( remindercenter );
                        reminderframe.add( reminderbottom );
                        reminderframe.pack( );
                        reminderframe.show( );
              public void SaveReminder( String dayID, String yearID, String monthID ) throws Exception {
                        file = new File( "Diary.xml" );
                        doc = DocumentBuilderFactory.newInstance( ).newDocumentBuilder( ).parse( file.toURL( ).toString( ) );
                        String year = yearID;
                        String month = monthID;
                        String day = dayID;
                        //System.out.println( year );
                        //System.out.println( month );
                        //System.out.println( day );
                        CreateEntry( doc.getDocumentElement( ) );
                        writeXmlFile( );
              public boolean CreateEntry( Node node ) {
                        Node searchNode;
                        searchNode = getYear( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Year" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", year );
                        node = searchNode;
                        searchNode = getMonth( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Month" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", month );
                        node = searchNode;
                        searchNode = getDay( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Day" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", day );
                        node = searchNode;
                        String entry = reminderinput.getText( );
                        Node textNode = doc.createTextNode( entry );
                        node.appendChild( textNode );
                        return true;
              private Node getYear( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if(node.getNodeName( ).equals( "Year" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == year )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getMonth( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Month" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == month )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getDay( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Day" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == day )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private void writeXmlFile( ) throws Exception {
                   Source source = new DOMSource( doc );
                        Result result = new StreamResult( file );
                   Transformer xformer = TransformerFactory.newInstance( ).newTransformer( );
                   xformer.setOutputProperty( OutputKeys.INDENT,"yes" );
                   xformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd" );
                   xformer.transform( source, result );
              public void actionPerformed( ActionEvent e ) {
                        String IDButton = e.getActionCommand( );
                        String IDYear = year1.getText( );
                        Object IDMonthObj = months.getSelectedItem( );
                        if( e.getSource( ) == fetch ) {
                             String YearText = year1.getText( );
                             int YearNumber = Integer.valueOf( YearText );
                             int MonthsIndex = months.getSelectedIndex( ) + 1;
                             DrawCalendar( MonthsIndex, YearNumber );
                        else if( e.getSource( ) == cancel ) {
                             reminderframe.hide( );
                        else if( e.getSource( ) == save ) {
                             String IDDay = dayno.getText( );
                             String IDMonth = String.valueOf( IDMonthObj );
                             SaveReminder( IDDay, IDYear, IDMonth );
                        else {
                             String IDMonth = String.valueOf( IDMonthObj );
                             Toolkit.getDefaultToolkit( ).beep( );
                             int n = JOptionPane.showConfirmDialog( null, "Set reminder on this date?", "Question", JOptionPane.YES_NO_OPTION );
                             if( n == JOptionPane.YES_OPTION ) {
                                  CreateReminder( IDButton, IDYear, IDMonth );
    If you compile it, you will realise that I get an error about exception handling. My lecturer gave me an example code of how to do the same thing without using a GUI:
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;
    import java.util.*;
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    public class CallDOM
         Document doc;
         File file;
         Scanner input;
         int year, month, day;
         String currentYear, currentMonth;
         public static void main(String args[]) throws Exception
              CallDOM cd=new CallDOM();          
         CallDOM() throws Exception
              file=new File("Diary.xml");
              //create DOM from file
              doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file.toURL().toString());
              input=new Scanner(System.in);
              System.out.println("1) Create entry");
              System.out.println("2) Read entry");
              System.out.println("3) Show Diary");
              System.out.println("4) Quit");
              int choice=input.nextInt();
              while(choice!=4)
                   switch(choice)
                        case 1: GetDate();CreateEntry(doc.getDocumentElement());break;
                        case 2: GetDate();ReadEntry(doc.getDocumentElement());break;
                        case 3: ShowDiary(doc.getDocumentElement());
                   System.out.println("1) Create entry");
                   System.out.println("2) Read entry");
                   System.out.println("3) Show Diary");
                   System.out.println("4) Quit");
                   choice=input.nextInt();
              writeXmlFile();
         public void GetDate()
              System.out.println("Enter date (dd mm yyyy)");
              day=input.nextInt();
              month=input.nextInt();
              year=input.nextInt();
         public boolean ReadEntry(Node node)
              node = getYear(node);
              if(node==null) return false;
              node = getMonth(node);
              if(node==null) return false;
              node = getDay(node);
              if(node==null) return false;
              node = node.getFirstChild();
              while(node!=null)
                   System.out.println(node.getNodeValue().trim());     
                   node=node.getNextSibling();
              return true;               
         public boolean CreateEntry(Node node)
              Node searchNode;
              searchNode = getYear(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Year");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(year));
              node = searchNode;
              searchNode = getMonth(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Month");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(month));
              node = searchNode;
              searchNode = getDay(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Day");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(day));
              node = searchNode;
              System.out.println("Enter Text");
              String entry=input.next();
              entry+=input.nextLine();
              Node textNode = doc.createTextNode(entry);
              node.appendChild(textNode);
              return true;               
         public void ShowDiary(Node node)
              Stack<Node> stack=new Stack<Node>();
              Node child;
              stack.push(node);
              while(!stack.empty())
                   node = stack.pop();
                   if(ProcessNode(node))
                        child = node.getLastChild();
                        while(child!=null)
                             stack.push(child);
                             child = child.getPreviousSibling();
         private boolean ProcessNode(Node node)
              if(node.getNodeName().equals("Year"))
                   currentYear=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Month"))
                   currentMonth=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Day"))
                   System.out.print(node.getAttributes().item(0).getNodeValue()+"/"+
                                            currentMonth+"/"+currentYear+": ");
                   node=node.getFirstChild();
                   while(node!=null)
                        System.out.println(node.getNodeValue().trim());
                        node=node.getNextSibling();
                   return false;
              return true;               
         private Node getYear(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Year")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==year)
                             return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getMonth(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Month")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==month)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getDay(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Day")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==day)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private void writeXmlFile() throws Exception
            Source source = new DOMSource(doc);
            Result result = new StreamResult(file);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.setOutputProperty(OutputKeys.INDENT,"yes");
            xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd");
            xformer.transform(source, result);
    }My question is, why does the exceptions in the example code not need to be caught? And why do I have to catch the exceptions in my code? Several exceptions are thrown in the example code, but there is no catch statement.
    Thanks for any advice!!

    Since your question didn't come with any relevant details, and since you have huge steaming piles of irrelevant code, all I can give is a general answer to "Why do I need to catch this exception?"
    [url http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]Exception tutorial at http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
    Here's a quick overview of exceptions:
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.

  • Import/insert data from XML into Oracle database tables?

    Hi. (I am using JDeveloper 10.1.3.3.0 and Oracle 10g)
    I have been able to export the data from one of my database tables by using a View Object and .writeXML.
    Now, I want to take an xml file that is formatted in the same way as what is spit out by the writeXML and put that info in my database table. I followed online examples and have tried using .readXML like so:
    Element element = XMLDoc.getDocumentElement();
    vo.readXML(element, -1);
    I know it is sort of working, because at first I got an error message that one of the required attributes was missing. So, I added that attribute to my xml file and ran my code. No errors. But, I checked my database, and the new records were not added.
    Is there something I have done wrong? Or is there perhaps something I left out? I also noticed there were several versions of readXML like readFromXML. Which one should I use and how?
    Thanks.

    KUBA, I changed my code to match your example:
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    File xmlFile = new File("C:/myfilehere.xml");
    Document doc = db.parse(xmlFile);
    Element element = doc.getDocumentElement();
    vo.readXML(element, -1);
    vo.getDBTransaction().commit();
    I still get no errors, but my database table has no new records.
    Any ideas why?
    Thanks.

Maybe you are looking for

  • Unable to delete songs from my iPad 2

    Last night for the first time ever I had problems updating iOs (version 7.0.4) on my iPad 2. I kept getting one of several messages, for example, saying: iTunes has detected an iPad in recovery mode. You must restore this iPad before it can be used w

  • Boot Camp won't boot Win 7 DVDs /Cloned disks - White cursor flashes once then Black Screen of Death.

    Hi Guys, I am having a serious issue with my machines ability to use boot camp. Here's what happend: I had Win 7 installed on the BOOTCAMP partition for a long while, then one day my HD crashed. So naturally I got my HD replaced from Apple and got Li

  • Msi pro-e mb possibly keeping psu fan on?

    Hello all, fresh i7920 build with msi pro-e mb, corsair xms3 6gb, and a corsair tx750w psu.  The problem i'm having is when i power down the system for the night the psu fan will continue to run all night long even though the system if off(not in sle

  • JAI and grayscale problems

    Hi! My problem concerns grayscale. First I load tiff-image from a file (OK) and then I want to change its colors to grayscale and after that I save that converted picture as Bmp, but this is not working. I have tried codes that I found from forum, bu

  • Upgrading from PDK 1.0 patch 3 to PDK 2.0

    hi, We have upgraded from PDK 1.0 patch 3 to PDK 2.0. Since the upgrade we have problems with the DropDownByKey control. It seems that the value of the SelectedKey property of the control is not behaving the same way it has before the upgrade and we