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

The following are Jave code examples for showing how to use setExpandEntityReferences() 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: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   View Source Code Vote up 9 votes
public static void unsafeManualConfig3() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    //dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 2
Project: alfresco-xml-factory   File: FactoryHelper.java   View Source Code Vote up 8 votes
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);
    }
}
 
Example 3
Project: vexillo   File: FlagParser.java   View Source Code Vote up 6 votes
public static Flag parse(String name, InputStream in) throws IOException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true); // make sure the XML is valid
		factory.setExpandEntityReferences(false); // don't allow custom entities
		DocumentBuilder builder = factory.newDocumentBuilder();
		builder.setEntityResolver(new KVXXEntityResolver());
		builder.setErrorHandler(new KVXXErrorHandler(name));
		Document document = builder.parse(new InputSource(in));
		return parseDocument(document);
	} catch (ParserConfigurationException pce) {
		throw new IOException(pce);
	} catch (SAXException saxe) {
		throw new IOException(saxe);
	}
}
 
Example 4
Project: tomcat7   File: WebdavServlet.java   View Source Code Vote up 6 votes
/**
 * Return JAXP document builder instance.
 */
protected DocumentBuilder getDocumentBuilder()
    throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(
                new WebdavResolver(this.getServletContext()));
    } catch(ParserConfigurationException e) {
        throw new ServletException
            (sm.getString("webdavservlet.jaxpfailed"));
    }
    return documentBuilder;
}
 
Example 5
Project: lams   File: BasicParserPool.java   View Source Code Vote up 6 votes
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializePool() throws XMLParserException {
    if (!dirtyBuilderConfiguration) {
        // in case the pool was initialized by some other thread
        return;
    }

    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    setAttributes(newFactory, builderAttributes);
    setFeatures(newFactory, builderFeatures);
    newFactory.setCoalescing(coalescing);
    newFactory.setExpandEntityReferences(expandEntityReferences);
    newFactory.setIgnoringComments(ignoreComments);
    newFactory.setIgnoringElementContentWhitespace(ignoreElementContentWhitespace);
    newFactory.setNamespaceAware(namespaceAware);
    newFactory.setSchema(schema);
    newFactory.setValidating(dtdValidating);
    newFactory.setXIncludeAware(xincludeAware);

    poolVersion++;
    dirtyBuilderConfiguration = false;
    builderFactory = newFactory;
    builderPool.clear();
}
 
Example 6
Project: lams   File: WebdavServlet.java   View Source Code Vote up 6 votes
/**
 * Return JAXP document builder instance.
 */
protected DocumentBuilder getDocumentBuilder()
    throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(
                new WebdavResolver(this.getServletContext()));
    } catch(ParserConfigurationException e) {
        throw new ServletException
            (sm.getString("webdavservlet.jaxpfailed"));
    }
    return documentBuilder;
}
 
Example 7
Project: Hydrograph   File: UiConverterUtil.java   View Source Code Vote up 6 votes
private Graph unMarshall(File inputFile) throws JAXBException, ParserConfigurationException, SAXException,
		IOException {
	LOGGER.debug("Un-Marshaling generated object into target XML");
	JAXBContext jaxbContext;
	Graph graph = null;
	Document document =null;
	parseXML(inputFile);
	String inputFileAsString = replaceParametersWithDefaultValues(inputFile);
	
	DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
	builderFactory.setExpandEntityReferences(false);
	builderFactory.setNamespaceAware(true);
	builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
	
	DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
	ByteArrayInputStream byteStream = new ByteArrayInputStream(inputFileAsString.getBytes());
	InputSource inputSource=new InputSource(byteStream);

	document = documentBuilder.parse(inputSource);
	jaxbContext = JAXBContext.newInstance(Graph.class);
	Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
	graph = (Graph) jaxbUnmarshaller.unmarshal(document);
	if (graph != null) {
		componentRepo.genrateComponentRepo(graph);
	}
	byteStream.close();
	return graph;
}
 
Example 8
Project: apache-tomcat-7.0.73-with-comment   File: WebdavServlet.java   View Source Code Vote up 6 votes
/**
 * Return JAXP document builder instance.
 */
