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:com.netsteadfast.greenstep.util.BusinessProcessManagementUtils.java

public static String getResourceProcessId(File activitiBpmnFile) throws Exception {
    if (null == activitiBpmnFile || !activitiBpmnFile.exists()) {
        throw new Exception("file no exists!");
    }//from   w w w.  j  a va2s.  co m
    if (!activitiBpmnFile.getName().endsWith(_SUB_NAME)) {
        throw new Exception("not resource file.");
    }
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(activitiBpmnFile);
    Element element = doc.getDocumentElement();
    if (!"definitions".equals(element.getNodeName())) {
        throw new Exception("not resource file.");
    }
    String processId = activitiBpmnFile.getName();
    if (processId.endsWith(_SUB_NAME)) {
        processId = processId.substring(0, processId.length() - _SUB_NAME.length());
    }
    NodeList nodes = element.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if ("process".equals(node.getNodeName())) {
            NamedNodeMap nodeMap = node.getAttributes();
            for (int attr = 0; attr < nodeMap.getLength(); attr++) {
                Node processAttr = nodeMap.item(attr);
                if ("id".equals(processAttr.getNodeName())) {
                    processId = processAttr.getNodeValue();
                }
            }
        }
    }
    return processId;
}

From source file:org.b3mn.poem.Representation.java

