Java 类javax.xml.parsers.DocumentBuilderFactory 实例源码

项目:org.alloytools.alloy    文件:InstanceCreator.java   
public InstanceCreator(InputStream in) {
    try {
        this.relations = new HashMap<Relation,Set<List<String>>>();
        this.atoms = new LinkedHashSet<String>();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        this.document = builder.parse(in);
    } catch (SAXException sxe) {
        // Error generated during parsing
        Exception x = sxe;
        if (sxe.getException() != null)
            x = sxe.getException();
        throw new InstanceCreationException("Error generated during parsing: " + x.getMessage());

    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        throw new InstanceCreationException("Parser with specified options cannot be built: " + pce.getMessage());

    } catch (IOException ioe) {
        // I/O error
        throw new InstanceCreationException("I/O error: " + ioe.getMessage());
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            // ignore
        }
    }
}
项目:trashjam2017    文件:ParticleIO.java   
/**
 * Save a single emitter to the XML file
 * 
 * @param out
 *            The location to which we should save
 * @param emitter
 *            The emitter to store to the XML file
 * @throws IOException
 *             Indicates a failure to write or encode the XML
 */
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
        throws IOException {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document document = builder.newDocument();

        document.appendChild(emitterToElement(document, emitter));
        Result result = new StreamResult(new OutputStreamWriter(out,
                "utf-8"));
        DOMSource source = new DOMSource(document);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer xformer = factory.newTransformer();
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");

        xformer.transform(source, result);
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to save emitter");
    }
}
项目:Progetto-C    文件:ParticleIO.java   
/**
 * Save a single emitter to the XML file
 * 
 * @param out
 *            The location to which we should save
 * @param emitter
 *            The emitter to store to the XML file
 * @throws IOException
 *             Indicates a failure to write or encode the XML
 */
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
        throws IOException {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        Document document = builder.newDocument();

        document.appendChild(emitterToElement(document, emitter));
        Result result = new StreamResult(new OutputStreamWriter(out,
                "utf-8"));
        DOMSource source = new DOMSource(document);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer xformer = factory.newTransformer();
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");

        xformer.transform(source, result);
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to save emitter");
    }
}
项目:hadoop    文件:TestAMWebServicesJobs.java   
@Test
public void testJobAttemptsXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1")
        .path("mapreduce").path("jobs").path(jobId).path("jobattempts")
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList attempts = dom.getElementsByTagName("jobAttempts");
    assertEquals("incorrect number of elements", 1, attempts.getLength());
    NodeList info = dom.getElementsByTagName("jobAttempt");
    verifyJobAttemptsXML(info, jobsMap.get(id));
  }
}
项目:doctemplate    文件:DOCXMergeEngine.java   
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("Relationships/*");
        NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
            int idNum = Integer.parseInt(id.substring("rId".length()));
            this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
        }
        return this.maxRId;
    }
