Example usage for javax.xml.parsers DocumentBuilder setEntityResolver

List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder setEntityResolver.

Prototype


public abstract void setEntityResolver(EntityResolver er);

Source Link

Document

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

Usage

From source file:net.jawr.web.bundle.processor.BundleProcessor.java

/**
 * Returns the XML document of the web.xml file
 * /*from  ww  w.  j  av  a 2s  .  co m*/
 * @param webXmlPath
 *            the web.xml path
 * @return the Xml document of the web.xml file
 * 
 * @throws ParserConfigurationException
 *             if a parser configuration exception occurs
 * @throws FactoryConfigurationError
 *             if a factory configuration exception occurs
 * @throws SAXException
 *             if a SAX exception occurs
 * @throws IOException
 *             if an IO exception occurs
 */
protected Document getWebXmlDocument(String baseDir)
        throws ParserConfigurationException, FactoryConfigurationError, SAXException, IOException {
    File webXml = new File(baseDir, WEB_XML_FILE_PATH);
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    docBuilder.setEntityResolver(new EntityResolver() {

        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

            return null;
        }
    });

    Document doc = docBuilder.parse(webXml);
    return doc;
}

From source file:ffx.ui.KeywordPanel.java

/**
 * Load up the Force Field X Keyword Definitions
 *//*www .j av a2s .c o m*/
private void loadXML() {
    NodeList groups, keywords, values;
    Element group, keyword, value;
    String groupName;
    String keywordName, keywordDescription, keywordGUI;
    groups = null;
    try {
        // Build the Document from the keywords.xml file
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new DTDResolver());
        URL keyURL = getClass().getClassLoader().getResource("ffx/ui/commands/keywords.xml");
        Document doc = db.parse(keyURL.openStream());
        Element document = doc.getDocumentElement();
        Element body = (Element) document.getElementsByTagName("body").item(0);
        groups = body.getElementsByTagName("section");
    } catch (ParserConfigurationException | SAXException | IOException e) {
        logger.warning(e.toString());
    }
    keywordHashMap = new LinkedHashMap<>();
    groupHashMap = new LinkedHashMap<>();
    groupHashMap.put("ACTIVE KEYWORDS", "Active Keywords");
    groupHashMap.put("FLAT FILE VIEW", "Flat File View");
    groupComboBox = new JComboBox<>();
    groupComboBox.addItem("Active Keywords");
    groupComboBox.addItem("Flat File View");
    descriptTextArea = new JTextArea();
    descriptTextArea.setLineWrap(true);
    descriptTextArea.setWrapStyleWord(true);
    Insets insets = descriptTextArea.getInsets();
    insets.set(5, 5, 5, 5);
    descriptTextArea.setMargin(insets);
    int length = groups.getLength();
    // Iterate through the Keyword Groups
    for (int i = 0; i < length; i++) {
        group = (Element) groups.item(i);
        groupName = group.getAttribute("name");
        groupComboBox.addItem(groupName);
        keywords = group.getElementsByTagName("subsection");
        int klength = keywords.getLength();
        for (int j = 0; j < klength; j++) {
            keyword = (Element) keywords.item(j);
            keywordName = keyword.getAttribute("name");
            Node text = keyword.getFirstChild();
            keywordDescription = text.getNodeValue().replace('\n', ' ');
            keywordDescription = keywordDescription.replaceAll("  +", " ");
            keywordGUI = keyword.getAttribute("rep");
            KeywordComponent.SwingRepresentation type;
            try {
                type = KeywordComponent.SwingRepresentation.valueOf(keywordGUI.toUpperCase());
            } catch (Exception e) {
                type = null;
                logger.log(Level.WARNING, "{0}: Unknown GUI Component - {1}",
                        new Object[] { keywordName, type });
                System.exit(-1);
            }
            KeywordComponent key;
            if (type == KeywordComponent.SwingRepresentation.CHECKBOXES
                    || type == KeywordComponent.SwingRepresentation.COMBOBOX) {
                values = keyword.getElementsByTagName("Value");
                String labels[] = new String[values.getLength()];
                for (int k = 0; k < values.getLength(); k++) {
                    value = (Element) values.item(k);
                    labels[k] = value.getAttribute("name");
                }
                key = new KeywordComponent(keywordName, groupName, type, keywordDescription, descriptTextArea,
                        labels);
            } else {
                key = new KeywordComponent(keywordName, groupName, type, keywordDescription, descriptTextArea);
            }
            keywordHashMap.put(keywordName.toUpperCase(), key);
            groupHashMap.put(groupName.toUpperCase(), groupName);
        }
    }
    groupComboBox.setSelectedIndex(0);
}

