Example usage for javax.xml.parsers DocumentBuilderFactory setCoalescing

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

Introduction

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

Prototype


public void setCoalescing(boolean coalescing) 

Source Link

Document

Specifies that the parser produced by this code will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node.

Usage

From source file:org.kuali.rice.kew.mail.service.impl.StyleableEmailContentServiceImpl.java

protected static DocumentBuilder getDocumentBuilder(boolean coalesce) {
    try {//from w  w  w . ja  v  a2  s . c o  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setCoalescing(coalesce);
        return dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        String message = "Error constructing document builder";
        LOG.error(message, e);
        throw new WorkflowRuntimeException(message, e);
    }
}

From source file:org.mule.modules.sugarcrm.automation.unit.TransformerXmlToCxfTest.java

@Test
public void validTransformationXmlFromSugar() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from www .  j a v  a  2s  .  co m
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    DocumentBuilder db = dbf.newDocumentBuilder();

    String xml = IOUtils.getResourceAsString("response-searchByModule.xml", getClass());
    String xmlTransform = new XmlToCxfTransformer().transform(xml);

    Document doc1 = db.parse(org.apache.commons.io.IOUtils.toInputStream(xmlTransform));
    doc1.normalizeDocument();

    Document doc2 = db.parse(IOUtils.getResourceAsStream("response-searchByModule-ok.xml", getClass()));
    doc2.normalizeDocument();

    Assert.assertTrue(doc1.isEqualNode(doc2));
}

From source file:org.opendatakit.aggregate.externalservice.GoogleMapsEngine.java

public static String parseGmeAssetId(IForm form, CallingContext cc) throws ODKDatastoreException,
        UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException {
    String gmeAssetId = null;/*from  ww w. ja  va2  s.c  o  m*/

    String formXml = form.getFormXml(cc);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(true);
    factory.setCoalescing(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(formXml.getBytes(HtmlConsts.UTF8_ENCODE)));

    Element rootXml = doc.getDocumentElement();
    NodeList instance = rootXml.getElementsByTagName("instance");

    for (int i = 0; i < instance.getLength(); ++i) {
        Node possibleInstanceNode = instance.item(i);
        NodeList possibleFormRootValues = possibleInstanceNode.getChildNodes();
        for (int j = 0; j < possibleFormRootValues.getLength(); ++j) {
            Node node = possibleFormRootValues.item(j);
            if (node instanceof Element) {
                Element possibleFormRoot = (Element) node;
                // extract form id
                String formId = possibleFormRoot.getAttribute("id");
                // if odk id is not present use namespace
                if (formId.equalsIgnoreCase(BasicConsts.EMPTY_STRING)) {
                    String schema = possibleFormRoot.getAttribute("xmlns");
                    if (!formId.equalsIgnoreCase(BasicConsts.EMPTY_STRING)) {
                        formId = schema;
                    }

                }

                // if form id is present correct node, therefore extract gme asset id
                if (form.getFormId().equals(formId)) {
                    gmeAssetId = possibleFormRoot.getAttribute(GME_ASSET_ID);
                }
            }
        }

    }
    return gmeAssetId;
}

From source file:org.opendatakit.aggregate.parser.SubmissionParser.java

/**
 * Helper Constructor an ODK submission by processing XML submission to
 * extract values//  w  w w. j  a  v a2 s  .  c  o m
 * 
 * @param inputStreamXML
 *          xml submission input stream
 * @param isIncomplete
 * 
 * @throws IOException
 * @throws ODKFormNotFoundException
 *           thrown if a form is not found with a matching ODK ID
 * @throws ODKParseException
 * @throws ODKIncompleteSubmissionData
 * @throws ODKConversionException
 * @throws ODKDatastoreException
 * @throws ODKFormSubmissionsDisabledException
 */
