Example usage for javax.xml.parsers DocumentBuilderFactory setAttribute

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

Introduction

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

Prototype

public abstract void setAttribute(String name, Object value) throws IllegalArgumentException;

Source Link

Document

Allows the user to set specific attributes on the underlying implementation.

Usage

From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java

public DefaultPluginDescriptorParser() {
    try {/*from  www.ja v a 2s. c  o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            URL url = new URL("http://www.qcadoo.com");
            url.openConnection();
            factory.setValidating(true);
        } catch (UnknownHostException e) {
            factory.setValidating(false);
        } catch (IOException e) {
            factory.setValidating(false);
        }
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");

        documentBuilder = factory.newDocumentBuilder();

        documentBuilder.setErrorHandler(new com.qcadoo.plugin.api.errorhandler.ValidationErrorHandler());

    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("Error while parsing plugin xml schema", e);
    }
}

From source file:integration.AbstractTest.java

/**
 * Parses the specified file and returns the document.
 * //from ww  w . ja va 2s  .  c om
 * @param file The file to parse.
 * @param schema The schema used to validate the specified file.
 * @return
 * @throws Exception Thrown if an error occurred.
 */
protected Document parseFile(File file, File schema) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file to parse.");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    if (schema != null) {
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        // Set the schema file
        dbf.setAttribute(JAXP_SCHEMA_SOURCE, schema);
    }
    DocumentBuilder builder = dbf.newDocumentBuilder();
    return builder.parse(file);
}

From source file:de.interactive_instruments.ShapeChange.Target.ReplicationSchema.ReplicationXmlSchema.java

