Java Code Examples for org.xml.sax.EntityResolver

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/context/support/.

Source file: ChainedEntityResolver.java

  22 
vote

public InputSource resolveEntity(String publicId,String systemId) throws SAXException, IOException {
  boolean trace=log.isTraceEnabled();
  for (  Map.Entry<EntityResolver,String> entry : resolvers.entrySet()) {
    EntityResolver entityResolver=entry.getKey();
    if (trace)     log.trace("Trying to resolve entity [" + publicId + "|"+ systemId+ "] through resolver "+ entry.getValue());
    InputSource entity=entityResolver.resolveEntity(publicId,systemId);
    String resolvedMsg=(entity != null ? "" : "not ");
    if (trace)     log.trace("Entity [" + publicId + "|"+ systemId+ "] was "+ resolvedMsg+ "resolved through entity resolver "+ entry.getValue());
    if (entity != null) {
      return entity;
    }
  }
  return null;
}
 

Example 2

From project lenya, under directory /org.apache.lenya.core.impl/src/main/java/org/apache/lenya/xml/.

Source file: DocumentHelper.java

  22 
vote

/** 
 * Creates a non-validating and namespace-aware DocumentBuilder.
 * @return A new DocumentBuilder object.
 * @throws ParserConfigurationException if an error occurs
 */
public static DocumentBuilder createBuilder() throws ParserConfigurationException {
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder builder=factory.newDocumentBuilder();
  EntityResolver resolver=entityResolver != null ? entityResolver : new CatalogResolver();
  builder.setEntityResolver(resolver);
  return builder;
}
 

Example 3

From project logback, under directory /logback-classic/src/test/java/ch/qos/logback/classic/html/.

Source file: HTMLLayoutTest.java

  22 
vote

Document parseOutput(String output) throws Exception {
  EntityResolver resolver=new XHTMLEntityResolver();
  SAXReader reader=new SAXReader();
  reader.setValidation(true);
  reader.setEntityResolver(resolver);
  return reader.read(new ByteArrayInputStream(output.getBytes()));
}
 

Example 4

From project bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/util/.

Source file: DOMUtils.java

  21 
vote

private void setEntityResolver(DocumentBuilder builder){
  String[] resolvers=new String[]{"org.jboss.ws.core.utils.JBossWSEntityResolver","org.jboss.util.xml.JBossEntityResolver"};
  EntityResolver entityResolver=null;
  ClassLoader loader=Thread.currentThread().getContextClassLoader();
  for (  String resolver : resolvers) {
    try {
      Class<?> resolverClass=loader.loadClass(resolver);
      entityResolver=(EntityResolver)resolverClass.newInstance();
    }
 catch (    Exception ex) {
      log.debug("Cannot load: " + resolver);
    }
  }
  if (entityResolver != null)   builder.setEntityResolver(entityResolver);
}
 

Example 5

From project descriptors, under directory /test/src/test/java/org/jboss/shrinkwrap/descriptor/test/jetty7/.

Source file: Jetty7TestCase.java

  21 
vote

@Test public void testJettyConfiguration() throws Exception {
  final JettyDescriptor jetty7Generated=create().clazz("class0").id("id0").getOrCreateNew().clazz("class1").id("id1").createArg().type("type0").getOrCreateArray().type("type1").id("id2").getOrCreateItem().type("type2").id("id3").getOrCreateCall().name("name0").clazz("class2").id("id4").createRef().id("id5").createSet().name("name1").type("type3").clazz("class3").getOrCreateCall().name("name2").clazz("class4").id("id6").createProperty().name("name3")._default("default0").id("id7").createGet().name("name4").clazz("class5").id("id8").createSet().name("name5").type("type4").clazz("class6").getOrCreateRef().id("id9").createPut().name("name6").type("type5").getOrCreateGet().name("name7").clazz("class7").id("id10").createArray().type("type6").id("id11").up().up().up().up().up().up().up().up().up().up().up().up().up().up().getOrCreateGet().name("name8").clazz("class8").id("id12").createProperty().name("name9")._default("default1").id("id13").createNew().clazz("class9").id("id14").createArg().type("type7").getOrCreateGet().name("name10").clazz("class10").id("id15").createCall().name("name11").clazz("class11").id("id16").createProperty().name("name12")._default("default2").id("id17").createArray().type("type8").id("id18").up().up().up().up().up().createPut().name("name13").type("type9").getOrCreateProperty().name("name14")._default("default3").id("id19").getOrCreateGet().name("name15").clazz("class12").id("id20").createArray().type("type10").id("id21").up().up().up().up().up().up().up().up();
  String generatedJettyXml=jetty7Generated.exportAsString();
  String originalJettyXml=this.getResourceContents("src/test/resources/test-orig-jetty7.xml");
  log.fine(generatedJettyXml);
  XMLUnit.setControlEntityResolver(new EntityResolver(){
    @Override public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      log.fine("Ignoring " + publicId + ", "+ systemId);
      return new InputSource(new StringReader(""));
    }
  }
);
  XmlAssert.assertIdentical(originalJettyXml,generatedJettyXml);
}
 

