Example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

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

Introduction

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

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

private static boolean generateAppfromXML(String fn) {

    long starttime = System.currentTimeMillis();

    // fn must not be null or empty
    if (fn == null || fn.isEmpty()) {
        log.error("Empty filename!");
        return false;
    }//from w w  w  .  j  ava2 s.com
    // fn must be a valid file and readable
    File runnableitem = new File(fn);
    if (!runnableitem.exists() || !runnableitem.canRead()) {
        log.error("{} doesn't exists or can't be read! ", fn);
        return false;
    }
    // load as xml file, validate it, and ...
    Document doc;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        //dbf.setValidating(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(runnableitem);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("{} occured: {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }
    // extract project id, name  and version from it.
    String projectid = doc.getDocumentElement().getAttribute("id");
    if ((projectid == null) || projectid.isEmpty()) {
        log.error("Missing project id in description file!");
        return false;
    }
    String projectname;
    try {
        projectname = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "name").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.error("Missing project name in description file!");
        return false;
    }

    String projectversion = "unknown";
    try {
        projectversion = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "version").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.warn("Missing project version in description file!");

    }

    File projectdir = new File(
            config.getProperty("project.dir", config.getProperty("target.dir") + "/" + projectid));

    mkdirs(projectdir + "/src/main/java");
    mkdirs(projectdir + "/src/main/config");
    mkdirs(projectdir + "/src/main/libs");
    mkdirs(projectdir + "/src/main/pages");
    mkdirs(projectdir + "/src/main/resources");
    mkdirs(projectdir + "/src/main/downloads");

    // place runnableitem in config dir
    try {
        Files.copy(runnableitem.toPath(), new File(projectdir + "/src/main/config/runnableitem.xml").toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        log.error("{} occurred : {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }

    // copy files from SKELETON to projectdir and replace wildcard expression
    String[] SKELETON_INPUT_ARRAY = { "/pom.xml", "/src/main/config/log4j-tool.properties" };
    String SKELETON_INPUT = null;
    try {
        for (int c = 0; c < SKELETON_INPUT_ARRAY.length; c++) {
            SKELETON_INPUT = SKELETON_INPUT_ARRAY[c];

            InputStream in = Main.class.getResourceAsStream("/SKELETON" + SKELETON_INPUT);
            if (in == null) {
                throw new IOException();
            }

            CopyAndReplace(in, new FileOutputStream(new File(projectdir, SKELETON_INPUT)), projectid,
                    projectname, projectversion);
        }

    } catch (IOException e) {
        log.error("Exception occurred while calling 'copyAndReplace(/SKELETON{},{}/{},{},{},{})'",
                SKELETON_INPUT, projectdir, SKELETON_INPUT, projectid, projectname, projectversion);
        return false;
    }

    log.info("Empty project created! ");

    try {
        // _base 

        generate(CodeGen_Implementation.class, runnableitem, projectdir);
        log.info("Implementation generated!");

        generate(CodeGen_Implementation_Threadworker.class, runnableitem, projectdir);
        log.info("Implementation_Threadworker generated!");

        generate(CodeGen_Utilities.class, runnableitem, projectdir);
        log.info("Utilities generated!");

        generate(CodeGen_Common.class, runnableitem, projectdir, "/templates/common", RESOURCETYPE.isDirectory);

        log.info("Common generated!");

        // _REST
        generate(CodeGen_REST.class, runnableitem, projectdir);
        generate(CodeGen_REST_general.class, runnableitem, projectdir);

        log.info("REST generated!");

        //_HTML
        generate(CodeGen_WebSubmissionPage.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Visualization.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Formatchooser.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Function.class, runnableitem, projectdir);
        generate(CodeGen_Session_Reset.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Controller.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_Webstart.class, runnableitem, projectdir); // can be removed ???
        generate(CodeGen_WebToolBeanContextConfig.class, runnableitem, projectdir);
        generate(CodeGen_WebManual.class, runnableitem, projectdir);
        generate(CodeGen_WebPage.class, runnableitem, projectdir, "/templates/pages", RESOURCETYPE.isDirectory);

        log.info("XHTML pages generated!");

        long time = (System.currentTimeMillis() - starttime) / 1000;

        log.info("Project \"{}\" (id:{}, version:{}) created at '{}' in {} seconds.", projectname, projectid,
                projectversion, projectdir, time);

    } catch (CodeGenParserException e) {
        log.error("CodeGenParserException occurred :", e);
        return false;
    }
    return true;
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

/**
 *
 * @param url// w  w  w .ja  va  2  s. c  om
 * @param serviceName
 * @param xml
 * @return
 */
public static String executeMobyCgiAsyncService(String url, String serviceName, String xml)
        throws MobyException {

    // First, let's get the queryIds
    org.w3c.dom.Document message = null;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();

        message = db.parse(new InputSource(new StringReader(xml)));
    } catch (Throwable t) {
        throw new MobyException("Error while parsing input query", t);
    }

    NodeList l_data = message.getElementsByTagNameNS(MobyPrefixResolver.MOBY_XML_NAMESPACE, MobyTags.MOBYDATA);
    if (l_data == null || l_data.getLength() == 0) {
        l_data = message.getElementsByTagNameNS(MobyPrefixResolver.MOBY_XML_NAMESPACE_INVALID,
                MobyTags.MOBYDATA);
    }

    // Freeing resources
    message = null;

    if (l_data == null || l_data.getLength() == 0) {
        throw new MobyException("Empty asynchronous MOBY query!");
    }

    int nnode = l_data.getLength();
    String[] queryIds = new String[nnode];
    String[] tmpQueryIds = new String[nnode];
    String[] results = new String[nnode];
    for (int inode = 0; inode < nnode; inode++) {
        String queryId = null;

        org.w3c.dom.Element mdata = (org.w3c.dom.Element) l_data.item(inode);

        queryId = mdata.getAttribute(MobyTags.QUERYID);
        if (queryId == null || queryId.length() == 0)
            queryId = mdata.getAttributeNS(MobyPrefixResolver.MOBY_XML_NAMESPACE, MobyTags.QUERYID);
        if (queryId == null || queryId.length() == 0)
            queryId = mdata.getAttributeNS(MobyPrefixResolver.MOBY_XML_NAMESPACE_INVALID, MobyTags.QUERYID);

        if (queryId == null || queryId.length() == 0) {
            throw new MobyException("Unable to extract queryId for outgoing MOBY message");
        }

        tmpQueryIds[inode] = queryIds[inode] = queryId;
        results[inode] = null;
    }

    // Freeing resources
    l_data = null;

    // Second, let's launch
    EndpointReference epr = launchCgiAsyncService(url, xml);

    // Third, waiting for the results
    try {
        // FIXME - add appropriate values here
        long pollingInterval = 1000L;
        double backoff = 1.0;

        // Max: one minute pollings
        long maxPollingInterval = 60000L;

        // Min: one second
        if (pollingInterval <= 0L)
            pollingInterval = 1000L;

        // Backoff: must be bigger than 1.0
        if (backoff <= 1.0)
            backoff = 1.5;

        do {
            try {
                Thread.sleep(pollingInterval);
            } catch (InterruptedException ie) {
                // DoNothing(R)
            }

            if (pollingInterval != maxPollingInterval) {
                pollingInterval = (long) ((double) pollingInterval * backoff);
                if (pollingInterval > maxPollingInterval) {
                    pollingInterval = maxPollingInterval;
                }
            }
        } while (pollAsyncCgiService(serviceName, url, epr, tmpQueryIds, results));
    } finally {

        // Call destroy on this service ....
        freeCgiAsyncResources(url, epr);

    }

    // Fourth, assembling back the results

    // Results array already contains mobyData
    Element[] mobydatas = new Element[results.length];
    for (int x = 0; x < results.length; x++) {
        // TODO remove the extra wrapping from our result
        try {
            Element inputElement = XMLUtilities.getDOMDocument(results[x]).getRootElement();
            if (inputElement.getName().indexOf("GetMultipleResourcePropertiesResponse") >= 0)
                if (inputElement.getChildren().size() > 0)
                    inputElement = (Element) inputElement.getChildren().get(0);
            if (inputElement.getName().indexOf("result_") >= 0)
                if (inputElement.getChildren().size() > 0)
                    inputElement = (Element) inputElement.getChildren().get(0);
            // replace results[x]
            mobydatas[x] = inputElement;
        } catch (MobyException e) {
            // TODO what should i do?
        }
    }
    Element e = null;
    try {
        e = XMLUtilities.createMultipleInvokations(mobydatas);
    } catch (Exception ex) {
        logger.error("There was a problem creating our XML message ...", ex);
    }
    // Fifth, returning results
    return e == null ? "" : new XMLOutputter(Format.getPrettyFormat()).outputString(e);
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Reads the content of the persistence.xml file into an object model, with
 * the root node of type {@link Document}.
 * //from  w  w w  . j  a  v  a  2s  .c  o m
 * @param is
 *            {@link InputStream} of the persistence.xml content
 * @return root node of the parsed xml content
 * @throws InvalidConfigurationException
 *             if the content could not be read due to an I/O error or could
 *             not be parsed?
 */
private static Document parseDocument(final InputStream is) throws InvalidConfigurationException {
    Document persistenceXmlDoc;
    final List parsingErrors = new ArrayList();
    final InputSource source = new InputSource(is);
    final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);

    try {
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new ErrorLogger("XML InputStream", parsingErrors));
        persistenceXmlDoc = docBuilder.parse(source);
    } catch (ParserConfigurationException e) {
        log.error("Error during parsing, Caused by: {}.", e);
        throw new PersistenceLoaderException("Error during parsing persistence.xml, caused by: ", e);
    } catch (IOException e) {
        throw new InvalidConfigurationException("Error reading persistence.xml, caused by: ", e);
    } catch (SAXException e) {
        throw new InvalidConfigurationException("Error parsing persistence.xml, caused by: ", e);
    }

    if (!parsingErrors.isEmpty()) {
        throw new InvalidConfigurationException("Invalid persistence.xml", (Throwable) parsingErrors.get(0));
    }

    return persistenceXmlDoc;
}

From source file:com.photon.phresco.framework.commons.ApplicationsUtil.java

public static Document getDocument(File file) throws ParserConfigurationException, SAXException, IOException {
    InputStream fis = null;//  w  ww . j  a v  a2  s .  c  o m
    DocumentBuilder builder = null;
    try {
        fis = new FileInputStream(file);
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false);
        builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(fis);
        return doc;

    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

From source file:io.personium.core.model.DavRsCmp.java

private static Element parseProp(String value) {
    // valDOM?Element
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;/*from   w  w  w . jav  a2  s  .  co m*/
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw PersoniumCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}

From source file:se.vgregion.usdservice.USDServiceImpl.java

/**
 * Convenience method./*from   w w w  .jav a2  s . co  m*/
 *
 * @param xml, the xml to be parsed
 * @return a DOM Document
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private static Document parseXml(String xml) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setNamespaceAware(true);
    dbfactory.setXIncludeAware(true);

    DocumentBuilder parser = dbfactory.newDocumentBuilder();

    // To avoid illegal xml character references
    xml = xml.replace("&", "&amp;");
    ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    return parser.parse(bais);
}

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Creates the parser instance based on dom parser factory Validates the xml file against the
 * XSD schema Return the documentElement of the xml document if validations succeeded
 * /*w  w w .  ja  va  2 s . c om*/
 * @param xmlFile - XML file to be parsed
 * @param xmlSchema - XSD that XML file should be validated against
 * @return documentElement of the XML file
 */
public static Document getXmlDocumentElement(String xmlFile, String xmlSchema) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setCoalescing(true);
    factory.setNamespaceAware(false);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
            XMLUtil.class.getResource(xmlSchema).getFile());
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler());
    // Parse the document from the classpath.
    URL xmlFileUri = XMLUtil.class.getResource(xmlFile);
    if (null == xmlFileUri) {
        log.error("Unable to find file on classpath: " + xmlFile);
        return null;
    }
    return builder.parse(xmlFileUri.getFile());
}

