java类javax.xml.parsers.DocumentBuilderFactory的实例源码

InstanceCreator.java 文件源码 项目:org.alloytools.alloy 阅读 20 收藏 0 点赞 0 评论 0
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
        }
    }
}
ParticleIO.java 文件源码 项目:trashjam2017 阅读 18 收藏 0 点赞 0 评论 0
/**
 * 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");
    }
}
ParticleIO.java 文件源码 项目:Progetto-C 阅读 23 收藏 0 点赞 0 评论 0
/**
 * 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");
    }
}
TestAMWebServicesJobs.java 文件源码 项目:hadoop 阅读 24 收藏 0 点赞 0 评论 0
@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));
  }
}
DOCXMergeEngine.java 文件源码 项目:doctemplate 阅读 31 收藏 0 点赞 0 评论 0
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;
    }
SamlUtils.java 文件源码 项目:cas4.0.x-server-wechat 阅读 20 收藏 0 点赞 0 评论 0
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;
    }
}
Bug5072946.java 文件源码 项目:openjdk-jdk10 阅读 21 收藏 0 点赞 0 评论 0
@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"));
}
Tag.java 文件源码 项目:ChronoBike 阅读 18 收藏 0 点赞 0 评论 0
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;
    }       
}
DOMderivationBuilder.java 文件源码 项目:TuLiPA-frames 阅读 23 收藏 0 点赞 0 评论 0
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;
    }       
}
ScriptDocument.java 文件源码 项目:L2J-Global 阅读 21 收藏 0 点赞 0 评论 0
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);
    }
}
SqlResults.java 文件源码 项目:elastic-db-tools-for-java 阅读 19 收藏 0 点赞 0 评论 0
/**
 * 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;
    }
}
Weather.java 文件源码 项目:EVE 阅读 29 收藏 0 点赞 0 评论 0
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));
}
Bug6941169Test.java 文件源码 项目:openjdk-jdk10 阅读 25 收藏 0 点赞 0 评论 0
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;
    }
EPRHeader.java 文件源码 项目:OpenJSharp 阅读 22 收藏 0 点赞 0 评论 0
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);
        }
    }
AuctionController.java 文件源码 项目:openjdk-jdk10 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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));
}
Game.java 文件源码 项目:HawkEngine 阅读 26 收藏 0 点赞 0 评论 0
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
}
XmlDoc.java 文件源码 项目:mobileAutomation 阅读 18 收藏 0 点赞 0 评论 0
/**
 * 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 );
}
AuctionController.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
/**
 * 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());
}
TrafficUtility.java 文件源码 项目:openrouteservice 阅读 31 收藏 0 点赞 0 评论 0
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);
}
TestNMWebServices.java 文件源码 项目:hadoop 阅读 20 收藏 0 点赞 0 评论 0
@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);
}
FactoryHelper.java 文件源码 项目:alfresco-xml-factory 阅读 23 收藏 0 点赞 0 评论 0
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);
    }
}
BlocklyActivityHelper.java 文件源码 项目:Blockly 阅读 28 收藏 0 点赞 0 评论 0
/**
 * @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;
}
ModelTranslationService.java 文件源码 项目:redirector 阅读 18 收藏 0 点赞 0 评论 0
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;
}
MyClientSOAP.java 文件源码 项目:Shopping-Cart-using-Web-Services 阅读 18 收藏 0 点赞 0 评论 0
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();
    }
}
Bug6531160.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
@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());
    }
}
XMLBodyVariableResolver.java 文件源码 项目:mockkid 阅读 19 收藏 0 点赞 0 评论 0
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;
}
Bug6513892.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@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());
    }
}
TestHsWebServicesJobConf.java 文件源码 项目:hadoop 阅读 17 收藏 0 点赞 0 评论 0
@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));
  }
}
DocumentBuilderFactoryTest.java 文件源码 项目:openjdk-jdk10 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 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();
        }
    }

}
AbstractSamlObjectBuilder.java 文件源码 项目:springboot-shiro-cas-mybatis 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 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;
    }
}


问题


面经


文章

微信
公众号

扫码关注公众号