当前位置: 首页>>代码示例>>Java>>正文


Java DocumentBuilder.setEntityResolver方法代码示例

本文整理汇总了Java中javax.xml.parsers.DocumentBuilder.setEntityResolver方法的典型用法代码示例。如果您正苦于以下问题:Java DocumentBuilder.setEntityResolver方法的具体用法?Java DocumentBuilder.setEntityResolver怎么用?Java DocumentBuilder.setEntityResolver使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.xml.parsers.DocumentBuilder的用法示例。


在下文中一共展示了DocumentBuilder.setEntityResolver方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getDocumentBuilder

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:21,代码来源:WebdavServlet.java

示例2: readXml

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * Read XML as DOM.
 */
public static Document readXml(InputStream is) throws SAXException, IOException, ParserConfigurationException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

	dbf.setValidating(false);
	dbf.setIgnoringComments(false);
	dbf.setIgnoringElementContentWhitespace(true);
	// dbf.setCoalescing(true);
	// dbf.setExpandEntityReferences(true);

	DocumentBuilder db = null;
	db = dbf.newDocumentBuilder();
	db.setEntityResolver(new NullResolver());

	// db.setErrorHandler( new MyErrorHandler());

	Document doc = db.parse(is);
	return doc;
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:22,代码来源:DomUtil.java

示例3: createBuilder

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * Creates a new document builder.
 * 
 * @return newly created document builder
 * 
 * @throws XMLParserException thrown if their is a configuration error with the builder factory
 */
protected DocumentBuilder createBuilder() throws XMLParserException {
    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        if (entityResolver != null) {
            builder.setEntityResolver(entityResolver);
        }

        if (errorHandler != null) {
            builder.setErrorHandler(errorHandler);
        }

        return builder;
    } catch (ParserConfigurationException e) {
        log.error("Unable to create new document builder", e);
        throw new XMLParserException("Unable to create new document builder", e);
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:26,代码来源:BasicParserPool.java

示例4: createParser

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * Creates a DocumentBuilder that is configured to read Xml Documents in a common way.
 *
 * @return A configured parser
 */
public static DocumentBuilder createParser() throws ParserConfigurationException {
    // Create a factory object for creating DOM parsers
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Specifies that the parser produced by this factory will validate documents as they are parsed.
    factory.setValidating(false);

    // Now use the factory to create a DOM parser
    DocumentBuilder parser = factory.newDocumentBuilder();

    // Specifies the EntityResolver to resolve DTD used in XML documents
    parser.setEntityResolver(new DefaultEntityResolver());

    // Specifies the ErrorHandler to handle warning/error/fatalError conditions
    parser.setErrorHandler(new DefaultErrorHandler());

    return parser;

}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:25,代码来源:AopConstants.java

示例5: loadXml

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
private List<RuleNode> loadXml(String path) throws Exception{
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    builder.setEntityResolver(new UrlDtdPathResolver());
    Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));

    List<RuleNode> results = new ArrayList<>();

    NodeList rootChildren = document.getDocumentElement().getChildNodes();
    for (int i = 0; i < rootChildren.getLength(); i++) {

        Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));

    }

    return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
 
开发者ID:justice-code,项目名称:QiuQiu,代码行数:18,代码来源:XmlDataContext.java

示例6: getDocBuilder

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
private static DocumentBuilder getDocBuilder(EntityResolver entityResolver) {
    try {
        DocumentBuilder docBuilder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
        if (entityResolver != null) {
            docBuilder.setEntityResolver(entityResolver);
        }
        return docBuilder;
    } catch (ParserConfigurationException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:12,代码来源:PomReader.java

示例7: testXmlParse

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
@Test
public void testXmlParse() {
    ByteArrayInputStream is = new ByteArrayInputStream(
            generatedXmlFile.getFormattedContent().getBytes());
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new TestEntityResolver());
        builder.setErrorHandler(new TestErrorHandler());
        builder.parse(is);
    } catch (Exception e) {
        fail("Generated XML File " + generatedXmlFile.getFileName() + " will not parse");
    }
}
 
