Exemple #1
0
  /**
   * Exports a <code>Transaction</code> instance to it's XML representation.
   *
   * @param transaction transaction to export
   * @return XML representation of transaction
   * @throws IOException
   * @throws XMLParsingException
   */
  public static XMLFragment export(Transaction transaction)
      throws IOException, XMLParsingException {

    XMLFragment xml = new XMLFragment();
    try {
      xml.load(TransactionResponse.class.getResource("TransactionTemplate.xml"));
    } catch (SAXException e) {
      throw new IOException("Internal error: Could not parse TransactionResponseTemplate.xml.");
    }
    Element root = xml.getRootElement();
    List ops = transaction.getOperations();
    for (int i = 0; i < ops.size(); i++) {
      try {
        if (ops.get(i) instanceof Insert) {
          appendInsert(root, (Insert) ops.get(i));
        } else if (ops.get(i) instanceof Update) {
          appendUpdate(root, (Update) ops.get(i));
        } else if (ops.get(i) instanceof Delete) {
          appendDelete(root, (Delete) ops.get(i));
        }
      } catch (XMLException e) {
        LOG.logError(e.getMessage(), e);
        throw new XMLParsingException(e.getMessage());
      } catch (FeatureException e) {
        LOG.logError(e.getMessage(), e);
        throw new XMLParsingException(e.getMessage());
      } catch (SAXException e) {
        LOG.logError(e.getMessage(), e);
        throw new XMLParsingException(e.getMessage());
      }
    }
    return xml;
  }
  /** Thread run method */
  public void run() {
    if (NiagraServer.RUNNING_NIPROF) JProf.registerThreadName(this.getName());

    if (NiagraServer.TIME_OPERATORS) {
      cpuTimer = new CPUTimer();
      cpuTimer.start();
    }

    boolean shutdown = false;
    String message = "normal";

    try {
      sr = new SAXDOMReader(dm.getInputStreamFor(resource));
      sr.readDocuments(outputStream);
    } catch (SAXException saxE) {
      System.err.println(
          "StreamThread::SAX exception parsing document. Message: " + saxE.getMessage());
      shutdown = true;
      message = "SAX Exception " + saxE.getMessage();
    } catch (java.io.IOException ioe) {
      System.err.println("StreamThread::IOException. Message: " + ioe.getMessage());
      shutdown = true;
      message = "StreamThread::IOException " + ioe.getMessage();
    } catch (ShutdownException se) {
      System.err.println("StreamThread::ShutdownException. Message " + se.getMessage());
      shutdown = true;
      message = se.getMessage();
    }

    cleanUp(shutdown, message);
    return;
  }
  protected void configureWebXml() throws InstallException {
    // --------------------------------------------------------------------
    // Configure web.xml
    // --------------------------------------------------------------------

    FileObject webXml = null;

    try {
      webXml = targetDir.resolveFile("WEB-INF/web.xml");

      // Get a DOM document of the web.xml :
      Node webXmlNode = loadAsDom(webXml);

      boolean modified = false;

      // Perform specific configurations
      if (configureFilters(webXmlNode)) modified = true;

      if (modified) {

        // Backup Container configuration.  If we cannot perform a backup, do nothing
        if (!backupFile(webXml, targetDir)) {
          getPrinter()
              .printActionWarnStatus(
                  "Configure",
                  targetDir.getName().getFriendlyURI() + "/WEB-INF/web.xml",
                  "Must be done manually (Follow setup guide)");
          return;
        }

        // Write modifications to file
        writeContentFromDom(webXmlNode, webXml);
        getPrinter()
            .printActionOkStatus(
                "Save", webXml.getName().getBaseName(), webXml.getName().getFriendlyURI());
      }

    } catch (IOException e) {
      log.error(e.getMessage(), e);
      getPrinter().printErrStatus("Cannot configure container : ", e.getMessage());
    } catch (SAXException e) {
      log.error(e.getMessage(), e);
      getPrinter().printErrStatus("Cannot configure container : ", e.getMessage());
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      getPrinter().printErrStatus("Cannot configure container : ", e.getMessage());
      getPrinter()
          .printActionWarnStatus(
              "Configure",
              targetDir.getName().getFriendlyURI() + "/WEB-INF/web.xml",
              "Must be done manually (Follow setup guide)");
    }
  }
  /** @tests javax.xml.parsers.DocumentBuilderFactory#setIgnoringComments(boolean). */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "setIgnoringComments",
      args = {boolean.class})
  public void test_setIgnoringCommentsZ() {
    commentElements.clear();

    dbf.setIgnoringComments(true);
    assertTrue(dbf.isIgnoringComments());

    try {
      DocumentBuilder parser = dbf.newDocumentBuilder();

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      goThroughDocument((Node) document, "");
      assertFalse(commentElements.contains("comment1"));
      assertFalse(commentElements.contains("comment2"));

    } catch (IOException e) {
      fail("Unexpected IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
      fail("Unexpected ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
      fail("Unexpected SAXException " + e.getMessage());
    }

    commentElements.clear();

    dbf.setIgnoringComments(false);
    assertFalse(dbf.isIgnoringComments());

    try {
      DocumentBuilder parser = dbf.newDocumentBuilder();

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      goThroughDocument((Node) document, "");
      assertTrue(commentElements.contains("comment1"));
      assertTrue(commentElements.contains("comment2"));

    } catch (IOException e) {
      fail("Unexpected IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
      fail("Unexpected ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
      fail("Unexpected SAXException " + e.getMessage());
    }
  }
  /** Shows statistics of device if they are supported by the device */
  @Override
  @FXML
  public void handleStatistics(ActionEvent e) {
    String[] stats = new String[] {"", "U_", "M_"};
    try {
      ((RemoteOrderDisplay) service).retrieveStatistics(stats);
      DOMParser parser = new DOMParser();
      parser.parse(new InputSource(new java.io.StringReader(stats[1])));

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new ByteArrayInputStream(stats[1].getBytes()));

      printStatistics(doc.getDocumentElement(), "");

      JOptionPane.showMessageDialog(
          null, statistics, "Statistics", JOptionPane.INFORMATION_MESSAGE);
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(null, ioe.getMessage());
      ioe.printStackTrace();
    } catch (SAXException saxe) {
      JOptionPane.showMessageDialog(null, saxe.getMessage());
      saxe.printStackTrace();
    } catch (ParserConfigurationException e1) {
      JOptionPane.showMessageDialog(null, e1.getMessage());
      e1.printStackTrace();
    } catch (JposException jpe) {
      jpe.printStackTrace();
      JOptionPane.showMessageDialog(
          null, "Statistics are not supported!", "Statistics", JOptionPane.ERROR_MESSAGE);
    }

    statistics = "";
  }
Exemple #6
0
  private ClasificacionOrganizacion findRestClasificacionOrganizacion(Integer id) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getClassOrganizacionUrl());
    get.addRequestHeader("Accept", "application/xml");
    ClasificacionOrganizacion ret = null;
    try {
      int result = httpclient.executeMethod(get);
      logger.info("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      logger.info("Response body: " + xmlString);

      ret = importClasificacionOrganizacion(xmlString, id);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
Exemple #7
0
  private Capacidad buscarCapacidad(int capacityCode) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getCapacidadUrl());
    get.addRequestHeader("Accept", "application/xml");
    Capacidad ret = null;
    try {
      int result = httpclient.executeMethod(get);
      if (logger.isTraceEnabled()) logger.trace("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      if (logger.isTraceEnabled()) logger.trace("Response body: " + xmlString);

      ret = importCapacidad(xmlString, capacityCode);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
  public void getEntryById(DBBroker broker, String path, String id, OutgoingMessage response)
      throws EXistException, BadRequestException {
    XQuery xquery = broker.getXQueryService();
    CompiledXQuery feedQuery = xquery.getXQueryPool().borrowCompiledXQuery(broker, entryByIdSource);

    XQueryContext context;
    if (feedQuery == null) {
      context = xquery.newContext(AccessContext.REST);
      try {
        feedQuery = xquery.compile(context, entryByIdSource);
      } catch (XPathException ex) {
        throw new EXistException("Cannot compile xquery " + entryByIdSource.getURL(), ex);
      } catch (IOException ex) {
        throw new EXistException(
            "I/O exception while compiling xquery " + entryByIdSource.getURL(), ex);
      }
    } else {
      context = feedQuery.getContext();
    }
    context.setStaticallyKnownDocuments(
        new XmldbURI[] {XmldbURI.create(path).append(AtomProtocol.FEED_DOCUMENT_NAME)});

    try {
      context.declareVariable("id", id);
      Sequence resultSequence = xquery.execute(feedQuery, null);
      if (resultSequence.isEmpty()) {
        throw new BadRequestException("No topic was found.");
      }
      String charset = getContext().getDefaultCharset();
      response.setContentType("application/atom+xml; charset=" + charset);
      Serializer serializer = broker.getSerializer();
      serializer.reset();
      try {
        Writer w = new OutputStreamWriter(response.getOutputStream(), charset);
        SAXSerializer sax =
            (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
        Properties outputProperties = new Properties();
        sax.setOutput(w, outputProperties);
        serializer.setProperties(outputProperties);
        serializer.setSAXHandlers(sax, sax);

        serializer.toSAX(resultSequence, 1, 1, false);

        SerializerPool.getInstance().returnObject(sax);
        w.flush();
        w.close();
      } catch (IOException ex) {
        LOG.fatal("Cannot read resource " + path, ex);
        throw new EXistException("I/O error on read of resource " + path, ex);
      } catch (SAXException saxe) {
        LOG.warn(saxe);
        throw new BadRequestException("Error while serializing XML: " + saxe.getMessage());
      }
      resultSequence.itemAt(0);
    } catch (XPathException ex) {
      throw new EXistException("Cannot execute xquery " + entryByIdSource.getURL(), ex);
    } finally {
      xquery.getXQueryPool().returnCompiledXQuery(entryByIdSource, feedQuery);
    }
  }
 public boolean isNamespaceAware() {
   try {
     return xmlReader.getFeature(NAMESPACES_FEATURE);
   } catch (SAXException x) {
     throw new IllegalStateException(x.getMessage());
   }
 }
  /**
   * Run validation on the pass in xml using this schema
   *
   * @param xml String with a (hopefully) well formed and schema compliant xml document
   * @return
   * @throws SAXException
   * @throws IOException
   */
  public Boolean validate(String xml) throws SAXException, IOException {
    // messages will contain this message if the schema is in a not yet supported format
    messages = "Not yet implemented";
    if (this.type == types.RELAXNG_COMPACT)
      System.setProperty(
          "javax.xml.validation.SchemaFactory:" + XMLConstants.RELAXNG_NS_URI,
          "com.thaiopensource.relaxng.jaxp.CompactSyntaxSchemaFactory");
    else
      System.setProperty(
          "javax.xml.validation.SchemaFactory:" + XMLConstants.RELAXNG_NS_URI,
          "com.thaiopensource.relaxng.jaxp.XMLSyntaxSchemaFactory");
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.RELAXNG_NS_URI);
    // change to use the schema stored here
    Schema schemaObj = factory.newSchema(new URL(schemaURL));
    Validator validator = schemaObj.newValidator();
    Source source = new StreamSource(new StringReader(xml));
    try {
      validator.validate(source);
      return (true);
    } catch (SAXException ex) {

      messages = ex.getMessage();
      return false;
    }
  }
Exemple #11
0
 /**
  * Starts the reading of the CML file. Whenever a new Molecule is read, a event is thrown to the
  * ReaderListener.
  */
 public void process() throws CDKException {
   logger.debug("Started parsing from input...");
   try {
     parser.setFeature("http://xml.org/sax/features/validation", false);
     logger.info("Deactivated validation");
   } catch (SAXException e) {
     logger.warn("Cannot deactivate validation.");
   }
   parser.setContentHandler(new EventCMLHandler(this, builder));
   parser.setEntityResolver(new CMLResolver());
   parser.setErrorHandler(new CMLErrorHandler());
   try {
     logger.debug("Parsing from Reader");
     parser.parse(new InputSource(input));
   } catch (IOException e) {
     String error = "Error while reading file: " + e.getMessage();
     logger.error(error);
     logger.debug(e);
     throw new CDKException(error, e);
   } catch (SAXParseException saxe) {
     SAXParseException spe = (SAXParseException) saxe;
     String error = "Found well-formedness error in line " + spe.getLineNumber();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   } catch (SAXException saxe) {
     String error = "Error while parsing XML: " + saxe.getMessage();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   }
 }
  public Document getDomElement(String xml) {
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

      DocumentBuilder db = dbf.newDocumentBuilder();

      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(xml));
      doc = db.parse(is);

      if (D) Log.d(TAG, "File was parsed successfully.");

    } catch (ParserConfigurationException e) {
      Log.e("ParserConfigurationException Error: ", e.getMessage());
      return null;
    } catch (SAXException e) {
      Log.e("SAXException Error: ", e.getMessage());
      return null;
    } catch (IOException e) {
      Log.e("IOException Error: ", e.getMessage());
      return null;
    }
    // return DOM
    return doc;
  }
Exemple #13
0
  /** Parses the resulting document tree. */
  public Formalism parse(String uri) {

    try {
      //	    DOMParser parser = new DOMParser();
      //	    parser.parse(uri);
      //	    Document document = parser.getDocument();
      Document document = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder().parse(uri);
      System.out.println("Document well formed :" + uri);
      parseFormalism(document.getDocumentElement());
      System.out.println("Document validated :" + uri);
      return formalism;
    } catch (IOException e) {
      System.err.println("** Error : file cannot be read " + uri);
    } catch (SAXException e) {
      System.err.println("** Error : SAX error in " + uri);
      System.err.println(e.getMessage());
    } catch (ParserConfigurationException e) {
      System.err.println("** Error : ParserConfiguration error in " + uri);
      System.err.println(e.getMessage());
    } catch (ArithmeticException e) {
      System.err.println("** Error : formalism parsing error in " + uri);
      // e.printStackTrace(System.err);
    }
    return null;
  }
Exemple #14
0
 @SuppressWarnings("unchecked")
 public static <T> T unmarshal(final InputStream in) throws IOException {
   final Unmarshaller unmarshaller = SardineUtil.createUnmarshaller();
   try {
     final XMLReader reader = XMLReaderFactory.createXMLReader();
     try {
       reader.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature(
           "http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     return (T) unmarshaller.unmarshal(new SAXSource(reader, new InputSource(in)));
   } catch (final SAXException e) {
     throw new RuntimeException(e.getMessage(), e);
   } catch (final JAXBException e) {
     // Server does not return any valid WebDAV XML that matches our JAXB context
     final IOException failure = new IOException("Not a valid DAV response");
     // Backward compatibility
     failure.initCause(e);
     throw failure;
   }
 }
 private static Element getDocumentElement(final String filename, final boolean usingBackupFile)
     throws XmlException, IOException {
   DocumentBuilderFactory factory;
   DocumentBuilder builder;
   Document doc;
   FileInputStream is = null;
   try {
     is = new FileInputStream(new File(filename));
     factory = DocumentBuilderFactory.newInstance();
     builder = factory.newDocumentBuilder();
     doc = builder.parse(is);
     return doc.getDocumentElement();
   } catch (SAXException ex) {
     if (is != null) { // Close file - so we can delete it...
       is.close();
     }
     if (!usingBackupFile && restoreBackupFile(filename)) {
       return getDocumentElement(filename, true);
     }
     throw new XmlException(ex.getMessage(), ex);
   } catch (ParserConfigurationException ex) {
     throw new XmlException(ex.getMessage(), ex);
   } finally {
     if (is != null) {
       is.close();
     }
   }
 }
 /**
  * @throws OGCWebServiceException
  * @see org.deegree.ogcwebservices.wpvs.configuration.AbstractDataSource#getOGCWebService()
  */
 @Override
 public OGCWebService getOGCWebService() throws OGCWebServiceException {
   WMSConfigurationType wmsConfig = null;
   synchronized (this) {
     URL url = getOwsCapabilities().getOnlineResource();
     wmsConfig = cache.get(url);
     if (!cache.containsKey(url) || wmsConfig == null) {
       WMSConfigurationDocument wmsDoc = new WMSConfigurationDocument();
       try {
         wmsDoc.load(getOwsCapabilities().getOnlineResource());
         wmsConfig = wmsDoc.parseConfiguration();
         cache.put(url, wmsConfig);
       } catch (IOException e) {
         throw new OGCWebServiceException(
             Messages.getMessage("WPVS_DATASOURCE_CAP_ERROR", toString()) + e.getMessage());
       } catch (SAXException e) {
         throw new OGCWebServiceException(
             Messages.getMessage("WPVS_DATASOURCE_CAP_ERROR", toString()) + e.getMessage());
       } catch (InvalidConfigurationException e) {
         throw new OGCWebServiceException(
             Messages.getMessage("WPVS_DATASOURCE_CAP_ERROR", toString()) + e.getMessage());
       }
     }
   }
   return WMServiceFactory.getWMSInstance(wmsConfig);
 }
Exemple #17
0
 public void parserXml(String fileName) {
   try {
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document document = db.parse(fileName);
     NodeList employees = document.getChildNodes();
     for (int i = 0; i < employees.getLength(); i++) {
       Node employee = employees.item(i);
       NodeList employeeInfo = employee.getChildNodes();
       for (int j = 0; j < employeeInfo.getLength(); j++) {
         Node node = employeeInfo.item(j);
         NodeList employeeMeta = node.getChildNodes();
         for (int k = 0; k < employeeMeta.getLength(); k++) {
           System.out.println(
               employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent());
         }
       }
     }
     System.out.println("解析完毕");
   } catch (FileNotFoundException e) {
     System.out.println(e.getMessage());
   } catch (ParserConfigurationException e) {
     System.out.println(e.getMessage());
   } catch (SAXException e) {
     System.out.println(e.getMessage());
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
  private SAXReader installModifyReader() throws DocumentException {
    try {
      SAXModifyReader reader = getSAXModifyReader();

      if (isPruneElements()) {
        modifyReader.setDispatchHandler(new PruningDispatchHandler());
      }

      reader.resetHandlers();

      Iterator modifierIt = this.modifiers.entrySet().iterator();

      while (modifierIt.hasNext()) {
        Map.Entry entry = (Map.Entry) modifierIt.next();

        SAXModifyElementHandler handler =
            new SAXModifyElementHandler((ElementModifier) entry.getValue());
        reader.addHandler((String) entry.getKey(), handler);
      }

      reader.setXMLWriter(getXMLWriter());
      reader.setXMLReader(getXMLReader());

      return reader;
    } catch (SAXException ex) {
      throw new DocumentException(ex.getMessage(), ex);
    }
  }
 public boolean isValidating() {
   try {
     return xmlReader.getFeature(VALIDATION_FEATURE);
   } catch (SAXException x) {
     throw new IllegalStateException(x.getMessage());
   }
 }
Exemple #20
0
 /**
  * Reads a property list from an input stream.
  *
  * @param in the input stream.
  * @exception IOException if an error occurred when reading from the input stream.
  * @since JDK1.0
  */
 public synchronized void load(InputStream in) throws IOException {
   try {
     p = new XMLParser(in, this);
   } catch (SAXException e) {
     throw new IOException(e.getMessage());
   }
 }
  // Suppressing the warning as the new exception is using the jaxbe error code and message to pass
  // on to the ResourceContextExcepiton
  @SuppressWarnings("PMD.PreserveStackTrace")
  @Override
  public Object perform(UnmarshallerValidator resource) {
    try {

      return resource.validateUnmarshal(cfgResource.newInputStream());
    } catch (JAXBException jaxbe) {
      throw new ResourceContextException(
          "Failed to unmarshall resource "
              + cfgResource.name()
              + " - "
              + jaxbe.getCause()
              + " - Error code: "
              + jaxbe.getErrorCode()
              + " - Reason: "
              + jaxbe.getMessage(),
          jaxbe.getLinkedException());
    } catch (IOException ioe) {
      throw new ResourceContextException(
          "An I/O error has occured while trying to read resource "
              + cfgResource.name()
              + " - Reason: "
              + ioe.getMessage(),
          ioe);
    } catch (SAXException se) {

      throw new ResourceContextException(
          "Validation error on resource " + cfgResource.name() + " - " + se.getMessage(), se);
    } catch (Exception ex) {
      throw new ResourceContextException(
          "Failed to unmarshall resource " + cfgResource.name() + " - Reason: " + ex.getMessage(),
          ex);
    }
  }
Exemple #22
0
 protected void addDocumentEnd() {
   try {
     h.endDocument();
   } catch (SAXException ex) {
     throw new RuntimeException(ex.getMessage(), ex.getException());
   }
 }
Exemple #23
0
  private String getXmlToken() {
    String token = null;
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getTokenUrl());
    get.addRequestHeader("Accept", "application/xml");

    NameValuePair userParam = new NameValuePair(USERNAME_PARAM, satelite.getUser());
    NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, satelite.getPassword());
    NameValuePair[] params = new NameValuePair[] {userParam, passwordParam};

    get.setQueryString(params);
    try {
      int statusCode = httpclient.executeMethod(get);
      if (statusCode != HttpStatus.SC_OK) {
        logger.error("Method failed: " + get.getStatusLine());
      }
      token = parseToken(get.getResponseBodyAsString());
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }

    return token;
  }
Exemple #24
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());
   }
 }
Exemple #25
0
  private Sector buscarSector(int sectorCode) {
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getSectorUrl());
    get.addRequestHeader("Accept", "application/xml");
    Sector ret = null;
    try {
      int result = httpclient.executeMethod(get);
      logger.info("Response status code: " + result);
      String xmlString = get.getResponseBodyAsString();
      logger.info("Response body: " + xmlString);

      ret = importSector(xmlString, sectorCode);
    } catch (HttpException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
      logger.error(e.getMessage());
    } catch (SAXException e) {
      logger.error(e.getMessage());
    } finally {
      get.releaseConnection();
    }
    return ret;
  }
Exemple #26
0
 protected final void addEnd(final String name) {
   try {
     h.endElement("", name, name);
   } catch (SAXException ex) {
     throw new RuntimeException(ex.getMessage(), ex.getException());
   }
 }
Exemple #27
0
  /**
   * Reads the specified .machines file to get host names
   *
   * @param fileName
   * @throws IOException
   */
  private static void readEmulators(String fileName) throws IOException {
    try {
      FileInputStream is = new FileInputStream(fileName);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder parser = factory.newDocumentBuilder();

      Document d = parser.parse(is);

      Element e = d.getDocumentElement();

      NodeList n = e.getElementsByTagName("emul");

      // For every class
      String hostName = null;
      for (int i = 0; i < n.getLength(); i++) {
        Element x = (Element) n.item(i);

        hostName = x.getAttribute("hostname");
        emulators.add(hostName);
      }

      is.close();

    } catch (ParserConfigurationException pce) {
      log.error(pce.getMessage());

    } catch (SAXException se) {
      log.error(se.getMessage());
    }
  }
  public static final Document XMLfromString(String xml) {

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

      DocumentBuilder db = dbf.newDocumentBuilder();

      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(xml));
      doc = db.parse(is);

    } catch (ParserConfigurationException e) {
      System.out.println("XML parse error: " + e.getMessage());
      return null;
    } catch (SAXException e) {
      System.out.println("Wrong XML file structure: " + e.getMessage());
      return null;
    } catch (IOException e) {
      System.out.println("I/O exeption: " + e.getMessage());
      return null;
    }
    return doc;
  }
 Parser(String uri) {
   try {
     SAXParserFactory parserFactory = SAXParserFactory.newInstance();
     SAXParser parser = parserFactory.newSAXParser();
     ConfigHandler handler = new ConfigHandler();
     parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", true);
     parser.parse(new File(uri), handler);
   } catch (IOException e) {
     System.out.println("Error reading URI: " + e.getMessage());
   } catch (SAXException e) {
     System.out.println("Error in parsing: " + e.getMessage());
   } catch (ParserConfigurationException e) {
     System.out.println("Error in XML parser configuration: " + e.getMessage());
   }
   // System.out.println("Number of Persons : " + Person.numberOfPersons());
   // nameLengthStatistics();
   // System.out.println("Number of Publications with authors/editors: " +
   //                   Publication.getNumberOfPublications());
   // System.out.println("Maximum number of authors/editors in a publication: " +
   //                           Publication.getMaxNumberOfAuthors());
   // publicationCountStatistics();
   // Person.enterPublications();
   // Person.printCoauthorTable();
   // Person.printNamePartTable();
   // Person.findSimilarNames();
 }
  public int validate(String uri) {
    int status;
    try {
      String filename;

      if (uri.contains("://")) {
        // file is a URL - download to temporary file...
        FileDownloader fileDownloader = new FileDownloader();
        filename = fileDownloader.downloadFile(uri);
      } else {
        logger.debug("processing local file...");
        filename = uri;
      }
      status = process(filename);
    } catch (ParserConfigurationException ex) {
      status = App.STATUS_EXCEPTION;
      exceptionMessage = "Parser Configuration error: " + ex.getMessage();
      logger.error(exceptionMessage);
    } catch (SAXException ex) {
      status = App.STATUS_EXCEPTION;
      exceptionMessage = "SAX error: " + ex.getMessage();
      logger.error(exceptionMessage);
    } catch (IOException ex) {
      status = App.STATUS_EXCEPTION;
      exceptionMessage = "IO error: " + ex.getMessage();
      logger.error(exceptionMessage);
    }
    return status;
  }