Java Code Examples for javax.xml.parsers.DocumentBuilderFactory.newInstance()

The following are Jave code examples for showing how to use newInstance() of the javax.xml.parsers.DocumentBuilderFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: oscm   File: PaypalResponse.java   View Source Code Vote up 11 votes
/**
 * Parses the response for Status and Preapproval Key.
 * 
 * @param response
 *            The Response which is received in
 *            BaseServlet.sendPaypalRequest()
 * @throws ParserConfigurationException
 *             SAX may throw this
 * @throws SAXException
 *             SAX may throw this
 * @throws IOException
 *             SAX may throw this
 */
public PaypalResponse(String response) throws ParserConfigurationException,
        SAXException, IOException {
    originalResponse = response;
    final DocumentBuilderFactory factory = DocumentBuilderFactory
            .newInstance();
    factory.setNamespaceAware(true);
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    final InputStream responseStream = new ByteArrayInputStream(
            response.getBytes());

    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document responseDocument = builder.parse(responseStream);

    final Node documentElement = responseDocument.getDocumentElement();
    final NodeList childs = documentElement.getChildNodes();

    for (int i = 0; i < childs.getLength(); i++) {
        final Node child = childs.item(i);
        if (checkNodeName(child, "preapprovalKey")) {
            preapprovalKey = child.getTextContent().trim();
        } else if (checkNodeName(child, "responseEnvelope")) {
            final NodeList childs2 = child.getChildNodes();
            for (int i2 = 0; i2 < childs2.getLength(); i2++) {
                final Node child2 = childs2.item(i2);
                if (checkNodeName(child2, "ack")) {
                    status = child2.getTextContent().trim();
                } else if (checkNodeName(child2, "message")) {
                    error = child2.getTextContent().trim();
                }
            }
        }
    }
}
 
Example 2
Project: pay   File: XMLParser.java   View Source Code Vote up 6 votes
public static Map<String,Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

        //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is =  IOUtils.toInputStream(xmlString);
        Document document = builder.parse(is);
        //获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, Object> map = new HashMap<String, Object>();
        int i=0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if(node instanceof Element){
                map.put(node.getNodeName(),node.getTextContent());
            }
            i++;
        }
        return map;

    }
 
Example 3
Project: OpenJSharp   File: XmlUtil.java   View Source Code Vote up 6 votes
public static DocumentBuilderFactory newDocumentBuilderFactory(boolean secureXmlProcessing) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessing));
    } catch (ParserConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
    }
    return factory;
}
 
Example 4
Project: openjdk-jdk10   File: Bug4972882.java   View Source Code Vote up 6 votes
@Test
public void test1() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
    dbf.setAttribute(SCHEMA_SOURCE, Bug4972882.class.getResource("targetNS00101m2_stub.xsd").toExternalForm());

    DocumentBuilder builder = dbf.newDocumentBuilder();
    builder.setErrorHandler(new DraconianErrorHandler());

    try {
        builder.parse(Bug4972882.class.getResource("targetNS00101m2_stub.xml").toExternalForm());
        Assert.fail("failure expected");
    } catch (SAXException e) {
        Assert.assertTrue(e.getMessage().indexOf("sch-props-correct.2") != -1);
    }
}
 
Example 5
Project: warrior-jenkins-plugin   File: WarriorPluginBuilder.java   View Source Code Vote up 6 votes
/**
 * Private method to get the name of the virtual environment
 * given in virtualenv tag of warhorn config file
 *
 * @param build Build
 * @param workspace Jenkins job workspace
 * @param listener Task listener
 * @return virtEnvName Name of the Virtual Environment
 * @throws ParserConfigurationException ParserConfigurationException
 * @throws SAXException SAXException
 * @throws IOException IOException
 */
private String getVirtEnvName(Run<?,?> build, FilePath workspace, TaskListener listener)
        throws ParserConfigurationException, SAXException, IOException{

    String absWarhornConfig = "";
    if (configType.equals("configGit")){
        absWarhornConfig = workspace.getRemote() + "/configRepo/" + gitConfigFile;
    } else {
        absWarhornConfig = workspace.getRemote() + "/warhorn_config.xml";
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File(absWarhornConfig));
    NodeList veNodeList = document.getElementsByTagName("virtualenv");

    String virtEnvName = "";
    if(veNodeList.getLength() > 0){
        Element element = (Element) veNodeList.item(0);
        virtEnvName = element.getAttribute("name");
    }

    return virtEnvName;
}
 
Example 6
Project: incubator-netbeans   File: ActionTracker.java   View Source Code Vote up 5 votes
DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
    if (dbfactory == null) {
        dbfactory = DocumentBuilderFactory.newInstance();
    }

    if (dbld == null) {
        dbld = dbfactory.newDocumentBuilder();
    }

    return dbld;
}
 