开发者ID:DomKing,项目名称:server-utility,代码行数:16,代码来源:XmlCodeGenerationTest.java

示例8: PlanLoader

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * Creates a plan loader that uses the specified module factory, converter factory and document builder.
 * @param moduleFactory module factory used to instantiate modules
 * @param converterFactory parameter converter factory used to convert parameter values
 * @param docBuilder document builder used to parse XML files
 * @param customEntities 
 * @throws PlanException 
 */
public PlanLoader(ModuleFactory<T> moduleFactory, ParamConverterFactory converterFactory, Document defaultParamValuesDoc, List<String> inputDirs, String outputDir, List<String> resourceBases, DocumentBuilder docBuilder, String creatorNameFeature, Map<String,String> customEntities) throws PlanException {
	super();
	this.moduleFactory = moduleFactory;
	this.converterFactory = converterFactory;
	this.defaultParamValues = buildDefaultParamValues(defaultParamValuesDoc);
	this.inputDirs = inputDirs;
	this.outputDir = outputDir;
	this.resourceBases = resourceBases;
	this.docBuilder = docBuilder;
	this.creatorNameFeature = creatorNameFeature;
	AlvisNLPEntityResolver entityResolver = new AlvisNLPEntityResolver(customEntities);
	docBuilder.setEntityResolver(entityResolver);
}
 
开发者ID:Bibliome,项目名称:alvisnlp,代码行数:22,代码来源:PlanLoader.java

示例9: executeValidityTest

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
protected void executeValidityTest(
   URL    schemaSource,
   String publicId,
   URL    xmlSource) throws Throwable
{
  // Fail fast on null URLs, since they mean we'll be failing
  // soon enough, but far more cryptically.
  if ((publicId != null) && (schemaSource == null))
    throw new NullPointerException("No source for schema/DTD");

  if (xmlSource == null)
    throw new NullPointerException("No source for XML document");

  ER er = new ER();
  er.registerPublicId(publicId, schemaSource);

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

  DocumentBuilder docBuilder = factory.newDocumentBuilder();
  // Make sure this test is relevant...
  assertTrue(docBuilder.isValidating());

  docBuilder.setEntityResolver(er);
  docBuilder.setErrorHandler(new Errors());
  docBuilder.parse(new InputSource(xmlSource.openStream()));
}
 
开发者ID:apache,项目名称:myfaces-trinidad,代码行数:29,代码来源:XMLValidityTestCase.java

示例10: createDocumentBuilder

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * Create a JAXP DocumentBuilder that this bean definition reader
 * will use for parsing XML documents. Can be overridden in subclasses,
 * adding further initialization of the builder.
 * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder
 * should be created with
 * @param entityResolver the SAX EntityResolver to use
 * @param errorHandler the SAX ErrorHandler to use
 * @return the JAXP DocumentBuilder
 * @throws ParserConfigurationException if thrown by JAXP methods
 */