项目:cas4.0.x-server-wechat    文件:SamlUtils.java   
private static org.w3c.dom.Document toDom(final Document doc) {
    try {
        final XMLOutputter xmlOutputter = new XMLOutputter();
        final StringWriter elemStrWriter = new StringWriter();
        xmlOutputter.output(doc, elemStrWriter);
        final byte[] xmlBytes = elemStrWriter.toString().getBytes();
        final DocumentBuilderFactory dbf = DocumentBuilderFactory
                .newInstance();
        dbf.setNamespaceAware(true);
        return dbf.newDocumentBuilder().parse(
                new ByteArrayInputStream(xmlBytes));
    } catch (final Exception e) {
        return null;
    }
}
项目:openjdk-jdk10    文件:Bug5072946.java   
@Test
public void test1() throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml"));

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema s = sf.newSchema(Bug5072946.class.getResource("Bug5072946.xsd"));
    Validator v = s.newValidator();

    DOMResult r = new DOMResult();
    // r.setNode(dbf.newDocumentBuilder().newDocument());
    v.validate(new DOMSource(dom), r);

    Node node = r.getNode();
    Assert.assertNotNull(node);
    Node fc = node.getFirstChild();
    Assert.assertTrue(fc instanceof Element);
    Element e = (Element) fc;

    Assert.assertEquals("value", e.getAttribute("foo"));
}
项目:ChronoBike    文件:Tag.java   
public boolean load(InputStream s)
{
    try
    {
        Source file = new StreamSource(s) ;
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ;
        Result res = new DOMResult(doc) ;
        TransformerFactory tr = TransformerFactory.newInstance();
        Transformer xformer = tr.newTransformer();
        xformer.transform(file, res);
        m_doc = doc;
        m_elem = m_doc.getDocumentElement();            
        return true;
    }
    catch (Exception e)
    {
        LogTagError.log(e);
        return false;
    }       
}
项目:TuLiPA-frames    文件:DOMderivationBuilder.java   
public static Document buildDOMderivation(ArrayList<ParseTreeCollection> all, String sentence) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder constructor    = factory.newDocumentBuilder();
        derivDoc                       = constructor.newDocument();
        derivDoc.setXmlVersion("1.0");
        derivDoc.setXmlStandalone(false);

        Element root = derivDoc.createElement("parses");
        root.setAttribute("sentence", sentence);
           for (ParseTreeCollection ptc : all)
           {
            buildOne(root, ptc.getDerivationTree().getDomNodes().get(0), ptc.getDerivedTree().getDomNodes().get(0), ptc.getSemantics(), ptc.getSpecifiedSemantics());
           }
        // finally we do not forget the root
        derivDoc.appendChild(root);
        return derivDoc;

    } catch (ParserConfigurationException e) {
        System.err.println(e);
        return null;
    }       
}
项目:L2J-Global    文件:ScriptDocument.java   
public ScriptDocument(String name, InputStream input)
{
    _name = name;

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try
    {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        _document = builder.parse(input);

    }
    catch (SAXException sxe)
    {
        // Error generated during parsing)
        Exception x = sxe;
        if (sxe.getException() != null)
        {
            x = sxe.getException();
        }
        _log.warning(getClass().getSimpleName() + ": " + x.getMessage());
    }
    catch (ParserConfigurationException pce)
    {
        // Parser with specified options can't be built
        _log.log(Level.WARNING, "", pce);

    }
    catch (IOException ioe)
    {
        // I/O error
        _log.log(Level.WARNING, "", ioe);
    }
}
项目:elastic-db-tools-for-java    文件:SqlResults.java   
/**
 * Constructs an instance of StoreLogEntry using parts of a row from ResultSet. Used for creating the store operation for Undo.
 *
 * @param reader
 *            ResultSet whose row has operation information.
 * @param offset
 *            Reader offset for column that begins operation information.
 */
public static StoreLogEntry readLogEntry(ResultSet reader,
        int offset) throws SQLException {
    try {
        UUID shardIdRemoves = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 4)) ? null : UUID.fromString(reader.getString(offset + 4));
        UUID shardIdAdds = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 5)) ? null : UUID.fromString(reader.getString(offset + 5));
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(reader.getSQLXML(offset + 2).getBinaryStream());

        return new StoreLogEntry(UUID.fromString(reader.getString(offset)), StoreOperationCode.forValue(reader.getInt(offset + 1)),
                (Element) doc.getFirstChild(), StoreOperationState.forValue(reader.getInt(offset + 3)), shardIdRemoves, shardIdAdds);
    }
    catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    }
}
项目:EVE    文件:Weather.java   
private void generateForecast(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException {
    city = c;

    // creating the URL
    String url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + city + ",us&mode=xml&cnt=6&appid=" + APIKey;

    // printing out XML
    URL urlString = new URL(url);
    URLConnection conn = urlString.openConnection();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(conn.getInputStream());

    TransformerFactory transformer = TransformerFactory.newInstance();
    Transformer xform = transformer.newTransformer();

    xform.transform(new DOMSource(doc), new StreamResult(System.out));
}
项目:openjdk-jdk10    文件:Bug6941169Test.java   
private static Document getDocument(InputStream in) {

        Document document = null;

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            document = db.parse(in);
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(e.toString());
        }

        return document;
    }