protected DocumentBuilder getDocumentBuilder()
    throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(
                new WebdavResolver(this.getServletContext()));
    } catch(ParserConfigurationException e) {
        throw new ServletException
            (sm.getString("webdavservlet.jaxpfailed"));
    }
    return documentBuilder;
}
 
Example 9
Project: incubator-servicecomb-java-chassis   File: FortifyUtils.java   View Source Code Vote up 5 votes
public static DocumentBuilderFactory getSecurityXmlDocumentFactory() throws ParserConfigurationException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  factory.setXIncludeAware(false);
  factory.setExpandEntityReferences(false);
  factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
  factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
  factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  factory.setValidating(true);

  return factory;
}
 
Example 10
Project: joai-project   File: XMLDocReader.java   View Source Code Vote up 5 votes
/**
 *  Gets a org.w3c.dom.Document for this record. This method is optimized to create only one DOM when
 *  accessed multiple times for the same XMLDocReader.
 *
 * @return    A org.w3c.dom.Document, or null if unable to read.
 */
public org.w3c.dom.Document getW3CXmlDoc() {
	if (w3cXmlDoc != null)
		return w3cXmlDoc;

	DocumentBuilderFactory docfactory
		 = DocumentBuilderFactory.newInstance();
	docfactory.setCoalescing(true);
	docfactory.setExpandEntityReferences(true);
	docfactory.setIgnoringComments(true);

	docfactory.setNamespaceAware(true);

	// We must set validation false since jdk1.4 parser
	// doesn't know about schemas.
	docfactory.setValidating(false);

	// Ignore whitespace doesn't work unless setValidating(true),
	// according to javadocs.
	docfactory.setIgnoringElementContentWhitespace(false);
	try {
		DocumentBuilder docbuilder = docfactory.newDocumentBuilder();
		w3cXmlDoc = docbuilder.parse(getXml());
	} catch (Throwable e) {
		return null;
	}
	return w3cXmlDoc;
}
 
Example 11
Project: lams   File: StaticBasicParserPool.java   View Source Code Vote up 5 votes
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializeFactory() throws XMLParserException {
    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    setAttributes(newFactory, builderAttributes);
    setFeatures(newFactory, builderFeatures);
    newFactory.setCoalescing(coalescing);
    newFactory.setExpandEntityReferences(expandEntityReferences);
    newFactory.setIgnoringComments(ignoreComments);
    newFactory.setIgnoringElementContentWhitespace(ignoreElementContentWhitespace);
    newFactory.setNamespaceAware(namespaceAware);
    newFactory.setSchema(schema);
    newFactory.setValidating(dtdValidating);
    newFactory.setXIncludeAware(xincludeAware);
    builderFactory = newFactory;
}
 
Example 12
Project: Hydrograph   File: XMLConfigUtil.java   View Source Code Vote up 5 votes
/** Reads the xml configuration files stored under the platform installation.
 * 	These files contain the configuration required to create the component on UI. 
 * @return see {@link Component}
 * @throws RuntimeException 
 * @throws IOException 
 * @throws SAXException 
 */
public List<Component> getComponentConfig() throws RuntimeException, SAXException, IOException {
	if(componentList != null && !componentList.isEmpty()){
		return componentList;
	}
	else{
		try{
			JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			String[] configFileList = getFilteredFiles(XML_CONFIG_FILES_PATH, getFileNameFilter(Messages.XMLConfigUtil_FILE_EXTENTION));
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			dbf.setExpandEntityReferences(false);
			dbf.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
			DocumentBuilder builder = dbf.newDocumentBuilder();
			for (int i = 0; i < configFileList.length; i++){
				logger.trace("Creating palette component: ", configFileList[i]);
				if(validateXMLSchema(COMPONENT_CONFIG_XSD_PATH, XML_CONFIG_FILES_PATH + SEPARATOR + configFileList[i])){
					
					Document document = builder.parse(new File(XML_CONFIG_FILES_PATH + SEPARATOR + configFileList[i]));
					Config config = (Config) unmarshaller.unmarshal(document);
					componentList.addAll(config.getComponent());
					builder.reset();
				}
			}
			validateAndFillComponentConfigList(componentList);
			return componentList;
		}catch(JAXBException | SAXException | IOException | ParserConfigurationException exception){
			Status status = new Status(IStatus.ERROR,Activator.PLUGIN_ID, "XML read failed", exception);
			StatusManager.getManager().handle(status, StatusManager.BLOCK);
			logger.error(exception.getMessage());
			throw new RuntimeException("Faild in reading XML Config files", exception); //$NON-NLS-1$
		}
	}
}
 