@Override
public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {

    schemaPi = p;/* www .jav  a  2 s.c  o  m*/
    model = m;
    options = o;
    result = r;
    diagnosticsOnly = diagOnly;

    result.addDebug(this, 1, schemaPi.name());

    outputDirectory = options.parameter(this.getClass().getName(), "outputDirectory");
    if (outputDirectory == null)
        outputDirectory = options.parameter("outputDirectory");
    if (outputDirectory == null)
        outputDirectory = options.parameter(".");

    outputFilename = schemaPi.name().replace("/", "_").replace(" ", "_") + ".xsd";

    // Check if we can use the output directory; create it if it
    // does not exist
    outputDirectoryFile = new File(outputDirectory);
    boolean exi = outputDirectoryFile.exists();
    if (!exi) {
        try {
            FileUtils.forceMkdir(outputDirectoryFile);
        } catch (IOException e) {
            result.addError(null, 600, e.getMessage());
            e.printStackTrace(System.err);
        }
        exi = outputDirectoryFile.exists();
    }
    boolean dir = outputDirectoryFile.isDirectory();
    boolean wrt = outputDirectoryFile.canWrite();
    boolean rea = outputDirectoryFile.canRead();
    if (!exi || !dir || !wrt || !rea) {
        result.addFatalError(null, 601, outputDirectory);
        throw new ShapeChangeAbortException();
    }

    File outputFile = new File(outputDirectoryFile, outputFilename);

    // check if output file already exists - if so, attempt to delete it
    exi = outputFile.exists();
    if (exi) {

        result.addInfo(this, 3, outputFilename, outputDirectory);

        try {
            FileUtils.forceDelete(outputFile);
            result.addInfo(this, 4);
        } catch (IOException e) {
            result.addInfo(null, 600, e.getMessage());
            e.printStackTrace(System.err);
        }
    }

    // identify map entries defined in the target configuration
    List<ProcessMapEntry> mapEntries = options.getCurrentProcessConfig().getMapEntries();

    if (mapEntries == null || mapEntries.isEmpty()) {

        result.addFatalError(this, 9);
        throw new ShapeChangeAbortException();

    } else {

        for (ProcessMapEntry pme : mapEntries) {
            this.mapEntryByType.put(pme.getType(), pme);
        }
    }

    // reset processed flags on all classes in the schema
    for (Iterator<ClassInfo> k = model.classes(schemaPi).iterator(); k.hasNext();) {
        ClassInfo ci = k.next();
        ci.processed(getTargetID(), false);
    }

    // ======================================
    // Parse configuration parameters
    // ======================================

    objectIdentifierFieldName = options.parameter(this.getClass().getName(),
            PARAM_OBJECT_IDENTIFIER_FIELD_NAME);
    if (objectIdentifierFieldName == null || objectIdentifierFieldName.trim().length() == 0) {
        objectIdentifierFieldName = DEFAULT_OBJECT_IDENTIFIER_FIELD_NAME;
    }

    suffixForPropWithFeatureValueType = options.parameter(this.getClass().getName(),
            PARAM_SUFFIX_FOR_PROPERTIES_WITH_FEATURE_VALUE_TYPE);
    if (suffixForPropWithFeatureValueType == null || suffixForPropWithFeatureValueType.trim().length() == 0) {
        suffixForPropWithFeatureValueType = "";
    }

    suffixForPropWithObjectValueType = options.parameter(this.getClass().getName(),
            PARAM_SUFFIX_FOR_PROPERTIES_WITH_OBJECT_VALUE_TYPE);
    if (suffixForPropWithObjectValueType == null || suffixForPropWithObjectValueType.trim().length() == 0) {
        suffixForPropWithObjectValueType = "";
    }

    targetNamespaceSuffix = options.parameter(this.getClass().getName(), PARAM_TARGET_NAMESPACE_SUFFIX);
    if (targetNamespaceSuffix == null || objectIdentifierFieldName.trim().length() == 0) {
        targetNamespaceSuffix = "";
    }

    String defaultSizeByConfig = options.parameter(this.getClass().getName(), PARAM_SIZE);
    if (defaultSizeByConfig != null) {
        try {
            defaultSize = Integer.parseInt(defaultSizeByConfig);
        } catch (NumberFormatException e) {
            MessageContext mc = result.addWarning(this, 8, PARAM_SIZE, e.getMessage());
            mc.addDetail(this, 0);
        }
    }

    // ======================================
    // Set up the document and create root
    // ======================================

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        result.addFatalError(null, 2);
        throw new ShapeChangeAbortException();
    }
    document = db.newDocument();

    root = document.createElementNS(Options.W3C_XML_SCHEMA, "schema");
    document.appendChild(root);

    addAttribute(root, "xmlns", Options.W3C_XML_SCHEMA);
    addAttribute(root, "elementFormDefault", "qualified");

    addAttribute(root, "version", schemaPi.version());
    targetNamespace = schemaPi.targetNamespace() + targetNamespaceSuffix;
    addAttribute(root, "targetNamespace", targetNamespace);
    addAttribute(root, "xmlns:" + schemaPi.xmlns(), targetNamespace);

    hook = document.createComment("XML Schema document created by ShapeChange - http://shapechange.net/");
    root.appendChild(hook);
}

From source file:de.interactive_instruments.ShapeChange.ShapeChangeResult.java

