org.xml.sax.EntityResolver类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(13.3k)|赞(0)|评价(0)|浏览(174)

本文整理了Java中org.xml.sax.EntityResolver类的一些代码示例,展示了EntityResolver类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。EntityResolver类的具体详情如下:
包路径:org.xml.sax.EntityResolver
类名称:EntityResolver

EntityResolver介绍

[英]Basic interface for resolving entities. This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY. See http://www.saxproject.org for further information.

If a SAX application needs to implement customized handling for external entities, it must implement this interface and register an instance with the SAX driver using the org.xml.sax.XMLReader#setEntityResolvermethod.

The XML reader will then allow the application to intercept any external entities (including the external DTD subset and external parameter entities, if any) before including them.

Many SAX applications will not need to implement this interface, but it will be especially useful for applications that build XML documents from databases or other specialised input sources, or for applications that use URI types other than URLs.

The following resolver would provide the application with a special character stream for the entity with the system identifier "http://www.myhost.com/today":

import org.xml.sax.EntityResolver; 
import org.xml.sax.InputSource; 
public class MyResolver implements EntityResolver { 
public InputSource resolveEntity (String publicId, String systemId) 
{ 
if (systemId.equals("http://www.myhost.com/today")) { 
// return a special input source 
MyReader reader = new MyReader(); 
return new InputSource(reader); 
} else { 
// use the default behaviour 
return null; 
} 
} 
}

The application can also use this interface to redirect system identifiers to local URIs or to look up replacements in a catalog (possibly by using the public identifier).
[中]用于解析实体的基本接口*此模块(包括源代码和文档)属于公共领域,不提供任何保修。*详见http://www.saxproject.org
如果SAX应用程序需要实现对外部实体的定制处理,它必须实现此接口,并使用org向SAX驱动程序注册一个实例。xml。萨克斯。XMLReader#SetEntityResolveMethod。
然后,XML读取器将允许应用程序在包含任何外部实体(包括外部DTD子集和外部参数实体,如果有的话)之前拦截它们。
许多SAX应用程序不需要实现此接口,但对于从数据库或其他专用输入源构建XML文档的应用程序,或者对于使用URL以外的URI类型的应用程序,它将特别有用。
以下解析器将为应用程序提供具有系统标识符的实体的特殊字符流“http://www.myhost.com/today":

import org.xml.sax.EntityResolver; 
import org.xml.sax.InputSource; 
public class MyResolver implements EntityResolver { 
public InputSource resolveEntity (String publicId, String systemId) 
{ 
if (systemId.equals("http://www.myhost.com/today")) { 
// return a special input source 
MyReader reader = new MyReader(); 
return new InputSource(reader); 
} else { 
// use the default behaviour 
return null; 
} 
} 
}

应用程序还可以使用此接口将系统标识符重定向到本地URI或在目录中查找替换项(可能通过使用公共标识符)。

代码示例

代码示例来源:origin: robovm/robovm

InputSource inputSource = entityResolver.resolveEntity(
    publicId, systemId);