Example 13
Project: Hydrograph   File: XMLConfigUtil.java   View Source Code Vote up 5 votes
/**
 * Gets the policy config.
 * 
 * @return the policy config
 * @throws RuntimeException
 *             the runtime exception
 * @throws SAXException
 *             the SAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public PolicyConfig getPolicyConfig() throws RuntimeException, SAXException, IOException {
	if(policyConfig !=null){
		return policyConfig;
	}
	else{
		try{
			JAXBContext jaxbContext = JAXBContext.newInstance(PolicyConfig.class);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			dbf.setExpandEntityReferences(false);
			dbf.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
			DocumentBuilder builder = dbf.newDocumentBuilder();
			
			String[] configFileList = getFilteredFiles(CONFIG_FILES_PATH + SEPARATOR + Messages.XMLConfigUtil_POLICY, getFileNameFilter(Messages.XMLConfigUtil_FILE_EXTENTION));
			for (int i = 0; i < configFileList.length; i++) {
				if(validateXMLSchema(POLICY_CONFIG_XSD_PATH, CONFIG_FILES_PATH + SEPARATOR + Messages.XMLConfigUtil_POLICY + SEPARATOR + configFileList[i]))	{
					Document document = builder.parse(new File(CONFIG_FILES_PATH + SEPARATOR
							+ Messages.XMLConfigUtil_POLICY + SEPARATOR + configFileList[i]));
					policyConfig = (PolicyConfig) unmarshaller.unmarshal(document);
					builder.reset();
				}
			}
			return policyConfig;
		}catch(JAXBException | SAXException | IOException | ParserConfigurationException  exception){
			Status status = new Status(IStatus.ERROR,Activator.PLUGIN_ID, "XML read failed", exception);
			StatusManager.getManager().handle(status, StatusManager.BLOCK);
			logger.error(exception.getMessage());
			throw new RuntimeException("Faild in reading XML Config files", exception); //$NON-NLS-1$
		}
	}
}
 
Example 14
Project: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   View Source Code Vote up 5 votes
public static void unsafeManualConfig1() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 15
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 testCheckDocumentBuilderFactory08() throws Exception {
    try (FileInputStream fis = new FileInputStream(new File(
            XML_DIR, "DocumentBuilderFactory02.xml"))) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setExpandEntityReferences(false);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.parse(fis);
        Element e = (Element) doc.getElementsByTagName("title").item(0);
        NodeList nl = e.getChildNodes();
        assertNull(nl.item(0).getNodeValue());
    }
}
 
Example 16
Project: openjdk-jdk10   File: ElementTraversal.java   View Source Code Vote up 5 votes
Document getDoc() {
    InputStream xmlFile = getClass().getResourceAsStream("ElementTraversal.xml");
    Document doc = null;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setExpandEntityReferences(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(xmlFile);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        System.out.println("fail: " + e.getMessage());
    }

    return doc;
}
 
Example 17
Project: lazycat   File: WebdavServlet.java   View Source Code Vote up 5 votes
/**
 * Return JAXP document builder instance.
 */
protected DocumentBuilder getDocumentBuilder() throws ServletException {
	DocumentBuilder documentBuilder = null;
	DocumentBuilderFactory documentBuilderFactory = null;
	try {
		documentBuilderFactory = DocumentBuilderFactory.newInstance();
		documentBuilderFactory.setNamespaceAware(true);
		documentBuilderFactory.setExpandEntityReferences(false);
		documentBuilder = documentBuilderFactory.newDocumentBuilder();
		documentBuilder.setEntityResolver(new WebdavResolver(this.getServletContext()));
	} catch (ParserConfigurationException e) {
		throw new ServletException(sm.getString("webdavservlet.jaxpfailed"));
	}
	return documentBuilder;
}
 
