コード例 #1
1
 public void read(JarPackageData jarPackage) throws CoreException {
   try {
     readXML(jarPackage);
   } catch (IOException ex) {
     String message =
         (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             JavaPlugin.getPluginId(),
             IJavaStatusConstants.INTERNAL_ERROR,
             message,
             ex));
   } catch (SAXException ex) {
     String message =
         (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             JavaPlugin.getPluginId(),
             IJavaStatusConstants.INTERNAL_ERROR,
             message,
             ex));
   }
 }
コード例 #2
0
ファイル: DomDemo.java プロジェクト: vtopqx/common
 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());
   }
 }
コード例 #3
0
 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();
 }
コード例 #4
0
  /**
   * Read parse trees from a Reader.
   *
   * @param filename
   * @param in The <code>Reader</code>
   * @param simplifiedTagset If `true`, convert part-of-speech labels to a simplified version of the
   *     EAGLES tagset, where the tags do not include extensive morphological analysis
   * @param aggressiveNormalization Perform aggressive "normalization" on the trees read from the
   *     provided corpus documents: split multi-word tokens into their constituent words (and infer
   *     parts of speech of the constituent words).
   * @param retainNER Retain NER information in preterminals (for later use in
   *     `MultiWordPreprocessor) and add NER-specific parents to single-word NE tokens
   * @param detailedAnnotations Retain detailed tree node annotations. These annotations on parse
   *     tree constituents may be useful for e.g. training a parser.
   */
  public SpanishXMLTreeReader(
      String filename,
      Reader in,
      boolean simplifiedTagset,
      boolean aggressiveNormalization,
      boolean retainNER,
      boolean detailedAnnotations) {
    TreebankLanguagePack tlp = new SpanishTreebankLanguagePack();

    this.simplifiedTagset = simplifiedTagset;
    this.detailedAnnotations = detailedAnnotations;

    stream = new ReaderInputStream(in, tlp.getEncoding());
    treeFactory = new LabeledScoredTreeFactory();
    treeNormalizer =
        new SpanishTreeNormalizer(simplifiedTagset, aggressiveNormalization, retainNER);

    DocumentBuilder parser = XMLUtils.getXmlParser();
    try {
      final Document xml = parser.parse(stream);
      final Element root = xml.getDocumentElement();
      sentences = root.getElementsByTagName(NODE_SENT);
      sentIdx = 0;

    } catch (SAXException e) {
      System.err.println("Parse exception while reading " + filename);
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
ファイル: XMLRecognizer.java プロジェクト: tm3553881/tesweb
  public static String RecogniseFromXml(byte[] bin) {

    String tranCode = "";
    String xmlStr = new String(bin);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Element theTranCode = null, root = null;
    try {
      factory.setIgnoringElementContentWhitespace(true);

      DocumentBuilder db = factory.newDocumentBuilder();

      final byte[] bytes = xmlStr.getBytes();
      final ByteArrayInputStream is = new ByteArrayInputStream(bytes);
      final InputSource source = new InputSource(is);

      Document xmldoc = db.parse(source);
      root = xmldoc.getDocumentElement();
      theTranCode = (Element) selectSingleNode("/root/head/transid", root);
      // Element nameNode = (Element) theTranCode.getElementsByTagName("price").item(0);
      if (theTranCode != null) {
        tranCode = theTranCode.getFirstChild().getNodeValue();
      } else {
        System.out.println("获取 /root/head/transid 失败!");
      }
      // System.out.println(tranCode);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return tranCode;
  }
コード例 #6
0
ファイル: DMOZParser.java プロジェクト: blouke/IRProject
 public static void main(String[] args) {
   String fileSeparator = System.getProperty("file.separator");
   try {
     FileInputStream fileInput =
         new FileInputStream(
             System.getProperty("user.dir")
                 + fileSeparator
                 + "resources"
                 + fileSeparator
                 + "content.rdf.u8");
     InputSource is;
     is = new InputSource(fileInput);
     SAXParserFactory spf = SAXParserFactory.newInstance();
     spf.setValidating(false);
     XMLReader r;
     r = spf.newSAXParser().getXMLReader();
     r.setContentHandler(new RDFHandler());
     r.parse(is);
   } catch (ParserConfigurationException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (SAXException e) {
     e.printStackTrace();
   }
 }
コード例 #7
0
  public void process(JCas aJCas) throws AnalysisEngineProcessException {
    if (!init) {
      try {
        initialize();
      } catch (ResourceInitializationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      init = true;
    }
    // retreive the filename of the input file from the CAS
    FSIterator it = aJCas.getAnnotationIndex(Product.type).iterator();
    File outFile = null;
    if (it.hasNext()) {
      Product fileLoc = (Product) it.next();
      outFile = new File(mOutputDir, fileLoc.getName() + ".xml");
    }
    if (outFile == null) {
      outFile = new File(mOutputDir, "doc" + mDocNum++ + ".xml");
    }
    // serialize XCAS and write to output file

    try {
      writeXCas(aJCas.getCas(), outFile);
    } catch (IOException e) {
      System.err.println("Could not write to output file");
      e.printStackTrace();
    } catch (SAXException e) {
      System.out.println("SAX Failure");
      e.printStackTrace();
    }
  }
コード例 #8
0
  /** 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 = "";
  }
コード例 #9
0
 private CloudServersException parseCloudServersException(HttpResponse response) {
   CloudServersException cse = new CloudServersException();
   try {
     BasicResponseHandler responseHandler = new BasicResponseHandler();
     String body = responseHandler.handleResponse(response);
     CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser();
     SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
     XMLReader xmlReader = saxParser.getXMLReader();
     xmlReader.setContentHandler(parser);
     xmlReader.parse(new InputSource(new StringReader(body)));
     cse = parser.getException();
   } catch (ClientProtocolException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (IOException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (ParserConfigurationException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (SAXException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (FactoryConfigurationError e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   }
   return cse;
 }
コード例 #10
0
ファイル: ValidatorImpl.java プロジェクト: karelyang/601_10.1
  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;
    }
  }
コード例 #11
0
ファイル: AtomFeeds.java プロジェクト: kingargyle/exist-1.4.x
  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);
    }
  }
コード例 #12
0
  public synchronized void unpack(ISOComponent c, InputStream in) throws ISOException, IOException {
    LogEvent evt = new LogEvent(this, "unpack");
    try {
      if (!(c instanceof ISOMsg)) throw new ISOException("Can't call packager on non Composite");

      while (!stk.empty())
        // purge from possible previous error
        stk.pop();

      reader.parse(new InputSource(in));
      if (stk.empty()) throw new ISOException("error parsing");

      ISOMsg m = (ISOMsg) c;
      m.merge((ISOMsg) stk.pop());

      if (logger != null) evt.addMessage(m);
    } catch (ISOException e) {
      evt.addMessage(e);
      throw e;
    } catch (SAXException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } finally {
      Logger.log(evt);
    }
  }
コード例 #13
0
  public synchronized int unpack(ISOComponent c, byte[] b) throws ISOException {
    LogEvent evt = new LogEvent(this, "unpack");
    try {
      if (!(c instanceof ISOMsg)) throw new ISOException("Can't call packager on non Composite");

      stk.clear();

      InputSource src = new InputSource(new ByteArrayInputStream(b));
      reader.parse(src);
      if (stk.empty()) throw new ISOException("error parsing");

      ISOMsg m = (ISOMsg) c;
      m.merge((ISOMsg) stk.pop());

      if (logger != null) evt.addMessage(m);
      return b.length;
    } catch (ISOException e) {
      evt.addMessage(e);
      throw e;
    } catch (IOException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } catch (SAXException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } finally {
      Logger.log(evt);
    }
  }
コード例 #14
0
 public boolean isValidating() {
   try {
     return xmlReader.getFeature(VALIDATION_FEATURE);
   } catch (SAXException x) {
     throw new IllegalStateException(x.getMessage());
   }
 }
コード例 #15
0
 public boolean isNamespaceAware() {
   try {
     return xmlReader.getFeature(NAMESPACES_FEATURE);
   } catch (SAXException x) {
     throw new IllegalStateException(x.getMessage());
   }
 }
コード例 #16
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  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;
  }
コード例 #17
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  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;
  }
コード例 #18
0
  /**
   * Parses the XML stored in the given file and returns a Document object that represents the
   * parsed XML file
   *
   * @param xml
   * @return
   */
  public static Document parseXML(File file) {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {

      // Using factory get an instance of document builder
      DocumentBuilder db = dbf.newDocumentBuilder();

      // parse using builder to get DOM representation of the XML file
      FileInputStream fis = new FileInputStream(file);
      Document domDoc = db.parse(fis);
      domDoc.normalize();
      fis.close();

      return domDoc;

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      System.err.println("File not found: " + e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
    }

    // default for exceptions
    return null;
  }
コード例 #19
0
ファイル: GodsProperties.java プロジェクト: nexcra/bittella
  /**
   * 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());
    }
  }
コード例 #20
0
  /**
   * 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
コード例 #21
0
ファイル: URLSElement.java プロジェクト: jfharney/esgf-web-fe
  /**
   * Description of fromFile()
   *
   * @param file
   */
  public void fromFile(String file) {

    // overwrite whatever was in the data structure
    this.urls = null;

    File fXmlFile = new File(file);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {
      dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);

      doc.getDocumentElement().normalize();
      org.w3c.dom.Element docElement = doc.getDocumentElement();

      this.readHelper(docElement);

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #22
0
  // 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);
    }
  }
コード例 #23
0
 /** Loads edits file, uses visitor to process all elements */
 public void loadEdits() throws IOException {
   try {
     XMLReader xr = XMLReaderFactory.createXMLReader();
     xr.setContentHandler(this);
     xr.setErrorHandler(this);
     xr.setDTDHandler(null);
     xr.parse(new InputSource(fileReader));
     visitor.close(null);
   } catch (SAXParseException e) {
     System.out.println(
         "XML parsing error: "
             + "\n"
             + "Line:    "
             + e.getLineNumber()
             + "\n"
             + "URI:     "
             + e.getSystemId()
             + "\n"
             + "Message: "
             + e.getMessage());
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (SAXException e) {
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (RuntimeException e) {
     visitor.close(e);
     throw e;
   } finally {
     fileReader.close();
   }
 }
コード例 #24
0
 /**
  * Cenverte o objeto informado para uma String que representa o XML do objeto.
  *
  * @param <T> Tipo generico que informa a classe
  * @param object O objeto a ser convertido. A classe deste objeto deve conter as anotações de
  *     JAXB.
  * @param schemaLocation {@link URL} do schema.
  * @return
  * @throws JAXBException
  */
 @SuppressWarnings("unchecked")
 public static <T> String marshal(T object, URL schemaLocation) throws JAXBException {
   Class<T> objClass = (Class<T>) object.getClass();
   JAXBContext context = JAXBContext.newInstance(objClass);
   Marshaller marshaller = context.createMarshaller();
   StringWriter sWriter = new StringWriter();
   XmlSchema xmlSchema = objClass.getPackage().getAnnotation(XmlSchema.class);
   if (xmlSchema != null && xmlSchema.namespace() != null) {
     XmlType xmlType = objClass.getAnnotation(XmlType.class);
     if (xmlType != null && xmlType.name() != null) {
       QName qName = new QName(xmlSchema.namespace(), xmlType.name());
       JAXBElement<T> elem = new JAXBElement<T>(qName, objClass, object);
       if (schemaLocation != null) {
         SchemaFactory schemaFactory =
             SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
         try {
           Schema schema = schemaFactory.newSchema(schemaLocation);
           marshaller.setSchema(schema);
         } catch (SAXException e) {
           e.printStackTrace();
         }
       }
       marshaller.marshal(elem, sWriter);
       return sWriter.toString();
     } else {
       throw new JAXBException("The xmlType could not be identified in class annotation");
     }
   } else {
     throw new JAXBException("The namespace could not be identified from package-info class");
   }
 }
 private void checkBomVersionInPom(String xml) {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder;
   Document doc = null;
   try {
     builder = factory.newDocumentBuilder();
     doc = builder.parse(new InputSource(new StringReader(xml)));
   } catch (SAXException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ParserConfigurationException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   XPathFactory xPathfactory = XPathFactory.newInstance();
   XPath xpath = xPathfactory.newXPath();
   XPathExpression expr = null;
   String bom_version = null;
   try {
     expr = xpath.compile("/project/properties/version.jboss.bom");
     bom_version = (String) expr.evaluate(doc, XPathConstants.STRING);
   } catch (XPathExpressionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   assertEquals(
       "jboss bom version in pom differs from the one given by wizard", version, bom_version);
 }
コード例 #26
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  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;
  }
コード例 #27
0
 public ArrayList validateXML(String xmlMessage) {
   StringBuffer validationError = new StringBuffer("");
   String result = "Pass";
   ArrayList list = new ArrayList();
   SubmitManufacturerPartyData sb = null;
   InputStream inFile = null;
   try {
     inFile = new ByteArrayInputStream(xmlMessage.getBytes());
     SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
     Schema schema = schemaFactory.newSchema(new File("PartydataManufacturer.xsd"));
     JAXBContext ctx = JAXBContext.newInstance(new Class[] {SubmitManufacturerPartyData.class});
     Unmarshaller um = ctx.createUnmarshaller();
     um.setSchema(schema);
     sb = (SubmitManufacturerPartyData) um.unmarshal(inFile);
   } catch (SAXException e) {
     result = "Fail";
     e.printStackTrace();
   } catch (UnmarshalException umex) {
     result = "Fail";
     System.out.println("---------- XML Validation Error -------------- ");
     System.out.println("#######" + umex.getLinkedException().getMessage());
     umex.printStackTrace();
   } catch (Exception e) {
     result = "Fail";
     e.printStackTrace();
   }
   list.add(sb);
   list.add(result);
   return list;
 }
コード例 #28
0
ファイル: XMLRestWorker.java プロジェクト: jormaral/SLdirect
  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;
  }
コード例 #29
0
ファイル: SVGParser.java プロジェクト: NwAurion/kosmor
  /**
   * 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;
  }
コード例 #30
0
  /**
   * Waits for an authentication response from the server. It must be called after the <code>
   * sendAuthentication</code> method call.
   *
   * @return true when the authentication hat been succesful, false othercase.
   * @throws IOException When the conection have not been initialized.
   */
  public boolean receiveAuthenticationResult() throws IOException {

    try {
      Document doc = receiveDocument();
      Element root = doc.getDocumentElement();
      if (root == null) return false;
      if (!root.getAttribute("type").equalsIgnoreCase("auth-response")) return false;
      NodeList nl = root.getChildNodes();
      Element authresult = null;
      for (int i = 0; i < nl.getLength(); i++) {
        Node n = nl.item(i);
        if (n.getNodeType() == Element.ELEMENT_NODE
            && n.getNodeName().equalsIgnoreCase("authentication")) {
          authresult = (Element) n;
          break;
        }
      }
      if (authresult != null && !authresult.getAttribute("result").equalsIgnoreCase("ok"))
        return false;
    } catch (SAXException e) {
      e.printStackTrace();
      return false;
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      return false;
    } catch (SocketClosedException e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }