/** Constructs one Document from an XML file */
  public static Document readDocument(File f)
      throws IOException, SAXException, ParserConfigurationException {
    Document document = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // factory.setValidating(true);
    // factory.setNamespaceAware(true);

    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(f);

      // displayDocument(document);

    } catch (SAXException sxe) {
      // Error generated during parsing)
      Exception x = sxe;
      if (sxe.getException() != null) x = sxe.getException();
      x.printStackTrace();
      throw sxe;
    } catch (ParserConfigurationException pce) {
      // Parser with specified options can't be built
      pce.printStackTrace();
      throw pce;
    } catch (IOException ioe) {
      // I/O error
      ioe.printStackTrace();
      throw ioe;
    }

    return document;
  } // readDocument
 private boolean readConfigFile(String cfgFile) {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   // factory.setValidating(true);
   // factory.setNamespaceAware(true);
   try {
     DocumentBuilder builder = factory.newDocumentBuilder();
     config = builder.parse(cfgFile);
     /** Configuration DOM */
     // Document config;
   } catch (SAXException sxe) {
     // Error generated during parsing)
     Exception x = sxe;
     if (sxe.getException() != null) x = sxe.getException();
     x.printStackTrace();
     return false;
   } catch (ParserConfigurationException pce) {
     // Parser with specified options can't be built
     pce.printStackTrace();
     return false;
   } catch (IOException ioe) {
     // I/O error
     ioe.printStackTrace();
     return false;
   }
   return true;
 }
Example #3
0
  public static void main(String[] args) throws Exception {
    Parseable p;

    ErrorHandler eh =
        new DefaultHandler() {
          public void error(SAXParseException e) throws SAXException {
            throw e;
          }
        };

    // the error handler passed to Parseable will receive parsing errors.
    if (args[0].endsWith(".rng")) p = new SAXParseable(new InputSource(args[0]), eh);
    else p = new CompactParseable(new InputSource(args[0]), eh);

    // the error handler passed to CheckingSchemaBuilder will receive additional
    // errors found during the RELAX NG restrictions check.
    // typically you'd want to pass in the same error handler,
    // as there's really no distinction between those two kinds of errors.
    SchemaBuilder sb = new CheckingSchemaBuilder(new DSchemaBuilderImpl(), eh);
    try {
      // run the parser
      p.parse(sb);
    } catch (BuildException e) {
      // I found that Crimson doesn't show the proper stack trace
      // when a RuntimeException happens inside a SchemaBuilder.
      // the following code shows the actual exception that happened.
      if (e.getCause() instanceof SAXException) {
        SAXException se = (SAXException) e.getCause();
        if (se.getException() != null) se.getException().printStackTrace();
      }
      throw e;
    }
  }
  public void updateList(String fileName, int corridorSize) {
    tilesToDownload.clear();
    File file = new File(fileName);
    if (file.exists() && file.isFile()) {
      try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(file);

        Node gpxNode = document.getFirstChild();
        if (!gpxNode.getNodeName().equalsIgnoreCase("gpx")) {
          throw new RuntimeException("invalid file!");
        }

        // Object result = expr.evaluate(document, XPathConstants.NODESET);
        // NodeList nodes = (NodeList) result;
        NodeList nodes = gpxNode.getChildNodes();
        int detectedTrackNumber = 0;
        for (int i = 0; i < nodes.getLength(); i++) {
          if (nodes.item(i).getLocalName() != null
              && nodes.item(i).getLocalName().equalsIgnoreCase("trk")) {
            detectedTrackNumber++;
            // if (detectedTrackNumber == 1) {
            // Download all zoomlevels
            for (int zoomLevel : getDownloadZoomLevels()) {
              // handle all trgSegments
              NodeList trkSegs = nodes.item(i).getChildNodes();
              for (int indexTrkSeg = 0; indexTrkSeg < trkSegs.getLength(); indexTrkSeg++) {
                if (trkSegs.item(indexTrkSeg).getLocalName() != null
                    && trkSegs.item(indexTrkSeg).getLocalName().equalsIgnoreCase("trkseg")) {
                  // handle all trkpts
                  NodeList trkPts = trkSegs.item(indexTrkSeg).getChildNodes();
                  for (int indexTrkPt = 0; indexTrkPt < trkPts.getLength(); indexTrkPt++) {
                    if (trkPts.item(indexTrkPt).getLocalName() != null
                        && trkPts.item(indexTrkPt).getLocalName().equalsIgnoreCase("trkpt")) {
                      handleTrkPt(trkPts.item(indexTrkPt), zoomLevel, corridorSize);
                    }
                  }
                }
              }
            }
            // }
          }
        }
      } catch (SAXParseException spe) {
        Exception e = (spe.getException() != null) ? spe.getException() : spe;
        log.log(
            Level.SEVERE, "Error parsing " + spe.getSystemId() + " line " + spe.getLineNumber(), e);
      } catch (SAXException sxe) {
        Exception e = (sxe.getException() != null) ? sxe.getException() : sxe;
        log.log(Level.SEVERE, "Error parsing GPX", e);
      } catch (ParserConfigurationException pce) {
        log.log(Level.SEVERE, "Error in parser configuration", pce);
      } catch (IOException ioe) {
        log.log(Level.SEVERE, "Error parsing GPX", ioe);
      }
    }
  }