Example 7
Project: oscm   File: XMLSignatureBuilder.java   View Source Code Vote up 5 votes
public Document sign(FileInputStream fileStream, KeyPair keyPair)
        throws ParserConfigurationException, SAXException, IOException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        KeyException, MarshalException, XMLSignatureException {

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

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(fileStream);

    DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
            document.getDocumentElement());
    XMLSignatureFactory signFactory = XMLSignatureFactory
            .getInstance("DOM");
    Reference ref = signFactory.newReference("", signFactory
            .newDigestMethod(digestMethod, null), Collections
            .singletonList(signFactory.newTransform(Transform.ENVELOPED,
                    (TransformParameterSpec) null)), null, null);
    SignedInfo si = signFactory.newSignedInfo(signFactory
            .newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null), signFactory
            .newSignatureMethod(signatureMethod, null), Collections
            .singletonList(ref));

    KeyInfoFactory kif = signFactory.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(keyPair.getPublic());
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    XMLSignature signature = signFactory.newXMLSignature(si, ki);
    signature.sign(signContext);

    return document;
}
 
Example 8
Project: minijax   File: LiquibaseHelper.java   View Source Code Vote up 5 votes
private static Document readXml(final File file) throws IOException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    try {
        return factory.newDocumentBuilder().parse(file);
    } catch (ParserConfigurationException | SAXException ex) {
        throw new IOException(ex.getMessage(), ex);
    }
}
 
Example 9
Project: javaide   File: PositionXmlParser.java   View Source Code Vote up 5 votes
private DomBuilder(String xml) throws ParserConfigurationException {
    mXml = xml;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    mDocument = docBuilder.newDocument();
    mDocument.setUserData(CONTENT_KEY, xml, null);
}
 