Example 6

From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/util/.

Source file: XmlSerializer.java

  21 
vote

/** 
 * Get a new DOM Document object from parsing the specified InputStream.
 * @param in the InputStream to parse.
 * @return a new DOM Document object.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created.
 * @throws SAXException If any parse errors occur.
 * @throws IOException If any IO errors occur.
 */
private static Document getDocument(InputStream in) throws ParserConfigurationException, SAXException, IOException {
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder builder=factory.newDocumentBuilder();
  builder.setEntityResolver(new EntityResolver(){
    @Override public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      return new InputSource(new StringReader(""));
    }
  }
);
  return builder.parse(in);
}
 

Example 7

From project jdocbook-core, under directory /src/main/java/org/jboss/jdocbook/util/.

Source file: XIncludeHelper.java

  21 
vote

/** 
 * Given a file which defining an XML document containing XInclude elements, collect all the referenced XInclude files.
 * @param root The file which (potentially) contains XIncludes.
 * @param schemaResolutionStrategy Which DocBook schema to use.
 * @return The set of files references via XIncludes.
 */
public static Set<File> locateInclusions(File root,DocBookSchemaResolutionStrategy schemaResolutionStrategy){
  final Set<File> includes=new TreeSet<File>();
  EntityResolver entityResolver=new EntityResolver(){
    public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      if (publicId == null && systemId != null && systemId.startsWith("file:/")) {
        try {
          includes.add(new File(new URL(systemId).getFile()));
        }
 catch (        MalformedURLException e) {
          throw new JDocBookProcessException("Unable to convert reported XInclude href into URL instance [" + systemId + "]");
        }
      }
      return null;
    }
  }
;
  EntityResolverChain entityResolverChain=new EntityResolverChain(entityResolver);
  entityResolverChain.addEntityResolver(new LocalDocBookSchemaResolver(schemaResolutionStrategy));
  try {
    SAXParserFactory parserFactory=new SAXParserFactoryImpl();
    parserFactory.setXIncludeAware(true);
    Source transformationSource=FileUtils.createSAXSource(root,entityResolverChain,null);
    Result transformationResult=new StreamResult(new NoOpWriter());
    javax.xml.transform.TransformerFactory transformerFactory=new com.icl.saxon.TransformerFactoryImpl();
    transformerFactory.newTransformer().transform(transformationSource,transformationResult);
  }
 catch (  TransformerException e) {
    throw new JDocBookProcessException("Problem performing 'transformation'",e);
  }
  return includes;
}
 

Example 8

From project rundeck, under directory /core/src/main/java/com/dtolabs/shared/resources/.

Source file: ResourceXMLParser.java

  21 
vote

/** 
 * Parse the document, applying the configured Receiver to the parsed entities
 * @throws ResourceXMLParserException
 * @throws FileNotFoundException
 */
public void parse() throws ResourceXMLParserException, IOException {
  final EntityResolver resolver=createEntityResolver();
  final SAXReader reader=new SAXReader(false);
  reader.setEntityResolver(resolver);
  try {
    final InputStream in;
    if (null != file) {
      in=new FileInputStream(file);
    }
 else {
      in=input;
    }
    try {
      final Document doc=reader.read(in);
      final EntitySet set=new EntitySet();
      final Element root=doc.getRootElement();
      final List list=root.selectNodes(entityXpath);
      for (      final Object n : list) {
        final Node node=(Node)n;
        final Entity ent=parseEnt(node,set);
        if (null != receiver) {
          if (!receiver.resourceParsed(ent)) {
            break;
          }
        }
      }
      if (null != receiver) {
        receiver.resourcesParsed(set);
      }
    }
  finally {
      if (null != file) {
        in.close();
      }
    }
  }
 catch (  DocumentException e) {
    throw new ResourceXMLParserException(e);
  }
}
 

Example 9

From project saiku, under directory /saiku-bi-platform-plugin/src/main/java/org/saiku/plugin/.

Source file: PentahoConnectionRetriever.java

  21 
vote

private static DynamicContentFinder makeContentFinder(final String dataSources){
  return new DynamicContentFinder(dataSources){
    @Override public String getContent(){
      String original=super.getContent();
      EntityResolver loader=new PentahoEntityResolver();
      Document originalDocument=null;
      try {
        originalDocument=XmlDom4JHelper.getDocFromString(original,loader);
      }
 catch (      XmlParseException e) {
        LOG.error(e);
        return null;
      }
      if (LOG.isDebugEnabled()) {
        LOG.debug("Original Document:" + originalDocument.asXML());
      }
      Document modifiedDocument=(Document)originalDocument.clone();
      String modified=modifiedDocument.asXML();
      modified=modified.replaceAll("solution:","file:" + PentahoSystem.getApplicationContext().getSolutionPath(""));
      LOG.debug("MODIFIED MY" + modified);
      return modified;
    }
  }
;
}
 

Example 10