Example #5
0
 private SVNErrorMessage readData(
     InputStream is, String method, String path, DefaultHandler handler)
     throws FactoryConfigurationError, UnsupportedEncodingException, IOException {
   try {
     if (mySAXParser == null) {
       mySAXParser = getSAXParserFactory().newSAXParser();
     }
     XMLReader reader = new XMLReader(is);
     while (!reader.isClosed()) {
       org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader();
       xmlReader.setContentHandler(handler);
       xmlReader.setDTDHandler(handler);
       xmlReader.setErrorHandler(handler);
       xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       xmlReader.parse(new InputSource(reader));
     }
   } catch (SAXException e) {
     if (e instanceof SAXParseException) {
       if (handler instanceof DAVErrorHandler) {
         // failed to read svn-specific error, return null.
         return null;
       }
     } else if (e.getException() instanceof SVNException) {
       return ((SVNException) e.getException()).getErrorMessage();
     } else if (e.getCause() instanceof SVNException) {
       return ((SVNException) e.getCause()).getErrorMessage();
     }
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "Processing {0} request response failed: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (ParserConfigurationException e) {
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "XML parser configuration error while processing {0} request response: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (EOFException e) {
     // skip it.
   } finally {
     if (mySAXParser != null) {
       // to avoid memory leaks when connection is cached.
       org.xml.sax.XMLReader xmlReader = null;
       try {
         xmlReader = mySAXParser.getXMLReader();
       } catch (SAXException e) {
       }
       if (xmlReader != null) {
         xmlReader.setContentHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       }
     }
     myRepository.getDebugLog().flushStream(is);
   }
   return null;
 }
