List of usage examples for org.w3c.dom Element insertBefore
public Node insertBefore(Node newChild, Node refChild) throws DOMException;
newChild
before the existing child node refChild
. From source file:org.wso2.carbon.apimgt.migration.client._200Specific.ResourceModifier200.java
public static void updateSynapseConfigs(List<SynapseDTO> synapseDTOs) { for (SynapseDTO synapseDTO : synapseDTOs) { Element handlersElement = (Element) synapseDTO.getDocument() .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_HANDLERS) .item(0);//from ww w .java 2s . c om Element existingLatencyStatHandler = SynapseUtil.getHandler(synapseDTO.getDocument(), Constants.SYNAPSE_API_VALUE_LATENCY_STATS_HANDLER); if (existingLatencyStatHandler != null) { log.info("handler '" + Constants.SYNAPSE_API_VALUE_LATENCY_STATS_HANDLER + "' already exist in " + synapseDTO.getFile().getAbsolutePath()); } else { Element newAPIMgtLatencyStatsHandler = synapseDTO.getDocument() .createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_HANDLER); newAPIMgtLatencyStatsHandler.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_CLASS, Constants.SYNAPSE_API_VALUE_LATENCY_STATS_HANDLER); handlersElement.insertBefore(newAPIMgtLatencyStatsHandler, handlersElement.getFirstChild()); } try { updateResources(synapseDTO.getDocument()); } catch (APIMigrationException e) { log.error("error occurred while migrating synapse at " + synapseDTO.getFile().getAbsolutePath(), e); } } }
From source file:org.wso2.carbon.apimgt.migration.client._200Specific.ResourceModifier200.java
private static void updateInSequence(Element resourceElement, Document doc) { // Find the inSequence Element inSequenceElement = (Element) resourceElement .getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_INSEQUENCE).item(0); // Find the property element in the inSequence NodeList filters = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER); for (int j = 0; j < filters.getLength(); ++j) { Element filterElement = (Element) filters.item(j); if (Constants.SYNAPSE_API_VALUE_AM_KEY_TYPE .equals(filterElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE))) { // Only one <then> element can exist in filter mediator Element thenElement = (Element) filterElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_THEN) .item(0);/* w w w . j av a 2s. c om*/ NodeList properties = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY); for (int i = 0; i < properties.getLength(); ++i) { Element propertyElement = (Element) properties.item(i); if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) { if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { thenElement.removeChild(propertyElement); break; } } } //removing bam mediator //for production url NodeList thenFilterElement = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER); if (thenFilterElement != null && thenFilterElement.getLength() > 0) { for (int i = 0; i < thenFilterElement.getLength(); ++i) { Element filterNode = (Element) thenFilterElement.item(i); if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE) .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) { thenElement.removeChild(filterNode); } } } //for sandbox url Element elseElement = (Element) filterElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, "else").item(0); NodeList elseFilterElement = elseElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER); if (elseFilterElement != null && elseFilterElement.getLength() > 0) { for (int i = 0; i < elseFilterElement.getLength(); ++i) { Element filterNode = (Element) elseFilterElement.item(i); if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE) .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) { elseElement.removeChild(filterNode); } } } //adding endpoint_address property, only for production Element sendElement = (Element) thenElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_SEND) .item(0); Element endpointElement = (Element) sendElement .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_ENDPOINT_XML_ELEMENT) .item(0); if (endpointElement != null) { NodeList failOverElements = endpointElement .getElementsByTagName(Constants.SYNAPSE_FAIL_OVER_XML_ELEMENT); NodeList loadBalanceElements = endpointElement .getElementsByTagName(Constants.SYNAPSE_LOAD_BALANCE_XML_ELEMENT); if (failOverElements.getLength() > 0) { Element failOverElement = (Element) failOverElements.item(0); NodeList endpointElements = failOverElement .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT); for (int i = 0; i < endpointElements.getLength(); i++) { addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc); } } else if (loadBalanceElements.getLength() > 0) { Element loadBalanceElement = (Element) loadBalanceElements.item(0); NodeList endpointElements = loadBalanceElement .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT); for (int i = 0; i < endpointElements.getLength(); i++) { addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc); } } else { addingAddressPropertyToEndpoint(endpointElement, doc); } } } } boolean isExistProp = false; NodeList properties = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY); for (int i = 0; i < properties.getLength(); ++i) { Element propertyElement = (Element) properties.item(i); if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) { if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { isExistProp = true; log.info("Property '" + Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME + "' already exist"); break; } } } if (!isExistProp) { Element propertyElement = doc.createElementNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_PROPERTY); propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_EXPRESSION, Constants.SYNAPSE_API_VALUE_EXPRESSION); propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME, Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME); if (filters.getLength() > 0) { inSequenceElement.insertBefore(propertyElement, filters.item(0)); } else { inSequenceElement.appendChild(propertyElement); } } }
From source file:org.wso2.carbon.appmgt.migration.client.MigrationClientImpl.java
private void synapseAPIMigration() throws APPMMigrationException { for (Tenant tenant : tenantsArray) { if (log.isDebugEnabled()) { log.debug(//w ww .ja va 2s. c o m "Synapse configuration file system migration is started for tenant " + tenant.getDomain()); } String apiPath = ResourceUtil.getApiPath(tenant.getId(), tenant.getDomain()); List<SynapseDTO> synapseDTOs = ResourceUtil.getVersionedAPIs(apiPath); for (SynapseDTO synapseDTO : synapseDTOs) { Document document = synapseDTO.getDocument(); NodeList resourceNodes = document.getElementsByTagName("resource"); for (int i = 0; i < resourceNodes.getLength(); i++) { Element resourceElement = (Element) resourceNodes.item(i); Element inSequenceElement = (Element) resourceElement .getElementsByTagName(Constants.SYNAPSE_IN_SEQUENCE_ELEMENT).item(0); //Set attribute values to in sequence 'noVersion' property //Find the property element in the inSequence NodeList propertyElements = inSequenceElement .getElementsByTagName(Constants.SYNAPSE_PROPERTY_ELEMENT); boolean isNoVersionPropertyExists = false; for (int j = 0; j < propertyElements.getLength(); j++) { Element propertyElement = (Element) propertyElements.item(j); if ("POST_TO_URI" .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VALUE, "false"); } else if ("noVersion" .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) { isNoVersionPropertyExists = true; } } if (!isNoVersionPropertyExists) { Element newElement = document.createElement(Constants.SYNAPSE_PROPERTY_ELEMENT); newElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME, Constants.SYNAPSE_API_NO_VERSION_PROPERTY); newElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_EXPRESSION, "get-property('transport', 'WSO2_APPM_INVOKED_WITHOUT_VERSION')"); newElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VALUE, "true"); inSequenceElement.insertBefore(newElement, inSequenceElement.getFirstChild()); } } ResourceUtil.transformXMLDocument(document, synapseDTO.getFile()); } if (log.isDebugEnabled()) { log.debug("Synapse configuration file system migration for tenant " + tenant.getDomain() + "is completed successfully"); } } }
From source file:org.wso2.carbon.appmgt.migration.client.MigrationClientImpl.java
private String modifySignUpConfiguration(String configXml) throws APPMMigrationException { Writer stringWriter = new StringWriter(); try {//w w w .j a v a2 s . co m DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource configInputSource = new InputSource(); configInputSource.setCharacterStream(new StringReader(configXml.trim())); Document doc = builder.parse(configInputSource); NodeList nodes = doc.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROOT); if (nodes.getLength() > 0) { // iterate through sign-up role list Element roleListParent = (Element) ((Element) nodes.item(0)) .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLES_ELEM).item(0); NodeList rolesEl = roleListParent.getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_ELEM); for (int i = 0; i < rolesEl.getLength(); i++) { Element tmpEl = (Element) rolesEl.item(i); Element permissionElement = (Element) tmpEl .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_PERMISSIONS).item(0); if (permissionElement == null) { Element externalRole = (Element) tmpEl .getElementsByTagName(AppMConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(0); Element newElement = doc.createElement(AppMConstants.SELF_SIGN_UP_REG_ROLE_PERMISSIONS); //Set default permissions into config newElement.setTextContent( "/permission/admin/login,/permission/admin/manage/webapp/subscribe"); tmpEl.insertBefore(newElement, externalRole); } } } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(doc), new StreamResult(stringWriter)); } catch (SAXException e) { handleException("Error occurred while parsing signup configuration.", e); } catch (IOException e) { handleException("Error occurred while reading the sign up configuration document. " + "Please check the existence of signup configuration file in registry.", e); } catch (ParserConfigurationException e) { handleException("Error occurred while trying to build the signup configuration xml document", e); } catch (TransformerException e) { handleException("Error occurred while saving modified signup configuration xml document", e); } return stringWriter.toString(); }
From source file:org.wso2.developerstudio.eclipse.esb.impl.ModelObjectImpl.java
protected Element addComments(Element self) throws Exception { if (comment != null) { for (int i = 0; i < comment.size(); ++i) { Node tempNode = self.getFirstChild(); for (int j = 0; (tempNode != null) && (j < comment.get(i).getPosition()); ++j) { tempNode = tempNode.getNextSibling(); }// w w w.ja va2 s .c o m self.insertBefore(self.getOwnerDocument().createComment(comment.get(i).getValue()), tempNode); } } return null; }
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 av 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
@Override public String inject(final List<QName> namespaces, final AppData normalized, final X509Certificate certificate, final byte[] sig) { try {//from w ww .ja v a 2 s. c om final String normalizedAppData = new String(normalized.content, "UTF8"); final Document doc = createDocumentFromFragment(namespaces, normalizedAppData); NodeList childNodes = doc.getDocumentElement().getChildNodes(); Element body = (Element) childNodes.item(0); Attr idAttr = body.getAttributeNodeNS(WSU, "Id"); if (idAttr == null) { throw new IllegalStateException("? "); } final String id = idAttr.getValue(); final Transforms transforms = new Transforms(doc); Element signature = doc.createElementNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE); signature = (Element) body.insertBefore(signature, body.getFirstChild()); transforms.setElement(signature, id); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); ByteArrayOutputStream c14nStream = new ByteArrayOutputStream(); MessageDigestAlgorithm mda = MessageDigestAlgorithm.getInstance(doc, MessageDigestAlgorithm.ALGO_ID_DIGEST_GOST3411); mda.reset(); XMLSignatureInput output = transforms.performTransforms(new XMLSignatureInput(body), c14nStream); DigesterOutputStream digesterStream = new DigesterOutputStream(mda); output.updateOutputStream(digesterStream); AppData check = new AppData(c14nStream.toByteArray(), digesterStream.getDigestValue()); if (!Arrays.equals(check.digest, normalized.digest)) { final StringBuilder sb = new StringBuilder(" ? ?:\n"); sb.append(": ").append(new String(normalized.digest, "UTF8")).append('\n'); sb.append(" : ").append(new String(check.digest, "UTF8")); throw new IllegalStateException(sb.toString()); } Element keyInfo = doc.createElementNS(Constants.SignatureSpecNS, "KeyInfo"); Element securityTokenReference = doc.createElementNS(WSSE, "SecurityTokenReference"); Element reference = doc.createElementNS(WSSE, "Reference"); reference.setAttribute("URI", "#CertId"); reference.setAttribute("ValueType", WSS_X509V3); securityTokenReference.appendChild(reference); keyInfo.appendChild(securityTokenReference); signature.appendChild(keyInfo); Element signatureValueElement = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_SIGNATUREVALUE); signature.appendChild(signatureValueElement); String base64codedValue = Base64.encode(sig); if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) { base64codedValue = "\n" + base64codedValue + "\n"; } signatureValueElement.appendChild(doc.createTextNode(base64codedValue)); return saxFilter(doc); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (CanonicalizationException e) { throw new RuntimeException(e); } catch (XMLSecurityException e) { throw new RuntimeException(e); } }
From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java
private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException, DatatypeConfigurationException, CertificateEncodingException, DOMException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, NoSuchProviderException { SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); Element soapEnvelopeElement = soapPart.getDocumentElement(); String soapPrefix = soapEnvelopeElement.getPrefix(); LOG.debug("SOAP prefix: " + soapPrefix); Element soapHeaderElement = soapPart.createElementNS(SOAP_NAMESPACE, soapPrefix + ":Header"); Element soapBodyElement = (Element) soapEnvelopeElement.getFirstChild(); soapBodyElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE); soapBodyElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "Body"); soapEnvelopeElement.insertBefore(soapHeaderElement, soapBodyElement); LOG.debug("adding WS-Security SOAP header"); Element wsSecurityHeaderElement = soapPart.createElementNS(WSSE_NAMESPACE, "wsse:Security"); soapHeaderElement.appendChild(wsSecurityHeaderElement); wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsse", WSSE_NAMESPACE); wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE); wsSecurityHeaderElement.setAttributeNS(SOAP_NAMESPACE, soapPrefix + ":mustUnderstand", "true"); Element tsElement = addTimestamp(wsSecurityHeaderElement); addBinarySecurityToken(wsSecurityHeaderElement); addSignature(wsSecurityHeaderElement, tsElement, soapBodyElement); }
From source file:ucar.unidata.idv.ui.ImageGenerator.java
/** * process the given node//from w ww . ja v a 2 s .c om * * @param node Node to process * * @return keep going * * @throws Throwable On badness */ protected boolean processTagImport(Element node) throws Throwable { Element parent = (Element) node.getParentNode(); String file = applyMacros(node, ATTR_FILE); Element root = XmlUtil.findRoot(node); Element newRoot = XmlUtil.getRoot(file, getClass()); newRoot = (Element) root.getOwnerDocument().importNode(newRoot, true); parent.insertBefore(newRoot, node); parent.removeChild(node); if (!processNode(newRoot)) { return false; } return true; }