Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

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

Introduction

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

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java

protected Document readContentAsDom(FileObject file, boolean nameSpaceAware) throws Exception {
    InputStream is = null;//  www  . ja  v  a  2  s .  com

    try {
        is = file.getContent().getInputStream();

        DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(nameSpaceAware);
        parserFactory.setIgnoringElementContentWhitespace(false);
        parserFactory.setIgnoringComments(false);

        DocumentBuilder builder = parserFactory.newDocumentBuilder();

        boolean dtdNotFound = false;
        Document doc = null;
        try {
            doc = builder.parse(is);
        } catch (FileNotFoundException e) {
            dtdNotFound = true;
        }

        // if dtd doesn't exist parse the document again without trying to load dtd
        if (dtdNotFound) {
            is = file.getContent().getInputStream();
            // disable dtd loading
            parserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            builder = parserFactory.newDocumentBuilder();
            doc = builder.parse(is);
        }

        DocumentType docType = doc.getDoctype();

        if (log.isDebugEnabled() && docType != null) {
            log.debug("docType.getPublicId()=" + docType.getPublicId());
            log.debug("docType.getSystemId()=" + docType.getSystemId());
        }

        return doc;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                /**/}
    }

}

From source file:org.jumpmind.symmetric.ClientSymmetricEngine.java

@Override
protected void init() {
    try {//from  ww w  .ja  va2  s  .c o m
        LogSummaryAppenderUtils.registerLogSummaryAppender();

        super.init();

        this.dataSource = platform.getDataSource();

        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(parameterService.getAllParameters());

        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(springContext);
        ctx.addBeanFactoryPostProcessor(configurer);

        List<String> extensionLocations = new ArrayList<String>();
        extensionLocations.add("classpath:/symmetric-ext-points.xml");
        if (registerEngine) {
            extensionLocations.add("classpath:/symmetric-jmx.xml");
        }

        String xml = parameterService.getString(ParameterConstants.EXTENSIONS_XML);
        File file = new File(parameterService.getTempDirectory(), "extension.xml");
        FileUtils.deleteQuietly(file);
        if (isNotBlank(xml)) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(false);
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                // the "parse" method also validates XML, will throw an exception if misformatted
                builder.parse(new InputSource(new StringReader(xml)));
                FileUtils.write(file, xml, false);
                extensionLocations.add("file:" + file.getAbsolutePath());
            } catch (Exception e) {
                log.error("Invalid " + ParameterConstants.EXTENSIONS_XML + " parameter.");
            }
        }

        try {
            ctx.setConfigLocations(extensionLocations.toArray(new String[extensionLocations.size()]));
            ctx.refresh();

            this.springContext = ctx;

            ((ClientExtensionService) this.extensionService).setSpringContext(springContext);
            this.extensionService.refresh();
        } catch (Exception ex) {
            log.error(
                    "Failed to initialize the extension points.  Please fix the problem and restart the server.",
                    ex);
        }
    } catch (RuntimeException ex) {
        destroy();
        throw ex;
    }
}

From source file:org.jzkit.search.provider.z3950.Z3950SearchTask.java