protected DocumentBuilder createDocumentBuilder(
		DocumentBuilderFactory factory, EntityResolver entityResolver, ErrorHandler errorHandler)
		throws ParserConfigurationException {

	DocumentBuilder docBuilder = factory.newDocumentBuilder();
	if (entityResolver != null) {
		docBuilder.setEntityResolver(entityResolver);
	}
	if (errorHandler != null) {
		docBuilder.setErrorHandler(errorHandler);
	}
	return docBuilder;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:25,代码来源:DefaultDocumentLoader.java

示例11: execute

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * Run the task.
 * @throws BuildException The exception raised during task execution.
 * @todo validate the source file is valid before opening, print a better error message
 * @todo add a verbose level log message listing the name of the file being loaded
 */
public void execute()
throws BuildException {

    try {
        InputStream is = getInputStream();
        if ( is == null ) {
            String msg = "XmlProperty task requires a file or xml attribute";
            throw new BuildException( msg );
        }

        log( "Loading " + ( src != null ? src.getAbsolutePath() : "xml properties" ), Project.MSG_VERBOSE );

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating( validate );
        factory.setNamespaceAware( false );
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver( getEntityResolver() );
        Document document = builder.parse( is );
        Element topElement = document.getDocumentElement();

        // Keep a hashtable of attributes added by this task.
        // This task is allow to override its own properties
        // but not other properties.  So we need to keep track
        // of which properties we've added.
        addedAttributes = new Hashtable();

        if ( keepRoot ) {
            addNodeRecursively( topElement, prefix, null );
        }
        else {
            NodeList topChildren = topElement.getChildNodes();
            int numChildren = topChildren.getLength();
            for ( int i = 0; i < numChildren; i++ ) {
                addNodeRecursively( topChildren.item( i ), prefix, null );
            }
        }

    }
    catch ( SAXException sxe ) {
        // Error generated during parsing
        Exception x = sxe;
        if ( sxe.getException() != null ) {
            x = sxe.getException();
        }
        throw new BuildException( x );

    }
    catch ( ParserConfigurationException pce ) {
        // Parser with specified options can't be built
        throw new BuildException( pce );
    }
    catch ( IOException ioe ) {
        // I/O error
        throw new BuildException( ioe );
    }
}
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:63,代码来源:XmlPropertyTask.java

示例12: testGenerateArchFileWhenEmptyWithDefaultAnswerForNbDepsQuestion

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
public void testGenerateArchFileWhenEmptyWithDefaultAnswerForNbDepsQuestion() throws Exception {
    java.io.File answers = extractString ("");
    answers.delete ();
    assertFalse ("Really deleted", answers.exists ());

    java.io.File f = extractString (
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<project name=\"Test Arch\" basedir=\".\" default=\"all\" >" +
        "  <taskdef name=\"arch\" classname=\"org.netbeans.nbbuild.Arch\" classpath=\"${nbantext.jar}\"/>" +
        "  <arch answers=\"" + answers + "\" output=\"x.html\" />" +
        "<target name=\"all\" >" +
        "  " +
        "</target>" +
        "</project>"

    );
    execute (f, new String[] { });

    assertTrue ("File is generated", answers.exists ());
    
    String res = readFile(answers);
    DocumentBuilderFactory fack = DocumentBuilderFactory.newInstance();
    fack.setValidating(false);
    DocumentBuilder build = fack.newDocumentBuilder();
    build.setEntityResolver(this);
    org.w3c.dom.Document dom;
    try {
        dom = build.parse(answers);
    } catch (IOException ex) {
        throw new IOException(ex.getMessage() + "\n" + msg.toString(), ex);
    }

    org.w3c.dom.NodeList list = dom.getElementsByTagName("defaultanswer");
    assertTrue("There is at least one defaultanswer: " + res, list.getLength() > 0);
    BIGLOOP: for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node n = list.item(i);
        while (n != null) {
            n = n.getParentNode();
            assertNotNull ("No parent node answer found: " + res, n);
            
            if (n.getNodeName().equals ("answer")) {
                String id = n.getAttributes().getNamedItem("id").getNodeValue();
                if (id.equals ("dep-nb")) {
                    // ok, we were searching for answer to dep-nb question
                    return;
                }
                continue BIGLOOP;
            }
        }
    }
    
    fail ("dep-nb question should have a defaultanswer: " + res);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:54,代码来源:ArchQuestionsTest.java

示例13: generateSourceFiles

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * Create source files based on the contents of an XML file
 * @param tempFileName the temporary file to be parsed, whose contents will
 *                     determine which files get created.
 * @param context contains information needed for processing, including
 *                information from WebMacro.properties and PatternGenerator
 *                properties.
 * @throws PatternGeneratorException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws WebMacroException
 * @throws SourceDecomposerException
 */
private void generateSourceFiles(String tempFileName, Context context)
        throws PatternGeneratorException, ParserConfigurationException,
               SAXException, IOException, WebMacroException,
               SourceDecomposerException {
    // parse the tempFileName.. Force XML validation
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    DocumentBuilder parser = factory.newDocumentBuilder();
    parser.setEntityResolver(new DefaultEntityResolver());
    parser.setErrorHandler(new DefaultErrorHandler());
    Document document = parser.parse(tempFileName);

    // check for Prerequisites
    // @todo : this currently only supports java files..
    // Need to enhance this logic to support other files too !!
    String preReqErrLog = null;
    Node preReq = document.getElementsByTagName(XML_PREREQUESITES).item(0);
    NodeList classes = preReq.getChildNodes();
    if (classes != null) {
        for (int i = 0; i < classes.getLength(); i++) {
            Node clazz = classes.item(i);
            if (clazz.getNodeType() == Node.ELEMENT_NODE) {
                String requiredClassName = XmlHelper.getTextTrim(clazz);
                try {
                    Class.forName(requiredClassName);
                } catch (ClassNotFoundException e) {
                    if (preReqErrLog == null) {
                        preReqErrLog = "";
                    }
                    preReqErrLog += "Error: PreRequesite Class " +
                                    requiredClassName + " not found\n";
                }
            }
        }
    }
    if (preReqErrLog != null) {
        writeMessage(m_auditFile, preReqErrLog, true);
        throw new PatternGeneratorException(preReqErrLog);
    }
    processComponents(context, document);
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:56,代码来源:PatternGenerator.java

示例14: implNbinstHost

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
private void implNbinstHost(TestHandler handler) throws ParserConfigurationException, IOException, IllegalArgumentException, SAXException {
        FileObject libs = FileUtil.getConfigFile("org-netbeans-api-project-libraries/Libraries");                
        if (libs != null) {
            final List<FileObject> schemas = new ArrayList<FileObject>(3);
            schemas.add(null);
            final FileObject schema2 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/2.xsd");
            if (schema2 != null) {
                schemas.add(schema2);
            }
            final FileObject schema3 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/3.xsd");
            if (schema3 != null) {
                schemas.add(schema3);
            }
next:       for (FileObject lib : libs.getChildren()) {
                SAXException lastException = null;
                for (FileObject schema : schemas) {
                    lastException = null;
                    try {
                        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        docBuilderFactory.setValidating(true);
                        if (schema != null) {
                            docBuilderFactory.setNamespaceAware(true);
                            docBuilderFactory.setAttribute(
                                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",   //NOI18N
                                "http://www.w3.org/2001/XMLSchema");                        //NOI18N
                            docBuilderFactory.setAttribute(
                                "http://java.sun.com/xml/jaxp/properties/schemaSource",     //NOI18N
                                schema.toURI().toString());
                        }
                        final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
                        builder.setErrorHandler(XMLUtil.defaultErrorHandler());
                        builder.setEntityResolver(EntityCatalog.getDefault());
                        Document doc = builder.parse(new InputSource(lib.toURL().toString()));
                        NodeList nl = doc.getElementsByTagName("resource");
                        for (int i = 0; i < nl.getLength(); i++) {
                            Element resource = (Element) nl.item(i);
                            validateNbinstURL(new URL(XMLUtil.findText(resource)), handler, lib);
                        }
                        continue next;
                    } catch (SAXException e) {
                        lastException = e;
                    }
                }
                throw lastException;
            }
        }
        for (FileObject f : NbCollections.iterable(FileUtil.getConfigRoot().getChildren(true))) {
            for (String attr : NbCollections.iterable(f.getAttributes())) {
                if (attr.equals("instanceCreate")) {
                    continue; // e.g. on Services/Hidden/org-netbeans-lib-jakarta_oro-antlibrary.instance prints stack trace
                }
                Object val = f.getAttribute(attr);
                if (val instanceof URL) {
                    validateNbinstURL((URL) val, handler, f);
                }
            }
        }
        assertNoErrors("No improper nbinst URLs", handler.errors());
    }
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:60,代码来源:ValidateNbinstTest.java

示例15: loadDiagram

import javax.xml.parsers.DocumentBuilder; //导入方法依赖的package包/类
/**
 * 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);
	}
}
 
开发者ID:IngSW-unipv,项目名称:Progetto-C,代码行数:59,代码来源:InkscapeLoader.java


注:本文中的javax.xml.parsers.DocumentBuilder.setEntityResolver方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。