org.w3c.dom.Document Java Examples

The following examples show how to use org.w3c.dom.Document. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyValue.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor KeyValue
 *
 * @param doc
 * @param pk
 */
public KeyValue(Document doc, PublicKey pk) {
    super(doc);

    XMLUtils.addReturnToElement(this.constructionElement);

    if (pk instanceof java.security.interfaces.DSAPublicKey) {
        DSAKeyValue dsa = new DSAKeyValue(this.doc, pk);

        this.constructionElement.appendChild(dsa.getElement());
        XMLUtils.addReturnToElement(this.constructionElement);
    } else if (pk instanceof java.security.interfaces.RSAPublicKey) {
        RSAKeyValue rsa = new RSAKeyValue(this.doc, pk);

        this.constructionElement.appendChild(rsa.getElement());
        XMLUtils.addReturnToElement(this.constructionElement);
    }
}
 
Example #2
Source File: SignedInfo.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Canonizes and signs a given input with the authentication private key. of the EBICS user.
 *
 * <p>The given input to be signed is first Canonized using the
 * http://www.w3.org/TR/2001/REC-xml-c14n-20010315 algorithm.
 *
 * <p>The element to be canonized is only the SignedInfo element that should be contained in the
 * request to be signed. Otherwise, a {@link TransformationException} is thrown.
 *
 * <p>The namespace of the SignedInfo element should be named <b>ds</b> as specified in the EBICS
 * specification for common namespaces nomination.
 *
 * <p>The signature is ensured using the user X002 private key. This step is done in {@link
 * EbicsUser#authenticate(byte[]) authenticate}.
 *
 * @param toSign the input to sign
 * @return the signed input
 * @throws EbicsException signature fails.
 */
public byte[] sign(byte[] toSign) throws AxelorException {
  try {
    DocumentBuilderFactory factory;
    DocumentBuilder builder;
    Document document;
    Node node;
    Canonicalizer canonicalizer;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new IgnoreAllErrorHandler());
    document = builder.parse(new ByteArrayInputStream(toSign));
    node = XPathAPI.selectSingleNode(document, "//ds:SignedInfo");
    canonicalizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    return Beans.get(EbicsUserService.class)
        .authenticate(user, canonicalizer.canonicalizeSubtree(node));
  } catch (Exception e) {
    e.printStackTrace();
    throw new AxelorException(e, TraceBackRepository.CATEGORY_CONFIGURATION_ERROR);
  }
}
 
Example #3
Source File: WSDLToCorbaBindingTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnionType() throws Exception {
    try {
        String fileName = getClass().getResource("/wsdl/uniontype.wsdl").toString();
        generator.setWsdlFile(fileName);
        generator.addInterfaceName("Test.MultiPart");

        Definition model = generator.generateCORBABinding();
        Document document = writer.getDocument(model);

        Element typemap = getElementNode(document, "corba:typeMapping");
        assertNotNull(typemap);
        assertEquals(1, typemap.getElementsByTagName("corba:union").getLength());
        assertEquals(1, typemap.getElementsByTagName("corba:enum").getLength());
        WSDLToIDLAction idlgen = new WSDLToIDLAction();
        idlgen.setBindingName("Test.MultiPartCORBABinding");
        idlgen.setOutputFile("uniontype.idl");
        idlgen.generateIDL(model);

        File f = new File("uniontype.idl");
        assertTrue("uniontype.idl should be generated", f.exists());
    } finally {
        new File("uniontype.idl").deleteOnExit();
    }

}
 