if (inputSource == null) {
try {
  EntityParser entityParser = new EntityParser(encoding, xmlReader,
      pointer, inputSource.getPublicId(),
      inputSource.getSystemId());

代码示例来源:origin: nu.validator/htmlparser

/**
 * @param is
 * @throws SAXException
 * @throws IOException
 * @throws MalformedURLException
 */
private void tokenize(InputSource is) throws SAXException, IOException, MalformedURLException {
  if (is == null) {
    throw new IllegalArgumentException("Null input.");            
  }
  if (is.getByteStream() == null && is.getCharacterStream() == null) {
    String systemId = is.getSystemId();
    if (systemId == null) {
      throw new IllegalArgumentException("No byte stream, no character stream nor URI.");
    }
    if (entityResolver != null) {
      is = entityResolver.resolveEntity(is.getPublicId(), systemId);
    }
    if (is.getByteStream() == null || is.getCharacterStream() == null) {
      is = new InputSource();
      is.setSystemId(systemId);
      is.setByteStream(new URL(systemId).openStream());
    }
  }
  driver.tokenize(is);
}

代码示例来源:origin: com.sun.xml.ws/rt

public Parser resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    InputSource source = core.resolveEntity(publicId,systemId);
    if(source==null)
      return null;    // default

    // ideally entity resolvers should be giving us the system ID for the resource
    // (or otherwise we won't be able to resolve references within this imported WSDL correctly),
    // but if none is given, the system ID before the entity resolution is better than nothing.
    if(source.getSystemId()!=null)
      systemId = source.getSystemId();

    URL url = new URL(systemId);
    InputStream stream;
    if (useStreamFromEntityResolver) {
      stream = source.getByteStream();
    } else {
      stream = url.openStream();
    }
    return new Parser(url,
        new TidyXMLStreamReader(XMLStreamReaderFactory.create(url.toExternalForm(), stream, true), stream));
  }
}

代码示例来源:origin: com.sun.xml.dtd-parser/dtd-parser

/**
 * Parse a DTD.
 */
public void parse(String uri)
    throws IOException, SAXException {
  InputSource inSource;
  init();
  // System.out.println ("parse (\"" + uri + "\")");
  inSource = resolver.resolveEntity(null, uri);
  // If custom resolver punts resolution to parser, handle it ...
  if (inSource == null) {
    inSource = Resolver.createInputSource(new java.net.URL(uri), false);
    // ... or if custom resolver doesn't correctly construct the
    // input entity, patch it up enough so relative URIs work, and
    // issue a warning to minimize later confusion.
  } else if (inSource.getSystemId() == null) {
    warning("P-065", null);
    inSource.setSystemId(uri);
  }
  parseInternal(inSource);
}

代码示例来源:origin: com.sun.xml.bind/jaxb-extra-osgi

public InputSource getInputSource (EntityResolver r)
            throws IOException, SAXException {

    InputSource    retval;
  
    retval = r.resolveEntity (publicId, systemId);
    // SAX sez if null is returned, use the URI directly
    if (retval == null)
      retval = Resolver.createInputSource (new URL (systemId), false);
    return retval;
  }
}

代码示例来源:origin: com.thaiopensource/jing

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
  if (BootstrapResolver.xmlCatalogPubId.equals(publicId)
    || BootstrapResolver.xmlCatalogSysId.equals(systemId)) {
   URL url = BootstrapResolver.class.getResource("/org/apache/xml/resolver/etc/catalog.dtd");
   if (url != null) {
    InputSource in = new InputSource(url.toString());
    // Avoid any weirdness the parser may perform on URLs
    in.setByteStream(url.openStream());
    in.setPublicId(publicId);
    return in;
   }
  }
  if (entityResolver != null)
   return entityResolver.resolveEntity(publicId, systemId);
  return null;
 }
}

代码示例来源:origin: org.codehaus.woodstox/woodstox-core-asl

URL url = new URL(baseURI);
String ref = new URL(url, systemID).toExternalForm();
InputSource isrc = mEntityResolver.resolveEntity(publicID, ref);
if (isrc != null) {
  InputStream in = isrc.getByteStream();
  if (in != null) {
    return in;
  Reader r = isrc.getCharacterStream();
  if (r != null) {
    return r;

代码示例来源:origin: org.apache.xmlbeans/xmlbeans

try
    source = resolver.resolveEntity(namespace, absoluteURL);
    Reader reader = source.getCharacterStream();
    if (reader != null)
    InputStream bytes = source.getByteStream();
    if (bytes != null)
      String encoding = source.getEncoding();
      XmlOptions options = new XmlOptions();
      options.setLoadLineNumbers();
    options.setLoadMessageDigest();
    options.setDocumentSourceName(absoluteURL);
    URL urlDownload = new URL(urlToLoad);
    return loader.parse(urlDownload, null, options);
options.setLoadLineNumbers();
options.setLoadMessageDigest();
URL urlDownload = new URL(absoluteURL);

代码示例来源:origin: org.apache.cxf/cxf-rt-core

@Override
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    InputSource source = super.resolveEntity(publicId, systemId);
    if (null == source && null != systemId) {
      // try the schema and dtd resolver in turn, ignoring the suffix in publicId
      LOG.log(Level.FINE, "Attempting to resolve systemId {0}", systemId);
      source = schemaResolver.resolveEntity(publicId, systemId);                
      if (null == source) {
        source = dtdResolver.resolveEntity(publicId, systemId); 
      }
    }
    String resourceLocation = schemaMappings.get(systemId);
    if (resourceLocation != null && publicId == null) {
      Resource resource = new ClassPathResource(resourceLocation, classLoader);
      if (resource != null && resource.exists()) {
        source.setPublicId(systemId);    
        source.setSystemId(resource.getURL().toString());
      }
    }
    return source;
  }    
}

代码示例来源:origin: geotools/geotools

/**
 * Delegate to {@link #entityResolver} if available.
 *
 * <p>
 *
 * <p>Note this is an XMLSchema based parser, all attempts to resolved DTDs are rejected.
 *
 * @param publicId The public identifier, or null if none is available.
 * @param systemId The system identifier provided in the XML document.
 * @return The new input source, or null to require the default behavior.
 * @exception java.io.IOException If there is an error setting up the new input source.
 * @exception org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
 */
public InputSource resolveEntity(String publicId, String systemId)
    throws SAXException, IOException {
  // avoid dtd files
  if (systemId != null && systemId.endsWith("dtd")) {
    return new InputSource(new StringReader(""));
  }
  if (entityResolver != null) {
    return entityResolver.resolveEntity(publicId, systemId);
  } else {
    return super.resolveEntity(publicId, systemId);
  }
}
// hints

代码示例来源:origin: webx/citrus

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    log.trace("Trying to locate XML entity {} as configuration points schema.", systemId);

    Schema schema = schemas.findSchema(systemId);

    if (schema == null) {
      if (defaultEntityResolver != null) {
        return defaultEntityResolver.resolveEntity(publicId, systemId);
      } else {
        return null;
      }
    }

    log.debug("Found XML schema for systemId {}: {}", systemId, schema);

    InputSource inputSource = new InputSource(schema.getInputStream());

    inputSource.setPublicId(publicId);
    inputSource.setSystemId(systemId);

    return inputSource;
  }
}

代码示例来源:origin: stackoverflow.com