Example #6
0
  public ByteArrayOutputStream cleanup(InputStream xml) throws XServerException {
    inputXml = xml;

    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
      // Parse the input
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse(inputXml, this);

      // close the stream
      inputXml.close();
    } catch (SAXParseException spe) {
      // Use the contained exception, if any
      Exception x = spe;

      if (spe.getException() != null) {
        x = spe.getException();
      }

      // Error generated by the parser
      LOG.warn(
          "XMLCleanup.cleanup() parsing exception: "
              + spe.getMessage()
              + " - xml line "
              + spe.getLineNumber()
              + ", uri "
              + spe.getSystemId(),
          x);
    } catch (SAXException sxe) {
      // Error generated by this application
      // (or a parser-initialization error)
      Exception x = sxe;

      if (sxe.getException() != null) {
        x = sxe.getException();
      }

      LOG.warn("XMLCleanup.cleanup() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
      // Parser with specified options can't be built
      LOG.warn("XMLCleanup.cleanup() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
      // I/O error
      LOG.warn("XMLCleanup.cleanup() IO exception", ioe);
    } catch (Throwable t) {
      LOG.warn("XMLCleanup.cleanup() exception", t);
    }

    if (error) {
      throw new XServerException(error_code, error_text);
    }

    return bytes;
  }
Example #7
0
 /**
  * Notifies the registered {@link ErrorHandler SAX error handler} (if any) of an input processing
  * error. The error handler can choose to absorb the error and let the processing continue.
  *
  * @param exception <code>JDOMException</code> containing the error information; will be wrapped
  *     in a {@link SAXParseException} when reported to the SAX error handler.
  * @throws JDOMException if no error handler has been registered or if the error handler fired a
  *     {@link SAXException}.
  */
 private void handleError(JDOMException exception) throws JDOMException {
   if (errorHandler != null) {
     try {
       errorHandler.error(new SAXParseException(exception.getMessage(), null, exception));
     } catch (SAXException se) {
       if (se.getException() instanceof JDOMException) {
         throw (JDOMException) (se.getException());
       }
       throw new JDOMException(se.getMessage(), se);
     }
   } else {
     throw exception;
   }
 }
Example #8
0
 protected void addDocumentEnd() {
   try {
     h.endDocument();
   } catch (SAXException ex) {
     throw new RuntimeException(ex.getMessage(), ex.getException());
   }
 }
Example #9
0
  /**
   * Parses a given .svg for nodes
   *
   * @return <b>bothNodeLists</b> an Array with two NodeLists
   */
  public static NodeList[] parseSVG(Date date) {

    /* As it has to return two things, it can not return them
     * directly but has to encapsulate it in another object.
     */
    NodeList[] bothNodeLists = new NodeList[2];
    ;
    try {

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

      String SVGFileName = "./draw_map_svg.svg";
      File svgMap = new File(SVGFileName);

      System.out.println("Parsing the svg"); // Status message #1 Parsing
      System.out.println("This should not longer than 30 seconds"); // Status message #2 Parsing

      Document doc = docBuilder.parse(SVGFileName);

      // "text" is the actual planet/warplanet
      NodeList listOfPlanetsAsXMLNode = doc.getElementsByTagName("text");

      // "line" is the line drawn by a warplanet. Used for calculation of warplanet coordinates.
      NodeList listOfLinesAsXMLNode = doc.getElementsByTagName("line");
      bothNodeLists[0] = listOfPlanetsAsXMLNode;
      bothNodeLists[1] = listOfLinesAsXMLNode;

      // normalize text representation
      doc.getDocumentElement().normalize();

      // Build the fileName the .svg should be renamed to, using the dateStringBuilder
      String newSVGFileName = MapTool.dateStringBuilder(MapTool.getKosmorDate(date), date);
      newSVGFileName = newSVGFileName.concat(" - Map - kosmor.com - .svg");

      // Making sure the directory does exist, if not, it is created
      File svgdir = new File("svg");
      if (!svgdir.exists() || !svgdir.isDirectory()) {
        svgdir.mkdir();
      }

      svgMap.renameTo(new File(svgdir + "\\" + newSVGFileName));

      System.out.println("Done parsing"); // Status message #3 Parsing

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    return bothNodeLists;
  }
Example #10
0
 protected final void addEnd(final String name) {
   try {
     h.endElement("", name, name);
   } catch (SAXException ex) {
     throw new RuntimeException(ex.getMessage(), ex.getException());
   }
 }
Example #11
0
  private boolean validate(Object o, boolean validateId) throws ValidationException {

    try {

      // ValidatableObject vo = Util.toValidatableObject(o);
      ValidatableObject vo = jaxbContext.getGrammarInfo().castToValidatableObject(o);

      if (vo == null) throw new ValidationException(Messages.format(Messages.NOT_VALIDATABLE));

      EventInterceptor ei = new EventInterceptor(eventHandler);
      ValidationContext context = new ValidationContext(jaxbContext, ei, validateId);
      context.validate(vo);
      context.reconcileIDs();

      return !ei.hadError();
    } catch (SAXException e) {
      // we need a consistent mechanism to convert SAXException into JAXBException
      Exception nested = e.getException();
      if (nested != null) {
        throw new ValidationException(nested);
      } else {
        throw new ValidationException(e);
      }
      // return false;
    }
  }
  protected XmlRpcRequest getRequest(final XmlRpcStreamRequestConfig pConfig, InputStream pStream)
      throws XmlRpcException {
    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);
    try {
      xr.parse(new InputSource(pStream));
    } catch (SAXException e) {
      Exception ex = e.getException();
      if (ex != null && ex instanceof XmlRpcException) {
        throw (XmlRpcException) ex;
      }
      throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
    } catch (IOException e) {
      throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
    }
    final List params = parser.getParams();
    return new XmlRpcRequest() {
      public XmlRpcRequestConfig getConfig() {
        return pConfig;
      }

      public String getMethodName() {
        return parser.getMethodName();
      }

      public int getParameterCount() {
        return params == null ? 0 : params.size();
      }

      public Object getParameter(int pIndex) {
        return params.get(pIndex);
      }
    };
  }
Example #13
0
  public void makeGraph(String inputFile, String outputFile) {
    try {

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      docBuilderFactory.setValidating(false);
      docBuilderFactory.setNamespaceAware(false);
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new File(inputFile));
      doc.getDocumentElement().normalize();
      parseCdaXml(doc);
      System.out.println(" Graph contains : " + data.graph.nodeList.size());

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
  /**
   * Locates an external subset for documents which do not explicitly provide one. If no external
   * subset is provided, this method should return <code>null</code>.
   *
   * @param grammarDescription a description of the DTD
   * @throws XNIException Thrown on general error.
   * @throws java.io.IOException Thrown if resolved entity stream cannot be opened or some other i/o
   *     error occurs.
   */
  public XMLInputSource getExternalSubset(XMLDTDDescription grammarDescription)
      throws XNIException, IOException {

    if (fEntityResolver != null) {

      String name = grammarDescription.getRootName();
      String baseURI = grammarDescription.getBaseSystemId();

      // Resolve using EntityResolver2
      try {
        InputSource inputSource = fEntityResolver.getExternalSubset(name, baseURI);
        return (inputSource != null) ? createXMLInputSource(inputSource, baseURI) : null;
      }
      // error resolving external subset
      catch (SAXException e) {
        Exception ex = e.getException();
        if (ex == null) {
          ex = e;
        }
        throw new XNIException(ex);
      }
    }

    // unable to resolve external subset
    return null;
  } // getExternalSubset(XMLDTDDescription):XMLInputSource
Example #15
0
 protected final void addStart(final String name, final Attributes attrs) {
   try {
     h.startElement("", name, name, attrs);
   } catch (SAXException ex) {
     throw new RuntimeException(ex.getMessage(), ex.getException());
   }
 }
Example #16
0
  public static void run() {
    try {
      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new File(TICKET_XML));

      // normalize text representation
      doc.getDocumentElement().normalize();
      System.out.println(
          "Root element of the doc is:  " + doc.getDocumentElement().getNodeName() + "");
      NodeList serviceNode = doc.getElementsByTagName("service");
      System.out.println("---service---");
      for (int s = 0; s < serviceNode.getLength(); s++) {
        Node firstServiceNode = serviceNode.item(s);
        if (firstServiceNode.getNodeType() == Node.ELEMENT_NODE) {
          Element serviceElement = (Element) firstServiceNode;
          String serviceID = serviceElement.getAttribute("ID");
          System.out.println(serviceID);
          String serviceName = serviceElement.getAttribute("name");
          System.out.println(serviceName);
          String serviceScheduleType = serviceElement.getAttribute("scheduleType");
          System.out.println(serviceScheduleType);
          String serviceAuthenticationType = serviceElement.getAttribute("authenticationType");
          System.out.println(serviceAuthenticationType);
          String serviceDeviceEndpoint = serviceElement.getAttribute("deviceEndpoint");
          System.out.println(serviceDeviceEndpoint);
          String serviceBusInterfaceEndpoint = serviceElement.getAttribute("businterfaceEndpoint");
          System.out.println(serviceBusInterfaceEndpoint);
        }
      }

      NodeList savoirNode = doc.getElementsByTagName("SAVOIR");
      System.out.println("------SAVOIR------");
      for (int s = 0; s < savoirNode.getLength(); s++) {
        Node firstSavoirNode = savoirNode.item(s);
        if (firstSavoirNode.getNodeType() == Node.ELEMENT_NODE) {
          Element savoirElement = (Element) firstSavoirNode;
          String protocol = savoirElement.getAttribute("protocol");
          String ipAddress = savoirElement.getAttribute("ipAddress");
          String portNumber = savoirElement.getAttribute("portNumber");
          System.out.println(protocol + "://" + ipAddress + ":" + portNumber);
          String savoirTopic = savoirElement.getAttribute("SAVOIRTopic");
          System.out.println(savoirTopic);
          String serviceTopic = savoirElement.getAttribute("serviceTopic");
          System.out.println(serviceTopic);
        }
      }
    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());
    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();
    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.exit(0);
  }
  /**
   * Parse an XML Catalog stream.
   *
   * @param catalog The catalog to which this catalog file belongs
   * @param is The input stream from which the catalog will be read
   * @throws MalformedURLException Improper fileUrl
   * @throws IOException Error reading catalog file
   * @throws CatalogException A Catalog exception
   */
  public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException {

    // Create an instance of the parser
    if (parserFactory == null && parserClass == null) {
      debug.message(1, "Cannot read SAX catalog without a parser");
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    debug = catalog.getCatalogManager().debug;
    EntityResolver bResolver = catalog.getCatalogManager().getBootstrapResolver();

    this.catalog = catalog;

    try {
      if (parserFactory != null) {
        SAXParser parser = parserFactory.newSAXParser();
        SAXParserHandler spHandler = new SAXParserHandler();
        spHandler.setContentHandler(this);
        if (bResolver != null) {
          spHandler.setEntityResolver(bResolver);
        }
        parser.parse(new InputSource(is), spHandler);
      } else {
        Parser parser =
            (Parser)
                Class.forName(
                        parserClass,
                        true,
                        loader != null ? loader : this.getClass().getClassLoader())
                    .newInstance();
        parser.setDocumentHandler(this);
        if (bResolver != null) {
          parser.setEntityResolver(bResolver);
        }
        parser.parse(new InputSource(is));
      }
    } catch (ClassNotFoundException cnfe) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (IllegalAccessException iae) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (InstantiationException ie) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (ParserConfigurationException pce) {
      throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
    } catch (SAXException se) {
      Exception e = se.getException();
      // FIXME: there must be a better way
      UnknownHostException uhe = new UnknownHostException();
      FileNotFoundException fnfe = new FileNotFoundException();
      if (e != null) {
        if (e.getClass() == uhe.getClass()) {
          throw new CatalogException(CatalogException.PARSE_FAILED, e.toString());
        } else if (e.getClass() == fnfe.getClass()) {
          throw new CatalogException(CatalogException.PARSE_FAILED, e.toString());
        }
      }
      throw new CatalogException(se);
    }
  }
  public ParserContext(XSOMParser owner, XMLParser parser) {
    this.owner = owner;
    this.parser = parser;

    try {
      parse(new InputSource(ParserContext.class.getResource("datatypes.xsd").toExternalForm()));

      SchemaImpl xs = (SchemaImpl) schemaSet.getSchema("http://www.w3.org/2001/XMLSchema");
      xs.addSimpleType(schemaSet.anySimpleType, true);
      xs.addComplexType(schemaSet.anyType, true);
    } catch (SAXException e) {
      // this must be a bug of XSOM
      if (e.getException() != null) e.getException().printStackTrace();
      else e.printStackTrace();
      throw new InternalError();
    }
  }
Example #19
0
 private static SAXException toSAXException(UserException e)
     throws IOException, IncorrectSchemaException {
   SAXException se = e.getException();
   Exception cause = se.getException();
   if (cause instanceof IncorrectSchemaException) throw (IncorrectSchemaException) cause;
   if (cause instanceof IOException) throw (IOException) cause;
   return se;
 }
Example #20
0
  public void getClassName() {

    try {
      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new File("src/resources/classdata.xml"));

      doc.getDocumentElement().normalize();

      NodeList listOfClasses = doc.getElementsByTagName("class");

      classes = new String[listOfClasses.getLength()];
      amountClasses = listOfClasses.getLength();
      String classID;
      String className;
      int classIDint;

      for (int s = 0; s < listOfClasses.getLength(); s++) {

        Node firstPersonNode = listOfClasses.item(s);
        if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {

          Element firstClassElement = (Element) firstPersonNode;
          NodeList idList = firstClassElement.getElementsByTagName("id");
          Element idElement = (Element) idList.item(0);
          NodeList textLNList = idElement.getChildNodes();
          classID = ((Node) textLNList.item(0)).getNodeValue().trim();

          NodeList NameList = firstClassElement.getElementsByTagName("name");
          Element NameElement = (Element) NameList.item(0);
          NodeList textFNList = NameElement.getChildNodes();
          className = ((Node) textFNList.item(0)).getNodeValue().trim();
          classIDint = Integer.parseInt(classID);

          classes[classIDint] = className;
        } // end of if clause
      } // end of for loop with s var

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    // System.exit (0);

  }
 /** Handle a SAXException thrown by the ContentHandler */
 public void handleSAXException(SAXException err) throws XPathException {
   Exception nested = err.getException();
   if (nested instanceof XPathException) {
     throw (XPathException) nested;
   } else if (nested instanceof SchemaException) {
     throw new DynamicError(nested);
   } else {
     DynamicError de = new DynamicError(err);
     de.setErrorCode(SaxonErrorCode.SXCH0003);
     throw de;
   }
 }
Example #22
0
  /**
   * Encodes an object.
   *
   * <p>An object is encoded as an object, name pair, where the name is the name of an element
   * declaration in a schema.
   *
   * @param object The object being encoded.
   * @param name The name of the element being encoded in the schema.
   * @param out The output stream.
   * @throws IOException
   */
  public void encode(Object object, QName name, OutputStream out) throws IOException {
    if (inline) {
      String msg = "Must use 'encode(Object,QName,ContentHandler)' when inline flag is set";
      throw new IllegalStateException(msg);
    }

    // create the document seriaizer
    XMLSerializer xmls = new XMLSerializer(out, outputFormat);

    xmls.setNamespaces(namespaceAware);
    try {
      encode(object, name, xmls);
    } catch (SAXException e) {
      // SAXException does not sets initCause(). Instead, it holds its own
      // "exception" field.
      if (e.getException() != null && e.getCause() == null) {
        e.initCause(e.getException());
      }
      throw (IOException) new IOException().initCause(e);
    }
  }
Example #23
0
     /**
     * Creates Java Source code (Object model) for the given XML Schema
     * @param InputSource - the InputSource representing the XML schema.
     * @param packageName the package for the generated source files
    **/
    public void generateSource(InputSource source, String packageName) {

        //-- get default parser from Configuration
        Parser parser = null;
        try {
	    parser = Configuration.getParser();
        }
        catch(RuntimeException rte) {}
        if (parser == null) {
            System.out.println("fatal error: unable to create SAX parser.");
            return;
        }

        SchemaUnmarshaller schemaUnmarshaller = null;
        try {
           schemaUnmarshaller = new SchemaUnmarshaller();
        } catch (SAXException e) {
          // can never happen since a SAXException is thrown
          // when we are dealing with an included schema
          e.printStackTrace();
        }

        parser.setDocumentHandler(schemaUnmarshaller);
        parser.setErrorHandler(schemaUnmarshaller);

        try {
            parser.parse(source);
        }
        catch(java.io.IOException ioe) {
            System.out.println("error reading XML Schema file");
            return;
        }
        catch(org.xml.sax.SAXException sx) {

            Exception except = sx.getException();
            if (except == null) except = sx;

            if (except instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException)except;
                System.out.println("SAXParseException: " + spe);
                System.out.print(" - occured at line ");
                System.out.print(spe.getLineNumber());
                System.out.print(", column ");
                System.out.println(spe.getColumnNumber());
            }
            else except.printStackTrace();
            return;
        }

        Schema schema = schemaUnmarshaller.getSchema();
        generateSource(schema, packageName);

    } //-- generateSource
  /**
   * Creates and populates a default site from stream. The parser assumes the stream contains a
   * default site manifest (site.xml) as documented by the platform.
   *
   * @param stream site stream
   * @return populated site model
   * @exception CoreException
   * @exception InvalidSiteTypeException
   * @since 2.0
   */
  public SiteModel parseSite(InputStream stream) throws CoreException, InvalidSiteTypeException {
    SiteModel result = null;
    try {
      parser.init(this);
      result = parser.parse(stream);
      if (parser.getStatus() != null) {
        // some internalError were detected
        IStatus status = parser.getStatus();
        throw new CoreException(status);
      }
    } catch (SAXException e) {
      // invalid Site type
      if (e.getException() instanceof InvalidSiteTypeException) {
        throw (InvalidSiteTypeException) e.getException();
      }

      throw Utilities.newCoreException(Messages.SiteModelObject_ErrorParsingSiteStream, e);
    } catch (IOException e) {
      throw Utilities.newCoreException(Messages.SiteModelObject_ErrorAccessingSiteStream, e);
    }
    return result;
  }
Example #25
0
  public static ArrayList<String> getFilterNames() {

    ArrayList<String> filters = new ArrayList<String>();

    try {

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new File("filters.xml"));

      // normalize text representation
      doc.getDocumentElement().normalize();
      NodeList listOfPersons = doc.getElementsByTagName("filter");
      int totalPersons = listOfPersons.getLength();
      System.out.println("Total of filters : " + totalPersons);

      for (int s = 0; s < listOfPersons.getLength(); s++) {

        Node firstPersonNode = listOfPersons.item(s);
        if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {

          Element firstPersonElement = (Element) firstPersonNode;

          // -------
          NodeList firstNameList = firstPersonElement.getElementsByTagName("name");
          Element firstNameElement = (Element) firstNameList.item(0);

          NodeList textFNList = firstNameElement.getChildNodes();

          System.out.println("Filter Name : " + ((Node) textFNList.item(0)).getNodeValue().trim());

          filters.add(((Node) textFNList.item(0)).getNodeValue().trim());
        } // end of if clause
      } // end of for loop with s var

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }
    // System.exit (0);

    return filters;
  } // end of main
 /** Constructor. */
 protected XMLContentHandler(String eventFile, String agentFile) {
   myEngine = EventEngine.theStack;
   agentTable = new Hashtable();
   try {
     XMLReader saxParser =
         (XMLReader) Class.forName("org.apache.xerces.parsers.SAXParser").newInstance();
     saxParser.setContentHandler(this);
     saxParser.setFeature("http://xml.org/sax/features/validation", true);
     // parse the xml specification for the event tags.
     saxParser.parse(agentFile);
     saxParser.parse(eventFile);
   } catch (SAXParseException spe) {
     // Error generated by the parser
     System.out.println(
         "\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId());
     System.out.println("   " + spe.getMessage());
     // Use the contained exception, if any
     Exception x = spe;
     if (spe.getException() != null) x = spe.getException();
     x.printStackTrace();
     System.exit(0);
   } catch (SAXException sxe) {
     // Error generated by this application
     // (or a parser-initialization error)
     Exception x = sxe;
     if (sxe.getException() != null) x = sxe.getException();
     x.printStackTrace();
     System.exit(0);
   } catch (IOException ioe) {
     // I/O error
     ioe.printStackTrace();
     System.exit(0);
   } catch (Exception pce) {
     // Parser with specified options can't be built
     pce.printStackTrace();
     System.exit(0);
   }
 }
  @Test
  public void deploymentDescriptorParse() throws Exception {
    URL descriptorLocation = getClass().getResource("wrong_namespace.xml");

    boolean gotException = false;

    try {
      GCMDeploymentParserImpl parser = new GCMDeploymentParserImpl(descriptorLocation, null);
    } catch (SAXException e) {
      gotException = e.getException().getMessage().contains("old format");
    }

    Assert.assertTrue(gotException);
  }
  public static void main(String[] args) throws IOException {
    String filename = "z.xml"; // NOT LOCALIZABLE, main

    try {
      String uri = "file:" + new File(filename).getAbsolutePath(); // NOT LOCALIZABLE, main

      //
      // turn it into an in-memory object.
      //
      Parser parser = getParser();
      parser.setDocumentHandler(new XmlParser());
      parser.setErrorHandler(new MyErrorHandler());
      parser.parse(uri);

    } catch (SAXParseException err) {
      Debug.trace(
          "** Parsing error" // NOT LOCALIZABLE, main
              + ", line "
              + err.getLineNumber() // NOT LOCALIZABLE
              + ", uri "
              + err.getSystemId()); // NOT LOCALIZABLE
      Debug.trace("   " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e;
      if (e.getException() != null) x = e.getException();
      x.printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    byte[] buf = new byte[256];
    Debug.trace("Press ENTER to exit."); // NOT LOCALIZABLE
    System.in.read(buf, 0, 256);
    System.exit(0);
  }
Example #29
0
  public void produce() throws DataSetException {
    logger.debug("produce() - start");

    try {
      SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
      XMLReader xmlReader = saxParser.getXMLReader();

      setDeclHandler(xmlReader, this);
      setLexicalHandler(xmlReader, this);
      xmlReader.setEntityResolver(this);
      xmlReader.parse(new InputSource(new StringReader(XML_CONTENT)));
    } catch (ParserConfigurationException e) {
      throw new DataSetException(e);
    } catch (SAXException e) {
      Exception exception = e.getException() == null ? e : e.getException();
      if (exception instanceof DataSetException) {
        throw (DataSetException) exception;
      } else {
        throw new DataSetException(exception);
      }
    } catch (IOException e) {
      throw new DataSetException(e);
    }
  }
Example #30
0
  public String[] getHelp(String opcodeName) {
    String help[] = new String[3];
    try {
      java.io.InputStream is = getClass().getResourceAsStream("/sim/help.xml");
      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(is);

      // normalize text representation
      doc.getDocumentElement().normalize();

      NodeList instrList = doc.getElementsByTagName("instruction");
      for (int i = 0; i < instrList.getLength(); i++) {
        Node instrNode = instrList.item(i);
        Element instrElement = (Element) instrNode;

        NodeList opcodeList = instrElement.getElementsByTagName("opcode");
        Node opcodeNode = opcodeList.item(0);
        if (opcodeNode.getTextContent().trim().equals(opcodeName)) {
          NodeList operandList = instrElement.getElementsByTagName("operand");
          Node operandNode = operandList.item(0);
          help[0] = operandNode.getTextContent().trim();

          NodeList shortList = instrElement.getElementsByTagName("short");
          Node shortNode = shortList.item(0);
          help[1] = shortNode.getTextContent().trim();

          NodeList longList = instrElement.getElementsByTagName("long");
          Node longNode = longList.item(0);
          help[2] = longNode.getTextContent().trim();
          return help;
        }
      }

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }
    return null;
  }