Example #4
Source File: CreateMVPFiles.java    From MvpCodeCreator with Apache License 2.0 6 votes vote down vote up
private String readPackageName() {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(project.getBasePath() + "/App/src/main/AndroidManifest.xml");

        NodeList dogList = doc.getElementsByTagName("manifest");
        for (int i = 0; i < dogList.getLength(); i++) {
            Node dog = dogList.item(i);
            Element elem = (Element) dog;
            return elem.getAttribute("package");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
Example #5
Source File: PXDOMStyleAdapter.java    From pixate-freestyle-android with Apache License 2.0 6 votes vote down vote up
@Override
public boolean updateStyle(List<PXRuleSet> ruleSets, List<PXStylerContext> contexts) {
    for (int i = 0; i < ruleSets.size(); i++) {
        PXStylerContext context = contexts.get(i);
        PXRuleSet ruleSet = ruleSets.get(i);
        Node node = (Node) context.getStyleable();
        Document ownerDocument = node.getOwnerDocument();
        NamedNodeMap attributes = node.getAttributes();
        for (PXDeclaration declaration : ruleSet.getDeclarations()) {
            String name = declaration.getName();
            String value = declaration.getStringValue();

            // Set the node's attribute
            Node attNode = ownerDocument.createAttribute(name);
            attNode.setNodeValue(value);
            attributes.setNamedItem(attNode);
        }
    }
    return true;
}
 
Example #6
Source File: FixProjectsUtils.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
private static void removeAndAddComment(Document doc, String moduleName) {
	Node extensionNode;
	Node moduleNode;
	moduleNode = doc.getElementsByTagName(moduleName).item(0);
	if (moduleNode != null) {
		extensionNode = moduleNode.getParentNode();
		NamedNodeMap attrs = moduleNode.getAttributes();
		StringBuilder sb = new StringBuilder("<");
		sb.append(moduleName);
		for (int i = 0 ; i<attrs.getLength() ; i++) {
	        Attr attribute = (Attr)attrs.item(i);     
	        sb.append(" " + attribute.getName() + "=\"" + attribute.getValue() + "\"");
	    }
		sb.append("/>");
		
		appendXmlFragment(extensionNode, sb.toString());
		extensionNode.removeChild(moduleNode);
	}
}
 
Example #7
Source File: DavCmpFsImpl.java    From io with Apache License 2.0 6 votes vote down vote up
private Element parseProp(String value) {
    // valをDOMでElement化
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
Example #8
Source File: WSDLParser.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public WSDLDocument parse() throws SAXException, IOException {
    // parse external binding files
    for (InputSource value : options.getWSDLBindings()) {
        errReceiver.pollAbort();
        Document root = forest.parse(value, false);
        if(root==null)       continue;   // error must have been reported
        Element binding = root.getDocumentElement();
        if (!Internalizer.fixNull(binding.getNamespaceURI()).equals(JAXWSBindingsConstants.NS_JAXWS_BINDINGS)
                || !binding.getLocalName().equals("bindings")){
                errReceiver.error(forest.locatorTable.getStartLocation(binding), WsdlMessages.PARSER_NOT_A_BINDING_FILE(
                    binding.getNamespaceURI(),
                    binding.getLocalName()));
            continue;
        }

        NodeList nl = binding.getElementsByTagNameNS(
            "http://java.sun.com/xml/ns/javaee", "handler-chains");
        for(int i = 0; i < nl.getLength(); i++){
            options.addHandlerChainConfiguration((Element) nl.item(i));
        }

    }
    return buildWSDLDocument();
}
 
Example #9
Source File: BasicLayoutProcessor.java    From ttt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public List<Area> layout(Document d) {
    List<Area> areas = null;
    if (d != null) {
        Element root = d.getDocumentElement();
        if (root != null) {
            LayoutState ls = makeLayoutState();
            if (isElement(root, isdSequenceElementName))
                areas = layoutISDSequence(root, ls);
            else if (isElement(root, isdInstanceElementName))
                areas = layoutISDInstance(root, ls);
            warnOnCounterViolations(ls);
        }
    }
    return (areas != null) ? areas : new java.util.ArrayList<Area>();
}
 
Example #10
Source File: WSDL11Validator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Document getWSDLDoc(String wsdl) {
    LOG.log(Level.FINE, new Message("VALIDATE_WSDL", LOG, wsdl).toString());
    try {
        OASISCatalogManager catalogResolver = OASISCatalogManager.getCatalogManager(this.getBus());

        String nw = new OASISCatalogManagerHelper().resolve(catalogResolver,
                                                            wsdl, null);
        if (nw == null) {
            nw = wsdl;
        }
        return new Stax2DOM().getDocument(URIParserUtil.getAbsoluteURI(nw));
    } catch (FileNotFoundException fe) {
        LOG.log(Level.WARNING, "Cannot find the wsdl " + wsdl + "to validate");
        return null;
    } catch (Exception e) {
        throw new ToolException(e);
    }
}
 
Example #11
Source File: Kyero_3.java    From OpenEstate-IO with Apache License 2.0 6 votes vote down vote up
/**
 * Upgrade &lt;currency&gt; elements to Kyero 3.
 * <p>
 * The &lt;currency&gt; only supports the values "EUR", "GBP", "USD" in
 * version 3.
 * <p>
 * Any &lt;currency&gt; with an unsupported value is removed from the
 * document.
 *
 * @param doc Kyero document in version 2.1
 * @throws JaxenException if xpath evaluation failed
 */
protected void upgradeCurrencyElements(Document doc) throws JaxenException {
    List nodes = XmlUtils.newXPath(
            "/io:root/io:property/io:currency",
            doc).selectNodes(doc);
    for (Object item : nodes) {
        Element node = (Element) item;
        Element parentNode = (Element) node.getParentNode();
        String value = StringUtils.trimToNull(node.getTextContent());
        if ("EUR".equalsIgnoreCase(value))
            node.setTextContent("EUR");
        else if ("GBP".equalsIgnoreCase(value))
            node.setTextContent("GBP");
        else if ("USD".equalsIgnoreCase(value))
            node.setTextContent("USD");
        else
            parentNode.removeChild(node);
    }
}
 
Example #12
Source File: WebProjectUtilsImpl.java    From gvnix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Append a css definition in loadScript.tagx
 * <p/>
 * This first append a "spring:url" (if not exists) and then add the "link"
 * tag (if not exists)
 * 
 * @param docTagx loadScript.tagx document
 * @param root root node
 * @param varName name of variable to hold css url
 * @param location css location
 * @return document has changed
 */

public boolean updateCssToTag(Document docTagx, Element root,
        String varName, String location) {
    boolean modified = false;

    // add url resolution
    modified = updateUrlToTag(docTagx, root, varName, location);

    // Add link
    Element cssElement = XmlUtils.findFirstElement(
            String.format("link[@href='${%s}']", varName), root);
    if (cssElement == null) {
        cssElement = docTagx.createElement("link");
        cssElement.setAttribute("rel", "stylesheet");
        cssElement.setAttribute("type", "text/css");
        cssElement.setAttribute("media", "screen");
        cssElement.setAttribute("href", "${".concat(varName).concat("}"));
        root.appendChild(cssElement);
        modified = true;
    }
    return modified;
}
 
Example #13
Source File: AlgorithmsParametersMarshallingProviderImpl.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<Node> marshalParameters(Algorithm alg, Document doc) throws UnsupportedAlgorithmException
{
    AlgorithmParametersMarshaller marshaller;
    try
    {
        ParameterizedType pt = Types.newParameterizedType(AlgorithmParametersMarshaller.class, alg.getClass());
        marshaller = (AlgorithmParametersMarshaller) injector.getInstance(Key.get(TypeLiteral.get(pt)));
    } catch (RuntimeException ex)
    {
        throw new UnsupportedAlgorithmException("AlgorithmParametersMarshaller not available", alg.getUri(), ex);
    }

    List<Node> params = marshaller.marshalParameters(alg, doc);
    if (params != null && params.isEmpty())
    {
        throw new IllegalArgumentException(String.format("Parameter marshaller returned empty parameter list for algorithm %s", alg.getUri()));
    }
    return params;
}
 
Example #14
Source File: AddonsListFetcher.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Takes an XML document as a string as parameter and returns a DOM for it.
 *
 * On error, returns null and prints a (hopefully) useful message on the monitor.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected Document getDocument(InputStream xml, ITaskMonitor monitor) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        assert xml.markSupported();
        xml.reset();
        Document doc = builder.parse(new InputSource(xml));

        return doc;
    } catch (ParserConfigurationException e) {
        monitor.logError("Failed to create XML document builder");

    } catch (SAXException e) {
        monitor.logError("Failed to parse XML document");

    } catch (IOException e) {
        monitor.logError("Failed to read XML document");
    }

    return null;
}
 
Example #15
Source File: SlaveServer.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public long getNextSlaveSequenceValue( String slaveSequenceName, long incrementValue ) throws KettleException {
  try {
    String xml =
      execService( NextSequenceValueServlet.CONTEXT_PATH + "/" + "?" + NextSequenceValueServlet.PARAM_NAME + "="
        + URLEncoder.encode( slaveSequenceName, "UTF-8" ) + "&" + NextSequenceValueServlet.PARAM_INCREMENT + "="
        + Long.toString( incrementValue ) );

    Document doc = XMLHandler.loadXMLString( xml );
    Node seqNode = XMLHandler.getSubNode( doc, NextSequenceValueServlet.XML_TAG );
    String nextValueString = XMLHandler.getTagValue( seqNode, NextSequenceValueServlet.XML_TAG_VALUE );
    String errorString = XMLHandler.getTagValue( seqNode, NextSequenceValueServlet.XML_TAG_ERROR );

    if ( !Utils.isEmpty( errorString ) ) {
      throw new KettleException( errorString );
    }
    if ( Utils.isEmpty( nextValueString ) ) {
      throw new KettleException( "No value retrieved from slave sequence '" + slaveSequenceName + "' on slave "
        + toString() );
    }
    long nextValue = Const.toLong( nextValueString, Long.MIN_VALUE );
    if ( nextValue == Long.MIN_VALUE ) {
      throw new KettleException( "Incorrect value '" + nextValueString + "' retrieved from slave sequence '"
        + slaveSequenceName + "' on slave " + toString() );
    }

    return nextValue;
  } catch ( Exception e ) {
    throw new KettleException( "There was a problem retrieving a next sequence value from slave sequence '"
      + slaveSequenceName + "' on slave " + toString(), e );
  }
}
 
Example #16
Source File: DOMForest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses an XML at the given location (
 * and XMLs referenced by it) into DOM trees
 * and stores them to this forest.
 *
 * @return the parsed DOM document object.
 */
public Document parse(String systemId, boolean root) throws SAXException, IOException{

    systemId = normalizeSystemId(systemId);

    InputSource is = null;

    // allow entity resolver to find the actual byte stream.
    is = entityResolver.resolveEntity(null, systemId);
    if (is == null)
        is = new InputSource(systemId);
    else {
        resolvedCache.put(systemId, is.getSystemId());
        systemId=is.getSystemId();
    }

    if (core.containsKey(systemId)) {
        // this document has already been parsed. Just ignore.
        return core.get(systemId);
    }

    if(!root)
        addExternalReferences(systemId);

    // but we still use the original system Id as the key.
    return parse(systemId, is, root);
}
 
Example #17
Source File: OutputConversionHTMLScriptElementHandler.java    From docx4j-template with Apache License 2.0 5 votes vote down vote up
@Override
public Element createScriptElement(OpcPackage opcPackage, Document document, String scriptDefinition) {
	Element ret = null;
	if ((scriptDefinition != null) && (scriptDefinition.length() > 0)) {
		ret = document.createElement("script");
		ret.setAttribute("type", "text/javascript");
		ret.appendChild(document.createComment(scriptDefinition));
	}
	return ret;
}
 
Example #18
Source File: PluggablePolicyValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void runInInterceptorAndValidateWss(
    Document document, AssertionInfoMap aim, List<CoverageType> types,
    Map<QName, SecurityPolicyValidator> validators
) throws Exception {

    PolicyBasedWSS4JInInterceptor inHandler = this.getInInterceptor(types);

    SoapMessage inmsg = this.getSoapMessageForDom(document, aim);

    Element securityHeaderElem = WSSecurityUtil.getSecurityHeader(document, "");
    if (securityHeaderElem != null) {
        SoapHeader securityHeader = new SoapHeader(new QName(securityHeaderElem.getNamespaceURI(),
                                                             securityHeaderElem.getLocalName()),
                                                   securityHeaderElem);
        inmsg.getHeaders().add(securityHeader);
    }

    if (validators != null) {
        inmsg.put(SecurityConstants.POLICY_VALIDATOR_MAP, validators);
    }

    inHandler.handleMessage(inmsg);

    for (CoverageType type : types) {
        switch(type) {
        case SIGNED:
            this.verifyWss4jSigResults(inmsg);
            break;
        case ENCRYPTED:
            this.verifyWss4jEncResults(inmsg);
            break;
        default:
            fail("Unsupported coverage type.");
        }
    }
}
 
Example #19
Source File: DOMForest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses the given document and add it to the DOM forest.
 *
 * @return null if there was a parse error. otherwise non-null.
 */
private @NotNull Document parse(String systemId, InputSource inputSource, boolean root) throws SAXException, IOException{
    Document dom = documentBuilder.newDocument();

    systemId = normalizeSystemId(systemId);

    // put into the map before growing a tree, to
    // prevent recursive reference from causing infinite loop.
    core.put(systemId, dom);

    dom.setDocumentURI(systemId);
    if (root)
        rootDocuments.add(systemId);

    try {
        XMLReader reader = createReader(dom);

        InputStream is = null;
        if(inputSource.getByteStream() == null){
            inputSource = entityResolver.resolveEntity(null, systemId);
        }
        reader.parse(inputSource);
        Element doc = dom.getDocumentElement();
        if (doc == null) {
            return null;
        }
        NodeList schemas = doc.getElementsByTagNameNS(SchemaConstants.NS_XSD, "schema");
        for (int i = 0; i < schemas.getLength(); i++) {
            inlinedSchemaElements.add((Element) schemas.item(i));
        }
    } catch (ParserConfigurationException e) {
        errorReceiver.error(e);
        throw new SAXException(e.getMessage());
    }
    resolvedCache.put(systemId, dom.getDocumentURI());
    return dom;
}
 
Example #20
Source File: SymbolExplorerTreeCreator.java    From mil-sym-java with Apache License 2.0 5 votes vote down vote up
public String buildXMLString(int symStd)
{
    Document xml = buildXML(symStd);
    DOMImplementationLS domImplLS = (DOMImplementationLS)xml.getImplementation();
    LSSerializer serializer = domImplLS.createLSSerializer();
    String strXML = serializer.writeToString(xml);
    return strXML;
}
 
Example #21
Source File: MmiHandler.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void sendYes(final String contextId, final String source,
        final String target) throws ParserConfigurationException,
        URISyntaxException, JAXBException, IOException {
    final Mmi mmi = new Mmi();
    final ExtensionNotification notification = new ExtensionNotification();
    mmi.setExtensionNotification(notification);
    notification.setContext(contextId);
    notification.setRequestId("4343");
    notification.setSource(source);
    notification.setTarget(target);
    final AnyComplexType any = new AnyComplexType();
    notification.setData(any);
    final DocumentBuilderFactory factory = DocumentBuilderFactory
            .newInstance();
    factory.setNamespaceAware(true);
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document document = builder.newDocument();
    final Element emma = document.createElementNS(EMMA_NAMESPACE,
            "emma:emma");
    emma.setAttribute("version", "1.0");
    document.appendChild(emma);
    final Element interpretation = document.createElementNS(EMMA_NAMESPACE,
            "emma:interpretation");
    interpretation.setAttribute("id", "demoinput");
    interpretation
            .setAttributeNS(EMMA_NAMESPACE, "emma:medium", "acoustic");
    any.addContent(emma);
    interpretation.setAttributeNS(EMMA_NAMESPACE, "emma:mode", "mmi");
    float confidence = 0.9f;
    interpretation.setAttributeNS(EMMA_NAMESPACE, "emma:confidence",
            Float.toString(confidence));
    final String tokens = "yes";
    interpretation.setAttributeNS(EMMA_NAMESPACE, "emma:tokens", tokens);
    emma.appendChild(interpretation);
    final URI targetUri = new URI(target);
    demo.send(mmi, targetUri);
}
 
Example #22
Source File: SpawnsData.java    From L2jOrg with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void parseDocument(Document doc, File f) {
    forEach(doc, "list", listNode -> forEach(listNode, "spawn", spawnNode ->
    {
        try {
            parseSpawn(spawnNode, f, spawns);
        } catch (Exception e) {
            LOGGER.warn("Error while processing spawn in file {}", f.getAbsolutePath(), e);
        }
    }));
}
 
Example #23
Source File: DOMX509Data.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);
    Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data",
                                            XMLSignature.XMLNS, dsPrefix);

    // append children and preserve order
    for (int i = 0, size = content.size(); i < size; i++) {
        Object object = content.get(i);
        if (object instanceof X509Certificate) {
            marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix);
        } else if (object instanceof XMLStructure) {
            if (object instanceof X509IssuerSerial) {
                ((DOMX509IssuerSerial)object).marshal
                    (xdElem, dsPrefix, context);
            } else {
                javax.xml.crypto.dom.DOMStructure domContent =
                    (javax.xml.crypto.dom.DOMStructure)object;
                DOMUtils.appendChild(xdElem, domContent.getNode());
            }
        } else if (object instanceof byte[]) {
            marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix);
        } else if (object instanceof String) {
            marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix);
        } else if (object instanceof X509CRL) {
            marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix);
        }
    }

    parent.appendChild(xdElem);
}
 