From project XcodeProjectJavaAPI, under directory /src/main/java/com/sap/prd/mobile/ios/mios/xcodeprojreader/jaxb/.

Source file: JAXBPlistParser.java

  21 
vote

private SAXSource createSAXSource(InputSource project,final InputSource dtd) throws SAXException, ParserConfigurationException {
  XMLReader xmlReader=SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  xmlReader.setEntityResolver(new EntityResolver(){
    @Override public InputSource resolveEntity(    String pid,    String sid) throws SAXException {
      if (sid.equals("http://www.apple.com/DTDs/PropertyList-1.0.dtd"))       return dtd;
      throw new SAXException("unable to resolve remote entity, sid = " + sid);
    }
  }
);
  SAXSource ss=new SAXSource(xmlReader,project);
  return ss;
}
 

Example 11

From project arquillian-core, under directory /config/impl-base/src/test/java/org/jboss/arquillian/config/descriptor/impl/.

Source file: ArquillianDescriptorTestCase.java

  20 
vote

private void validateXML(String xml) throws Exception {
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  dbf.setValidating(true);
  dbf.setNamespaceAware(true);
  dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage","http://www.w3.org/2001/XMLSchema");
  DocumentBuilder db=dbf.newDocumentBuilder();
  db.setErrorHandler(new ErrorHandler(){
    @Override public void warning(    SAXParseException exception) throws SAXException {
      throw exception;
    }
    @Override public void fatalError(    SAXParseException exception) throws SAXException {
      throw exception;
    }
    @Override public void error(    SAXParseException exception) throws SAXException {
      throw exception;
    }
  }
);
  db.setEntityResolver(new EntityResolver(){
    @Override public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      if ("http://jboss.org/schema/arquillian/arquillian_1_0.xsd".equals(systemId)) {
        return new InputSource(this.getClass().getClassLoader().getResourceAsStream("arquillian_1_0.xsd"));
      }
      return null;
    }
  }
);
  db.parse(new ByteArrayInputStream(xml.getBytes()));
}
 

Example 12

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/dbunit/dataset/xml/.

Source file: DtdResolver.java

  20 
vote

/** 
 * @param xmlFile
 * @return name of DTD file specified in the !DOCTYPE or null if not specified.
 */
public String resolveDtdLocation(final String xmlFile){
  final InputStream xmlStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFile);
  try {
    final DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver(){
      @Override public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        return new InputSource(new StringReader(""));
      }
    }
);
    final Document document=builder.parse(xmlStream);
    if (document.getDoctype() == null) {
      return null;
    }
    return document.getDoctype().getSystemId();
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to resolve dtd for " + xmlFile,e);
  }
}
 

Example 13

From project dev-examples, under directory /template/src/main/java/org/richfaces/example/.

Source file: XMLBody.java

  20 
vote

/** 
 * Load XML document and parse it into DOM.
 * @param input
 * @throws ParsingException
 */
public void loadXML(InputStream input,boolean namespaceAware) throws ParsingException {
  try {
    DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringElementContentWhitespace(true);
    docFactory.setValidating(false);
    docFactory.setNamespaceAware(namespaceAware);
    DocumentBuilder docBuilder=docFactory.newDocumentBuilder();
    docBuilder.setEntityResolver(new EntityResolver(){
      public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        return new InputSource(new StringReader(""));
      }
    }
);
    xmlDocument=docBuilder.parse(input);
    rootElement=xmlDocument.getDocumentElement();
  }
 catch (  Exception e) {
    throw new ParsingException("Error load XML ",e);
  }
}
 

Example 14

From project echo2, under directory /src/exampleapp/chatclient/src/java/echo2example/chatclient/.

Source file: XmlHttpConnection.java

  20 
vote

/** 
 * POSTs an XML message to a web service.
 * @param url the URL of the service
 * @param requestDocument the DOM document to POST
 * @return the XML response
 */
public static Document send(String url,Document requestDocument) throws IOException {
  try {
    URL u=new URL(url);
    HttpURLConnection conn=(HttpURLConnection)u.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out=conn.getOutputStream();
    TransformerFactory tFactory=TransformerFactory.newInstance();
    Transformer transformer=tFactory.newTransformer();
    DOMSource source=new DOMSource(requestDocument);
    StreamResult result=new StreamResult(out);
    transformer.transform(source,result);
    out.close();
    conn.connect();
    InputStream in=conn.getInputStream();
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder=factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver(){
      /** 
 * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,java.lang.String)
 */
      public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        throw new SAXException("External entities not supported.");
      }
    }
);
    return builder.parse(in);
  }
 catch (  ParserConfigurationException ex) {
    throw new IOException("Unable to parse response: " + ex.toString());
  }
catch (  SAXException ex) {
    throw new IOException("Unable to parse response: " + ex.toString());
  }
catch (  TransformerException ex) {
    throw new IOException("Unable to write document to OutputStream: " + ex.toString());
  }
}
 

Example 15

From project echo3, under directory /src/server-java-examples/chatclient/src/java/chatclient/.