项目:OpenJSharp    文件:EPRHeader.java   
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
项目:openjdk-jdk10    文件:AuctionController.java   
/**
 * Check usage of TypeInfo interface introduced in DOM L3.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testGetTypeInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    docBuilder.setErrorHandler(new MyErrorHandler());

    Document document = docBuilder.parse(xmlFile);
    Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
    TypeInfo typeInfo = userId.getSchemaTypeInfo();
    assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
    assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));

    Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
    TypeInfo roletypeInfo = role.getSchemaTypeInfo();
    assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
    assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
}
项目:HawkEngine    文件:Game.java   
public void LoadCustomBehavior(String filePath, boolean resourcesIncluded)
{
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    Document doc = null;
    try
    {
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(new File((resourcesIncluded ? "Resources/" : "") + filePath));
    } catch (Exception e)
    {
        e.printStackTrace();
        return;
    }

    //TODO: Load into behavior class
}
项目:mobileAutomation    文件:XmlDoc.java   
/**
 * Create a new XML doc with root element. 
 *
 * @param rootName - the tagName of the root element
 */
public XmlDoc( String rootName )
{
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance( );
    DocumentBuilder db = null;

    try
    {
        db = dbf.newDocumentBuilder( );
    }
    catch ( ParserConfigurationException e )
    {
        logger.log(""+e);
        throw new TestCaseFailure(e.getMessage());
    }

    Doc = db.newDocument( );
    final Element root = Doc.createElement( rootName );
    Doc.appendChild( root );
}
项目:openjdk-jdk10    文件:AuctionController.java   
/**
 * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
 * test throws DOM Level 1 node error.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateNewItem2SellRetry() throws Exception  {
    String xmlFile = XML_DIR + "accountInfo.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document document = dbf.newDocumentBuilder().parse(xmlFile);

    DOMConfiguration domConfig = document.getDomConfig();
    MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
    domConfig.setParameter("error-handler", errHandler);

    DOMImplementationLS impl =
         (DOMImplementationLS) DOMImplementationRegistry.newInstance()
                 .getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    MyDOMOutput domoutput = new MyDOMOutput();

    domoutput.setByteStream(System.out);
    writer.write(document, domoutput);

    document.normalizeDocument();
    writer.write(document, domoutput);
    assertFalse(errHandler.isError());
}
项目:openrouteservice    文件:TrafficUtility.java   
public static Date getMessageDateTime(String tmcMessage) throws ParserConfigurationException, SAXException,
        IOException, ParseException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    InputStream stream = new ByteArrayInputStream(tmcMessage.getBytes(StandardCharsets.UTF_8));
    Document doc = docBuilder.parse(stream);

    doc.getDocumentElement().normalize();
    String timeStamp = doc.getDocumentElement().getAttribute("FGT");

    // FGT="2014-05-01T15:06:00"
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

    return formatter.parse(timeStamp);
}
项目:hadoop    文件:TestNMWebServices.java   
@Test
public void testSingleNodesXML() throws JSONException, Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("node")
      .path("info/").accept(MediaType.APPLICATION_XML)
      .get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
  String xml = response.getEntity(String.class);
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodes = dom.getElementsByTagName("nodeInfo");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyNodesXML(nodes);
}
项目:alfresco-xml-factory    文件:FactoryHelper.java   
private void setFeature(DocumentBuilderFactory factory, String feature, boolean enable)
{
    try
    {
        if (ADDITIONAL_FEATURE_X_INCLUDE_AWARE.equals(feature))
        {
            factory.setXIncludeAware(enable);
        }
        else if (ADDITIONAL_FEATURE_EXPAND_ENTITY_REFERENCES.equals(feature))
        {
            factory.setExpandEntityReferences(enable);
        }
        else
        {
            factory.setFeature(feature, enable);
        }
        debug(debugCounter+" DocumentBuilderFactory "+feature+" "+enable);
    }
    catch (ParserConfigurationException pce)
    {
        logConfigurationFailure(factory.getClass().getName(), feature, pce);
    }
}
项目:Blockly    文件:BlocklyActivityHelper.java   
/**
 * @param fileName
 * @return
 */