Example #24
Source File: DocumentSerializerHelper.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
protected Document parseDocumentFromXml(String xmlSource) throws CommonException {
	try {
		return getDocumentBuilder().parse(new InputSource(new StringReader(xmlSource)));
	} catch(SAXException | IOException e) {
		throw new CommonException("Unable to parse XML", e);
	}
}
 
Example #25
Source File: XalanXmlDataSource.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Document subDocument() throws JRException
{
	if(currentNode == null)
	{
		throw 
			new JRException(
				EXCEPTION_MESSAGE_KEY_NODE_NOT_AVAILABLE,
				(Object[])null);
	}
	
	// create a new document from the current node
	return documentProducer.getDocument(currentNode);
}
 
Example #26
Source File: Packet.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gives a list of Reference Parameters in the Message
 * <p>
 * Headers which have attribute wsa:IsReferenceParameter="true"
 * This is not cached as one may reset the Message.
 *<p>
 */
@Property(MessageContext.REFERENCE_PARAMETERS)
public
@NotNull
List<Element> getReferenceParameters() {
    Message msg = getMessage();
    List<Element> refParams = new ArrayList<Element>();
    if (msg == null) {
        return refParams;
    }
    MessageHeaders hl = msg.getHeaders();
    for (Header h : hl.asList()) {
        String attr = h.getAttribute(AddressingVersion.W3C.nsUri, "IsReferenceParameter");
        if (attr != null && (attr.equals("true") || attr.equals("1"))) {
            Document d = DOMUtil.createDom();
            SAX2DOMEx s2d = new SAX2DOMEx(d);
            try {
                h.writeTo(s2d, XmlUtil.DRACONIAN_ERROR_HANDLER);
                refParams.add((Element) d.getLastChild());
            } catch (SAXException e) {
                throw new WebServiceException(e);
            }
            /*
            DOMResult result = new DOMResult(d);
            XMLDOMWriterImpl domwriter = new XMLDOMWriterImpl(result);
            try {
                h.writeTo(domwriter);
                refParams.add((Element) result.getNode().getLastChild());
            } catch (XMLStreamException e) {
                throw new WebServiceException(e);
            }
            */
        }
    }
    return refParams;
}
 