Source file: XmlHttpConnection.java

  20 
vote

/** 
 * POSTs an XML message to a web service.
 * @param url the URL of the service
 * @param requestDocument the DOM document to POST
 * @return the XML response
 */
public static Document send(String url,Document requestDocument) throws IOException {
  try {
    URL u=new URL(url);
    HttpURLConnection conn=(HttpURLConnection)u.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out=conn.getOutputStream();
    TransformerFactory tFactory=TransformerFactory.newInstance();
    Transformer transformer=tFactory.newTransformer();
    DOMSource source=new DOMSource(requestDocument);
    StreamResult result=new StreamResult(out);
    transformer.transform(source,result);
    out.close();
    conn.connect();
    InputStream in=conn.getInputStream();
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder=factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver(){
      /** 
 * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,java.lang.String)
 */
      public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        throw new SAXException("External entities not supported.");
      }
    }
);
    return builder.parse(in);
  }
 catch (  ParserConfigurationException ex) {
    throw new IOException("Unable to parse response: " + ex.toString());
  }
catch (  SAXException ex) {
    throw new IOException("Unable to parse response: " + ex.toString());
  }
catch (  TransformerException ex) {
    throw new IOException("Unable to write document to OutputStream: " + ex.toString());
  }
}
 

Example 16

From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/readers/.

Source file: WMSServerInfo.java

  20 
vote

protected static WMSServerInfo parseCapabilities(InputStream stream) throws ParserConfigurationException, SAXException, IOException {
  DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
  documentBuilder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      return new InputSource(new StringReader(""));
    }
  }
);
  Document doc=documentBuilder.parse(stream);
  NodeList tileSets=doc.getElementsByTagName("TileSet");
  boolean isTileCache=(tileSets.getLength() > 0);
  final WMSServerInfo result=new WMSServerInfo();
  if (isTileCache) {
    result.tileCacheLayers=new HashMap<String,TileCacheLayerInfo>();
    NodeList layers=doc.getElementsByTagName("Layer");
    for (int i=0; i < tileSets.getLength(); ++i) {
      final Node tileSet=tileSets.item(i);
      final Node layer=layers.item(i + 1);
      String resolutions=DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Resolutions"));
      int width=Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Width")));
      int height=Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Height")));
      Element bbox=DOMUtil.getFirstChildElement(layer,"BoundingBox");
      float minX=Float.parseFloat(DOMUtil.getAttrValue(bbox,"minx"));
      float minY=Float.parseFloat(DOMUtil.getAttrValue(bbox,"miny"));
      float maxX=Float.parseFloat(DOMUtil.getAttrValue(bbox,"maxx"));
      float maxY=Float.parseFloat(DOMUtil.getAttrValue(bbox,"maxy"));
      String format=DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Format"));
      String layerName=DOMUtil.getChildText(DOMUtil.getFirstChildElement(layer,"Name"));
      final TileCacheLayerInfo info=new TileCacheLayerInfo(resolutions,width,height,minX,minY,maxX,maxY,format);
      result.tileCacheLayers.put(layerName,info);
    }
  }
  return result;
}
 

Example 17

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/util/.

Source file: LoggerLog4j.java

  20 
vote

/** 
 * Loads the configuration from the specified url location. A DOM configuration will be triggered if the url ends with ".xml". 
 * @param url the url of the configuration source.
 * @throws Exception if the operation is unsuccessful. 
 * @see hk.hku.cecid.piazza.commons.module.PersistentComponent#loading(java.net.URL)
 */
protected void loading(URL url) throws Exception {
  if (url.getPath().toLowerCase().endsWith(".xml")) {
    Properties params=getParameters();
    if (params != null) {
      String checkConfig=params.getProperty("checkConfig");
      if (checkConfig != null) {
        if (checkConfig.equals("true")) {
          SAXReader xmlReader=new SAXReader();
          xmlReader.setEntityResolver(new EntityResolver(){
            public InputSource resolveEntity(            String publicId,            String systemId) throws SAXException, IOException {
              return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
          }
);
          org.dom4j.Document doc=xmlReader.read(url);
          Node node=doc.selectSingleNode("/*[local-name()='configuration']/category/priority");
          String priority=node.valueOf("@value");
          if (!chechPriorityString(priority)) {
            throw new UtilitiesException("Log4j does not support the value for priority - " + priority);
          }
          String priority2=node.valueOf("@value");
          if (!chechPriorityString(priority2)) {
            throw new UtilitiesException("Log4j does not support the value for priority - " + priority2);
          }
        }
      }
    }
    DOMConfigurator.configure(url);
  }
 else {
    PropertyConfigurator.configure(url);
  }
}
 

Example 18

From project jumpnevolve, under directory /lib/slick/src/org/newdawn/slick/svg/.

Source file: InkscapeLoader.java

  20 
vote

/** 
 * Load a SVG document into a diagram
 * @param in The input stream from which to read the SVG
 * @param offset Offset the diagram for the height of the document
 * @return The diagram loaded
 * @throws SlickException Indicates a failure to process the document
 */
private Diagram loadDiagram(InputStream in,boolean offset) throws SlickException {
  try {
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);
    DocumentBuilder builder=factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver(){
      public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        return new InputSource(new ByteArrayInputStream(new byte[0]));
      }
    }
);
    Document doc=builder.parse(in);
    Element root=doc.getDocumentElement();
    String widthString=root.getAttribute("width");
    while (Character.isLetter(widthString.charAt(widthString.length() - 1))) {
      widthString=widthString.substring(0,widthString.length() - 1);
    }
    String heightString=root.getAttribute("height");
    while (Character.isLetter(heightString.charAt(heightString.length() - 1))) {
      heightString=heightString.substring(0,heightString.length() - 1);
    }
    float docWidth=Float.parseFloat(widthString);
    float docHeight=Float.parseFloat(heightString);
    diagram=new Diagram(docWidth,docHeight);
    if (!offset) {
      docHeight=0;
    }
    loadChildren(root,Transform.createTranslateTransform(0,-docHeight));
    return diagram;
  }
 catch (  Exception e) {
    throw new SlickException("Failed to load inkscape document",e);
  }
}
 

