Java Code Examples for org.w3c.dom.Document#createElementNS()

The following examples show how to use org.w3c.dom.Document#createElementNS() . 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: ElementProxy.java    From openjdk-8 with GNU General Public License v2.0 7 votes vote down vote up
protected Element createElementForFamilyLocal(
    Document doc, String namespace, String localName
) {
    Element result = null;
    if (namespace == null) {
        result = doc.createElementNS(null, localName);
    } else {
        String baseName = this.getBaseNamespace();
        String prefix = ElementProxy.getDefaultPrefix(baseName);
        if ((prefix == null) || (prefix.length() == 0)) {
            result = doc.createElementNS(namespace, localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
        } else {
            result = doc.createElementNS(namespace, prefix + ":" + localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
        }
    }
    return result;
}
 
Example 2
Source File: XSLTProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Adds the specified parameters to the xsl template as variables within the alfresco namespace.
 * 
 * @param xsltModel
 *            the variables to place within the xsl template
 * @param xslTemplate
 *            the xsl template
 */
protected void addParameters(final XSLTemplateModel xsltModel, final Document xslTemplate)
{
    final Element docEl = xslTemplate.getDocumentElement();
    final String XSL_NS = docEl.getNamespaceURI();
    final String XSL_NS_PREFIX = docEl.getPrefix();

    for (Map.Entry<QName, Object> e : xsltModel.entrySet())
    {
        if (ROOT_NAMESPACE.equals(e.getKey()))
        {
            continue;
        }
        final Element el = xslTemplate.createElementNS(XSL_NS, XSL_NS_PREFIX + ":variable");
        el.setAttribute("name", e.getKey().toPrefixString());
        final Object o = e.getValue();
        if (o instanceof String || o instanceof Number || o instanceof Boolean)
        {
            el.appendChild(xslTemplate.createTextNode(o.toString()));
            // ALF-15413. Add the variables at the end of the list of children
            docEl.insertBefore(el, null);
        }
    }
}
 
Example 3
Source File: XmlNode.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
static XmlNode newElementWithText(XmlProcessor processor, XmlNode reference, XmlNode.QName qname, String value) {
    if (reference instanceof org.w3c.dom.Document) throw new IllegalArgumentException("Cannot use Document node as reference");
    Document document = null;
    if (reference != null) {
        document = reference.dom.getOwnerDocument();
    } else {
        document = processor.newDocument();
    }
    Node referenceDom = (reference != null) ? reference.dom : null;
    Namespace ns = qname.getNamespace();
    Element e = (ns == null || ns.getUri().length() == 0)
        ? document.createElementNS(null, qname.getLocalName())
        : document.createElementNS(ns.getUri(),
                                   qname.qualify(referenceDom));
    if (value != null) {
        e.appendChild(document.createTextNode(value));
    }
    return XmlNode.createImpl(e);
}
 
Example 4
Source File: JAXBEncoderDecoderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnmarshallWithoutClzInfo() throws Exception {
    QName elName = new QName(wrapperAnnotation.targetNamespace(),
                             wrapperAnnotation.localName());

    Document doc = DOMUtils.getEmptyDocument();
    Element elNode = doc.createElementNS(elName.getNamespaceURI(),
                                         elName.getLocalPart());
    Element rtEl = doc.createElementNS(elName.getNamespaceURI(), "requestType");
    elNode.appendChild(rtEl);
    rtEl.appendChild(doc.createTextNode("Hello Test"));

    Object obj = JAXBEncoderDecoder.unmarshall(context.createUnmarshaller(),
                                               elNode,
                                               null,
                                               true);
    assertNotNull(obj);
    assertEquals(GreetMe.class,  obj.getClass());
    assertEquals("Hello Test", ((GreetMe)obj).getRequestType());
}
 
Example 5
Source File: UsernameTokenInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example 6
Source File: StaxUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultMaxAttributeLength() throws XMLStreamException {
    Document doc = DOMUtils.newDocument();
    Element documentElement = doc.createElementNS(null, "root");
    doc.appendChild(documentElement);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 1024; i++) {
        sb.append(i);
    }

    documentElement.setAttributeNS(null, "attr", sb.toString());

    // Should be OK
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new StringReader(StaxUtils.toString(doc)));
    assertNotNull(StaxUtils.read(reader));

    for (int i = 0; i < 1024 * 64; i++) {
        sb.append(i);
    }

    documentElement.setAttributeNS(null, "attr", sb.toString());
    assertTrue(documentElement.getAttributeNS(null, "attr").length() > (1024 * 64));

    // Should fail as we are over the max attribute length
    reader = StaxUtils.createXMLStreamReader(new StringReader(StaxUtils.toString(doc)));
    try {
        StaxUtils.read(reader);
        fail("Failure expected on exceeding the limit");
    } catch (XMLStreamException ex) {
        assertTrue(ex.getMessage().contains("Maximum attribute size limit"));
    }

}
 
