Example usage for javax.xml.parsers DocumentBuilderFactory setExpandEntityReferences

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

Introduction

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

Prototype


public void setExpandEntityReferences(boolean expandEntityRef) 

Source Link

Document

Specifies that the parser produced by this code will expand entity reference nodes.

Usage

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

/**
 * The method import schema rows from schema file into schema grid.
 * /*from w w w.java 2  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:de.knowwe.defi.usermanager.XMLUserDatabase.java

private void buildDOM() {
    // Read DOM//from w ww  .ja v  a 2 s . com
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setExpandEntityReferences(false);
    factory.setIgnoringComments(true);
    factory.setNamespaceAware(false);
    try {
        c_dom = factory.newDocumentBuilder().parse(c_file);
        Log.fine("Database successfully initialized");
        c_lastModified = c_file.lastModified();
        c_lastCheck = System.currentTimeMillis();
    } catch (ParserConfigurationException e) {
        Log.severe("Configuration error: " + e.getMessage());
    } catch (SAXException e) {
        Log.severe("SAX error: " + e.getMessage());
    } catch (FileNotFoundException e) {
        Log.info("User database not found; creating from scratch...");
    } catch (IOException e) {
        Log.severe("IO error: " + e.getMessage());
    }
    if (c_dom == null) {
        try {
            //
            //  Create the DOM from scratch
            //
            c_dom = factory.newDocumentBuilder().newDocument();
            c_dom.appendChild(c_dom.createElement("users"));
        } catch (ParserConfigurationException e) {
            Log.severe("Could not create in-memory DOM");
        }
    }
}

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

/**
 *Converts xml-stream into its equivalent jaxb object
 * /*  w  ww.  j  a  v a2s. 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:com.silverwrist.venice.std.TrackbackManager.java

/**
 * Only one instance of this class can/should exist.
 *///from w w w.  ja v  a 2  s  . c  o m
private TrackbackManager() {
    m_page_cache = new HashMap();
    m_item_cache = new HashMap();
    m_end_recognizers = new HashMap();
    m_http_client = new HttpClient();

    try { // create the XML parsers we use
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        fact.setCoalescing(true);
        fact.setExpandEntityReferences(true);
        fact.setIgnoringComments(true);
        fact.setNamespaceAware(true);
        fact.setValidating(false);
        m_rdf_parser = fact.newDocumentBuilder();
        fact.setCoalescing(true);
        fact.setExpandEntityReferences(true);
        fact.setIgnoringComments(true);
        fact.setNamespaceAware(false);
        fact.setValidating(false);
        m_tbresp_parser = fact.newDocumentBuilder();

    } // end try
    catch (ParserConfigurationException e) { // this is bad!
        logger.fatal("XML parser creation failed", e);

    } // end catch

}

From source file:com.fluidops.iwb.provider.XMLProvider.java

/**
 * Constructs a w3c DOM from an InputStream. Depending on whether the InputStream is constructed from
 * an html or xml file, it will used JTidy for clean-up and constructing the document DOM.
 * @param in any input stream that contains (x)html/xml data
 * @return the DOM of an HTML or XML constructed from any InputStream
 * @throws SAXException//from w ww .  ja  v  a2  s  . c om
 * @throws IOException
 * @throws ParserConfigurationException
 */
protected Document getDocument(InputStream in) throws SAXException, IOException, ParserConfigurationException {
    Tidy tidy = new Tidy();
    tidy.setHideComments(true);
    tidy.setTidyMark(false);
    tidy.setQuiet(true);
    tidy.setShowErrors(1);
    tidy.setShowWarnings(false);
    if (StringUtil.isNotNullNorEmpty(config.inputEncoding)) {
        tidy.setInputEncoding(config.inputEncoding);
    }
    tidy.setOutputEncoding("UTF-8");
    tidy.setMakeClean(true);

    Document doc = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder db = factory.newDocumentBuilder();

    // we assume that xml is provided, if no file extension .htm(l) is provided
    if (!config.xmlfile.toLowerCase().endsWith(".htm") && !config.xmlfile.toLowerCase().endsWith("html")) {
        // let jtidy know that it needs to handle xml, instead of html
        tidy.setXmlOut(true);
        tidy.setXmlTags(true);

        // need to have another (re)rewrite of the DOM in order to gain a clean w3c.dom 
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            doc = tidy.parseDOM(in, outputStream);
            is = new ByteArrayInputStream(outputStream.toByteArray());
            doc = db.parse(is);
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(is);
        }
    } else {
        doc = tidy.parseDOM(in, null);
    }
    return doc;
}

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