Example 10
Project: openjdk-jdk10   File: Bug6465722.java   View Source Code Vote up 5 votes
@Test
public void test() {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document d = dbf.newDocumentBuilder().getDOMImplementation().createDocument(null, "r", null);
        d.getDocumentElement().setAttributeNS("http://nowhere.net/", "id", "1");

        Transformer t = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT)));
        t.transform(new DOMSource(d), new StreamResult(new StringWriter()));
    } catch (Throwable ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
 
Example 11
Project: ibm-cos-sdk-java   File: XpathUtils.java   View Source Code Vote up 5 votes
/**
 * This method closes the given input stream upon completion.
 */
public static Document documentFrom(InputStream is)
        throws SAXException, IOException, ParserConfigurationException {
    is = new NamespaceRemovingInputStream(is);
    // DocumentBuilderFactory is not thread safe
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // ensure that parser writes error/warning messages to the logger
    // rather than stderr
    builder.setErrorHandler(ERROR_HANDLER);
    Document doc = builder.parse(is);
    is.close();
    return doc;
}
 
Example 12
Project: jmt   File: GuiXMLWriter.java   View Source Code Vote up 5 votes
/**
 * Returns the entire Document representing GUI data structure.
 * @param model data structure
 * @return complete GUI data structure in Document format
 */
public static Document getDocument(CommonModel model) {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = null;
	try {
		docBuilder = dbf.newDocumentBuilder();
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
		return null;
	}
	Document modelDoc = docBuilder.newDocument();
	// Writes all elements on Document
	writeGuiInfos(modelDoc, model);
	return modelDoc;
}
 
Example 13
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   View Source Code Vote up 5 votes
/**
 * Test the setExpandEntityReferences.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckDocumentBuilderFactory07() throws Exception {
    try (FileInputStream fis = new FileInputStream(new File(
            XML_DIR, "DocumentBuilderFactory02.xml"))) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setExpandEntityReferences(true);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.parse(fis);
        Element e = (Element) doc.getElementsByTagName("title").item(0);
        NodeList nl = e.getChildNodes();
        assertTrue(dbf.isExpandEntityReferences());
        assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W');
    }
}
 
Example 14
Project: openjdk-jdk10   File: FactoryConfErrorTest.java   View Source Code Vote up 4 votes
/**
 * To test exception thrown if javax.xml.parsers.DocumentBuilderFactory is
 * invalid.
 */
@Test(expectedExceptions = FactoryConfigurationError.class)
public void testNewInstance02() {
    DocumentBuilderFactory.newInstance();
}
 
Example 15
Project: DAFramework   File: DomXmlUtils.java   View Source Code Vote up 4 votes
/**
 * 初始化一个DocumentBuilderFactory
 *
 * @return a DocumentBuilderFactory
 */
public static DocumentBuilderFactory newDocumentBuilderFactory() {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	return dbf;
}
 
Example 16
Project: kaltura-ce-sakai-extension   File: CollectionEntityTest.java   View Source Code Vote up 4 votes
/**
     * Test method for {@link org.sakaiproject.kaltura.logic.entity.CollectionEntity#toXml(org.w3c.dom.Document, java.util.Stack)}.
     */
    public void testToXml() throws Exception {
        // setup test data
        MediaCollection mc = new MediaCollection(null, "AZlocation", "AZowner", "AZcollection", true, MediaCollection.SHARING_PUBLIC);
        ArrayList<MediaItem> items = new ArrayList<MediaItem>();
        MediaItem mi1 = new MediaItem(null, "1_itjk7baf", "own2", true, false, false);
        mi1.setCollection(mc);
        items.add(mi1);
        MediaItem mi2 = new MediaItem(null, "1_dgvh2sxv", "own2", true, false, false);
        mi2.setCollection(mc);
        items.add(mi2);
        MediaItem mi3 = new MediaItem(null, "0_ir33td8e", "own2", true, false, false);
        mi3.setCollection(mc);
        items.add(mi3);
        mc.setItems(items);
        CollectionEntity collectionEntity = new CollectionEntity(mc);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();
        Stack<Element> stack = new Stack<Element>();
        Element e = collectionEntity.toXml(doc, stack);
        assertNotNull(e);
        assertEquals(CollectionEntity.XML_COLLECTION_KEY, e.getNodeName());

        // turn the DOM object into raw XML
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = result.getWriter().toString();
        assertNotNull(xmlString);
        assertTrue(xmlString.contains("<collection"));
        assertTrue(xmlString.contains("<item"));
        /*
<collection dateCreated="2012-05-01T16:03:28.307-04:00" dateModified="2012-05-01T16:03:28.307-04:00" description="" hidden="true" id="" locationId="AZlocation" ownerId="AZowner" sharing="public" title="AZcollection">
  <item creatorId="own2" dateCreated="2012-05-01T16:03:28.344-04:00" dateModified="2012-05-01T16:03:28.344-04:00" hidden="true" id="" kalturaId="1_itjk7baf" ownerId="own2" position="0" remixable="false" shared="false" type=""/>
  <item creatorId="own2" dateCreated="2012-05-01T16:03:28.344-04:00" dateModified="2012-05-01T16:03:28.344-04:00" hidden="true" id="" kalturaId="1_dgvh2sxv" ownerId="own2" position="0" remixable="false" shared="false" type=""/>
  <item creatorId="own2" dateCreated="2012-05-01T16:03:28.344-04:00" dateModified="2012-05-01T16:03:28.344-04:00" hidden="true" id="" kalturaId="0_ir33td8e" ownerId="own2" position="0" remixable="false" shared="false" type=""/>
</collection>
         */
    }
 
Example 17
Project: DAFramework   File: DomXmlUtils.java   View Source Code Vote up 4 votes
public static Document parse(String xmlFile) throws Exception {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	return builder.parse(new File(xmlFile));
}
 
Example 18
Project: mycat-src-1.6.1-RELEASE   File: FirewallConfig.java   View Source Code Vote up 4 votes
public synchronized static void updateToFile(String host, List<UserConfig> userConfigs) throws Exception{
	LOGGER.debug("set white host:" + host + "user:" + userConfigs);
	String filename = SystemConfig.getHomePath()+ File.separator +"conf"+ File.separator +"server.xml";
	//String filename = "E:\\MyProject\\Mycat-Server\\src\\main\\resources\\server.xml";

       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       factory.setNamespaceAware(false);
       factory.setValidating(false);
       DocumentBuilder builder = factory.newDocumentBuilder();
       builder.setEntityResolver(new IgnoreDTDEntityResolver());
       Document xmldoc = builder.parse(filename);
       Element whitehost = (Element) xmldoc.getElementsByTagName("whitehost").item(0);
       Element firewall = (Element) xmldoc.getElementsByTagName("firewall").item(0);
       
	if (firewall == null) {
		firewall = xmldoc.createElement("firewall");
           Element root = xmldoc.getDocumentElement();
           root.appendChild(firewall);
           if(whitehost==null){
           	whitehost = xmldoc.createElement("whitehost");
           	firewall.appendChild(whitehost);
           }
       }

       for(UserConfig userConfig : userConfigs){
       	String user = userConfig.getName();
       	Element hostEle = xmldoc.createElement("host");
       	hostEle.setAttribute("host", host);
       	hostEle.setAttribute("user", user);

       	whitehost.appendChild(hostEle);
       }
       
            
       TransformerFactory factory2 = TransformerFactory.newInstance();
       Transformer former = factory2.newTransformer();
       String systemId = xmldoc.getDoctype().getSystemId();
       if(systemId!=null){
           former.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM, systemId);    
       }
       former.transform(new DOMSource(xmldoc), new StreamResult(new File(filename)));

}
 
Example 19
Project: oscm   File: XMLConverterTest.java   View Source Code Vote up 4 votes
@Before
public void setup() throws Exception {
    builderFactory = DocumentBuilderFactory.newInstance();
    builder = builderFactory.newDocumentBuilder();
}
 
Example 20
Project: adobe-air-db-connector   File: XmlEncoder.java   View Source Code Vote up 3 votes
public Element stringToElement(String xmlString) throws Exception{
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	
	DocumentBuilder builder = factory.newDocumentBuilder();
	
	Document doc = builder.parse(new InputSource(new StringReader(xmlString)));

	return doc.getDocumentElement();
}