From source file:Main.java

public static DocumentBuilder getDocumentBuilder(boolean secure) throws ParserConfigurationException {
    String feature;//w ww.j a  v  a2 s .  c o  m
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    feature = "http://xml.org/sax/features/external-general-entities";
    factory.setFeature(feature, false);
    feature = "http://xml.org/sax/features/external-parameter-entities";
    factory.setFeature(feature, false);
    feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    factory.setFeature(feature, false);
    feature = "http://apache.org/xml/features/disallow-doctype-decl";
    factory.setFeature(feature, true);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    factory.setNamespaceAware(true);
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secure);
    return factory.newDocumentBuilder();
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Constructs a DocumentBuilder object for XML documents
 *
 * @return DocumentBuilder object with the proper initializations
 *///from   ww w  .ja v  a2s.  co  m
public static DocumentBuilder generateDocumentBuilder() {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        return dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("ParserConfigurationException when attempting to generate a document builder.");
    }
    return null;
}

From source file:cz.cas.lib.proarc.common.export.mets.JhoveUtility.java

/**
 * Gets MIX of a source image file./*from  www. j a  va 2 s . c om*/
 *
 * @param sourceFile image file to describe with MIX
 * @param jhoveContext JHove
 * @param deviceMix optional device description
 * @param dateCreated optional date of creation of the source
 * @param originalFileName optional image file name
 * @return the MIX description
 * @throws MetsExportException failure
 */