private void constructorHelper(InputStream inputStreamXML, boolean isIncomplete, CallingContext cc)
        throws IOException, ODKFormNotFoundException, ODKParseException, ODKIncompleteSubmissionData,
        ODKConversionException, ODKDatastoreException, ODKFormSubmissionsDisabledException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setCoalescing(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(inputStreamXML);
        root = doc.getDocumentElement();
        // if debugging: printNode(root);

        // check for odk id
        formId = root.getAttribute(ParserConsts.FORM_ID_ATTRIBUTE_NAME);

        // if odk id is not present use namespace
        if (formId.equalsIgnoreCase(BasicConsts.EMPTY_STRING)) {
            String schema = root.getAttribute(ParserConsts.NAMESPACE_ATTRIBUTE);

            // TODO: move this into FormDefinition?
            if (schema == null) {
                throw new ODKIncompleteSubmissionData(Reason.ID_MISSING);
            }

            formId = schema;
        }

    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    } catch (SAXException e) {
        e.printStackTrace();
        throw new IOException(e);
    }

    // need to escape all slashes... for xpath processing...
    formId = formId.replaceAll(ParserConsts.FORWARD_SLASH, ParserConsts.FORWARD_SLASH_SUBSTITUTION);

    String fullyQualifiedId = FormFactory.extractWellFormedFormId(formId);

    form = FormFactory.retrieveFormByFormId(fullyQualifiedId, cc);
    if (!form.getSubmissionEnabled()) {
        throw new ODKFormSubmissionsDisabledException();
    }

    String modelVersionString = root.getAttribute(ParserConsts.MODEL_VERSION_ATTRIBUTE_NAME);
    String uiVersionString = root.getAttribute(ParserConsts.UI_VERSION_ATTRIBUTE_NAME);
    Long modelVersion = null;
    Long uiVersion = null;
    if (modelVersionString != null && modelVersionString.length() > 0) {
        modelVersion = Long.valueOf(modelVersionString);
    }
    if (uiVersionString != null && uiVersionString.length() > 0) {
        uiVersion = Long.valueOf(uiVersionString);
    }

    String instanceId = getOpenRosaInstanceId();
    if (instanceId == null) {
        instanceId = root.getAttribute(ParserConsts.INSTANCE_ID_ATTRIBUTE_NAME);
        if (instanceId == null || instanceId.length() == 0) {
            instanceId = CommonFieldsBase.newUri();
        }
    }

    Date submissionDate = new Date();
    String submissionDateString = root.getAttribute(ParserConsts.SUBMISSION_DATE_ATTRIBUTE_NAME);
    if (submissionDateString != null && submissionDateString.length() != 0) {
        submissionDate = WebUtils.parseDate(submissionDateString);
    }

    Date markedAsCompleteDate = new Date();
    String markedAsCompleteDateString = root.getAttribute(ParserConsts.MARKED_AS_COMPLETE_DATE_ATTRIBUTE_NAME);
    if (markedAsCompleteDateString != null && markedAsCompleteDateString.length() != 0) {
        markedAsCompleteDate = WebUtils.parseDate(markedAsCompleteDateString);
    }

    // retrieve the record with this instanceId from the database or
    // create a new one. This supports submissions having more than
    // 10MB of attachments. In that case, ODK Collect will post the
    // submission in multiple parts and Aggregate needs to be able to
    // merge the parts together. This SHOULD NOT be used to 'update'
    // an existing submission, only to attach additional binary content
    // to an already-uploaded submission.
    boolean preExisting = false;
    try {
        Datastore ds = cc.getDatastore();
        User user = cc.getCurrentUser();
        TopLevelInstanceData fi = (TopLevelInstanceData) ds.getEntity(
                form.getTopLevelGroupElement().getFormDataModel().getBackingObjectPrototype(), instanceId,
                user);
        try {
            submission = new Submission(fi, form, cc);
        } catch (ODKDatastoreException e) {
            Log logger = LogFactory.getLog(Submission.class);
            e.printStackTrace();
            logger.error("Unable to reconstruct submission for " + fi.getSchemaName() + "." + fi.getTableName()
                    + " uri " + fi.getUri());
            if ((e instanceof ODKEntityNotFoundException) || (e instanceof ODKEnumeratedElementException)) {
                // this is a malformed submission...
                // try to clean this up...
                DeleteHelper.deleteDamagedSubmission(fi, form.getAllBackingObjects(), cc);
            }
            throw e;
        }
        preExisting = true;
        preExistingComplete = submission.isComplete();
    } catch (ODKEntityNotFoundException e) {
        submission = new Submission(modelVersion, uiVersion, instanceId, form, submissionDate, cc);
    }

    topLevelTableKey = submission.getKey();

    Map<String, Integer> repeatGroupIndices = new HashMap<String, Integer>();
    FormElementModel formRoot = form.getTopLevelGroupElement();
    // if the submission is pre-existing in the datastore, ONLY update binaries
    boolean uploadAllBinaries = processSubmissionElement(formRoot, root, submission, repeatGroupIndices,
            preExisting, cc);
    submission.setIsComplete(uploadAllBinaries);
    if (uploadAllBinaries) {
        submission.setMarkedAsCompleteDate(markedAsCompleteDate);
    }
    // save the elements inserted into the top-level submission
    try {
        submission.persist(cc);
    } catch (Exception e) {
        List<EntityKey> keys = new ArrayList<EntityKey>();
        submission.recursivelyAddEntityKeysForDeletion(keys, cc);
        keys.add(submission.getKey());
        try {
            DeleteHelper.deleteEntities(keys, cc);
        } catch (Exception ex) {
            // ignore... we are rolling back...
        }
        throw new ODKDatastoreException("Unable to persist data", e);
    }
}