public Z3950SearchTask(Z3950Origin protocol_endpoint, Observer[] observers,
        RecordFormatSpecification default_spec) {
    super(observers);
    dbg_counter++;/*  ww  w.ja  v  a  2s  . co m*/
    this.protocol_endpoint = protocol_endpoint;
    this.default_spec = default_spec;
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setValidating(false);
        docBuilder = docFactory.newDocumentBuilder();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.kapott.hbci.tools.TransactionsToXML.java

public Document createXMLDocument(List<UmsLine> transactions, String rawMT940) {
    // Empfangene Transaktionen als XML-Datei aufbereiten
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    fac.setIgnoringComments(true);/*from   w ww. j  a  va 2  s .  c o m*/
    fac.setValidating(false);

    // create document
    DocumentBuilder builder;
    try {
        builder = fac.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();

    Element root = doc.createElement("account_transactions");
    doc.appendChild(root);

    // <transactions>
    if (transactions != null) {
        Element transElement = doc.createElement("transactions");
        root.appendChild(transElement);
        createTransactionElements(doc, transElement, transactions);
    }

    // <raw>
    if (rawMT940 != null) {
        Element rawElem = doc.createElement("raw");
        root.appendChild(rawElem);

        try {
            String mt940_encoded = Base64.encodeBase64String(rawMT940.getBytes("ISO-8859-1"));
            rawElem.appendChild(doc.createCDATASection(mt940_encoded));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return doc;
}

From source file:org.kchine.rpf.reg.ServantProviderFactoryReg.java

void initPoolsHashMap(InputStream poolsXmlStream) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//from   ww  w.j  a  v a 2s.c o m
    domFactory.setValidating(false);
    DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(poolsXmlStream);
    NodeList pools = document.getDocumentElement().getChildNodes();
    for (int i = 0; i < pools.getLength(); ++i) {
        Node p = pools.item(i);
        if (p.getNodeName().equals("pool")) {
            String name = p.getAttributes().getNamedItem("name").getNodeValue();
            int timeout = p.getAttributes().getNamedItem("borrowTimeout") == null ? DEFAULT_TIMEOUT
                    : Integer.decode(p.getAttributes().getNamedItem("borrowTimeout").getNodeValue());
            PoolData poolData = new PoolData(name, timeout, new Vector<PoolNode>());
            _poolHashMap.put(poolData.getPoolName(), poolData);

            NodeList pnodes = p.getChildNodes();
            for (int j = 0; j < pnodes.getLength(); ++j) {
                Node pn = pnodes.item(j);
                if (pn.getNodeName().equals("node")) {
                    String prefix = pn.getAttributes().getNamedItem("prefix") == null ? DEFAULT_PREFIX
                            : pn.getAttributes().getNamedItem("prefix").getNodeValue();
                    String host = pn.getAttributes().getNamedItem("registryHost") == null
                            ? DEFAULT_REGISTRY_HOST
                            : pn.getAttributes().getNamedItem("registryHost").getNodeValue();
                    int port = pn.getAttributes().getNamedItem("registryPort") == null ? DEFAULT_REGISTRY_PORT
                            : Integer.decode(pn.getAttributes().getNamedItem("registryPort").getNodeValue());
                    poolData.getNodes().add(new PoolNode(prefix, host, port));
                }
            }
        }
    }

    _defaultPoolName = document.getDocumentElement().getAttribute("default");
    if (_poolHashMap.get(_defaultPoolName) == null)
        throw new Exception("bad default pool name");
}

From source file:org.kepler.dataproxy.datasource.geon.GEONDatabaseResource.java

/**
 * Creates the schema definition from the cached metadata file
 *///from  ww w. j  ava2s.c  o  m
private void createSchemaFromData(File cachedMetaDataFile) {
    StringBuffer schema = new StringBuffer();
    schema.append("<schema>\n");
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is = new FileInputStream(cachedMetaDataFile);
        Document doc = builder.parse(is);

        int numTables = 0;

        // NodeList tables = XPathAPI.selectNodeList(doc, TABLEENTITY);
        NodeList schemas = XPathAPI.selectNodeList(doc, SCHEMAENTITY);
        for (int x = 0; x < schemas.getLength(); x++) {
            String schemaName = ((Element) schemas.item(x)).getAttribute(SCHEMANAMEATT);
            NodeList tables = schemas.item(x).getChildNodes();
            for (int i = 0; i < tables.getLength(); i++) {
                Node child = tables.item(i);
                if (!(child instanceof Element))
                    continue;
                // get table name
                String tableName = ((Element) tables.item(i)).getAttribute(TABLENAMEATT);
                if (tableName == null || tableName.equals(""))
                    continue; // table with no name
                else {
                    // get fields
                    if (schemaName != null && !schemaName.equals("") && schemas.getLength() > 1)
                        tableName = schemaName + "." + tableName;
                    StringBuffer table = new StringBuffer();
                    table.append("  <table name=\"" + tableName + "\">\n");
                    int numFields = 0;

                    NodeList fields = ((Element) tables.item(i)).getElementsByTagName(FIELDTAG);
                    for (int j = 0; j < fields.getLength(); j++) {
                        Element field = (Element) fields.item(j);
                        // get field name
                        String fieldName = field.getAttribute(FIELDATT);
                        if (fieldName == null || fieldName.equals(""))
                            continue;
                        else {
                            numFields++;

                            // get field type
                            NodeList datatypes = field.getElementsByTagName(FIELDDATATYPE);
                            String datatype = datatypes.item(0).getFirstChild().getNodeValue();
                            if (datatype == null || datatype.equals(""))
                                datatype = "UNKNOWN";
                            NodeList fieldsizes = field.getElementsByTagName(FIELDSIZE);
                            String size = fieldsizes.item(0).getFirstChild().getNodeValue();
                            if (size != null && !size.equals(""))
                                datatype += "(" + size + ")";
                            NodeList constraints = field.getElementsByTagName(FIELDRESTRICTION);
                            String constraint = constraints.item(0).getFirstChild().getNodeValue();
                            if (constraint != null && constraint.trim().toLowerCase().startsWith("no"))
                                datatype += "  not null";
                            table.append(
                                    "    <field name=\"" + fieldName + "\" dataType=\"" + datatype + "\"/>\n");
                        }
                    }
                    table.append("  </table>\n");
                    if (numFields > 0) {
                        numTables++;
                        schema.append(table.toString());
                    }
                }
            }
        }
        schema.append("</schema>");
        if (numTables > 0) {
            _schemaAttr.setExpression(schema.toString());
        } else {
            setIconStatus(TITLE_ERROR, MAGENTA);
        }

    } catch (Exception ex) {
        System.out.println("Unable to populate schema: " + ex.getMessage());
    }

}

From source file:org.kuali.kfs.module.purap.service.impl.ElectronicInvoiceHelperServiceImpl.java

protected byte[] addNamespaceDefinition(ElectronicInvoiceLoad eInvoiceLoad, File invoiceFile) {

    boolean result = true;

    if (LOG.isInfoEnabled()) {
        LOG.info("Adding namespace definition");
    }/*from w w w. ja va2 s  .com*/

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(false); // It's not needed to validate here
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder(); // Create the parser
    } catch (ParserConfigurationException e) {
        LOG.error("Error getting document builder - " + e.getMessage());
        throw new RuntimeException(e);
    }

    Document xmlDoc = null;

    try {
        xmlDoc = builder.parse(invoiceFile);
    } catch (Exception e) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Error parsing the file - " + e.getMessage());
        }
        rejectElectronicInvoiceFile(eInvoiceLoad, UNKNOWN_DUNS_IDENTIFIER, invoiceFile, e.getMessage(),
                PurapConstants.ElectronicInvoice.FILE_FORMAT_INVALID);
        return null;
    }

    Node node = xmlDoc.getDocumentElement();
    Element element = (Element) node;

    String xmlnsValue = element.getAttribute("xmlns");
    String xmlnsXsiValue = element.getAttribute("xmlns:xsi");

    File namespaceAddedFile = getInvoiceFile(invoiceFile.getName());

    if (StringUtils.equals(xmlnsValue, "http://www.kuali.org/kfs/purap/electronicInvoice")
            && StringUtils.equals(xmlnsXsiValue, "http://www.w3.org/2001/XMLSchema-instance")) {
        if (LOG.isInfoEnabled()) {
            LOG.info("xmlns and xmlns:xsi attributes already exists in the invoice xml");
        }
    } else {
        element.setAttribute("xmlns", "http://www.kuali.org/kfs/purap/electronicInvoice");
        element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    }

    OutputFormat outputFormat = new OutputFormat(xmlDoc);
    outputFormat.setOmitDocumentType(true);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer(out, outputFormat);
    try {
        serializer.asDOMSerializer();
        serializer.serialize(xmlDoc.getDocumentElement());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("Namespace validation completed");
    }

    return out.toByteArray();

}