From source file:com.naryx.tagfusion.cfm.document.cfDOCUMENT.java

public Document getDocument(String _renderedBody) throws cfmRunTimeException {
    try {//w ww  .  ja  v  a 2s .c  o  m
        DocumentBuilder builder;
        InputSource is = new InputSource(new StringReader(_renderedBody));
        Document doc;
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setValidating(false);
        builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(new NoValidationResolver());
        doc = builder.parse(is);
        return doc;
    } catch (Exception e) {
        throw newRunTimeException("Failed to create valid xhtml document due to " + e.getClass().getName()
                + ": " + e.getMessage());
    }
}

From source file:ffx.ui.ModelingPanel.java

private void initialize() {
    // Command Description
    descriptTextArea = new JTextArea();
    descriptTextArea.setEditable(false);
    descriptTextArea.setLineWrap(true);/*ww w .j  av  a2 s . c o  m*/
    descriptTextArea.setWrapStyleWord(true);
    descriptTextArea.setDoubleBuffered(true);
    Insets insets = descriptTextArea.getInsets();
    insets.set(5, 5, 5, 5);
    descriptTextArea.setMargin(insets);
    descriptScrollPane = new JScrollPane(descriptTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    descriptScrollPane.setBorder(etchedBorder);
    // Command Input
    commandTextArea = new JTextArea();
    commandTextArea.setEditable(false);
    commandTextArea.setLineWrap(true);
    commandTextArea.setWrapStyleWord(true);
    commandTextArea.setDoubleBuffered(true);
    commandTextArea.setMargin(insets);
    // Command Options
    optionsTabbedPane = new JTabbedPane();
    statusLabel = new JLabel();
    statusLabel.setBorder(etchedBorder);
    statusLabel.setToolTipText("  Modeling command that will be executed");
    commandPanel = new JPanel(flowLayout);
    commandPanel.add(optionsTabbedPane);
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, commandPanel, descriptScrollPane);
    splitPane.setContinuousLayout(true);
    splitPane.setResizeWeight(1.0d);
    splitPane.setOneTouchExpandable(true);
    setLayout(new BorderLayout());
    add(splitPane, BorderLayout.CENTER);
    add(statusLabel, BorderLayout.SOUTH);
    // Initialize the Amino/Nucleic Acid ComboBox.
    acidComboBox.setEditable(false);
    acidComboBox.setMaximumSize(sizer.getPreferredSize());
    acidComboBox.setPreferredSize(sizer.getPreferredSize());
    acidComboBox.setMinimumSize(sizer.getPreferredSize());
    acidComboBox.setFont(Font.decode("Monospaced"));
    acidTextField.setMaximumSize(sizer.getPreferredSize());
    acidTextField.setMinimumSize(sizer.getPreferredSize());
    acidTextField.setPreferredSize(sizer.getPreferredSize());
    acidTextArea.setEditable(false);
    acidTextArea.setWrapStyleWord(true);
    acidTextArea.setLineWrap(true);
    acidTextArea.setFont(Font.decode("Monospaced"));
    acidScrollPane = new JScrollPane(acidTextArea);
    Dimension d = new Dimension(300, 400);
    acidScrollPane.setPreferredSize(d);
    acidScrollPane.setMaximumSize(d);
    acidScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    // Load the FFX commands.xml file that defines FFX commands.
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new DTDResolver());
        URL comURL = getClass().getClassLoader().getResource("ffx/ui/commands/commands.xml");
        Document doc = db.parse(comURL.openStream());
        NodeList nodelist = doc.getChildNodes();
        Node commandroot = null;
        for (int i = 0; i < nodelist.getLength(); i++) {
            commandroot = nodelist.item(i);
            if (commandroot.getNodeName().equals("FFXCommands") && commandroot instanceof Element) {
                break;
            }
        }
        if (commandroot == null || !(commandroot instanceof Element)) {
            commandList = null;
        }
        commandList = ((Element) commandroot).getElementsByTagName("Command");
    } catch (ParserConfigurationException | SAXException | IOException e) {
        System.err.println(e);
    } finally {
        if (commandList == null) {
            System.out.println("Force Field X commands.xml could not be parsed.");
            logger.severe("Force Field X will exit.");
            System.exit(-1);
        }
    }
    // Create a ComboBox with commands specific to each type of coordinate
    // file.
    xyzCommands = new JComboBox<>();
    intCommands = new JComboBox<>();
    arcCommands = new JComboBox<>();
    pdbCommands = new JComboBox<>();
    anyCommands = new JComboBox<>();
    Element command;
    String name;
    int numcommands = commandList.getLength();
    for (int i = 0; i < numcommands; i++) {
        command = (Element) commandList.item(i);
        name = command.getAttribute("name");
        String temp = command.getAttribute("fileType");
        if (temp.contains("ANY")) {
            temp = "XYZ INT ARC PDB";
            anyCommands.addItem(name);
        }
        String[] types = temp.split(" +");
        for (String type : types) {
            if (type.contains("XYZ")) {
                xyzCommands.addItem(name);
            }
            if (type.contains("INT")) {
                intCommands.addItem(name);
            }
            if (type.contains("ARC")) {
                arcCommands.addItem(name);
            }
            if (type.contains("PDB")) {
                pdbCommands.addItem(name);
            }
        }
    }
    initCommandComboBox(xyzCommands);
    initCommandComboBox(intCommands);
    initCommandComboBox(arcCommands);
    initCommandComboBox(pdbCommands);
    initCommandComboBox(anyCommands);
    currentCommandBox = anyCommands;
    activeCommand = (String) anyCommands.getSelectedItem();
    // Load the default Command.
    loadCommand();
    // Load the default Log File Settings.
    logSettings.setActionCommand("LogSettings");
    loadLogSettings();

    // Create the Toolbar.
    toolBar = new JToolBar("Modeling Commands", JToolBar.HORIZONTAL);
    toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
    jbLaunch = new JButton(new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/cog_go.png")));
    jbLaunch.setActionCommand("Launch");
    jbLaunch.setToolTipText("Launch the Force Field X Command");
    jbLaunch.addActionListener(this);
    insets.set(2, 2, 2, 2);
    jbLaunch.setMargin(insets);
    toolBar.add(jbLaunch);
    jbStop = new JButton(new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/stop.png")));
    jbStop.setActionCommand("End");
    jbStop.setToolTipText("Terminate the Current Force Field X Command");
    jbStop.addActionListener(this);
    jbStop.setMargin(insets);
    jbStop.setEnabled(false);
    toolBar.add(jbStop);
    toolBar.addSeparator();
    toolBar.add(anyCommands);
    currentCommandBox = anyCommands;
    toolBar.addSeparator();
    /*
     toolBar.add(logSettings);
     JButton jbdelete = new JButton(new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/page_delete.png")));
     jbdelete.setActionCommand("Delete");
     jbdelete.setToolTipText("Delete Log Files");
     jbdelete.addActionListener(this);
     jbdelete.setMargin(insets);
     toolBar.add(jbdelete);
     toolBar.addSeparator();
     */
    ImageIcon icinfo = new ImageIcon(getClass().getClassLoader().getResource("ffx/ui/icons/information.png"));
    descriptCheckBox = new JCheckBoxMenuItem(icinfo);
    descriptCheckBox.addActionListener(this);
    descriptCheckBox.setActionCommand("Description");
    descriptCheckBox.setToolTipText("Show/Hide Modeling Command Descriptions");
    descriptCheckBox.setMargin(insets);
    toolBar.add(descriptCheckBox);
    toolBar.add(new JLabel(""));
    toolBar.setBorderPainted(false);
    toolBar.setFloatable(false);
    toolBar.setRollover(true);
    add(toolBar, BorderLayout.NORTH);
    // Load ModelingPanel preferences.
    Preferences prefs = Preferences.userNodeForPackage(ffx.ui.ModelingPanel.class);
    descriptCheckBox.setSelected(!prefs.getBoolean("JobPanel_description", true));
    descriptCheckBox.doClick();
}

From source file:net.sourceforge.pmd.lang.xml.ast.XmlParser.java

protected Document parseDocument(Reader reader) throws ParseException {
    nodeCache.clear();//  w ww.  j a v a2s .  co m
    try {
        String xmlData = IOUtils.toString(reader);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(parserOptions.isNamespaceAware());
        dbf.setValidating(parserOptions.isValidating());
        dbf.setIgnoringComments(parserOptions.isIgnoringComments());
        dbf.setIgnoringElementContentWhitespace(parserOptions.isIgnoringElementContentWhitespace());
        dbf.setExpandEntityReferences(parserOptions.isExpandEntityReferences());
        dbf.setCoalescing(parserOptions.isCoalescing());
        dbf.setXIncludeAware(parserOptions.isXincludeAware());
        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
        documentBuilder.setEntityResolver(parserOptions.getEntityResolver());
        Document document = documentBuilder.parse(new InputSource(new StringReader(xmlData)));
        DOMLineNumbers lineNumbers = new DOMLineNumbers(document, xmlData);
        lineNumbers.determine();
        return document;
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new ParseException(e);
    }
}

From source file:net.ymate.framework.commons.XPathHelper.java

private void __doInit(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler)
        throws Exception {
    DocumentBuilder _builder = documentFactory.newDocumentBuilder();
    if (entityResolver != null) {
        _builder.setEntityResolver(entityResolver);
    }/*ww w .j a  v a2s .co  m*/
    if (errorHandler != null) {
        _builder.setErrorHandler(errorHandler);
    }
    __path = xpathFactory.newXPath();
    __document = _builder.parse(inputSource);
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

static public Document buildDomDocument(Reader in, boolean namespaceAware, boolean xslt2,
        boolean resolveExternalEntities) throws DomBuilderException {
    Document document;//  w  w w. jav a  2  s.c o m
    InputSource src;

    DocumentBuilderFactory factory = getDocumentBuilderFactory(xslt2, namespaceAware);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        if (!resolveExternalEntities) {
            builder.setEntityResolver(new XmlExternalEntityResolver());
        }
        src = new InputSource(in);
        document = builder.parse(src);
    } catch (SAXParseException e) {
        throw new DomBuilderException(e);
    } catch (ParserConfigurationException e) {
        throw new DomBuilderException(e);
    } catch (IOException e) {
        throw new DomBuilderException(e);
    } catch (SAXException e) {
        throw new DomBuilderException(e);
    }
    if (document == null) {
        throw new DomBuilderException("Parsed Document is null");
    }
    return document;
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

/**
 * Performs an Identity-transform, with resolving entities with the content files in the classpath
 * @param input/*from   w w  w.  j  a va2s.c  o m*/
 * @return String (the complete and xml)
 * @throws DomBuilderException
 */
static public String identityTransform(ClassLoader classLoader, String input) throws DomBuilderException {
    String result = "";
    try {
        DocumentBuilderFactory factory = getDocumentBuilderFactory();
        Document document;
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new ClassPathEntityResolver(classLoader));
        StringReader sr = new StringReader(input);
        InputSource src = new InputSource(sr);
        document = builder.parse(src);
        Transformer t = XmlUtils.createTransformer(IDENTITY_TRANSFORM);
        Source s = new DOMSource(document);
        result = XmlUtils.transformXml(t, s);
    } catch (Exception tce) {
        throw new DomBuilderException(tce);
    }

    return result;
}

From source file:org.ambraproject.service.crossref.CrossRefLookupServiceImpl.java

private Document getArticle(String doi) throws FileStoreException {
    String fsid = fileStoreService.objectIDMapper().doiTofsid(doi, "XML");
    Document doc;/*from  w  w  w. ja v a 2s  .  c  o  m*/

    InputStream is = fileStoreService.getFileInStream(fsid);

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

        DocumentBuilder builder = factory.newDocumentBuilder();
        EntityResolver resolver = CachedSource.getResolver(XMLServiceImpl.NLM_DTD_URL);
        builder.setEntityResolver(resolver);

        doc = builder.parse(is);
    } catch (Exception e) {
        log.error("Error parsing the article xml for article " + doi, e);
        return null;
    }

    return doc;
}

From source file:org.ambraproject.service.xml.XMLServiceImpl.java

/**
 * Convenience method to create a DocumentBuilder with the factory configs
 *
 * @return Document Builder//from   www  .  java2s.  c  o  m
 * @throws javax.xml.parsers.ParserConfigurationException
 */
@Override
public DocumentBuilder createDocBuilder() throws ParserConfigurationException {
    // Create the builder and parse the file
    final DocumentBuilder builder = factory.newDocumentBuilder();
    EntityResolver resolver = validateArticleXml ? CachedSource.getResolver()
            : CachedSource.getResolver(NLM_DTD_URL);
    builder.setEntityResolver(resolver);

    return builder;
}