Example 7
Source File: Converter.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Converts a CMIS extension element to a DOM node
 * 
 * @param source the source extension
 * @param parent the parent element
 * @param doc the current document
 * 
 * @return the DOM node
 */
private static Node convertCmisExtensionElementToNode(CmisExtensionElement source, Element parent, Document doc) {
	if (source == null) {
		return null;
	}

	Element element = doc.createElementNS(
			(source.getNamespace() == null ? DEFAULT_EXTENSION_NS : source.getNamespace()), source.getName());

	if (source.getValue() != null) {
		element.appendChild(doc.createTextNode(source.getValue()));
	} else {
		for (CmisExtensionElement child : source.getChildren()) {
			element.appendChild(convertCmisExtensionElementToNode(child, element, doc));
		}
	}

	// set attributes
	if (source.getAttributes() != null) {
		for (Map.Entry<String, String> e : source.getAttributes().entrySet()) {
			element.setAttributeNS((source.getNamespace() == null ? DEFAULT_EXTENSION_NS : source.getNamespace()),
					e.getKey(), e.getValue());
		}
	}

	return element;
}
 
Example 8
Source File: ClassPathSupportCallbackImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Element createLibraryElement(AntProjectHelper antProjectHelper, Document doc, String pathItem, Item item) {
    Element libraryElement = doc.createElementNS(WebProjectType.PROJECT_CONFIGURATION_NAMESPACE, TAG_LIBRARY);
    Element webFile = doc.createElementNS(WebProjectType.PROJECT_CONFIGURATION_NAMESPACE, TAG_FILE);
    libraryElement.appendChild(webFile);
    webFile.appendChild(doc.createTextNode("${" + pathItem + "}"));
    if (item.getAdditionalProperty(PATH_IN_DEPLOYMENT) != null) {
        Element pathInWar = doc.createElementNS(WebProjectType.PROJECT_CONFIGURATION_NAMESPACE, TAG_PATH_IN_WAR);
        pathInWar.appendChild(doc.createTextNode(item.getAdditionalProperty(PATH_IN_DEPLOYMENT)));
        libraryElement.appendChild(pathInWar);
    }
    AntProjectUtil.updateDirsAttributeInCPSItem(item, libraryElement);
    return libraryElement;
}
 
Example 9
Source File: IssueJWTRealmUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Element createAppliesToElement(String addressUrl) {
    Document doc = DOMUtils.getEmptyDocument();
    Element appliesTo = doc.createElementNS(STSConstants.WSP_NS, "wsp:AppliesTo");
    appliesTo.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:wsp", STSConstants.WSP_NS);
    Element endpointRef = doc.createElementNS(STSConstants.WSA_NS_05, "wsa:EndpointReference");
    endpointRef.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:wsa", STSConstants.WSA_NS_05);
    Element address = doc.createElementNS(STSConstants.WSA_NS_05, "wsa:Address");
    address.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:wsa", STSConstants.WSA_NS_05);
    address.setTextContent(addressUrl);
    endpointRef.appendChild(address);
    appliesTo.appendChild(endpointRef);
    return appliesTo;
}
 