From source file:org.topazproject.mulgara.itql.XmlHelper.java

/**
 * Helper to parse an XML string into a DOM.
 *
 * @param xml the xml string//w w  w  .j  a  v a2  s  . co  m
 * @return the document
 * @throws AnswerException if an error occured parsing the xml
 */
public static Document parseXml(String xml) throws AnswerException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setIgnoringComments(true);
    builderFactory.setCoalescing(true);

    DocumentBuilder builder;
    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        throw new RuntimeException(pce); // can this happen?
    }

    try {
        return builder.parse(new InputSource(new StringReader(xml)));
    } catch (IOException ioe) {
        throw new Error(ioe); // can't happen
    } catch (SAXException se) {
        throw new AnswerException("Unexpected response: '" + xml + "'", se);
    }
}

From source file:org.topazproject.mulgara.resolver.CacheInvalidator.java

/** 
 * Create a new cache-invalidator instance. 
 * //from  ww w .  j a v  a  2 s  .  co m
 * @param config  the configuration to use
 * @param base    the prefix under which the current <var>config</var> was retrieved
 * @param sf      the session-factory we belong to
 * @param dbURI   the uri of our database
 * @throws Exception 
 */
public CacheInvalidator(Configuration config, String base, SessionFactory sf, URI dbURI) throws Exception {
    super(0, getInvIval(config), "CacheInvalidator-Worker", false, logger);
    xaResource = new CIXAResource();

    config = config.subset("cacheInvalidator");
    base += ".cacheInvalidator";

    // parse the rules file
    String rulesLoc = config.getString("rulesFile", null);
    if (rulesLoc == null)
        throw new IOException("Missing configuration entry '" + base + ".rulesFile");

    URL loc = findResOrURL(rulesLoc);
    if (loc == null)
        throw new IOException("Rules-file '" + rulesLoc + "' not found");

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setIgnoringComments(true);
    builderFactory.setCoalescing(true);

    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Element rules = builder.parse(new InputSource(loc.toString())).getDocumentElement();

    this.aliases = parseAliases(rules, dbURI);
    this.rules = parseRules(rules, aliases);

    // set up the Ehcache
    disableJULInfoMessages();
    String ehcConfigLoc = config.getString("ehcacheConfig", null);
    boolean useSingleton = config.getBoolean("useSharedCacheManager", false);
    if (ehcConfigLoc != null) {
        loc = findResOrURL(ehcConfigLoc);
        if (loc == null)
            throw new IOException("Ehcache config file '" + ehcConfigLoc + "' not found");

        cacheManager = useSingleton ? CacheManager.create(loc) : new CacheManager(loc);
    } else {
        cacheManager = useSingleton ? CacheManager.create() : new CacheManager();
    }

    String qcName = config.getString("queryCache", DEF_QC_NAME);
    queryCache = cacheManager.getEhcache(qcName);
    if (queryCache != null)
        logger.info("Using cache '" + qcName + "' for the query caching");
    else
        logger.info("No cache named '" + qcName + "' found - disabling query caching");

    // delay session creation because at this point we're already in a session-creation call
    sessFactory = sf;

    // we're ready
    worker.start();
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

@Override
public String signElement(String sourceXML, String elementName, String namespace, boolean removeIdAttribute,
        boolean signatureAfterElement, boolean inclusive) throws Exception {
    loadCertificate();/*from   w w w.  j a v a 2  s .  c  o  m*/
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setCoalescing(true);
    dbf.setNamespaceAware(true);
    DocumentBuilder documentBuilder = dbf.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(sourceXML));
    Document doc = documentBuilder.parse(is);
    Element elementForSign = (Element) doc.getElementsByTagNameNS(namespace, elementName).item(0);

    Node parentNode = null;
    Element detachedElementForSign;
    Document detachedDocument;
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
        detachedElementForSign = detachedDocument.getDocumentElement();
    } else {
        detachedElementForSign = elementForSign;
        detachedDocument = doc;
    }

    String signatureMethodUri = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411";
    String canonicalizationMethodUri = inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
            : "http://www.w3.org/2001/10/xml-exc-c14n#";
    XMLSignature sig = new XMLSignature(detachedDocument, "", signatureMethodUri, canonicalizationMethodUri);
    if (!removeIdAttribute) {
        detachedElementForSign.setAttribute("Id", detachedElementForSign.getTagName());
    }
    if (signatureAfterElement)
        detachedElementForSign.insertBefore(sig.getElement(),
                detachedElementForSign.getLastChild().getNextSibling());
    else {
        detachedElementForSign.insertBefore(sig.getElement(), detachedElementForSign.getFirstChild());
    }
    Transforms transforms = new Transforms(detachedDocument);
    transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
    transforms.addTransform(inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
            : "http://www.w3.org/2001/10/xml-exc-c14n#");

    String digestURI = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
    sig.addDocument(removeIdAttribute ? "" : "#" + detachedElementForSign.getTagName(), transforms, digestURI);
    sig.addKeyInfo(cert);
    sig.sign(privateKey);

    if ((!elementForSign.isSameNode(doc.getDocumentElement())) && (parentNode != null)) {
        Node signedNode = doc.importNode(detachedElementForSign, true);
        parentNode.appendChild(signedNode);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    trans.setOutputProperty("omit-xml-declaration", "yes");
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    trans.transform(new DOMSource(doc), streamResult);
    return stringWriter.toString();
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

private Document createDocumentFromFragment(List<QName> namespaces, String appData)
        throws SAXException, IOException, ParserConfigurationException {
    // ? ?  ???   :
    final QName wsu = new QName(WSU, "wsu");
    final QName ds = new QName("http://www.w3.org/2000/09/xmldsig#", "ds");
    if (namespaces.indexOf(wsu) == -1) {
        namespaces.add(wsu);/*www . j  av a2s .  com*/
    }
    if (namespaces.indexOf(ds) == -1) {
        namespaces.add(ds);
    }
    final StringBuilder sb = new StringBuilder();
    sb.append("<root");
    for (final QName name : namespaces) {
        sb.append(" xmlns:");
        sb.append(name.getLocalPart());
        sb.append("=\"");
        sb.append(name.getNamespaceURI());
        sb.append("\"");
    }
    sb.append(">");
    sb.append(appData);
    sb.append("</root>");
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringElementContentWhitespace(true);
    factory.setCoalescing(true);
    factory.setNamespaceAware(true);
    return factory.newDocumentBuilder().parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
}

From source file:ru.codeinside.gws3572c.GMPClientSignTest.java

private Document createDocumentFromElement(Element element)
        throws ParserConfigurationException, IOException, SAXException {
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // ? , ?    ? ?   XML-
    dbf.setIgnoringElementContentWhitespace(true);
    // ? , ?   CDATA  ?    XML-
    dbf.setCoalescing(true);
    // ? , ?  ??    XML-
    dbf.setNamespaceAware(true);//from  www.ja  va 2  s. c  o m
    InputSource is = new InputSource(new StringReader(convertElementToString(element)));
    return dbf.newDocumentBuilder().parse(is);

}

From source file:ws.argo.AsynchListener.AsynchListener.java

private ArrayList<ServiceInfoBean> parseProbeResponseXML(String xmlString) throws SAXException, IOException {
    ArrayList<ServiceInfoBean> serviceList = new ArrayList<ServiceInfoBean>();

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setCoalescing(true);
    DocumentBuilder builder = null;
    try {/*  w w w .  java 2s  . c  o  m*/
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    InputStream is = IOUtils.toInputStream(xmlString);
    Document document = builder.parse(is);

    NodeList list = document.getElementsByTagName("service");

    for (int i = 0; i < list.getLength(); i++) {
        Element service = (Element) list.item(i);
        String contractID = null;
        String serviceID = null;

        contractID = service.getAttribute("contractID");
        serviceID = service.getAttribute("id");

        ServiceInfoBean config = new ServiceInfoBean(serviceID);

        config.serviceContractID = contractID;

        // Need some better error handling here.  The xml MUST have all config items in it 
        // or bad things happen.
        Node n;
        n = service.getElementsByTagName("ipAddress").item(0);
        config.ipAddress = ((Element) n).getTextContent();
        n = service.getElementsByTagName("port").item(0);
        config.port = ((Element) n).getTextContent();
        n = service.getElementsByTagName("url").item(0);
        config.url = ((Element) n).getTextContent();
        n = service.getElementsByTagName("data").item(0);
        config.data = ((Element) n).getTextContent();
        n = service.getElementsByTagName("description").item(0);
        config.description = ((Element) n).getTextContent();
        n = service.getElementsByTagName("contractDescription").item(0);
        config.contractDescription = ((Element) n).getTextContent();
        n = service.getElementsByTagName("serviceName").item(0);
        config.serviceName = ((Element) n).getTextContent();
        n = service.getElementsByTagName("consumability").item(0);
        config.consumability = ((Element) n).getTextContent();
        n = service.getElementsByTagName("ttl").item(0);
        config.ttl = Integer.decode(((Element) n).getTextContent());

        serviceList.add(config);

    }
    return serviceList;

}