List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver
public abstract void setEntityResolver(EntityResolver er);
From source file:org.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetriever.java
/** * @return Document for the specified InputStream */// www . ja v a2s . c o m private Document getDocument(InputStream aStream) { Document doc; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder db = factory.newDocumentBuilder(); db.setEntityResolver(new MyEntityResolver()); doc = db.parse(aStream); return doc; } catch (FactoryConfigurationError e) { throw new RuntimeException("Unable to parse document object", e); } catch (ParserConfigurationException e) { throw new RuntimeException("Unable to parse document object", e); } catch (SAXException e) { throw new RuntimeException("Unable to parse document object", e); } catch (IOException e) { throw new RuntimeException("Unable to parse document object", e); } finally { try { aStream.close(); } catch (IOException e) { logger.warn("Failed to close input stream for portlet.xml", e); } } }
From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParserTest.java
private DocumentBuilder initDocumentBuilder() throws Exception { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { @Override//from ww w . j av a2s . c om public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }); return db; }
From source file:com.adaptris.util.text.xml.XsltTransformerFactory.java
public Transformer createTransformer(String url, EntityResolver entityResolver) throws Exception { DocumentBuilder docBuilder = documentFactoryBuilder() .newDocumentBuilder(DocumentBuilderFactory.newInstance()); if (entityResolver != null) { docBuilder.setEntityResolver(entityResolver); }//from w ww . ja va2 s.com Document xmlDoc = docBuilder.parse(new InputSource(url)); return configure(newInstance()).newTransformer(new DOMSource(xmlDoc, url)); }
From source file:co.id.app.sys.util.StringUtils.java
/** * Return a new XML Document for the given input stream and XML entity * resolver.// w ww. j a v a 2 s . co m * * @param inputStream the input stream * @param entityResolver the XML entity resolver * @return new XML Document * @throws RuntimeException if a parsing error occurs */ public static Document buildDocument(InputStream inputStream, EntityResolver entityResolver) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); if (entityResolver != null) { builder.setEntityResolver(entityResolver); } return builder.parse(inputStream); } catch (Exception ex) { throw new RuntimeException("Error parsing XML", ex); } }
From source file:com.icesoft.jasper.xmlparser.ParserUtils.java
/** * Parse the specified XML document, and return a <code>TreeNode</code> that * corresponds to the root node of the document tree. * * @param uri URI of the XML document being parsed * @param is Input stream containing the deployment descriptor * @throws JasperException if an input/output error occurs * @throws JasperException if a parsing error occurs *//* w w w . j a v a 2 s.co m*/ public TreeNode parseXMLDocument(String uri, InputStream is) throws JasperException { Document document = null; // Perform an XML parse of this document, via JAXP try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(validating); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(errorHandler); document = builder.parse(is); } catch (ParserConfigurationException ex) { throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), ex); } catch (SAXParseException ex) { throw new JasperException(Localizer.getMessage("jsp.error.parse.xml.line", uri, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex); } catch (SAXException sx) { if (log.isErrorEnabled()) { log.error("XML parsing failed for " + uri + "SAXException: " + sx.getMessage()); } throw new JasperException( Localizer.getMessage("jsp.error.parse.xml", uri) + "SAXException: " + sx.getMessage(), sx); } catch (IOException io) { throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), io); } // Convert the resulting document to a graph of TreeNodes return (convert(null, document.getDocumentElement())); }
From source file:XMLBody.java
/** * Load XML document and parse it into DOM. * /*from ww w.j a v a2 s . co m*/ * @param input * @throws ParsingException */ public void loadXML(InputStream input) throws Exception { try { // Create Document Builder Factory DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setValidating(false); // Create Document Builder DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); docBuilder.isValidating(); // Disable loading of external Entityes docBuilder.setEntityResolver(new EntityResolver() { // Dummi resolver - alvays do nothing public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }); // open and parse XML-file xmlDocument = docBuilder.parse(input); // Get Root xmlElement rootElement = xmlDocument.getDocumentElement(); } catch (Exception e) { throw new Exception("Error load XML ", e); } }
From source file:org.ambraproject.service.XMLServiceImpl.java
/** * Convenience method to create a DocumentBuilder with the factory configs * * @return Document Builder/*from w ww . j a v a2 s. c o m*/ * @throws javax.xml.parsers.ParserConfigurationException */ public DocumentBuilder createDocBuilder() throws ParserConfigurationException { // Create the builder and parse the file final DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(CachedSource.getResolver()); return builder; }
From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java
@Override public InputStream generateHibernateMapping() { if (resolver == null) { throw new IllegalStateException("Expected table resolver to be set before this method is called."); }//from w w w . j a va2 s. c om try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setExpandEntityReferences(false); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); documentBuilder.setEntityResolver(HibernateStorage.ENTITY_RESOLVER); Document document = documentBuilder .parse(this.getClass().getResourceAsStream(HIBERNATE_MAPPING_TEMPLATE)); MappingGenerator mappingGenerator = getMappingGenerator(document, resolver); for (Map.Entry<String, Class<? extends Wrapper>> classNameToClass : registeredClasses.entrySet()) { ComplexTypeMetadata typeMetadata = knownTypes.get(classNameToClass.getKey()); if (typeMetadata != null && typeMetadata.getSuperTypes().isEmpty()) { Element classElement = typeMetadata.accept(mappingGenerator); if (classElement != null) { // Class element might be null if mapping is not applicable for this type document.getDocumentElement().appendChild(classElement); } } } return toInputStream(document); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:demo.SourceHttpMessageConverter.java
private DOMSource readDOMSource(InputStream body) throws IOException { try {//from ww w. j av a 2 s . c o m DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); if (!isProcessExternalEntities()) { documentBuilder.setEntityResolver(NO_OP_ENTITY_RESOLVER); } Document document = documentBuilder.parse(body); return new DOMSource(document); } catch (ParserConfigurationException ex) { throw new HttpMessageNotReadableException("Could not set feature: " + ex.getMessage(), ex); } catch (SAXException ex) { throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex); } }
From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java
public Document generateHibernateConfiguration(RDBMSDataSource rdbmsDataSource) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);// w w w . j a v a 2 s .co m factory.setExpandEntityReferences(false); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); documentBuilder.setEntityResolver(HibernateStorage.ENTITY_RESOLVER); Document document = documentBuilder .parse(DefaultStorageClassLoader.class.getResourceAsStream(HIBERNATE_CONFIG_TEMPLATE)); String connectionUrl = rdbmsDataSource.getConnectionURL(); String userName = rdbmsDataSource.getUserName(); String driverClass = rdbmsDataSource.getDriverClassName(); RDBMSDataSource.DataSourceDialect dialectType = rdbmsDataSource.getDialectName(); String dialect = getDialect(dialectType); String password = rdbmsDataSource.getPassword(); String indexBase = rdbmsDataSource.getIndexDirectory(); int connectionPoolMinSize = rdbmsDataSource.getConnectionPoolMinSize(); int connectionPoolMaxSize = rdbmsDataSource.getConnectionPoolMaxSize(); if (connectionPoolMaxSize == 0) { LOGGER.info("No value provided for property connectionPoolMaxSize of datasource " //$NON-NLS-1$ + rdbmsDataSource.getName() + ". Using default value: " //$NON-NLS-1$ + RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT); connectionPoolMaxSize = RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT; } setPropertyValue(document, "hibernate.connection.url", connectionUrl); //$NON-NLS-1$ setPropertyValue(document, "hibernate.connection.username", userName); //$NON-NLS-1$ setPropertyValue(document, "hibernate.connection.driver_class", driverClass); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dialect", dialect); //$NON-NLS-1$ setPropertyValue(document, "hibernate.connection.password", password); //$NON-NLS-1$ // Sets up DBCP pool features setPropertyValue(document, "hibernate.dbcp.initialSize", String.valueOf(connectionPoolMinSize)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxActive", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxIdle", String.valueOf(10)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxTotal", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$ setPropertyValue(document, "hibernate.dbcp.maxWaitMillis", "60000"); //$NON-NLS-1$ //$NON-NLS-2$ Node sessionFactoryElement = document.getElementsByTagName("session-factory").item(0); //$NON-NLS-1$ if (rdbmsDataSource.supportFullText()) { /* <property name="hibernate.search.default.directory_provider" value="filesystem"/> <property name="hibernate.search.default.indexBase" value="/var/lucene/indexes"/> */ addProperty(document, sessionFactoryElement, "hibernate.search.default.directory_provider", //$NON-NLS-1$ "filesystem"); //$NON-NLS-1$ addProperty(document, sessionFactoryElement, "hibernate.search.default.indexBase", //$NON-NLS-1$ indexBase + '/' + storageName); addProperty(document, sessionFactoryElement, "hibernate.search.default.sourceBase", //$NON-NLS-1$ indexBase + '/' + storageName); addProperty(document, sessionFactoryElement, "hibernate.search.default.source", ""); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "hibernate.search.default.exclusive_index_use", "false"); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "hibernate.search.lucene_version", "LUCENE_CURRENT"); //$NON-NLS-1$ //$NON-NLS-2$ } else { addProperty(document, sessionFactoryElement, "hibernate.search.autoregister_listeners", "false"); //$NON-NLS-1$ //$NON-NLS-2$ } if (dataSource.getCacheDirectory() != null && !dataSource.getCacheDirectory().isEmpty()) { /* <!-- Second level cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property> */ addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "hibernate.cache.provider_class", //$NON-NLS-1$ "net.sf.ehcache.hibernate.EhCacheProvider"); //$NON-NLS-1$ addProperty(document, sessionFactoryElement, "hibernate.cache.use_query_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$ addProperty(document, sessionFactoryElement, "net.sf.ehcache.configurationResourceName", "ehcache.xml"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Hibernate configuration does not define second level cache extensions due to datasource configuration."); //$NON-NLS-1$ } addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "false"); //$NON-NLS-1$ //$NON-NLS-2$ } // Override default configuration with values from configuration Map<String, String> advancedProperties = rdbmsDataSource.getAdvancedProperties(); for (Map.Entry<String, String> currentAdvancedProperty : advancedProperties.entrySet()) { setPropertyValue(document, currentAdvancedProperty.getKey(), currentAdvancedProperty.getValue()); } // Order of elements highly matters and mapping shall be declared after <property/> and before <event/>. Element mapping = document.createElement("mapping"); //$NON-NLS-1$ Attr resource = document.createAttribute("resource"); //$NON-NLS-1$ resource.setValue(HIBERNATE_MAPPING); mapping.getAttributes().setNamedItem(resource); sessionFactoryElement.appendChild(mapping); if (rdbmsDataSource.supportFullText()) { addEvent(document, sessionFactoryElement, "post-update", //$NON-NLS-1$ "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$ addEvent(document, sessionFactoryElement, "post-insert", //$NON-NLS-1$ "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$ addEvent(document, sessionFactoryElement, "post-delete", //$NON-NLS-1$ "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$ } else if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Hibernate configuration does not define full text extensions due to datasource configuration."); //$NON-NLS-1$ } return document; }