Example 10
Source File: Marshal.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example 11
Source File: StaxUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCommentNode() throws Exception {
    //CXF-3034
    Document document = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().newDocument();
    Element root = document.createElementNS("urn:test", "root");
    root.appendChild(document.createComment("test comment"));
    StaxUtils.copy(StaxUtils.createXMLStreamReader(root), StaxUtils.createXMLStreamWriter(System.out));
}
 
Example 12
Source File: TestXmlDumper.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void dumpXmlTests(Writer outWriter, TestCollection collection) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Schema schema = schemaFactory.newSchema(DesignerUtil.getResource("testschema/rule-tests_1_0_0.xsd"));
        dbf.setSchema(schema);
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = getDocumentBuilder(dbf);


        Document doc = builder.newDocument();
        Element root = doc.createElementNS(NS, "test-data");
        doc.appendChild(root);

        root.setAttribute("xmlns", NS);
        root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.setAttribute("xsi:schemaLocation", SCHEMA_LOCATION);

        new TestXmlDumper().appendTests(doc, collection.getStash());

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{" + NS + "}code");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // FIXME whatever i try this indents by 3 spaces which is not
        //  compatible with our style
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");


        transformer.transform(new DOMSource(doc), new StreamResult(outWriter));
    } finally {
        outWriter.close();
    }

}
 
Example 13
Source File: SettingsWriter.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
private void writeColorSettings(Document xmldoc, ColorSettings colorSettings) {
	Element colorSettingsNode = xmldoc.createElementNS(null, "colorsettings");
	xmldoc.getDocumentElement().appendChild(colorSettingsNode);
	setAttributeOptional(colorSettingsNode, "theme", colorSettings.getColorTheme().getType());
	for (ColorEntry colorEntry : ColorEntry.values()) {
		Element colorNode = xmldoc.createElementNS(null, "color");
		setAttribute(colorNode, "name", colorEntry);
		setAttributeOptional(colorNode, "background", colorSettings.getBackground(colorEntry));
		setAttributeOptional(colorNode, "foreground", colorSettings.getForeground(colorEntry));
		colorSettingsNode.appendChild(colorNode);
	}
}
 
Example 14
Source File: QueryOptionsManagerTest.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testXMLDocsAsSearchOptions()
  throws ParserConfigurationException, SAXException, IOException, ResourceNotFoundException, ForbiddenUserException, FailedRequestException, ResourceNotResendableException
{
  String optionsName = "invalid";

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setValidating(false);
  DocumentBuilder documentBldr = factory.newDocumentBuilder();

  Document domDocument = documentBldr.newDocument();
  Element root = domDocument.createElementNS("http://marklogic.com/appservices/search","options");
  Element rf = domDocument.createElementNS("http://marklogic.com/appservices/search","return-facets");
  rf.setTextContent("true");
  root.appendChild(rf);
  root.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:lang", "en");  // MarkLogic adds this if I don't
  domDocument.appendChild(root);

  QueryOptionsManager queryOptionsMgr =
    Common.adminClient.newServerConfigManager().newQueryOptionsManager();

  queryOptionsMgr.writeOptions(optionsName, new DOMHandle(domDocument));

  String domString =
          ((DOMImplementationLS) documentBldr.getDOMImplementation()).createLSSerializer().writeToString(domDocument);

  String optionsString = queryOptionsMgr.readOptions(optionsName, new StringHandle()).get();
  assertNotNull("Read null string for XML content",optionsString);
  logger.debug("Two XML Strings {} and {}", domString, optionsString);

  Document readDoc = queryOptionsMgr.readOptions(optionsName, new DOMHandle()).get();
  assertNotNull("Read null document for XML content",readDoc);

}
 