Example #27
Source File: HttpProtocol.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void parseXML( HttpMessage message, Value value, String charset )
	throws IOException {
	try {
		if( message.size() > 0 ) {
			DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
			InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
			src.setEncoding( charset );
			Document doc = builder.parse( src );
			XmlUtils.documentToValue( doc, value, false );
		}
	} catch( ParserConfigurationException | SAXException pce ) {
		throw new IOException( pce );
	}
}
 
Example #28
Source File: WSDLToDataService.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private static ModelProperty createModelProperty(Map<QName, Document> modelMap, Node propEl) {
	ModelProperty property = new ModelProperty();
	NamedNodeMap propAttrs = propEl.getAttributes();
	property.setName(propAttrs.getNamedItem("name").getNodeValue());
	Node isArrayNode = propAttrs.getNamedItem("array");
	if (isArrayNode != null) {
		property.setArray("yes".equals(isArrayNode.getNodeValue()));
	} else {
		property.setArray(false);
	}
	Node isPrimitiveNode = propAttrs.getNamedItem("primitive");
	boolean primitive;
	if (isPrimitiveNode != null) {
		primitive = "yes".equals(isPrimitiveNode.getNodeValue());
	} else {
		primitive = false;
	}
	Node isSimpleNode = propAttrs.getNamedItem("simple");
	boolean simple;
	if (isSimpleNode != null) {
		simple = "yes".equals(isSimpleNode.getNodeValue());
	} else {
		simple = false;
	}
	ModelBean type = null;
	if (!primitive && !simple) {
		type = createModelBean(modelMap,
				new QName(propAttrs.getNamedItem("nsuri").getNodeValue(), 
						propAttrs.getNamedItem("shorttypename").getNodeValue()));
	}
	if (type != null) {
		property.setType(type);
	} else {
		property.setSimpleType(propAttrs.getNamedItem("shorttypename").getNodeValue());
	}
	return property;
}
 