Example 19

From project logsaw-app, under directory /net.sf.logsaw.dialect.log4j/src/net/sf/logsaw/dialect/log4j/xml/.

Source file: Log4JXMLLayoutDialect.java

  20 
vote

@Override public void parse(final ILogResource log,final InputStream input,ILogEntryCollector collector) throws CoreException {
  Assert.isNotNull(log,"log");
  Assert.isNotNull(input,"input");
  Assert.isNotNull(collector,"collector");
  try {
    InputStream eventSetIS=getClass().getResourceAsStream(FILENAME_EVENTSET_XML);
    XMLReader reader=XMLReaderFactory.createXMLReader();
    XMLFilter filter=new Log4JXMLFilter(collector);
    filter.setParent(reader);
    filter.setEntityResolver(new EntityResolver(){
      @Override public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        if ((systemId != null) && systemId.toLowerCase().endsWith(FILENAME_LOG4J_DTD)) {
          InputStream is=getClass().getResourceAsStream(FILENAME_LOG4J_DTD);
          return new InputSource(is);
        }
        if ((systemId != null) && systemId.equals("%file%")) {
          InputSource src=new InputSource(input);
          IHasEncoding enc=(IHasEncoding)log.getAdapter(IHasEncoding.class);
          src.setEncoding(enc.getEncoding());
          return src;
        }
        return null;
      }
    }
);
    filter.parse(new InputSource(eventSetIS));
  }
 catch (  OperationCanceledException e) {
  }
catch (  Exception e) {
    throw new CoreException(new Status(IStatus.ERROR,Log4JDialectPlugin.PLUGIN_ID,NLS.bind(Messages.Log4JDialect_error_parsingFailed,new Object[]{log.getName(),e.getLocalizedMessage()}),e));
  }
}
 

Example 20

From project mapfish-print, under directory /src/main/java/org/mapfish/print/map/readers/.

Source file: WMSServerInfo.java

  20 
vote

protected static WMSServerInfo parseCapabilities(InputStream stream) throws ParserConfigurationException, SAXException, IOException {
  DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
  documentBuilder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      return new InputSource(new StringReader(""));
    }
  }
);
  Document doc=documentBuilder.parse(stream);
  NodeList tileSets=doc.getElementsByTagName("TileSet");
  boolean isTileCache=(tileSets.getLength() > 0);
  final WMSServerInfo result=new WMSServerInfo();
  if (isTileCache) {
    result.tileCacheLayers=new HashMap<String,TileCacheLayerInfo>();
    NodeList layers=doc.getElementsByTagName("Layer");
    for (int i=0; i < tileSets.getLength(); ++i) {
      final Node tileSet=tileSets.item(i);
      final Node layer=layers.item(i + 1);
      String resolutions=DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Resolutions"));
      int width=Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Width")));
      int height=Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Height")));
      Element bbox=DOMUtil.getFirstChildElement(layer,"BoundingBox");
      float minX=Float.parseFloat(DOMUtil.getAttrValue(bbox,"minx"));
      float minY=Float.parseFloat(DOMUtil.getAttrValue(bbox,"miny"));
      float maxX=Float.parseFloat(DOMUtil.getAttrValue(bbox,"maxx"));
      float maxY=Float.parseFloat(DOMUtil.getAttrValue(bbox,"maxy"));
      String format=DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Format"));
      String layerName=DOMUtil.getChildText(DOMUtil.getFirstChildElement(layer,"Name"));
      final TileCacheLayerInfo info=new TileCacheLayerInfo(resolutions,width,height,minX,minY,maxX,maxY,format);
      result.tileCacheLayers.put(layerName,info);
    }
  }
  return result;
}
 

Example 21

From project mapfish-print_1, under directory /src/main/java/org/mapfish/print/map/readers/.

Source file: WMSServerInfo.java

  20 
vote