Example 15
Source File: XMLDSigWithSecMgr.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    URI policyURI =
        new File(System.getProperty("test.src", "."), "policy").toURI();
    Policy.setPolicy
        (Policy.getInstance("JavaPolicy", new URIParameter(policyURI)));
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 16
Source File: SerializableMetadata.java    From oodt with Apache License 2.0 4 votes vote down vote up
public Document toXML() throws IOException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        factory.setNamespaceAware(true);
        Document document = factory.newDocumentBuilder().newDocument();

        Element root = document.createElementNS("http://oodt.jpl.nasa.gov/1.0/cas", "metadata");
        root.setPrefix("cas");
        document.appendChild(root);

        // now add the set of metadata elements in the properties object
        for (String key : this.getAllKeys()) {
            Element metadataElem = document.createElement("keyval");
            Element keyElem = document.createElement("key");
            if (this.useCDATA) {
                keyElem.appendChild(document.createCDATASection(key));
            } else {
                keyElem.appendChild(document.createTextNode(URLEncoder.encode(key, this.xmlEncoding)));
            }
            
            metadataElem.appendChild(keyElem);

            metadataElem.setAttribute("type", "vector");

            for (String value : this.getAllMetadata(key)) {
                Element valElem = document.createElement("val");
                if (value == null) {
                    throw new Exception("Attempt to write null value "
                            + "for property: [" + key + "]: val: [null]");
                }
                if (this.useCDATA) {
                    valElem.appendChild(document
                        .createCDATASection(value));
                } else {
                    valElem.appendChild(document.createTextNode(URLEncoder
                        .encode(value, this.xmlEncoding)));
                }
                metadataElem.appendChild(valElem);
            }
            root.appendChild(metadataElem);
        }
        return document;
    } catch (Exception e) {
        LOG.log(Level.SEVERE, e.getMessage());
        throw new IOException(
                "Failed to create XML DOM Document for SerializableMetadata : "
                        + e.getMessage());
    }
}
 
Example 17
Source File: SymbolWriter.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
@Override
public Node toNode(AbstractWmlConversionContext context, Object unmarshalledNode, 
		Node modelContent, TransformState state, Document doc)
		throws TransformerException {
	R.Sym modelData = (R.Sym)unmarshalledNode;
	String fontName = modelData.getFont();
	String textValue =  modelData.getChar();
	PhysicalFont pf = context.getWmlPackage().getFontMapper().get(fontName);
	char chValue = '\0';
	Typeface typeface = null;
  
  	if (pf != null) {
  		typeface = pf.getTypeface();
  		
  	  	if (typeface != null) {
	  	  	if (textValue.length() > 1) {
	  	  		try {
	  	  			chValue = (char)Integer.parseInt(textValue, 16);
	  	  		}
	  	  		catch (NumberFormatException nfe) {
	  	  			chValue = '\0';
	  	  		}
	  	  	}
	  	  	else {
	  	  		chValue = textValue.charAt(0);
	  	  	}
	  	  	
	  	  	if (chValue != '\0') {
	  	  		if (chValue > 0xf000) { //let's check first the character in the lower ascii (Pre-process according to ECMA-376 2.3.3.29)
	  	  			chValue -= 0xf000;
	  	  		}
	  	  		if (typeface.mapChar(chValue) == 0) {
	  	  			chValue += 0xf000;
	  	  			if (typeface.mapChar(chValue) == 0) {
	  	  				chValue = '\0';
	  	  			}
	  	  		}
	  	  		if (chValue != '\0') {//character was found
	  	  			textValue = Character.toString(chValue);
	  	  		}
	  	  	}
  	  	}
  	}
    
    Text theChar = doc.createTextNode(textValue);
	DocumentFragment docfrag = doc.createDocumentFragment();

	if (pf==null) {
		log.warn("No physical font present for:" + fontName);		
	    docfrag.appendChild( theChar );
		
	} else {
		
	    Element foInline = doc.createElementNS("http://www.w3.org/1999/XSL/Format", "fo:inline");
	    docfrag.appendChild(foInline);
		
	    foInline.setAttribute("font-family", pf.getName() );
	    foInline.appendChild(theChar);
	}
    
    return docfrag;
}
 
Example 18
Source File: JavaActions.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Add an action binding to project.xml.
 * If there is no required context, the action is also added to the context menu of the project node.
 * @param command the command name
 * @param scriptPath the path to the generated script
 * @param target the name of the target (in scriptPath)
 * @param propertyName a property name to hold the selection (or null for no context, in which case remainder should be null)
 * @param dir the raw text to use for the directory name
 * @param pattern the regular expression to match, or null
 * @param format the format to use
 * @param separator the separator to use for multiple files, or null for single file only
 */