protected static String erdfToJson(String erdf, String serverUrl) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;/* ww w .j  a  va2s.c om*/
    try {
        builder = factory.newDocumentBuilder();
        Document rdfDoc = builder.parse(new ByteArrayInputStream(erdfToRdf(erdf).getBytes(("UTF-8"))));
        return RdfJsonTransformation.toJson(rdfDoc, serverUrl).toString();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * Get Certificate thumb print and Issuer Name from the ACS token.
 * @param acsToken the acs token/*from  w w  w.j  a  v a 2  s  .  co m*/
 * @return returnData the Map containing Thumb print and issuer name of X509Certiificate
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
public static Map<String, String> getCertificateThumbPrintAndIssuerName(String acsToken)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    byte[] acsTokenByteArray = null;
    Map<String, String> returnData = new HashMap<String, String>();

    try {
        acsTokenByteArray = acsToken.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder;
    String issuerName = null;
    StringBuffer thumbprint = null;

    try {
        docBuilder = builderFactory.newDocumentBuilder();
        Document resultDoc = docBuilder.parse(new ByteArrayInputStream(acsTokenByteArray));
        Element keyInfo = (Element) resultDoc.getDocumentElement()
                .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo").item(0);

        NodeList x509CertNodeList = keyInfo.getElementsByTagName("X509Certificate");
        Element x509CertNode = (Element) x509CertNodeList.item(0);
        if (x509CertNode == null) {
            return null;
        }
        //generating Certificate to retrieve its detail.
        String x509CertificateData = x509CertNode.getTextContent();
        InputStream inStream = new Base64InputStream(new ByteArrayInputStream(x509CertificateData.getBytes()));
        CertificateFactory x509CertificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) x509CertificateFactory
                .generateCertificate(inStream);
        String issuerDN = x509Certificate.getIssuerDN().toString();
        String[] issuerDNData = issuerDN.split("=");
        issuerName = issuerDNData[1];

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = x509Certificate.getEncoded();
        md.update(der);
        thumbprint = new StringBuffer();
        thumbprint.append(Hex.encodeHex(md.digest()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    returnData.put("IssuerName", issuerName);
    returnData.put("Thumbprint", thumbprint.toString().toUpperCase());
    return returnData;
}

From source file:com.impetus.kundera.ejb.PersistenceXmlLoader.java

/**
 * Gets the document./*from w  w  w.  j  av  a 2 s .  co  m*/
 * 
 * @param configURL
 *            the config url
 * @return the document
 * @throws Exception
 *             the exception
 */
private static Document getDocument(URL configURL) throws Exception {
    InputStream is = null;
    if (configURL != null) {
        URLConnection conn = configURL.openConnection();
        conn.setUseCaches(false); // avoid JAR locking on Windows and Tomcat
        is = conn.getInputStream();
    }
    if (is == null) {
        throw new IOException("Failed to obtain InputStream from url: " + configURL);
    }

    DocumentBuilderFactory docBuilderFactory = null;
    docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setValidating(true);
    docBuilderFactory.setNamespaceAware(true);

    try {
        // otherwise Xerces fails in validation
        docBuilderFactory.setAttribute("http://apache.org/xml/features/validation/schema", true);
    } catch (IllegalArgumentException e) {
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(false);
    }

    InputSource source = new InputSource(is);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    // docBuilder.setEntityResolver( resolver );

    List errors = new ArrayList();
    docBuilder.setErrorHandler(new ErrorLogger("XML InputStream", errors));
    Document doc = docBuilder.parse(source);

    if (errors.size() != 0) {
        throw new PersistenceException("invalid persistence.xml", (Throwable) errors.get(0));
    }
    is.close(); //Close input Stream
    return doc;
}

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

/**
 *
 * @param xml: xml file content/* w ww  .  jav a2  s.c  o  m*/
 * @return
 * @throws Exception
 */
public static Document loadXMLFromStringContent(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * return true if the String passed in is something like XML
 *
 *
 * @param inString a string that might be XML
 * @return true of the string is XML, false otherwise
 *///  ww  w .  j a  v  a 2s.c  o  m
public static boolean isXML(String xml) {
    if (StringUtils.isBlank(xml)) {
        return false;
    }

    boolean isXml = true;
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    final DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    } catch (Exception e) {
        isXml = false;
    }
    return isXml;
}

From source file:com.google.code.joliratools.bind.apt.JAXROProcessorJSONTest.java

/**
 * @param xmlContent//from  w w w . j  a  v a 2  s . co  m
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private static XMLNode parse(final String xmlContent)
        throws ParserConfigurationException, SAXException, IOException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);

    final DocumentBuilder builder = factory.newDocumentBuilder();

    builder.setErrorHandler(new ErrorHandler() {
        @Override
        public void error(final SAXParseException exception) throws SAXException {
            throw exception;
        }

        @Override
        public void fatalError(final SAXParseException exception) throws SAXException {
            throw exception;
        }

        @Override
        public void warning(final SAXParseException exception) throws SAXException {
            throw exception;
        }
    });

    final Document document = builder.parse(new InputSource(new StringReader(xmlContent)));
    final XMLNode root = new XMLNode(document);
    return root;
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

public static Document parseXmlInputStream(InputStream inputStream, String features) throws Exception {
    Document xmlDocument;/* w  w w .  j  a v a  2 s .  co  m*/
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    XmlUtils.setFeatures(builderFactory, features);

    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    xmlDocument = builder.parse(inputStream);
    return xmlDocument;
}

From source file:com.microsoft.tfs.util.xml.JAXPUtils.java

/**
 * <p>//from   w w  w  .j ava2s.  c  o m
 * Creates a new (or configures an existing) {@link DocumentBuilderFactory}
 * that will perform XML Schema validation when parsing. This method is
 * called before parsing to obtain a configured
 * {@link DocumentBuilderFactory} that produces {@link DocumentBuilder}s
 * that will be used for XML Schema for validation.
 * </p>
 *
 * <p>
 * The supplied <code>schemaSource</code> object must be one of the
 * following:
 * <ul>
 * <li>A {@link String} that points to the URI of the schema</li>
 *
 * <li>An {@link InputStream} with the schema contents (will not be closed
 * by this method)</li>
 *
 * <li>A SAX {@link InputSource} that indicates the schema</li>
 *
 * <li>A {@link File} that indicates the schema</li>
 *
 * <li>An array of objects, each one of which is one of the above</li>
 * </ul>
 * </p>
 *
 * @throws XMLException
 *         if the {@link DocumentBuilderFactory} can't be created or
 *         properly configured
 *
 * @param factory
 *        the {@link DocumentBuilderFactory} to configure, or
 *        <code>null</code> to create a {@link DocumentBuilderFactory} using
 *        the {@link #newDocumentBuilderFactory()} method
 * @param schemaSource
 *        the schema source as described above
 * @return a configured {@link DocumentBuilderFactory} (never
 *         <code>null</code>)
 */
public static DocumentBuilderFactory newDocumentBuilderFactoryForXSValidation(DocumentBuilderFactory factory,
        final Object schemaSource) {
    if (factory == null) {
        factory = newDocumentBuilderFactory();
    }

    factory.setNamespaceAware(true);
    factory.setValidating(true);

    try {
        factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    } catch (final IllegalArgumentException e) {
        final String messageFormat = "The DocumentBuilderFactory [{0}] loaded from ClassLoader [{1}] does not support JAXP 1.2"; //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, factory.getClass().getName(),
                factory.getClass().getClassLoader());
        throw new XMLException(message, e);
    }

    if (schemaSource != null) {
        factory.setAttribute(JAXP_SCHEMA_SOURCE, schemaSource);
    }

    return factory;
}

From source file:gpms.utils.PolicyTestUtil.java

/**
 * This creates the expected XACML response from a file
 *
 * @param rootDirectory//from   ww w . j ava2  s. c  om
 *            root directory of the response files
 * @param versionDirectory
 *            version directory of the response files
 * @param responseId
 *            response file name
 * @return ResponseCtx or null if any error
 */
public static ResponseCtx createResponse(String rootDirectory, String versionDirectory, String responseId) {

    File file = new File(".");
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.RESPONSE_DIRECTORY + File.separator + responseId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        return ResponseCtx.getInstance(doc.getDocumentElement());
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        // ignore any exception and return null
    }

    return null;
}