Example 18
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 19
Project: incubator-netbeans   File: CslJar.java   View Source Code Vote up 4 votes
public String getModifiedLayer(InputStream is) throws BuildException {
    try {
        BufferedInputStream bis = new BufferedInputStream(is);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setExpandEntityReferences(false);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        docBuilder.setEntityResolver(new EntityResolver() {
            public org.xml.sax.InputSource resolveEntity(String pubid, String sysid) {
                return new org.xml.sax.InputSource(new ByteArrayInputStream(new byte[0]));
            }
        });

        Document doc = docBuilder.parse(bis);

        // Process
        updateLayer(doc);

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

        DOMSource source = new DOMSource(doc);
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        transformer.transform(source, result);

        // The above transform seems to drop the DOCTYPE etc. -- replace this part
        String emittedDom = sw.toString();
        String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><filesystem>"; // NOI18N
        if (emittedDom.startsWith(HEADER)) {
            emittedDom =
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + // NOI18N
                    "<!DOCTYPE filesystem PUBLIC \"-//NetBeans//DTD Filesystem 1.1//EN\" \"http://www.netbeans.org/dtds/filesystem-1_1.dtd\">\n" + // NOI18N
                    "<filesystem>" + // NOI18N
                    emittedDom.substring(HEADER.length());
        }

        return emittedDom;
    } catch (ParserConfigurationException pce) {
        throw new BuildException(pce);
    } catch (TransformerConfigurationException tce) {
        throw new BuildException(tce);
    } catch (TransformerException te) {
        throw new BuildException(te);
    } catch (SAXException se) {
        throw new BuildException("XML parsing exception - " + se.getMessage(), se);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new BuildException("IO error during CSL layer processing:" + ioe.getMessage(), ioe);
    }
}
 
Example 20
Project: joai-project   File: XMLDoc.java   View Source Code Vote up 4 votes
/**
 *  Reads and parses the XML from the given source.
 */		
private final void doParseDoc(
	InputSource xmlSource,
	boolean validating,			// does parser validate
	boolean namespaceAware,		// is parser namespace aware
	boolean expandEntities)		// expand Entity refs
throws XMLException
{
	this.doc = null;

	if (bugs >= 1)
		prtln("getXmlDoc: systemid: \"" + systemid + "\"");
	DocumentBuilderFactory factory = null;
	try {
		factory = DocumentBuilderFactory.newInstance();
	} catch (FactoryConfigurationError fce) {
		mkerror("factory config error: " + fce);
	}

	factory.setValidating(validating);
	factory.setNamespaceAware(namespaceAware);
	factory.setExpandEntityReferences(expandEntities); // expand Entity rfs

	factory.setCoalescing(true);	// convert CDATA nodes to Text nodes
	factory.setIgnoringElementContentWhitespace(true);

	DocumentBuilder bldr = null;
	try {
		bldr = factory.newDocumentBuilder();
	} catch (ParserConfigurationException pce) {
		mkerror("parser config exc: " + pce);
	}

	SimpleErrorHandler simpleErrorHandler
		= new SimpleErrorHandler(errors, warnings);
	bldr.setErrorHandler(simpleErrorHandler);

	try {
		doc = bldr.parse(xmlSource);
	} catch (IOException ioe) {
		mkerror("Could not read xml doc file \"" + systemid
			 + "\"  exc: " + ioe.getMessage());
	} catch (SAXException sxe) {
		mkerror("Could not parse xml doc file \"" + systemid
			 + "\"  exc: " + sxe.getMessage());
	}
	hasErrors = simpleErrorHandler.hasErrors();
	hasWarnings = simpleErrorHandler.hasWarnings();
	///try{
	///	xmlSource.getByteStream().close();
	///}catch(Throwable e){}
	///xmlSource = null;
}