void addBinding(String command, String scriptPath, String target, String propertyName, String dir, String pattern, String format, String separator) throws IOException {
    // XXX cannot use FreeformProjectGenerator since that is currently not a public support SPI from ant/freeform
    // XXX should this try to find an existing binding? probably not, since it is assumed that if there was one, we would never get here to begin with
    Element data = Util.getPrimaryConfigurationData(helper);
    Element ideActions = XMLUtil.findElement(data, "ide-actions", Util.NAMESPACE); // NOI18N
    if (ideActions == null) {
        //fix for #58442:
        ideActions = data.getOwnerDocument().createElementNS(Util.NAMESPACE, "ide-actions"); // NOI18N
        XMLUtil.appendChildElement(data, ideActions, rootElementsOrder);
    }
    Document doc = data.getOwnerDocument();
    Element action = doc.createElementNS(Util.NAMESPACE, "action"); // NOI18N
    action.setAttribute("name", command); // NOI18N
    Element script = doc.createElementNS(Util.NAMESPACE, "script"); // NOI18N
    script.appendChild(doc.createTextNode(scriptPath));
    action.appendChild(script);
    Element targetEl = doc.createElementNS(Util.NAMESPACE, "target"); // NOI18N
    targetEl.appendChild(doc.createTextNode(target));
    action.appendChild(targetEl);
    if (propertyName != null) {
        Element context = doc.createElementNS(Util.NAMESPACE, "context"); // NOI18N
        Element property = doc.createElementNS(Util.NAMESPACE, "property"); // NOI18N
        property.appendChild(doc.createTextNode(propertyName));
        context.appendChild(property);
        Element folder = doc.createElementNS(Util.NAMESPACE, "folder"); // NOI18N
        folder.appendChild(doc.createTextNode(dir));
        context.appendChild(folder);
        if (pattern != null) {
            Element patternEl = doc.createElementNS(Util.NAMESPACE, "pattern"); // NOI18N
            patternEl.appendChild(doc.createTextNode(pattern));
            context.appendChild(patternEl);
        }
        Element formatEl = doc.createElementNS(Util.NAMESPACE, "format"); // NOI18N
        formatEl.appendChild(doc.createTextNode(format));
        context.appendChild(formatEl);
        Element arity = doc.createElementNS(Util.NAMESPACE, "arity"); // NOI18N
        if (separator != null) {
            Element separatorEl = doc.createElementNS(Util.NAMESPACE, "separated-files"); // NOI18N
            separatorEl.appendChild(doc.createTextNode(separator));
            arity.appendChild(separatorEl);
        } else {
            arity.appendChild(doc.createElementNS(Util.NAMESPACE, "one-file-only")); // NOI18N
        }
        context.appendChild(arity);
        action.appendChild(context);
    } else {
        // Add a context menu item, since it applies to the project as a whole.
        // Assume there is already a <context-menu> defined, which is quite likely.
        Element view = XMLUtil.findElement(data, "view", Util.NAMESPACE); // NOI18N
        if (view != null) {
            Element contextMenu = XMLUtil.findElement(view, "context-menu", Util.NAMESPACE); // NOI18N
            if (contextMenu != null) {
                Element ideAction = doc.createElementNS(Util.NAMESPACE, "ide-action"); // NOI18N
                ideAction.setAttribute("name", command); // NOI18N
                contextMenu.appendChild(ideAction);
            }
        }
    }
    ideActions.appendChild(action);
    Util.putPrimaryConfigurationData(helper, data);
    ProjectManager.getDefault().saveProject(project);
}
 
Example 19
Source File: XMLEncryptionUtil.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Given an element in a Document, encrypt the element and replace the element in the document with the encrypted
 * data
 *
 * @param elementQName QName of the element that we like to encrypt
 * @param document
 * @param publicKey
 * @param secretKey
 * @param keySize
 * @param wrappingElementQName A QName of an element that will wrap the encrypted element
 * @param addEncryptedKeyInKeyInfo Need for the EncryptedKey to be placed in ds:KeyInfo
 *
 * @throws ProcessingException
 */