From source file:org.kuali.kfs.sys.context.CheckModularization.java

protected Document generateDwrConfigDocument(String fileName) throws Exception {
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader(ClassLoaderUtils.getDefaultClassLoader());
    InputStream in = resourceLoader.getResource(fileName).getInputStream();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new DTDEntityResolver());
    db.setErrorHandler(new LogErrorHandler());

    Document doc = db.parse(in);/*from  ww w.jav  a2  s. co m*/
    return doc;
}

From source file:org.kuali.ole.module.purap.service.impl.ElectronicInvoiceHelperServiceImpl.java

protected byte[] addNamespaceDefinition(ElectronicInvoiceLoad eInvoiceLoad, File invoiceFile) {

    boolean result = true;

    if (LOG.isInfoEnabled()) {
        LOG.info("Adding namespace definition");
    }/*from ww w.  j ava 2s.  c  o m*/

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setValidating(false); // It's not needed to validate here
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder(); // Create the parser
    } catch (ParserConfigurationException e) {
        LOG.error("Error getting document builder - " + e.getMessage());
        throw new RuntimeException(e);
    }

    Document xmlDoc = null;

    try {
        xmlDoc = builder.parse(invoiceFile);
    } catch (Exception e) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Error parsing the file - " + e.getMessage());
        }
        rejectElectronicInvoiceFile(eInvoiceLoad, UNKNOWN_DUNS_IDENTIFIER, invoiceFile, e.getMessage(),
                PurapConstants.ElectronicInvoice.FILE_FORMAT_INVALID);
        return null;
    }

    Node node = xmlDoc.getDocumentElement();
    Element element = (Element) node;

    String xmlnsValue = element.getAttribute("xmlns");
    String xmlnsXsiValue = element.getAttribute("xmlns:xsi");

    File namespaceAddedFile = getInvoiceFile(invoiceFile.getName());

    if (StringUtils.equals(xmlnsValue, "http://www.kuali.org/ole/purap/electronicInvoice")
            && StringUtils.equals(xmlnsXsiValue, "http://www.w3.org/2001/XMLSchema-instance")) {
        if (LOG.isInfoEnabled()) {
            LOG.info("xmlns and xmlns:xsi attributes already exists in the invoice xml");
        }
    } else {
        element.setAttribute("xmlns", "http://www.kuali.org/ole/purap/electronicInvoice");
        element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    }

    OutputFormat outputFormat = new OutputFormat(xmlDoc);
    outputFormat.setOmitDocumentType(true);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer(out, outputFormat);
    try {
        serializer.asDOMSerializer();
        serializer.serialize(xmlDoc.getDocumentElement());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("Namespace validation completed");
    }

    return out.toByteArray();

}