Example usage for javax.xml.parsers DocumentBuilderFactory setFeature

List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setFeature.

Prototype

public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;

Source Link

Document

Set a feature for this DocumentBuilderFactory and DocumentBuilder s created by this factory.

Usage

From source file:it.greenvulcano.gvesb.api.controller.GvConfigurationControllerRest.java

public GvConfigurationControllerRest() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setValidating(true);
    documentBuilderFactory.setFeature("http://xml.org/sax/features/namespaces", false);
    documentBuilderFactory.setFeature("http://xml.org/sax/features/validation", false);
    documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.GridRowLoader.java

/**
 * The method import schema rows from schema file into schema grid.
 * //from w ww.j  a  v a2 s.c  o  m
 */
public List<GridRow> importGridRowsFromXML(ListenerHelper helper, Table table) {

    List<GridRow> schemaGridRowListToImport = null;

    ELTGridDetails gridDetails = (ELTGridDetails) helper.get(HelperType.SCHEMA_GRID);
    List<GridRow> grids = gridDetails.getGrids();
    grids.clear();
    try (InputStream xml = new FileInputStream(schemaFile);
            InputStream xsd = new FileInputStream(SCHEMA_CONFIG_XSD_PATH);) {
        if (StringUtils.isNotBlank(schemaFile.getPath())) {

            if (!schemaFile.getName().contains(".")) {
                logger.error(Messages.IMPORT_XML_IMPROPER_EXTENSION);
                throw new Exception(Messages.IMPORT_XML_IMPROPER_EXTENSION);
            }

            if (!(schemaFile.getPath().endsWith(".schema")) && !(schemaFile.getPath().endsWith(".xml"))) {
                logger.error(Messages.IMPORT_XML_INCORRECT_FILE);
                throw new Exception(Messages.IMPORT_XML_INCORRECT_FILE);
            }

            if (validateXML(xml, xsd)) {

                DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
                builderFactory.setExpandEntityReferences(false);
                builderFactory.setNamespaceAware(true);
                builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true);

                DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(schemaFile);

                JAXBContext jaxbContext = JAXBContext.newInstance(Schema.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

                Schema schema = (Schema) jaxbUnmarshaller.unmarshal(document);
                fields = schema.getFields();
                List<Field> fieldsList = fields.getField();
                GridRow gridRow = null;
                schemaGridRowListToImport = new ArrayList<GridRow>();

                if (Messages.GENERIC_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        addRowToList(gridDetails, grids, getBasicSchemaGridRow(field),
                                schemaGridRowListToImport);
                    }
                } else if (Messages.FIXEDWIDTH_GRID_ROW.equals(gridRowType)) {

                    for (Field field : fieldsList) {
                        addRowToList(gridDetails, grids, getFixedWidthGridRow(field),
                                schemaGridRowListToImport);
                    }
                } else if (Messages.GENERATE_RECORD_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        addRowToList(gridDetails, grids, getGenerateRecordGridRow(field),
                                schemaGridRowListToImport);
                    }
                } else if (Messages.XPATH_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        Text loopXPathData = null;
                        if (table.getData() != null
                                && Text.class.isAssignableFrom(table.getData().getClass())) {
                            loopXPathData = (Text) table.getData();
                        }
                        XPathGridRow xPathGridRow = new XPathGridRow();
                        populateCommonFields(xPathGridRow, field);
                        xPathGridRow.setXPath(field.getAbsoluteOrRelativeXpath());
                        if (loopXPathData != null && StringUtils.isNotBlank(loopXPathData.getText())) {
                            xPathGridRow.setAbsolutexPath(
                                    loopXPathData.getText() + Path.SEPARATOR + xPathGridRow.getXPath());
                        } else {
                            xPathGridRow.setAbsolutexPath(xPathGridRow.getXPath());
                        }
                        addRowToList(gridDetails, grids, xPathGridRow, schemaGridRowListToImport);
                    }
                } else if (Messages.MIXEDSCHEME_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        addRowToList(gridDetails, grids, getMixedSchemeGridRow(field),
                                schemaGridRowListToImport);
                    }
                }
            }
        } else {
            logger.error(Messages.EXPORT_XML_EMPTY_FILENAME);
            throw new Exception(Messages.EXPORT_XML_EMPTY_FILENAME);
        }
    } catch (JAXBException e1) {
        grids.clear();
        showMessageBox(Messages.IMPORT_XML_FORMAT_ERROR + " -\n" + e1.getMessage(), "Error", SWT.ERROR);
        logger.error(Messages.IMPORT_XML_FORMAT_ERROR);
        return null;
    } catch (DuplicateFieldException e1) {
        grids.clear();
        showMessageBox(e1.getMessage(), "Error", SWT.ERROR);
        logger.error(e1.getMessage());
        return null;
    } catch (Exception e) {
        grids.clear();
        showMessageBox(Messages.IMPORT_XML_ERROR + " -\n" + e.getMessage(), "Error", SWT.ERROR);
        logger.error(Messages.IMPORT_XML_ERROR);
        return null;
    }

    return schemaGridRowListToImport;
}

From source file:net.sf.jasperreports.engine.util.JRStyledTextParser.java

/**
 *
 *///from w ww  .  j av  a2  s .  co m