protected static WMSServerInfo parseCapabilities(InputStream stream) throws ParserConfigurationException, SAXException, IOException {
  DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
  documentBuilder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity(    String publicId,    String systemId) throws SAXException, IOException {
      return new InputSource(new StringReader(""));
    }
  }
);
  Document doc=documentBuilder.parse(stream);
  NodeList tileSets=doc.getElementsByTagName("TileSet");
  boolean isTileCache=(tileSets.getLength() > 0);
  final WMSServerInfo result=new WMSServerInfo();
  if (isTileCache) {
    result.tileCacheLayers=new HashMap<String,TileCacheLayerInfo>();
    NodeList layers=doc.getElementsByTagName("Layer");
    for (int i=0; i < tileSets.getLength(); ++i) {
      final Node tileSet=tileSets.item(i);
      final Node layer=layers.item(i + 1);
      String resolutions=DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Resolutions"));
      int width=Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Width")));
      int height=Integer.parseInt(DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Height")));
      Element bbox=DOMUtil.getFirstChildElement(layer,"BoundingBox");
      float minX=Float.parseFloat(DOMUtil.getAttrValue(bbox,"minx"));
      float minY=Float.parseFloat(DOMUtil.getAttrValue(bbox,"miny"));
      float maxX=Float.parseFloat(DOMUtil.getAttrValue(bbox,"maxx"));
      float maxY=Float.parseFloat(DOMUtil.getAttrValue(bbox,"maxy"));
      String format=DOMUtil.getChildText(DOMUtil.getFirstChildElement(tileSet,"Format"));
      String layerName=DOMUtil.getChildText(DOMUtil.getFirstChildElement(layer,"Name"));
      final TileCacheLayerInfo info=new TileCacheLayerInfo(resolutions,width,height,minX,minY,maxX,maxY,format);
      result.tileCacheLayers.put(layerName,info);
    }
  }
  return result;
}
 

Example 22

From project org.openscada.external, under directory /org.openscada.external.jOpenDocument/src/org/jopendocument/dom/.

Source file: OOUtils.java

  20 
vote

/** 
 * Return a builder who doesn't load DTD.
 * @return a builder who doesn't load DTD.
 */
static public SAXBuilder getBuilder(){
  SAXBuilder builder=new SAXBuilder();
  builder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity(    String publicId,    String systemId){
      if (systemId.endsWith(".dtd")) {
        InputSource in=new InputSource();
        in.setCharacterStream(new StringReader(""));
        return in;
      }
 else       return null;
    }
  }
);
  return builder;
}
 

Example 23

From project pluto, under directory /pluto-util/src/main/java/org/apache/pluto/util/descriptors/web/.

Source file: PlutoWebXmlRewriter.java

  20 
vote

protected static Document parseXml(InputStream source) throws Exception {
  DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
  domFactory.setNamespaceAware(true);
  DocumentBuilder builder=domFactory.newDocumentBuilder();
  builder.setEntityResolver(new EntityResolver(){
    public InputSource resolveEntity(    java.lang.String publicId,    java.lang.String systemId) throws SAXException, java.io.IOException {
      if (systemId.equals("http://java.sun.com/dtd/web-app_2_3.dtd")) {
        return new InputSource(getClass().getResourceAsStream("web-app_2_3.dtd"));
      }
      return null;
    }
  }
);
  Document document=builder.parse(source);
  return document;
}
 

Example 24

From project rapid, under directory /rapid-generator/rapid-generator/src/main/java/cn/org/rapid_framework/generator/util/.

Source file: XMLHelper.java

  20 
vote

static Document getLoadingDoc(InputStream in) throws SAXException, IOException {
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  dbf.setIgnoringElementContentWhitespace(false);
  dbf.setValidating(false);
  dbf.setCoalescing(false);
  dbf.setIgnoringComments(false);
  try {
    DocumentBuilder db=dbf.newDocumentBuilder();
    db.setEntityResolver(new EntityResolver(){
      public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        InputSource is=new InputSource(new StringReader(""));
        is.setSystemId(systemId);
        return is;
      }
    }
);
    InputSource is=new InputSource(in);
    return db.parse(is);
  }
 catch (  ParserConfigurationException x) {
    throw new Error(x);
  }
}
 

Example 25

From project sitebricks, under directory /sitebricks/src/main/java/com/google/sitebricks/compiler/.

Source file: XmlTemplateCompiler.java

  20 
vote