public String convertXMLFileToString(String fileName) {

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        InputStream inputStream = new FileInputStream(new File(fileName));
        org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(doc), new StreamResult(stw));
        return stw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:redirector    文件:ModelTranslationService.java   
public URLRuleModel translateUrlRules(URLRules source, NamespacedListRepository namespacedLists) {
    String urlRulesXML = getUrlRulesXML(source);
    URLRuleModel model = null;
    try {
        if (StringUtils.isNotBlank(urlRulesXML)) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document newDocument = builder.parse(new ByteArrayInputStream(urlRulesXML.getBytes(UTF8_CHARSET)));
            model = new URLRuleModel(newDocument, namespacedLists);
            log.info("Rules created from xml: \n{}", urlRulesXML);
        } else {
            log.error("Trying to init null model");
        }
    } catch (Exception ex) {
        log.error("Exception while creating model from xml: \n{}Root cause: {}", urlRulesXML, ex.getCause().getMessage());
    }

    return model;
}
项目:Shopping-Cart-using-Web-Services    文件:MyClientSOAP.java   
private void parseUserActionResponse(String xml){
    messageList = new ArrayList<String>();
    //get the factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        domARB = db.parse(new InputSource(new StringReader(xml)));
        domARB.getDocumentElement().normalize();
        NodeList nList = domARB.getElementsByTagName("messagetouser");
        messageList.clear();
        //put all message from server in a list
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode; 
                messageList.add(eElement.getTextContent());
            }
        }
        //catch total items returned from server
        totalItem=domARB.getElementsByTagName("totalitem").item(0).getTextContent();

    }catch(ParserConfigurationException pce) {          pce.printStackTrace();
    }catch(SAXException se) {                           se.printStackTrace();
    }catch(IOException ioe) {                           ioe.printStackTrace();
    }catch (Exception e){                               e.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:Bug6531160.java   
@Test
public void testDOMLevel1Validation() throws Exception {
    SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = fact.newSchema(new StreamSource(new StringReader(XSD)));
    DocumentBuilderFactory docfact = DocumentBuilderFactory.newInstance();
    docfact.setNamespaceAware(true);

    Document doc = docfact.newDocumentBuilder().newDocument();
    doc.appendChild(doc.createElement("root"));

    try {
        schema.newValidator().validate(new DOMSource(doc));
    } catch (SAXParseException e) {
        Assert.fail("Validation failed: " + e.getMessage());
    }
}
项目:mockkid    文件:XMLBodyVariableResolver.java   
public static String extractValueFromXml(String name, HttpServletRequest request) {
    try {
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(((MockkidRequest) request).getSafeInputStream());

        XPath xPath =  XPathFactory.newInstance().newXPath();
        String expression = name.replace("body", "").replaceAll("\\.", "/");
        String result = xPath.compile(expression).evaluate(document);
        if (result.isEmpty()) return null; //empty string can mean node doesn't exist, or value is empty
        return result;
    } catch (Exception e) {
        logger.warn("Couldn't extract variable", e);
    }
    return null;
}
项目:openjdk-jdk10    文件:Bug6513892.java   
@Test
public void test0() {
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(getClass().getResourceAsStream("redirect.xsl"), getClass().getResource("redirect.xsl")
                .toString()));

        StreamSource src1 = new StreamSource(getClass().getResourceAsStream("redirect.xml"));
        t.transform(src1, new StreamResult("redirect1.xml"));

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document d1 = db.parse(new File("redirect1.xml"));
        Document d2 = db.parse(new File("redirect2.xml"));

        Assert.assertTrue(d1.getDocumentElement().getFirstChild().getNodeValue().equals(d2.getDocumentElement().getFirstChild().getNodeValue()));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
项目:hadoop    文件:TestHsWebServicesJobConf.java   
@Test
public void testJobConfXML() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history").path("mapreduce")
        .path("jobs").path(jobId).path("conf")
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList info = dom.getElementsByTagName("conf");
    verifyHsJobConfXML(info, jobsMap.get(id));
  }
}
项目:openjdk-jdk10    文件:DocumentBuilderFactoryTest.java   
/**
 * Test the default functionality of schema support method. In
 * this case the schema source property is set.
 * @throws Exception If any errors occur.
 */