public ShapeChangeResult(Options o) {
    init();//from w  w  w  .j a va  2 s .  c o m

    options = o;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
        DocumentBuilder db = dbf.newDocumentBuilder();
        document = db.newDocument();

        root = document.createElementNS(Options.SCRS_NS, "ShapeChangeResult");
        document.appendChild(root);
        root.setAttribute("resultCode", "0");
        root.setAttribute("xmlns:r", Options.SCRS_NS);
        root.setAttribute("start", (new Date()).toString());

        String version = "[dev]";
        InputStream stream = getClass().getResourceAsStream("/sc.properties");
        if (stream != null) {
            Properties properties = new Properties();
            properties.load(stream);
            version = properties.getProperty("sc.version");
        }
        root.setAttribute("version", version);

        messages = document.createElementNS(Options.SCRS_NS, "Messages");
        root.appendChild(messages);

        resultFiles = document.createElementNS(Options.SCRS_NS, "Results");
        root.appendChild(resultFiles);
    } catch (ParserConfigurationException e) {
        System.err.println("Bootstrap Error: XML parser was unable to be configured.");
        String m = e.getMessage();
        if (m != null) {
            System.err.println(m);
        }
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (Exception e) {
        System.err.println("Bootstrap Error: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(1);
    }

    outputFormat.setProperty("encoding", "UTF-8");
    outputFormat.setProperty("indent", "yes");
    outputFormat.setProperty("{http://xml.apache.org/xalan}indent-amount", "2");
}

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???/* www . j  a v a2  s .  co 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:com.amalto.workbench.utils.Util.java

public static Document parse(String xmlString, String schema) throws Exception {

    // parse//from ww w.j a  v  a 2 s.c om
    Document d = null;
    SAXErrorHandler seh = new SAXErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setValidating((schema != null));
        documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", //$NON-NLS-1$
                "http://www.w3.org/2001/XMLSchema");//$NON-NLS-1$
        if (schema != null) {
            documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", //$NON-NLS-1$
                    new InputSource(new StringReader(schema)));
        }

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setErrorHandler(seh);
        if (xmlString == null || xmlString.length() == 0 || xmlString.matches("\\s+")) {
            return d;
        }
        d = documentBuilder.parse(new InputSource(new StringReader(xmlString)));

        if (schema != null) {
            String errors = seh.getErrors();
            if (!errors.equals("")) {//$NON-NLS-1$
                String err = Messages.Util_12 + errors + Messages.Util_13;
                throw new Exception(err);
            }
        }
        return d;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        String err = Messages.Util_14 + Messages.Util_15 + e.getClass().getName() + Messages.Util_16
                + e.getLocalizedMessage() + Messages.Util_17 + xmlString;
        throw new Exception(err);
    }
}

From source file:nl.imvertor.common.file.XmlFile.java

public boolean isValid() {
    messages.removeAllElements();//  ww w  .  j a va  2  s.  c  o  m
    try {
        wfcode = WFCODE_OKAY;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        factory.setXIncludeAware(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");

        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(this);
        builder.parse(new InputSource(this.getCanonicalPath()));
    } catch (Exception e) {
        wfcode = WFCODE_FATAL;
    }
    return wfcode < WFCODE_ERROR;
}

From source file:org.apache.beehive.netui.util.config.internal.catalog.CatalogParser.java

public CatalogConfig parse(final String resourcePath, final InputStream inputStream) {
    CatalogConfig catalogConfig = null;/*from   www .  java  2s  .com*/
    InputStream xmlInputStream = null;
    InputStream xsdInputStream = null;
    try {
        xmlInputStream = inputStream;
        xsdInputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);

        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException exception) {
                LOG.info("Validation warning validating config file \"" + resourcePath
                        + "\" against XML Schema \"" + CONFIG_SCHEMA);
            }

            public void error(SAXParseException exception) {
                throw new RuntimeException("Validation errors occurred parsing the config file \""
                        + resourcePath + "\".  Cause: " + exception, exception);
            }

            public void fatalError(SAXParseException exception) {
                throw new RuntimeException("Validation errors occurred parsing the config file \""
                        + resourcePath + "\".  Cause: " + exception, exception);
            }
        });

        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.endsWith("/catalog-config.xsd")) {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA);
                    return new InputSource(inputStream);
                } else
                    return null;
            }
        });

        Document document = db.parse(xmlInputStream);
        Element catalogElement = document.getDocumentElement();
        catalogConfig = parse(catalogElement);

    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } catch (IOException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } catch (SAXException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } finally {
        try {
            if (xsdInputStream != null)
                xsdInputStream.close();
        } catch (IOException e) {
        }
    }

    return catalogConfig;
}

From source file:org.apache.rahas.TrustUtil.java

/**
 * Create DocumentBuilderFactory with the XXE and XEE prevention measurements
 *
 * @return DocumentBuilderFactory instance
 *//* ww w  . j  a  va2s .  com*/
public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    try {
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        logger.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE
                + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or "
                + Constants.LOAD_EXTERNAL_DTD_FEATURE + "or secure-processing.");
    }

    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);

    return dbf;
}