throw new IllegalStateException();
docBuilder.setEntityResolver(new EntityResolver() {
  @Override
  public InputSource resolveEntity(String publicId, String systemId)
      throws SAXException, IOException {
    if (systemId.endsWith("include.txt")) {
      return new InputSource(includeStream);

代码示例来源:origin: org.opencms/opencms-core

/**
   * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
   */
  @Override
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    if (systemId.startsWith(XHTML_PREFIX)) {
      String name = systemId.substring(XHTML_PREFIX.length());
      //final InputStream resourceAsStream = getClass().getResourceAsStream(name);
      URL resource = getClass().getResource(name);
      if (resource != null) {
        InputSource inputSource = new InputSource(resource.toExternalForm());
        inputSource.setPublicId(publicId);
        //inputSource.setByteStream(resourceAsStream);
        return inputSource;
      }
    }

    // Let file: URLs just get loaded using the default mechanism
    if (systemId.startsWith("file:") || systemId.startsWith("jar:")) {
      return null;
    }
    if (m_next != null) {
      return m_next.resolveEntity(publicId, systemId);
    } else {
      return null;
    }
  }
}

代码示例来源:origin: com.github.skjolber.xml-log-filter/xml-log-filter-conformance

@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
  int index = systemId.lastIndexOf('/');
  String fileName = systemId.substring(index+1);
  
  String entity =  entities.get(fileName);
  if(entity == null) {
    InputSource inputSource = delegate.resolveEntity(publicId, systemId);
    entity = IOUtils.toString(inputSource.getCharacterStream());
    entities.put(fileName, entity);
  }
  return new InputSource(new StringReader(entity));
}

代码示例来源:origin: com.sun.xml.ws/jaxws-rt

public Parser resolveEntity (String publicId, String systemId) throws IOException, XMLStreamException {
  if (systemId != null) {
    SDDocumentSource doc = metadata.get(systemId);
    if (doc != null)
      return new Parser(doc);
    synchronized(this) {
      while(origMetadata.hasNext()) {
        doc = origMetadata.next();
        String extForm = doc.getSystemId().toExternalForm();
        this.metadata.put(extForm,doc);
        if (systemId.equals(extForm))
          return new Parser(doc);
      }
    }
  }
  if (resolver != null) {
    try {
      InputSource source = resolver.resolveEntity(publicId, systemId);
      if (source != null) {
        Parser p = new Parser(null, XMLStreamReaderFactory.create(source, true));
        return p;
      }
    } catch (SAXException e) {
      throw new XMLStreamException(e);
    }
  }
  return null;
}

代码示例来源:origin: mulesoft/mule

protected boolean canResolveEntity(String publicId, String systemId) throws SAXException, IOException {
 final InputSource resolvedEntity = muleEntityResolver.resolveEntity(publicId, systemId);
 try {
  return resolvedEntity != null;
 } finally {
  if (resolvedEntity != null) {
   if (resolvedEntity.getByteStream() != null) {
    resolvedEntity.getByteStream().close();
   }
   if (resolvedEntity.getCharacterStream() != null) {
    resolvedEntity.getCharacterStream().close();
   }
  }
 }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public InputSource resolveEntity(String publicId, @Nullable String systemId) throws SAXException, IOException {
  if (systemId != null) {
    if (systemId.endsWith(DTD_SUFFIX)) {
      return this.dtdResolver.resolveEntity(publicId, systemId);
    }
    else if (systemId.endsWith(XSD_SUFFIX)) {
      return this.schemaResolver.resolveEntity(publicId, systemId);
    }
  }
  return null;
}

代码示例来源:origin: org.milyn/milyn-commons

private static Schema getSchema(EntityResolver entityResolver) throws SAXException, IOException {
  SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  if(entityResolver instanceof LocalXSDEntityResolver) {
    return schemaFactory.newSchema(((LocalXSDEntityResolver)entityResolver).getSchemaSources());
  }
  return schemaFactory.newSchema(new StreamSource(entityResolver.resolveEntity("default", "default").getByteStream()));
}

代码示例来源:origin: apache/geode

/**
 * Resolve the cache.xml XSD using the {@link PivotalEntityResolver}. Verifies that the
 * META-INF/schemas files are correctly found.
 *
 * @since GemFire 8.1
 */
@Test
public void testResolveEntity() throws Exception {
 final InputSource inputSource = getEntityResolver().resolveEntity(null, getSystemId());
 assertNotNull(inputSource);
 assertEquals(getSystemId(), inputSource.getSystemId());
}

代码示例来源:origin: highsource/maven-jaxb2-plugin

@Override
public Reader getCharacterStream() {
  final Reader originalReader = inputSource.getCharacterStream();
  if (originalReader == null) {
    return null;
  } else {
    try {
      InputSource resolvedEntity = this.entityResolver.resolveEntity(
          getPublicId(), getSystemId());
      if (resolvedEntity != null) {
        return resolvedEntity.getCharacterStream();
      } else {
        return originalReader;
      }
    } catch (IOException ioex) {
      return originalReader;
    } catch (SAXException saxex) {
      return originalReader;
    }
  }
}

相关文章