public static void encryptElement(QName elementQName, Document document, PublicKey publicKey, SecretKey secretKey,
                                  int keySize, QName wrappingElementQName, boolean addEncryptedKeyInKeyInfo) throws ProcessingException {
    if (elementQName == null)
        throw logger.nullArgumentError("elementQName");
    if (document == null)
        throw logger.nullArgumentError("document");
    String wrappingElementPrefix = wrappingElementQName.getPrefix();
    if (wrappingElementPrefix == null || "".equals(wrappingElementPrefix))
        throw logger.wrongTypeError("Wrapping element prefix invalid");

    Element documentElement = DocumentUtil.getElement(document, elementQName);

    if (documentElement == null)
        throw logger.domMissingDocElementError(elementQName.toString());

    XMLCipher cipher = null;
    EncryptedKey encryptedKey = encryptKey(document, secretKey, publicKey, keySize);

    String encryptionAlgorithm = getXMLEncryptionURL(secretKey.getAlgorithm(), keySize);
    // Encrypt the Document
    try {
        cipher = XMLCipher.getInstance(encryptionAlgorithm);
        cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    } catch (XMLEncryptionException e1) {
        throw logger.processingError(e1);
    }

    Document encryptedDoc;
    try {
        encryptedDoc = cipher.doFinal(document, documentElement);
    } catch (Exception e) {
        throw logger.processingError(e);
    }

    // The EncryptedKey element is added
    Element encryptedKeyElement = cipher.martial(document, encryptedKey);

    final String wrappingElementName;

    if (StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElementName = wrappingElementQName.getLocalPart();
    } else {
        wrappingElementName = wrappingElementPrefix + ":" + wrappingElementQName.getLocalPart();
    }
    // Create the wrapping element and set its attribute NS
    Element wrappingElement = encryptedDoc.createElementNS(wrappingElementQName.getNamespaceURI(), wrappingElementName);

    if (! StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + wrappingElementPrefix, wrappingElementQName.getNamespaceURI());
    }

    // Get Hold of the Cipher Data
    NodeList cipherElements = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA);
    if (cipherElements == null || cipherElements.getLength() == 0)
        throw logger.domMissingElementError("xenc:EncryptedData");
    Element encryptedDataElement = (Element) cipherElements.item(0);

    Node parentOfEncNode = encryptedDataElement.getParentNode();
    parentOfEncNode.replaceChild(wrappingElement, encryptedDataElement);

    wrappingElement.appendChild(encryptedDataElement);

    if (addEncryptedKeyInKeyInfo) {
        // Outer ds:KeyInfo Element to hold the EncryptionKey
        Element sigElement = encryptedDoc.createElementNS(XMLSignature.XMLNS, DS_KEY_INFO);
        sigElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:ds", XMLSignature.XMLNS);
        sigElement.appendChild(encryptedKeyElement);

        // Insert the Encrypted key before the CipherData element
        NodeList nodeList = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
        if (nodeList == null || nodeList.getLength() == 0)
            throw logger.domMissingElementError("xenc:CipherData");
        Element cipherDataElement = (Element) nodeList.item(0);
        Node cipherParent = cipherDataElement.getParentNode();
        cipherParent.insertBefore(sigElement, cipherDataElement);
    } else {
        // Add the encrypted key as a child of the wrapping element
        wrappingElement.appendChild(encryptedKeyElement);
    }
}
 
Example 20
Source File: DOMUtils.java    From openjdk-8-source with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Creates an element in the specified namespace, with the specified tag
 * and namespace prefix.
 *
 * @param doc the owner document
 * @param tag the tag
 * @param nsURI the namespace URI
 * @param prefix the namespace prefix
 * @return the newly created element
 */
public static Element createElement(Document doc, String tag,
                                    String nsURI, String prefix)
{
    String qName = (prefix == null || prefix.length() == 0)
                   ? tag : prefix + ":" + tag;
    return doc.createElementNS(nsURI, qName);
}