public Renderable compile(Class<?> page,Template template){
  PageCompilingContext pc=new PageCompilingContext();
  pc.page=page;
  pc.template=template;
  pc.lexicalScopes.push(new MvelEvaluatorCompiler(page));
  WidgetChain widgetChain;
  try {
    final SAXReader reader=new SAXReader();
    reader.setMergeAdjacentText(true);
    reader.setXMLFilter(Dom.newLineNumberFilter());
    reader.setValidation(false);
    reader.setIncludeExternalDTDDeclarations(true);
    reader.setEntityResolver(new EntityResolver(){
      public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        if (systemId.contains(".dtd")) {
          return new InputSource(new StringReader(""));
        }
 else {
          return null;
        }
      }
    }
);
    widgetChain=walk(pc,reader.read(new StringReader(template.getText())));
  }
 catch (  DocumentException e) {
    pc.errors.add(CompileError.in(template.getText()).near(0).causedBy(CompileErrors.MALFORMED_TEMPLATE));
    metrics.logErrorsAndWarnings(page,pc.errors,pc.warnings);
    throw new TemplateParseException(e);
  }
  if (!pc.errors.isEmpty() || !pc.warnings.isEmpty()) {
    metrics.logErrorsAndWarnings(page,pc.errors,pc.warnings);
    if (!pc.errors.isEmpty()) {
      throw new TemplateCompileException(page,template.getText(),pc.errors,pc.warnings);
    }
  }
  return widgetChain;
}
 

Example 26

From project cdk, under directory /xinclude/src/main/java/org/apache/cocoon/pipeline/component/xpointer/.

Source file: XPointerContext.java

  19 
vote

public XPointerContext(String xPointer,InputSource source,SAXConsumer xmlConsumer,EntityResolver resolver,Logger log){
  this.xPointer=xPointer;
  this.source=source;
  this.xmlConsumer=xmlConsumer;
  this.resolver=resolver;
  this.logger=log;
}
 

Example 27

From project ha-jdbc, under directory /src/test/java/net/sf/hajdbc/xml/.

Source file: PropertyReplacementFilterTest.java

  19 
vote

@Before public void before(){
  this.contentHandler=mock(ContentHandler.class);
  this.dtdHandler=mock(DTDHandler.class);
  this.errorHandler=mock(ErrorHandler.class);
  this.resolver=mock(EntityResolver.class);
  this.parent=mock(XMLReader.class);
  Properties properties=new Properties();
  properties.setProperty("existing","Release");
  this.filter=new PropertyReplacementFilter(this.parent,properties);
  this.filter.setContentHandler(this.contentHandler);
  this.filter.setDTDHandler(this.dtdHandler);
  this.filter.setEntityResolver(this.resolver);
  this.filter.setErrorHandler(this.errorHandler);
}
 

Example 28

From project hibernate-tools, under directory /src/java/org/hibernate/tool/ant/.

Source file: ConfigurationTask.java

  19 
vote

/** 
 */
protected void doConfiguration(Configuration configuration){
  validateParameters();
  if (entityResolver != null) {
    try {
      Class resolver=ReflectHelper.classForName(entityResolver,this.getClass());
      Object object=resolver.newInstance();
      configuration.setEntityResolver((EntityResolver)object);
      getProject().log("Using " + entityResolver + " as entity resolver");
    }
 catch (    Exception e) {
      throw new BuildException("Could not create or find " + entityResolver + " class to use for entity resolvement");
    }
  }
  if (namingStrategy != null) {
    try {
      Class resolver=ReflectHelper.classForName(namingStrategy,this.getClass());
      Object object=resolver.newInstance();
      configuration.setNamingStrategy((NamingStrategy)object);
      getProject().log("Using " + namingStrategy + " as naming strategy");
    }
 catch (    Exception e) {
      throw new BuildException("Could not create or find " + namingStrategy + " class to use for naming strategy");
    }
  }
  if (configurationFile != null)   configuration.configure(configurationFile);
  addMappings(getFiles());
  Properties p=getProperties();
  if (p != null) {
    Properties overrides=new Properties();
    overrides.putAll(configuration.getProperties());
    overrides.putAll(p);
    configuration.setProperties(overrides);
  }
}
 

Example 29

From project interoperability-framework, under directory /interfaces/web/generic-soap-client/src/main/java/eu/impact_project/wsclient/generic/util/.

Source file: XsdAnnotationParser.java

  19 
vote

@Override public ContentHandler getContentHandler(AnnotationContext context,String parentElementName,ErrorHandler handler,EntityResolver resolver){
  return new ContentHandler(){
    private boolean parsingDocumentation=false;
    @Override public void characters(    char[] ch,    int start,    int length) throws SAXException {
      if (parsingDocumentation) {
        documentation.append(ch,start,length);
      }
    }
    @Override public void endElement(    String uri,    String localName,    String name) throws SAXException {
      if (localName.equals("documentation")) {
        parsingDocumentation=false;
      }
    }
    @Override public void startElement(    String uri,    String localName,    String name,    Attributes atts) throws SAXException {
      if (localName.equals("documentation")) {
        parsingDocumentation=true;
      }
    }
    @Override public void endDocument() throws SAXException {
    }
    @Override public void endPrefixMapping(    String prefix) throws SAXException {
    }
    @Override public void ignorableWhitespace(    char[] ch,    int start,    int length) throws SAXException {
    }
    @Override public void processingInstruction(    String target,    String data) throws SAXException {
    }
    @Override public void setDocumentLocator(    Locator locator){
    }
    @Override public void skippedEntity(    String name) throws SAXException {
    }
    @Override public void startDocument() throws SAXException {
    }
    @Override public void startPrefixMapping(    String prefix,    String uri) throws SAXException {
    }
  }
;
}
 