private boolean verifyExtSchemaSync(List<GridRow> schemaInGrid) {
    List<GridRow> schemasFromFile = new ArrayList<GridRow>();
    File schemaFile = getPath(extSchemaPathText, SCHEMA_FILE_EXTENSION, true, SCHEMA_FILE_EXTENSION,
            XML_FILE_EXTENSION);/*ww  w  .  j  a  v a2  s . c  o m*/
    if (schemaFile == null) {
        return false;
    }
    Fields fields;
    boolean verifiedSchema = true;
    try (InputStream xml = new FileInputStream(schemaFile);
            InputStream xsd = new FileInputStream(SCHEMA_CONFIG_XSD_PATH);) {

        if (validateXML(xml, xsd)) {
            try {

                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(hydrograph.ui.common.schema.Schema.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

                hydrograph.ui.common.schema.Schema schema = (hydrograph.ui.common.schema.Schema) jaxbUnmarshaller
                        .unmarshal(document);
                fields = schema.getFields();
                ArrayList<Field> fieldsList = (ArrayList<Field>) fields.getField();
                GridRow gridRow = null;

                if (Messages.GENERIC_GRID_ROW.equals(gridRowType)) {

                    for (Field field : fieldsList) {
                        gridRow = new BasicSchemaGridRow();
                        populateCommonFields(gridRow, field);
                        schemasFromFile.add(gridRow);
                    }

                } else if (Messages.XPATH_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        gridRow = new XPathGridRow();
                        populateCommonFields(gridRow, field);
                        String xpath = field.getAbsoluteOrRelativeXpath();
                        ((XPathGridRow) gridRow).setXPath(StringUtils.isNotBlank(xpath) ? xpath : "");
                        schemasFromFile.add(gridRow);
                    }
                } else if (Messages.FIXEDWIDTH_GRID_ROW.equals(gridRowType)) {

                    for (Field field : fieldsList) {
                        gridRow = new FixedWidthGridRow();
                        populateCommonFields(gridRow, field);

                        if (field.getLength() != null)
                            ((FixedWidthGridRow) gridRow).setLength(String.valueOf(field.getLength()));
                        else
                            ((FixedWidthGridRow) gridRow).setLength("");
                        schemasFromFile.add(gridRow);
                    }
                } else if (Messages.MIXEDSCHEME_GRID_ROW.equals(gridRowType)) {

                    for (Field field : fieldsList) {
                        gridRow = new MixedSchemeGridRow();
                        populateCommonFields(gridRow, field);
                        if (field.getLength() != null)
                            ((MixedSchemeGridRow) gridRow).setLength(String.valueOf(field.getLength()));
                        else
                            ((MixedSchemeGridRow) gridRow).setLength("");
                        ((MixedSchemeGridRow) gridRow).setDelimiter(field.getDelimiter());
                        schemasFromFile.add(gridRow);
                    }
                } else if (Messages.GENERATE_RECORD_GRID_ROW.equals(gridRowType)) {

                    for (Field field : fieldsList) {
                        gridRow = new GenerateRecordSchemaGridRow();
                        populateCommonFields(gridRow, field);

                        if (field.getLength() != null)
                            ((GenerateRecordSchemaGridRow) gridRow)
                                    .setLength(String.valueOf(field.getLength()));
                        else
                            ((GenerateRecordSchemaGridRow) gridRow).setLength("");

                        if (field.getDefault() != null)
                            ((GenerateRecordSchemaGridRow) gridRow)
                                    .setDefaultValue((String.valueOf(field.getDefault())));
                        else
                            ((GenerateRecordSchemaGridRow) gridRow).setDefaultValue((String.valueOf("")));

                        if (field.getRangeFrom() != null)
                            ((GenerateRecordSchemaGridRow) gridRow)
                                    .setRangeFrom(String.valueOf(field.getRangeFrom()));
                        else
                            ((GenerateRecordSchemaGridRow) gridRow).setRangeFrom("");

                        if (field.getRangeFrom() != null)
                            ((GenerateRecordSchemaGridRow) gridRow)
                                    .setRangeTo(String.valueOf(field.getRangeTo()));
                        else
                            ((GenerateRecordSchemaGridRow) gridRow).setRangeTo("");

                        schemasFromFile.add(gridRow);

                    }

                }
            } catch (JAXBException | ParserConfigurationException | SAXException | IOException e) {
                logger.error(Messages.EXPORTED_SCHEMA_SYNC_ERROR, e);
            }

        }
        if (!equalLists(schemaInGrid, schemasFromFile, new GridComparator())) {
            verifiedSchema = false;
            //MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Information", Messages.EXPORTED_SCHEMA_NOT_IN_SYNC);
            MessageBox dialog = new MessageBox(Display.getCurrent().getActiveShell(),
                    SWT.ICON_INFORMATION | SWT.OK);
            dialog.setText(Messages.INFORMATION);
            dialog.setMessage(Messages.EXPORTED_SCHEMA_NOT_IN_SYNC);
        }

    } catch (FileNotFoundException e) {
        logger.error(Messages.EXPORTED_SCHEMA_SYNC_ERROR, e);

    } catch (IOException e) {
        logger.error(Messages.EXPORTED_SCHEMA_SYNC_ERROR, e);
    }
    return verifiedSchema;

}

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * Return JAXP document builder instance.
 *
 * @return The documentBuilder value//from w  w w.j ava2  s . co m
 * @throws javax.servlet.ServletException Description of the Exception
 */
protected DocumentBuilder getDocumentBuilder() throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new ServletException(sm.getString("webdavservlet.jaxpfailed"));
    }
    return documentBuilder;
}