Example #29
Source File: FragmentDialect.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method. It adds new Node as the last child of parent.
 * @param ownerDocument Document, where the Node is added.
 * @param parent Parent, where the Node is added.
 * @param value Value defined in the Value element. It represents newly added Node.
 */
private void addNode(Document ownerDocument, Node parent, Node nextSibling, ValueType value) {
    if (ownerDocument == parent && ownerDocument.getDocumentElement() != null) {
        throw new InvalidRepresentation();
    }
    for (Object o : value.getContent()) {
        if (o instanceof String) {
            parent.setTextContent(parent.getTextContent() + ((String) o));
        } else if (o instanceof Node) {
            Node node = (Node) o;
            if (
                    FragmentDialectConstants.FRAGMENT_2011_03_IRI.equals(node.getNamespaceURI())
                            && FragmentDialectConstants.FRAGMENT_ATTR_NODE_NAME.equals(node.getLocalName())) {
                String attrName = ((Element)node).getAttributeNS(
                        FragmentDialectConstants.FRAGMENT_2011_03_IRI,
                        FragmentDialectConstants.FRAGMENT_ATTR_NODE_NAME_ATTR);
                String attrValue = node.getTextContent();
                if (attrName == null) {
                    throw new SoapFault("wsf:AttributeNode@name is not present.", getSoapVersion().getSender());
                }
                if (((Element) parent).hasAttribute(attrName)) {
                    throw new InvalidRepresentation();
                }
                ((Element) parent).setAttribute(attrName, attrValue);
            } else {
                // import the node to the ownerDocument
                Node importedNode = ownerDocument.importNode((Node) o, true);
                if (nextSibling == null) {
                    parent.appendChild(importedNode);
                } else {
                    parent.insertBefore(importedNode, nextSibling);
                }
            }
        } else {
            throw new InvalidExpression();
        }
    }
}
 
Example #30
Source File: DigitalSignatureServiceProxy.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Element createSignatureType() throws ParserConfigurationException {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   dbf.setNamespaceAware(true);
   DocumentBuilder builder = dbf.newDocumentBuilder();
   Document doc = builder.newDocument();
   Element signatureType = doc.createElementNS("urn:oasis:names:tc:dss:1.0:core:schema", "SignatureType");
   signatureType.setTextContent("urn:ietf:rfc:3447");
   return signatureType;
}