List of usage examples for org.w3c.dom Document getElementById
public Element getElementById(String elementId);
Element
that has an ID attribute with the given value. From source file:no.digipost.api.EbmsReferenceExtractor.java
public Map<String, Reference> getReferences(final SoapMessage message) { List<String> hrefs = getHrefsToInclude(message); Map<String, Reference> references = new HashMap<String, Reference>(); SoapHeaderElement wssec = message.getSoapHeader().examineHeaderElements(Constants.WSSEC_HEADER_QNAME) .next();// w w w. j ava 2s . c o m Element element = (Element) Marshalling.unmarshal(jaxb2Marshaller, wssec, Object.class); Document doc = ((DOMSource) (message.getEnvelope().getSource())).getNode().getOwnerDocument(); for (String href : hrefs) { List<Node> refs = XpathUtil.getDOMXPath("//ds:Reference[@URI='" + href + "']", element); if (refs.size() == 0) { List<Node> parts = XpathUtil.getDOMXPath("//*[@Id='" + href.substring(1) + "']", message.getDocument().getDocumentElement()); if (parts.size() > 0) { String refId = parts.get(0).getAttributes() .getNamedItemNS(Constants.WSSEC_UTILS_NAMESPACE, "Id").getNodeValue(); refs = XpathUtil.getDOMXPath("//ds:Reference[@URI='#" + refId + "']", element); } } if (refs.size() > 0) { Reference ref = Marshalling.unmarshal(jaxb2Marshaller, refs.get(0), Reference.class); String name = "attachment"; Element elm = doc.getElementById(href.replace("#", "")); if (elm != null) { name = elm.getLocalName().toLowerCase(); } references.put(name, ref); } else { throw new SecurityException("Missing reference for " + href); } } return references; }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void createModuleDef(com.krawler.utils.json.base.JSONArray jsonData, String classname) { String result = ""; try {//from w w w. j av a 2 s. c om DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile())); //Document doc = docBuilder.newDocument(); NodeList modules = doc.getElementsByTagName("modules"); Node modulesNode = modules.item(0); Element module_ex = doc.getElementById(classname); if (module_ex != null) { modulesNode.removeChild(module_ex); } Element module = doc.createElement("module"); Element property_list = doc.createElement("property-list"); module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname); module.setAttribute("type", "pojo"); module.setAttribute("id", classname); for (int cnt = 0; cnt < jsonData.length(); cnt++) { Element propertyNode = doc.createElement("property"); JSONObject jsonObj = jsonData.optJSONObject(cnt); propertyNode.setAttribute("name", jsonObj.optString("varname")); propertyNode.setAttribute("type", jsonObj.optString("modulename").toLowerCase()); property_list.appendChild(propertyNode); } module.appendChild(property_list); modulesNode.appendChild(module); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://localhost/dtds/module.dtd"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // create string from xml tree File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile()); outputFile.setWritable(true); // StringWriter sw = new StringWriter(); StreamResult sresult = new StreamResult(outputFile); DOMSource source = new DOMSource(doc); trans.transform(source, sresult); // result = sw.toString(); } catch (SAXException ex) { logger.warn(ex.getMessage(), ex); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void createModuleDef(ArrayList list, String classname) { String result = ""; try {/*from w w w. jav a 2s . c om*/ DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile())); //Document doc = docBuilder.newDocument(); NodeList modules = doc.getElementsByTagName("modules"); Node modulesNode = modules.item(0); Element module_ex = doc.getElementById(classname); if (module_ex != null) { modulesNode.removeChild(module_ex); } Element module = doc.createElement("module"); Element property_list = doc.createElement("property-list"); module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname); module.setAttribute("type", "pojo"); module.setAttribute("id", classname); for (int cnt = 0; cnt < list.size(); cnt++) { Element propertyNode = doc.createElement("property"); Hashtable mapObj = (Hashtable) list.get(cnt); propertyNode.setAttribute("name", mapObj.get("name").toString()); propertyNode.setAttribute("type", mapObj.get("type").toString().toLowerCase()); property_list.appendChild(propertyNode); } module.appendChild(property_list); modulesNode.appendChild(module); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/module.dtd"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // create string from xml tree File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile()); outputFile.setWritable(true); // StringWriter sw = new StringWriter(); StreamResult sresult = new StreamResult(outputFile); DOMSource source = new DOMSource(doc); trans.transform(source, sresult); // result = sw.toString(); } catch (SAXException ex) { logger.warn(ex.getMessage(), ex); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); } finally { // System.out.println(result); // return result; } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void createBusinessProcessforCRUD(String classname, String companyid) { try {//w w w. j av a2s.com DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse(new ClassPathResource("logic/businesslogicEx.xml").getFile()); //Document doc = docBuilder.newDocument(); NodeList businessrules = doc.getElementsByTagName("businessrules"); Node businessruleNode = businessrules.item(0); Element processEx = doc.getElementById(classname + "_addNew"); if (processEx != null) { businessruleNode.removeChild(processEx); } processEx = doc.getElementById(classname + "_delete"); if (processEx != null) { businessruleNode.removeChild(processEx); } processEx = doc.getElementById(classname + "_edit"); if (processEx != null) { businessruleNode.removeChild(processEx); } Element process = createBasicProcessNode(doc, classname, "createNewRecord", "_addNew", "createNew"); businessruleNode.appendChild(process); process = createBasicProcessNode(doc, classname, "deleteRecord", "_delete", "deleteRec"); businessruleNode.appendChild(process); process = createBasicProcessNode(doc, classname, "editRecord", "_edit", "editRec"); businessruleNode.appendChild(process); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/businesslogicEx.dtd"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // create string from xml tree File outputFile = (new ClassPathResource("logic/businesslogicEx.xml").getFile()); outputFile.setWritable(true); // StringWriter sw = new StringWriter(); StreamResult sresult = new StreamResult(outputFile); DOMSource source = new DOMSource(doc); trans.transform(source, sresult); } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); } catch (SAXException ex) { logger.warn(ex.getMessage(), ex); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); } }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Validate references present in the XmlSignature. * @param xmlSignature the xml signature whose references are to be validated. not null. * @param valContext validation context used to validate the signature itself. not null. * @param document document the signature belongs to. not null. * @param timestampNode the timestamp node of the soap security header within the document. * @throws XMLSignatureException when the validation fails. *///from w ww. j a v a2s .c o m private void validateSignatureReferences(XMLSignature xmlSignature, DOMValidateContext valContext, Document document, Node timestampNode) throws XMLSignatureException { assert xmlSignature != null; assert valContext != null; assert document != null; assert timestampNode != null; // If a signature is applied to a request then it must include: // Either the <S11:Body>, or the WS-Trust element as a direct child of the <S11:Body> // The <wsu:Timestamp>, if present in the <S11:Header>. // (in fact this must be present as per same spec, and SOAPHeaderExtractor validates it) Node soapBody = getSoapBody(document); Node wsTrustNode = getWsTrustNode(soapBody); boolean foundTimestampElement = false; boolean foundBodyOrWSTrustElement = false; List<Reference> references = xmlSignature.getSignedInfo().getReferences(); if ((references == null) || (references.size() == 0)) { throw new XMLSignatureException("Signature's SignInfo does not contain any references."); } for (Reference reference : references) { if (reference != null) { validateReferenceTransforms(reference); validateReferenceUri(reference); // note: order is important, we should not try to validate digests // before we checked expected transforms, and uri etc. if (!reference.validate(valContext)) { throw new XMLSignatureException( String.format("Signature reference '%s' is invalid.", reference.getURI())); } if (!foundTimestampElement || !foundBodyOrWSTrustElement) { String id = org.jcp.xml.dsig.internal.dom.Utils.parseIdFromSameDocumentURI(reference.getURI()); Node referencedNode = document.getElementById(id); foundTimestampElement = (foundTimestampElement) || (timestampNode.isSameNode(referencedNode)); foundBodyOrWSTrustElement = (foundBodyOrWSTrustElement) || (soapBody.isSameNode(referencedNode)) || (wsTrustNode.isSameNode(referencedNode)); } } } // for each reference if (!foundTimestampElement || !foundBodyOrWSTrustElement) { throw new XMLSignatureException( "Signature must include <wsu:Timestamp> and either SoapBody, or the WSTrust element within it."); } }
From source file:de.decoit.visa.rdf.RDFManager.java
/** * Import the contents of a VSA template into the topology. The devices of * the VSA will be grouped into a group with the specified name. Connections * between VSA and existing topology are created according to the user's * input./*from ww w . j a va2s .c o m*/ * * @param pTplID ID number of the template * @param pGroupName Name of the VSA group * @param pConnTargets Information about connections to the existing * topology * @param pConnVLANs Information about VLAN assignment of new interfaces * @throws IOException if the template RDF/XML file cannot be accessed * @throws RDFSourceException if the RDF/XML file contains errors */ public void importRDFTemplate(int pTplID, String pGroupName, Map<String, String> pConnTargets, Map<String, String> pConnVLANs) throws IOException, RDFSourceException { ComponentGroup vsaCG = TEBackend.TOPOLOGY_STORAGE.getComponentGroupByName(pGroupName); Document tpl = vsaTemplates.get(pTplID); Element vsaElement = (Element) (tpl.getElementsByTagName("VSA").item(0)); Path vsaRDF = Paths.get("res/vsa", vsaElement.getAttribute("rdf")); InputStream is = Files.newInputStream(vsaRDF); String modURI = VISA.createModelURI(vsaCG.getIdentifier()); ds.begin(ReadWrite.WRITE); try { activeNamedModel = ds.getNamedModel(modURI); // If the model contains statements, clear it before importing the // new statements if (!activeNamedModel.isEmpty()) { activeNamedModel.removeAll(); } // Read the RDF file into the model activeNamedModel.read(is, null); // Remove existing grouping information from the template List<RDFNode> cgList = activeNamedModel.listObjectsOfProperty(VISABackup.GROUP).toList(); for (RDFNode node : cgList) { if (node.isResource()) { // If the group node is a resource, remove the name literal // connected to it Resource res = (Resource) node; activeNamedModel.removeAll(res, VISA.NAME, null); } activeNamedModel.removeAll(null, VISABackup.GROUP, node); } // Remove network information from the model List<RDFNode> netList = activeNamedModel.listObjectsOfProperty(VISA.NETWORK).toList(); for (RDFNode node : netList) { if (node.isResource()) { Resource res = (Resource) node; activeNamedModel.removeAll(res, VISA.INTERNAL_NAME, null); activeNamedModel.removeAll(res, VISA.TYPE, null); activeNamedModel.removeAll(res, VISA.VALUE, null); activeNamedModel.removeAll(res, VISA.NETMASK_LENGTH, null); activeNamedModel.removeAll(null, VISA.NETWORK, res); } } // Remove address information from the model List<RDFNode> ifList = activeNamedModel.listObjectsOfProperty(VISA.ADDRESS).toList(); for (RDFNode node : ifList) { if (node.isResource()) { Resource res = (Resource) node; activeNamedModel.removeAll(res, VISA.INTERNAL_NAME, null); activeNamedModel.removeAll(res, VISA.TYPE, null); activeNamedModel.removeAll(res, VISA.VALUE, null); activeNamedModel.removeAll(null, VISA.ADDRESS, res); } } // Add new grouping information to model List<RDFNode> devList = activeNamedModel.listObjectsOfProperty(VISA.DEVICE).toList(); for (RDFNode node : devList) { if (node.isResource()) { Resource devRes = (Resource) node; StringBuilder sbURI = new StringBuilder(VISABackup.getURI()); sbURI.append(vsaCG.getIdentifier()); Resource cgRes = activeNamedModel.getResource(sbURI.toString()); activeNamedModel.add(devRes, VISABackup.GROUP, cgRes); activeNamedModel.add(cgRes, VISABackup.NAME, vsaCG.getName()); } } // Alter the local names of the nodes String lnSuffix = preventLocalNameCollisions(modURI); // Alter the root node to fit the root node of the current model alterRootNode(modURI, rootNode); // Process data stored in the model and create topology objects // from it HashSet<String> addedLocNames = processModel(modURI); // Insert the new model into the existing one ds.getDefaultModel().add(activeNamedModel); activeNamedModel = null; int routerID = 0; for (Map.Entry<String, String> connEntry : pConnTargets.entrySet()) { Element e = tpl.getElementById(connEntry.getKey()); StringBuilder sbSrc = new StringBuilder(e.getAttribute("component")); sbSrc.append(lnSuffix); if (e.hasAttribute("vlan")) { StringBuilder sbVLAN = new StringBuilder(e.getAttribute("vlan")); sbVLAN.append(lnSuffix); } // NetworkComponent inside the VSA NetworkComponent ncSrc = TEBackend.TOPOLOGY_STORAGE.getComponent(sbSrc.toString()); // NetworkComponent in the existing topology NetworkComponent ncTarget = TEBackend.TOPOLOGY_STORAGE.getComponent(connEntry.getValue()); addedLocNames.add(ncTarget.getRDFLocalName()); // Interface inside the VSA (source) Interface ifSrc = ncSrc.getConfig().createInterface(PortOrientation.TOP); // Interface in the existing topology (target) Interface ifTarget = ncTarget.getConfig().createInterface(PortOrientation.TOP); GroupInterface gIf = TEBackend.TOPOLOGY_STORAGE.getComponentGroupByName(pGroupName) .createOuterConnection(ifSrc, ifTarget); TEBackend.TOPOLOGY_STORAGE.createCable(ifSrc, ifTarget, gIf); // Check if the target component is a switch and the connection is part of a VLAN if (ncTarget instanceof NCSwitch && pConnVLANs.containsKey(connEntry.getKey())) { HashSet<VLAN> vlan = ifTarget.getAllVLAN(); // Add the VLAN to the target interface vlan.add(TEBackend.TOPOLOGY_STORAGE.getVLAN(pConnVLANs.get(connEntry.getKey()))); ifTarget.setVLAN(vlan); } // If a target VLAN inside the VSA is specified, create a router VM to connect the topology with that VLAN if (e.hasAttribute("vlan") && e.getAttribute("vlan").length() > 0) { StringBuilder sbVLAN = new StringBuilder(e.getAttribute("vlan")); sbVLAN.append(lnSuffix); ArrayList<String> ifOrientation = new ArrayList<>(); ifOrientation.add(PortOrientation.TOP.toString()); ifOrientation.add(PortOrientation.TOP.toString()); StringBuilder sbRtName = new StringBuilder("VSA Router "); sbRtName.append(routerID); NCVM router = TEBackend.TOPOLOGY_STORAGE.createVM(ifOrientation, sbRtName.toString(), null, null); router.getConfig().setComponentGroup(vsaCG.getName()); HashMap<String, Interface> ifMap = router.getConfig().getPorts(); Set<String> ifMapKeySet = ifMap.keySet(); Iterator<String> it = ifMapKeySet.iterator(); // Configure the interface connected to the VSA Interface ifInt = ncSrc.getConfig().createInterface(PortOrientation.TOP); Interface rtIfInt = ifMap.get(it.next()); TEBackend.TOPOLOGY_STORAGE.createCable(ifInt, rtIfInt, null); VLAN intVLAN = TEBackend.TOPOLOGY_STORAGE.getVLAN(sbVLAN.toString()); HashSet<VLAN> ifIntVLANs = new HashSet<>(); ifIntVLANs.add(intVLAN); ifInt.setVLAN(ifIntVLANs); // Configure the interface connected to the topology Interface ifExt = ncSrc.getConfig().createInterface(PortOrientation.TOP); Interface rtIfExt = ifMap.get(it.next()); TEBackend.TOPOLOGY_STORAGE.createCable(ifExt, rtIfExt, null); if (pConnVLANs.containsKey(connEntry.getKey())) { VLAN extVLAN = TEBackend.TOPOLOGY_STORAGE.getVLAN(pConnVLANs.get(connEntry.getKey())); HashSet<VLAN> ifExtVLANs = new HashSet<>(); ifExtVLANs.add(extVLAN); ifExt.setVLAN(ifExtVLANs); } } } // Layout the topology TEBackend.TOPOLOGY_STORAGE.layoutTopology(); TEBackend.TOPOLOGY_STORAGE.updateInterfaceOrientations(addedLocNames); ds.commit(); } catch (Throwable ex) { ds.abort(); throw ex; } finally { activeNamedModel = null; ds.end(); TDB.sync(ds); is.close(); } }
From source file:org.apache.nifi.minifi.bootstrap.util.ConfigTransformer.java
protected static DOMSource createFlowXml(ConfigSchema configSchema) throws IOException, ConfigurationChangeException, ConfigTransformerException { try {/*w ww .j a va 2 s .co m*/ // create a new, empty document final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final Document doc = docBuilder.newDocument(); // populate document with controller state final Element rootNode = doc.createElement("flowController"); doc.appendChild(rootNode); CorePropertiesSchema coreProperties = configSchema.getCoreProperties(); addTextElement(rootNode, "maxTimerDrivenThreadCount", String.valueOf(coreProperties.getMaxConcurrentThreads())); addTextElement(rootNode, "maxEventDrivenThreadCount", String.valueOf(coreProperties.getMaxConcurrentThreads())); FlowControllerSchema flowControllerProperties = configSchema.getFlowControllerProperties(); final Element element = doc.createElement("rootGroup"); rootNode.appendChild(element); ProcessGroupSchema processGroupSchema = configSchema.getProcessGroupSchema(); processGroupSchema.setId(ROOT_GROUP); processGroupSchema.setName(flowControllerProperties.getName()); processGroupSchema.setComment(flowControllerProperties.getComment()); addProcessGroup(doc, element, processGroupSchema, new ParentGroupIdResolver(processGroupSchema)); SecurityPropertiesSchema securityProperties = configSchema.getSecurityProperties(); if (securityProperties.useSSL()) { Element controllerServicesNode = doc.getElementById("controllerServices"); if (controllerServicesNode == null) { controllerServicesNode = doc.createElement("controllerServices"); } rootNode.appendChild(controllerServicesNode); addSSLControllerService(controllerServicesNode, securityProperties); } ProvenanceReportingSchema provenanceProperties = configSchema.getProvenanceReportingProperties(); if (provenanceProperties != null) { final Element reportingTasksNode = doc.createElement("reportingTasks"); rootNode.appendChild(reportingTasksNode); addProvenanceReportingTask(reportingTasksNode, configSchema); } return new DOMSource(doc); } catch (final ParserConfigurationException | DOMException | TransformerFactoryConfigurationError | IllegalArgumentException e) { throw new ConfigTransformerException(e); } catch (Exception e) { throw new ConfigTransformerException( "Failed to parse the config YAML while writing the top level of the flow xml", e); } }
From source file:org.apache.xml.security.utils.IdResolver.java
/** * Method getElementByIdUsingDOM//from ww w.j a v a2s . c o m * * @param doc the document * @param id the value of the ID * @return the element obtained by the id, or null if it is not found. */ private static Element getElementByIdUsingDOM(Document doc, String id) { if (log.isDebugEnabled()) { log.debug("getElementByIdUsingDOM() Search for ID " + id); } return doc.getElementById(id); }
From source file:org.apereo.portal.layout.dlm.DeleteManager.java
/** Attempt to apply a single delete command and return true if it succeeds or false otherwise. If the delete is disallowed or the target element no longer exists in the document the delete command fails and returns false./*from w w w . j a v a 2 s . c o m*/ */ private static boolean applyDelete(Element delete, Document ilf) { String nodeID = delete.getAttribute(Constants.ATT_NAME); Element e = ilf.getElementById(nodeID); if (e == null) return false; String deleteAllowed = e.getAttribute(Constants.ATT_DELETE_ALLOWED); if (deleteAllowed.equals("false")) return false; Element p = (Element) e.getParentNode(); e.setIdAttribute(Constants.ATT_ID, false); p.removeChild(e); return true; }
From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java
public IUserLayoutNodeDescription getNode(String nodeId) throws PortalException { if (nodeId == null) return null; Document uld = this.getUserLayoutDOM(); if (uld == null) throw new PortalException( "UserLayout has not been initialized for " + owner.getAttribute(IPerson.USERNAME) + "."); // find an element with a given id Element element = uld.getElementById(nodeId); if (element == null) { throw new PortalException("Element with ID=\"" + nodeId + "\" doesn't exist for " + owner.getAttribute(IPerson.USERNAME) + "."); }/*from www . jav a 2 s. c om*/ // instantiate the node description IUserLayoutNodeDescription desc = createNodeDescription(element); if (nodeId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX) && desc instanceof ChannelDescription) { FragmentChannelInfo info = this.distributedLayoutStore.getFragmentChannelInfo(nodeId); ((ChannelDescription) desc).setFragmentChannelInfo(info); } return desc; }