private JRStyledTextParser() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature(JRXmlUtils.FEATURE_DISALLOW_DOCTYPE, true);

        documentBuilder = factory.newDocumentBuilder();
        documentBuilder.setErrorHandler(this);
    } catch (ParserConfigurationException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:hydrograph.ui.common.util.ExternalOperationExpressionUtil.java

/**
 *Converts xml-stream into its equivalent jaxb object
 * //  ww  w  .j  a v  a 2 s . c o  m
 * @param xmlInputStream
 * @param type
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws JAXBException
 */
public Object unmarshal(InputStream xmlInputStream, Class<?> type)
        throws ParserConfigurationException, SAXException, IOException, JAXBException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setExpandEntityReferences(false);
    builderFactory.setNamespaceAware(true);
    builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true);
    DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(xmlInputStream);
    JAXBContext jaxbContext = JAXBContext.newInstance(type);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    return jaxbUnmarshaller.unmarshal(document);
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

private DocumentBuilder getDocumentBuilder() throws XFormsException {
    // ensure xerces dom
    try {//from w  w w  . j  a v a  2 s  . c o  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        // factory.setAttribute("http://apache.org/xml/properties/dom/document-class-name", "org.apache.xerces.dom.DocumentImpl");

        DocumentBuilder db = factory.newDocumentBuilder();
        // use an empty entity resolver to avoid that Xerces may try to
        // download the system DTD (can cause latency problems)
        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return null;
            };
        });
        return db;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java

/**
 * Initializes the connector and prepares it for use.
 *//* w ww  .j av a 2 s  . c o  m*/
public void initialize() {

    initialized = true;

    initializeConnectionManager();

    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        domFactory.setValidating(false);
        String feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        domFactory.setFeature(feature, false);
        documentBuilder = domFactory.newDocumentBuilder();

    } catch (ParserConfigurationException e) {
        log.error("javax.xml.parsers.ParserConfigurationException: " + e);
    }

    for (int i = 0; i < rwsAttributes.size(); i++) {
        RwsAttribute attr = rwsAttributes.get(i);
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            log.debug("xpath for {} is {}", attr.name, attr.xPath);
            attr.xpathExpression = xpath.compile(attr.xPath);
        } catch (XPathExpressionException e) {
            log.error("xpath expr: " + e);
        }
    }

    activators = new Vector<String>(configuredActivators);
    refreshActivators();

    registerTemplate();
    initializeCache();

}

From source file:jef.tools.XMLUtils.java

private static DocumentBuilderFactory initFactory(boolean ignorComments, boolean namespaceAware) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(false); // DTD
    dbf.setIgnoringComments(ignorComments);
    dbf.setNamespaceAware(namespaceAware);
    // dbf.setCoalescing(true);//CDATA
    // ?Text???/* w  w w  .  j  a v  a 2 s . c  o  m*/
    try {
        // dbf.setFeature("http://xml.org/sax/features/namespaces", false);
        // dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (ParserConfigurationException e) {
        log.warn(
                "Your xerces implemention is too old to support 'load-dtd-grammar' and 'load-external-dtd' feature. Please upgrade xercesImpl.jar to 2.6.2 or above.");
    } catch (AbstractMethodError e) {
        log.warn(
                "Your xerces implemention is too old to support 'load-dtd-grammar' and 'load-external-dtd' feature. Please upgrade xercesImpl.jar to 2.6.2 or above.");
    }

    try {
        dbf.setAttribute("http://xml.org/sax/features/external-general-entities", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'external-general-entities' attribute.");
    }
    try {
        dbf.setAttribute("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'external-parameter-entities' attribute.");
    }
    try {
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (IllegalArgumentException e) {
        log.warn("Your xerces implemention is too old to support 'load-external-dtd' attribute.");
    }
    return dbf;
}

From source file:fi.foyt.fni.materials.MaterialController.java

private org.w3c.dom.Document tidyForPdf(String title, String bodyContent)
        throws ParserConfigurationException, IOException, SAXException {
    String documentHtml = HtmlUtils.getAsHtmlText(title, bodyContent);
    String cleanedHtml = null;//from w  w w. ja v a  2s.  c  o m

    ByteArrayOutputStream tidyStream = new ByteArrayOutputStream();
    try {
        Tidy tidy = new Tidy();
        tidy.setInputEncoding("UTF-8");
        tidy.setOutputEncoding("UTF-8");
        tidy.setShowWarnings(true);
        tidy.setNumEntities(false);
        tidy.setXmlOut(true);
        tidy.setXHTML(true);

        cleanedHtml = HtmlUtils.printDocument(tidy.parseDOM(new StringReader(documentHtml), null));
    } catch (Exception e) {
        throw e;
    } finally {
        tidyStream.flush();
        tidyStream.close();
    }

    InputStream documentStream = new ByteArrayInputStream(cleanedHtml.getBytes("UTF-8"));
    try {

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(false);
        builderFactory.setValidating(false);
        builderFactory.setFeature("http://xml.org/sax/features/namespaces", false);
        builderFactory.setFeature("http://xml.org/sax/features/validation", false);
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        return builder.parse(documentStream);

    } finally {
        documentStream.close();
    }
}