@Test(dataProvider = "schema-source")
public void testCheckSchemaSupport2(Object schemaSource) throws Exception {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                W3C_XML_SCHEMA_NS_URI);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
        MyErrorHandler eh = MyErrorHandler.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(eh);
        db.parse(new File(XML_DIR, "test1.xml"));
        assertFalse(eh.isErrorOccured());
    } finally {
        if (schemaSource instanceof Closeable) {
            ((Closeable) schemaSource).close();
        }
    }

}
项目:springboot-shiro-cas-mybatis    文件:AbstractSamlObjectBuilder.java   
/**
 * Convert the received jdom doc to a Document element.
 *
 * @param doc the doc
 * @return the org.w3c.dom. document
 */
private org.w3c.dom.Document toDom(final Document doc) {
    try {
        final XMLOutputter xmlOutputter = new XMLOutputter();
        final StringWriter elemStrWriter = new StringWriter();
        xmlOutputter.output(doc, elemStrWriter);
        final byte[] xmlBytes = elemStrWriter.toString().getBytes(Charset.defaultCharset());
        final DocumentBuilderFactory dbf = DocumentBuilderFactory
                .newInstance();
        dbf.setNamespaceAware(true);
        return dbf.newDocumentBuilder().parse(
                new ByteArrayInputStream(xmlBytes));
    } catch (final Exception e) {
        logger.trace(e.getMessage(), e);
        return null;
    }
}
项目:hadoop    文件:TestAMWebServicesJobs.java   
@Test
public void testJobIdXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).accept(MediaType.APPLICATION_XML)
        .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList job = dom.getElementsByTagName("job");
    verifyAMJobXML(job, appContext);
  }

}
项目:javaide    文件:FormatFactory.java   
private static String formatXml(Context context, String src) throws TransformerException,
        ParserConfigurationException, IOException, SAXException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(src)));

    AppSetting setting = new AppSetting(context);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", setting.getTab().length() + "");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    //initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    return result.getWriter().toString();
}
项目:openjdk-jdk10    文件:SOAPDocumentImpl.java   
private Document createDocument() {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", SAAJUtil.getSystemClassLoader());
    try {
        final DocumentBuilder documentBuilder = docFactory.newDocumentBuilder();
        return documentBuilder.newDocument();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Error creating xml document", e);
    }
}
项目:defense-solutions-proofs-of-concept    文件:CoTAdapterInbound.java   
private NodeList unpackXML(String xml, String targetTag) throws Exception {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource source = new InputSource();
        source.setCharacterStream(new StringReader(xml));
        Document doc = db.parse(source);
        NodeList nodeList = doc.getElementsByTagName(targetTag);
        return nodeList;
    } catch (Exception e) {
        log.error(e);
        log.error(e.getStackTrace());
        throw (e);
    }
}
项目:redirector    文件:PathRuleWithMultipleNamespacesExpressionTest.java   
private static Document fromString(String xmlString) {
    try {
        return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xmlString.getBytes()));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:r2-streamer-java    文件:EpubParser.java   