Example 30

From project jOryx_1, under directory /src/org/jdom/transform/.

Source file: XSLTransformer.java

  19 
vote

/** 
 * Transforms the given document to an output document.
 * @param inputDoc            input document
 * @param resolver			   entity resolver for the input document
 * @return                     transformed output document
 * @throws XSLTransformException       if there's a problem in the transformation
 */
public Document transform(Document inputDoc,EntityResolver resolver) throws XSLTransformException {
  JDOMSource source=new JDOMSource(inputDoc,resolver);
  JDOMResult result=new JDOMResult();
  result.setFactory(factory);
  try {
    templates.newTransformer().transform(source,result);
    return result.getDocument();
  }
 catch (  TransformerException e) {
    throw new XSLTransformException("Could not perform transformation",e);
  }
}
 

Example 31

From project movsim, under directory /core/src/main/java/org/movsim/input/.

Source file: XmlReaderSimInput.java

  19 
vote

/** 
 * Gets the Document.
 * @param inputSource the input source
 * @return the document
 */
private Document getDocument(final InputSource inputSource){
  final Document doc=(Document)AccessController.doPrivileged(new PrivilegedAction<Object>(){
    @Override public Object run(){
      try {
        final SAXBuilder builder=new SAXBuilder();
        builder.setIgnoringElementContentWhitespace(true);
        builder.setEntityResolver(new EntityResolver(){
          @Override public InputSource resolveEntity(          String publicId,          String systemId) throws SAXException, IOException {
            final InputStream is=XmlReaderSimInput.class.getResourceAsStream(dtdFilename);
            final InputSource input=new InputSource(is);
            return input;
          }
        }
);
        final Document document=builder.build(inputSource);
        return document;
      }
 catch (      final JDOMException e) {
        e.printStackTrace();
        System.exit(-1);
        return null;
      }
catch (      final Exception e) {
        e.printStackTrace();
        return null;
      }
    }
  }
);
  return doc;
}
 

Example 32

From project phing-eclipse, under directory /org.ganoro.phing.ui/src/org/ganoro/phing/ui/internal/dtd/.

Source file: Parser.java

  19 
vote

/** 
 * Parse the XML document at the input source and return a document walker that can be used to validate any document with the same DTD (internal and external) or provide user assistance for this document.
 * @param inputSource Source for XML document to start DTD parse. Mustcontain a DOCTYPE declaration with internal or external subset, or both.
 * @param entityResolver EntityResolver or null.
 * @return schema for document.
 * @throws ParseError for NOT_SUPPORTED or PARSE_ERROR.
 * @throws IOException
 */
public ISchema parse(InputSource inputSource,EntityResolver entityResolver) throws ParseError, IOException {
  XMLReader parser=null;
  SchemaFactory factory=new SchemaFactory();
  try {
    parser=getXMLReader();
    DeclHandler handler=factory;
    parser.setProperty("http://xml.org/sax/properties/declaration-handler",handler);
    if (entityResolver != null) {
      parser.setEntityResolver(entityResolver);
    }
    parser.parse(inputSource);
  }
 catch (  SAXNotRecognizedException e) {
    throw new ParseError(NOT_SUPPORTED);
  }
catch (  SAXNotSupportedException e) {
    throw new ParseError(NOT_SUPPORTED);
  }
catch (  SAXException e) {
    factory.setErrorException(e);
  }
  return factory.getSchema();
}
 

Example 33

From project scufl2, under directory /scufl2-ucfpackage/src/main/java/uk/org/taverna/scufl2/ucfpackage/impl/odfdom/pkg/.

Source file: OdfPackage.java

  19 
vote

/** 
 * Get EntityResolver to be used in XML Parsers which can resolve content inside the OdfPackage
 * @return a SAX EntityResolver
 */
public EntityResolver getEntityResolver(){
  if (mResolver == null) {
    mResolver=new Resolver();
  }
  return mResolver;
}
 

Example 34

From project spring-migration-analyzer, under directory /contributions/src/main/java/org/springframework/migrationanalyzer/contributions/xml/.

Source file: StandardXmlArtifactAnalyzer.java

  19 
vote

private Document getDocument(InputStream inputStream,EntityResolver entityResolver) throws AnalysisFailedException {
  DocumentBuilderFactory xmlFact=DocumentBuilderFactory.newInstance();
  xmlFact.setNamespaceAware(isNamespaceAware());
  DocumentBuilder builder;
  try {
    builder=xmlFact.newDocumentBuilder();
    if (entityResolver != null) {
      builder.setEntityResolver(entityResolver);
    }
    return builder.parse(new InputSource(inputStream));
  }
 catch (  ParserConfigurationException e) {
    throw new AnalysisFailedException(e);
  }
catch (  SAXException e) {
    throw new AnalysisFailedException(e);
  }
catch (  IOException e) {
    throw new AnalysisFailedException(e);
  }
}