public static JHoveOutput getMix(File sourceFile, JhoveContext jhoveContext, MixType deviceMix,
        XMLGregorianCalendar dateCreated, String originalFileName) throws MetsExportException {

    JHoveOutput jhoveOutput = new JHoveOutput();

    if (sourceFile == null || !sourceFile.isFile() || !sourceFile.exists()) {
        LOG.log(Level.SEVERE, "target file '" + sourceFile + "' cannot be found.");
        throw new MetsExportException("target file '" + sourceFile + "' cannot be found.", false, null);
    }
    try {
        JhoveBase jhoveBase = jhoveContext.getJhoveBase();
        File outputFile = File.createTempFile("jhove", "output");
        LOG.log(Level.FINE, "JHOVE output file " + outputFile);
        Module module = jhoveBase.getModule(null);
        OutputHandler aboutHandler = jhoveBase.getHandler(null);
        OutputHandler xmlHandler = jhoveBase.getHandler("XML");
        LOG.log(Level.FINE, "Calling JHOVE dispatch(...) on file " + sourceFile);
        jhoveBase.dispatch(jhoveContext.getJhoveApp(), module, aboutHandler, xmlHandler,
                outputFile.getAbsolutePath(), new String[] { sourceFile.getAbsolutePath() });
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document jHoveDoc = builder.parse(outputFile);

        outputFile.delete();
        Node node = getNodeRecursive(jHoveDoc, "mix");
        if (node == null) {
            return jhoveOutput;
        }
        Mix mix = MixUtils.unmarshal(new DOMSource(node), Mix.class);

        XPath xpath = XPathFactory.newInstance().newXPath();
        String formatVersion = xpath
                .compile("*[local-name()='jhove']/*[local-name()='repInfo']/*[local-name()='version']")
                .evaluate(jHoveDoc);
        if ((formatVersion == null) || ("0".equals(formatVersion)) || (formatVersion.trim().length() == 0)) {
            formatVersion = "1.0";
        }
        String formatName = xpath
                .compile("*[local-name()='jhove']/*[local-name()='repInfo']/*[local-name()='mimeType']")
                .evaluate(jHoveDoc);
        if ((formatName == null) || (formatName.trim().length() == 0)) {
            formatName = "unknown";
        }
        jhoveOutput.setFormatVersion(formatVersion);
        // merge device and jhove Mix
        mergeMix(mix, deviceMix);
        // insert date time created
        if ((dateCreated != null) && (mix != null)) {
            insertDateCreated(mix, dateCreated);
        }

        // insert ChangeHistory
        if ((dateCreated != null) && (originalFileName != null)) {
            insertChangeHistory(mix, dateCreated, originalFileName);
        }

        // add formatVersion
        if (mix != null) {
            if (mix.getBasicDigitalObjectInformation() == null) {
                mix.setBasicDigitalObjectInformation(new BasicDigitalObjectInformationType());
            }
            if (mix.getBasicDigitalObjectInformation().getFormatDesignation() == null) {
                mix.getBasicDigitalObjectInformation()
                        .setFormatDesignation(new BasicDigitalObjectInformationType.FormatDesignation());
            }
            StringType formatNameType = new StringType();
            StringType formatVersionType = new StringType();
            formatNameType.setValue(formatName);
            formatVersionType.setValue(formatVersion);
            mix.getBasicDigitalObjectInformation().getFormatDesignation().setFormatName(formatNameType);
            mix.getBasicDigitalObjectInformation().getFormatDesignation().setFormatVersion(formatVersionType);
        }

        // workarround for bug in Jhove - Unknown compression for jpeg2000
        if ("image/jp2".equals(formatName)) {
            if (mix.getBasicDigitalObjectInformation() == null) {
                mix.setBasicDigitalObjectInformation(new BasicDigitalObjectInformationType());
            }
            mix.getBasicDigitalObjectInformation().getCompression().clear();
            Compression compression = new BasicDigitalObjectInformationType.Compression();
            StringType jpeg2000Type = new StringType();
            jpeg2000Type.setValue("JPEG 2000");
            compression.setCompressionScheme(jpeg2000Type);
            mix.getBasicDigitalObjectInformation().getCompression().add(compression);
        }
        jhoveOutput.setMix(mix);
    } catch (Exception e) {
        throw new MetsExportException("Error inspecting file '" + sourceFile + "' - " + e.getMessage(), false,
                e);
    }
    return jhoveOutput;
}