private String containerXmlParser(String containerData) throws EpubParserException {           //parsing container.xml
    try {
        String xml = containerData.replaceAll("[^\\x20-\\x7e]", "").trim();         //in case encoding problem

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xml)));
        document.getDocumentElement().normalize();
        if (document == null) {
            throw new EpubParserException("Error while parsing container.xml");
        }

        Element rootElement = (Element) ((Element) document.getDocumentElement().getElementsByTagName("rootfiles").item(0)).getElementsByTagName("rootfile").item(0);
        if (rootElement != null) {
            String opfFile = rootElement.getAttribute("full-path");
            if (opfFile == null) {
                throw new EpubParserException("Missing root file element in container.xml");
            }

            //Log.d(TAG, "Root file: " + opfFile);
            return opfFile;                    //returns opf file
        }
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return null;
}
项目:jaffa-framework    文件:WSDLTrimmer.java   
/**
 * Trims the sourceWSDL based on the excludedFields that are declared for the graphClass associated with the input WebService implementation class.
 * The targetWSDL will be generated as a result.
 * @param sourceWSDL a source WSDL.
 * @param targetWSDLToGenerate the WSDL to generate.
 * @param webServiceImplementationClassName the WebService implementation class that may have an annotation declaring the need for WSDL trimming.
 */
public static void trim(File sourceWSDL, File targetWSDLToGenerate, String webServiceImplementationClassName) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, ClassNotFoundException {
    Map<Class, Collection<String>> excludedFields = getExcludedFields(webServiceImplementationClassName);
    if (excludedFields != null && excludedFields.size() > 0) {
        if (log.isDebugEnabled())
            log.debug("Trimming '" + sourceWSDL + "' by excluding " + excludedFields);

        //Parse the source WSDL
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document document = parser.parse(sourceWSDL);

        //Trim the source WSDL
        trim(document.getDocumentElement(), excludedFields);

        //Generate the target WSDL
        if (log.isDebugEnabled())
            log.debug("Generating: " + targetWSDLToGenerate);
        Source source = new DOMSource(document);
        Result result = new StreamResult(targetWSDLToGenerate);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        //transformerFactory.setAttribute("indent-number", 2);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } else if (!sourceWSDL.equals(targetWSDLToGenerate)) {
        if (log.isDebugEnabled())
            log.debug("None of the fields are excluded. '" + targetWSDLToGenerate + "'  will be created as a copy of '" + sourceWSDL + '\'');
        copy(sourceWSDL, targetWSDLToGenerate);
    }
}
项目:hadoop    文件:TestQueuePlacementPolicy.java   
private QueuePlacementPolicy parse(String str) throws Exception {
  // Read and parse the allocations file.
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
      .newInstance();
  docBuilderFactory.setIgnoringComments(true);
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(IOUtils.toInputStream(str));
  Element root = doc.getDocumentElement();
  return QueuePlacementPolicy.fromXml(root, configuredQueues, conf);
}
项目:Android_Code_Arbiter    文件:DocumentBuilderSafeProperty.java   
public static void unsafeNoSpecialSettings() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
项目:OpenJSharp    文件:DOMForest.java   
public DOMForest( InternalizationLogic logic, Options opt ) {

        if (opt == null) throw new AssertionError("Options object null");
        this.options = opt;

        try {
            DocumentBuilderFactory dbf = XmlFactory.createDocumentBuilderFactory(opt.disableXmlSecurity);
            this.documentBuilder = dbf.newDocumentBuilder();
            this.parserFactory = XmlFactory.createParserFactory(opt.disableXmlSecurity);
        } catch( ParserConfigurationException e ) {
            throw new AssertionError(e);
        }

        this.logic = logic;
    }