List of usage examples for org.w3c.dom Element getFirstChild
public Node getFirstChild();
From source file:edu.lternet.pasta.portal.search.BrowseGroup.java
public static BrowseGroup generateKeywordCache() { BrowseGroup controlledVocabulary = new BrowseGroup("Controlled Vocabulary"); BrowseGroup lterSiteCache = generateLterSiteCache(); controlledVocabulary.addBrowseGroup(lterSiteCache); try {/*w w w. j ava2 s . c o m*/ String topTermsXML = ControlledVocabularyClient.webServiceFetchTopTerms(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(topTermsXML, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList documentNodeList = documentElement.getElementsByTagName("term"); for (int i = 0; i < documentNodeList.getLength(); i++) { Node documentNode = documentNodeList.item(i); NodeList childNodes = documentNode.getChildNodes(); String termId = null; String value = null; for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); if (childNode instanceof Element) { Element childElement = (Element) childNode; if (childElement.getTagName().equals("term_id")) { Text text = (Text) childElement.getFirstChild(); termId = text.getData().trim(); } else if (childElement.getTagName().equals("string")) { Text text = (Text) childElement.getFirstChild(); value = text.getData().trim(); } } } BrowseGroup topTerm = new BrowseGroup(value); controlledVocabulary.addBrowseGroup(topTerm); topTerm.setTermId(termId); topTerm.setHasMoreDown("1"); topTerm.addFetchDownElements(); } } catch (Exception e) { logger.error("Exception:\n" + e.getMessage()); e.printStackTrace(); /* * By returning null, we let callers know that there was a problem * refreshing the browse cache, so callers will know not to * overwrite the previous results. */ controlledVocabulary = null; } return controlledVocabulary; }
From source file:gov.nist.healthcare.ttt.parsing.Parsing.java
private static MetadataLevel getMetadataLevelFromSoap(String soap) { Envelope env = (Envelope) JAXB.unmarshal(new StringReader(soap), Envelope.class); List<Object> headers = env.getHeader().getAny(); if (headers == null) { return MetadataLevel.XDS; }//from w w w.j a v a2s . c om Iterator it = headers.iterator(); while (it.hasNext()) { Element header = (Element) it.next(); if (header.getLocalName().equals(ELEMENT_NAME_METADATA_LEVEL) && header.getNamespaceURI().equals(NAMESPACE_DIRECT)) { String metadataLevel = header.getFirstChild().getTextContent(); if (metadataLevel.equals(METADATA_LEVEL_MINIMAL)) { return MetadataLevel.MINIMAL; } else if (metadataLevel.equals(METADATA_LEVEL_XDS)) { return MetadataLevel.XDS; } } else if (header.getLocalName().equals(ELEMENT_NAME_DIRECT_ADDRESS_BLOCK) && header.getNamespaceURI().equals(NAMESPACE_DIRECT)) { Element directAddressBlock = header; NodeList childrenDirectAddressBlock = directAddressBlock.getChildNodes(); for (int i = 0; i < childrenDirectAddressBlock.getLength(); i++) { Element child = null; if (childrenDirectAddressBlock.item(i) instanceof Element) { child = (Element) childrenDirectAddressBlock.item(i); if (child.getLocalName().equals(ELEMENT_NAME_METADATA_LEVEL) && child.getNamespaceURI().equals(NAMESPACE_DIRECT)) { String metadataLevel = child.getFirstChild().getTextContent(); if (metadataLevel.equals(METADATA_LEVEL_MINIMAL)) { return MetadataLevel.MINIMAL; } else if (metadataLevel.equals(METADATA_LEVEL_XDS)) { return MetadataLevel.XDS; } } } } } } return MetadataLevel.XDS; }
From source file:Main.java
/** * Performs the actual recursive dumping of a DOM tree to a given * <CODE>PrintStream</CODE>. Note that dump is intended to be a detailed * debugging aid rather than pretty to look at. * /*from w w w.j a v a 2s. co m*/ * @param out The <CODE>PrintStream</CODE> to write to. * @param node The <CODE>Node</CODE> under consideration. * @param indent The level of indentation. * @see #dump(Node) * @see #dump(PrintStream, Node) * @since TFP 1.0 */ private static void doDump(PrintStream out, final Node node, int indent) { if (node != null) { for (int index = 0; index < indent; ++index) out.write(' '); switch (node.getNodeType()) { case Node.DOCUMENT_NODE: { Document document = (Document) node; out.println("DOCUMENT:"); doDump(out, document.getDoctype(), indent + 1); doDump(out, document.getDocumentElement(), indent + 1); break; } case Node.DOCUMENT_TYPE_NODE: { DocumentType type = (DocumentType) node; out.println("DOCTYPE: [" + "name=" + format(type.getName()) + "," + "publicId=" + format(type.getPublicId()) + "," + "systemId=" + format(type.getSystemId()) + "]"); break; } case Node.ELEMENT_NODE: { Element element = (Element) node; out.println("ELEMENT: [" + "ns=" + format(element.getNamespaceURI()) + "," + "name=" + format(element.getLocalName()) + "]"); NamedNodeMap attrs = element.getAttributes(); for (int index = 0; index < attrs.getLength(); ++index) doDump(out, attrs.item(index), indent + 1); for (Node child = element.getFirstChild(); child != null;) { doDump(out, child, indent + 1); child = child.getNextSibling(); } break; } case Node.ATTRIBUTE_NODE: { Attr attr = (Attr) node; out.println("ATTRIBUTE: [" + "ns=" + format(attr.getNamespaceURI()) + "," + "prefix=" + format(attr.getPrefix()) + "," + "name=" + format(attr.getLocalName()) + "," + "value=" + format(attr.getNodeValue()) + "]"); break; } case Node.TEXT_NODE: { Text text = (Text) node; out.println("TEXT: [" + format(text.getNodeValue()) + "]"); for (Node child = text.getFirstChild(); child != null;) { doDump(out, child, indent + 1); child = child.getNextSibling(); } break; } case Node.CDATA_SECTION_NODE: { CDATASection data = (CDATASection) node; out.println("CDATA: [" + format(data.getNodeValue()) + "]"); break; } case Node.COMMENT_NODE: { Comment comm = (Comment) node; out.println("COMMENT: [" + format(comm.getNodeValue()) + "]"); break; } default: out.println("UNKNOWN: [type=" + node.getNodeType() + "]"); break; } } }
From source file:Main.java
/** * Performs the actual recursive dumping of a DOM tree to a given * <CODE>PrintWriter</CODE>. Note that dump is intended to be a detailed * debugging aid rather than pretty to look at. * /*w w w . j a v a 2 s .c o m*/ * @param out The <CODE>PrintWriter</CODE> to write to. * @param node The <CODE>Node</CODE> under consideration. * @param indent The level of indentation. * @see #dump(PrintWriter, Node) * @since TFP 1.0 */ private static void doDump(PrintWriter out, final Node node, int indent) { if (node != null) { for (int index = 0; index < indent; ++index) out.write(' '); switch (node.getNodeType()) { case Node.DOCUMENT_NODE: { Document document = (Document) node; out.println("DOCUMENT:"); doDump(out, document.getDoctype(), indent + 1); doDump(out, document.getDocumentElement(), indent + 1); break; } case Node.DOCUMENT_TYPE_NODE: { DocumentType type = (DocumentType) node; out.println("DOCTYPE: [" + "name=" + format(type.getName()) + "," + "publicId=" + format(type.getPublicId()) + "," + "systemId=" + format(type.getSystemId()) + "]"); break; } case Node.ELEMENT_NODE: { Element element = (Element) node; out.println("ELEMENT: [" + "ns=" + format(element.getNamespaceURI()) + "," + "name=" + format(element.getLocalName()) + "]"); NamedNodeMap attrs = element.getAttributes(); for (int index = 0; index < attrs.getLength(); ++index) doDump(out, attrs.item(index), indent + 1); for (Node child = element.getFirstChild(); child != null;) { doDump(out, child, indent + 1); child = child.getNextSibling(); } break; } case Node.ATTRIBUTE_NODE: { Attr attr = (Attr) node; out.println("ATTRIBUTE: [" + "ns=" + format(attr.getNamespaceURI()) + "," + "prefix=" + format(attr.getPrefix()) + "," + "name=" + format(attr.getLocalName()) + "," + "value=" + format(attr.getNodeValue()) + "]"); break; } case Node.TEXT_NODE: { Text text = (Text) node; out.println("TEXT: [" + format(text.getNodeValue()) + "]"); for (Node child = text.getFirstChild(); child != null;) { doDump(out, child, indent + 1); child = child.getNextSibling(); } break; } case Node.CDATA_SECTION_NODE: { CDATASection data = (CDATASection) node; out.println("CDATA: [" + format(data.getNodeValue()) + "]"); break; } case Node.COMMENT_NODE: { Comment comm = (Comment) node; out.println("COMMENT: [" + format(comm.getNodeValue()) + "]"); break; } default: out.println("UNKNOWN: [type=" + node.getNodeType() + "]"); break; } } }
From source file:Main.java
private static void collectResults(Element element, String[] path, int index, Collection destination) { // If we matched all the way to the leaf of the path, add the element to the destination.... String elemName = element.getNodeName(); int lastColon = elemName.lastIndexOf(':'); if (lastColon > 0) { elemName = elemName.substring(0, lastColon); }// www. jav a 2 s .c o m if (!elemName.equals(path[index])) return; // No match in this subtree if (index >= path.length - 1) { destination.add(element); return; } // OK, we have a match on the path so far, now check rest of the path (possibly none) Node child = element.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { // Recursive step, try t collectResults((Element) child, path, index + 1, destination); } child = child.getNextSibling(); } }
From source file:be.fedict.eid.dss.ws.DSSUtil.java
/** * Adds a DSS Verification Report to specified optional output element from * the specified list of {@link SignatureInfo}'s * /*from www . j ava2 s . c o m*/ * @param optionalOutput * optional output to add verification report to * @param signatureInfos * signature infos to use in verification report. */ public static void addVerificationReport(AnyType optionalOutput, List<SignatureInfo> signatureInfos) { LOG.debug("return verification report"); VerificationReportType verificationReport = vrObjectFactory.createVerificationReportType(); List<IndividualReportType> individualReports = verificationReport.getIndividualReport(); for (SignatureInfo signatureInfo : signatureInfos) { X509Certificate signerCertificate = signatureInfo.getSigner(); IndividualReportType individualReport = vrObjectFactory.createIndividualReportType(); individualReports.add(individualReport); SignedObjectIdentifierType signedObjectIdentifier = vrObjectFactory.createSignedObjectIdentifierType(); individualReport.setSignedObjectIdentifier(signedObjectIdentifier); SignedPropertiesType signedProperties = vrObjectFactory.createSignedPropertiesType(); signedObjectIdentifier.setSignedProperties(signedProperties); SignedSignaturePropertiesType signedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(signatureInfo.getSigningTime()); signedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.Result individualResult = vrDssObjectFactory.createResult(); individualReport.setResult(individualResult); individualResult.setResultMajor(DSSConstants.RESULT_MAJOR_SUCCESS); individualResult.setResultMinor(DSSConstants.RESULT_MINOR_VALID_SIGNATURE); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.AnyType details = vrDssObjectFactory.createAnyType(); individualReport.setDetails(details); DetailedSignatureReportType detailedSignatureReport = vrObjectFactory .createDetailedSignatureReportType(); details.getAny().add(vrObjectFactory.createDetailedSignatureReport(detailedSignatureReport)); VerificationResultType formatOKVerificationResult = vrObjectFactory.createVerificationResultType(); formatOKVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); detailedSignatureReport.setFormatOK(formatOKVerificationResult); SignatureValidityType signatureOkSignatureValidity = vrObjectFactory.createSignatureValidityType(); detailedSignatureReport.setSignatureOK(signatureOkSignatureValidity); VerificationResultType sigMathOkVerificationResult = vrObjectFactory.createVerificationResultType(); signatureOkSignatureValidity.setSigMathOK(sigMathOkVerificationResult); sigMathOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); if (null != signatureInfo.getRole()) { PropertiesType properties = vrObjectFactory.createPropertiesType(); detailedSignatureReport.setProperties(properties); SignedPropertiesType vrSignedProperties = vrObjectFactory.createSignedPropertiesType(); properties.setSignedProperties(vrSignedProperties); SignedSignaturePropertiesType vrSignedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); vrSignedProperties.setSignedSignatureProperties(vrSignedSignatureProperties); vrSignedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); SignerRoleType signerRole = vrObjectFactory.createSignerRoleType(); vrSignedSignatureProperties.setSignerRole(signerRole); ClaimedRolesListType claimedRolesList = vrXadesObjectFactory.createClaimedRolesListType(); signerRole.setClaimedRoles(claimedRolesList); be.fedict.eid.dss.ws.profile.vr.jaxb.xades.AnyType claimedRoleAny = vrXadesObjectFactory .createAnyType(); claimedRolesList.getClaimedRole().add(claimedRoleAny); claimedRoleAny.getContent().add(signatureInfo.getRole()); } CertificatePathValidityType certificatePathValidity = vrObjectFactory .createCertificatePathValidityType(); detailedSignatureReport.setCertificatePathValidity(certificatePathValidity); VerificationResultType certPathVerificationResult = vrObjectFactory.createVerificationResultType(); certPathVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); certificatePathValidity.setPathValiditySummary(certPathVerificationResult); X509IssuerSerialType certificateIdentifier = vrXmldsigObjectFactory.createX509IssuerSerialType(); certificatePathValidity.setCertificateIdentifier(certificateIdentifier); certificateIdentifier.setX509IssuerName(signerCertificate.getIssuerX500Principal().toString()); certificateIdentifier.setX509SerialNumber(signerCertificate.getSerialNumber()); CertificatePathValidityVerificationDetailType certificatePathValidityVerificationDetail = vrObjectFactory .createCertificatePathValidityVerificationDetailType(); certificatePathValidity.setPathValidityDetail(certificatePathValidityVerificationDetail); CertificateValidityType certificateValidity = vrObjectFactory.createCertificateValidityType(); certificatePathValidityVerificationDetail.getCertificateValidity().add(certificateValidity); certificateValidity.setCertificateIdentifier(certificateIdentifier); certificateValidity.setSubject(signerCertificate.getSubjectX500Principal().toString()); VerificationResultType chainingOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setChainingOK(chainingOkVerificationResult); chainingOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType validityPeriodOkVerificationResult = vrObjectFactory .createVerificationResultType(); certificateValidity.setValidityPeriodOK(validityPeriodOkVerificationResult); validityPeriodOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType extensionsOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setExtensionsOK(extensionsOkVerificationResult); extensionsOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); try { certificateValidity.setCertificateValue(signerCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("X509 encoding error: " + e.getMessage(), e); } certificateValidity.setSignatureOK(signatureOkSignatureValidity); CertificateStatusType certificateStatus = vrObjectFactory.createCertificateStatusType(); certificateValidity.setCertificateStatus(certificateStatus); VerificationResultType certStatusOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateStatus.setCertStatusOK(certStatusOkVerificationResult); certStatusOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); } Document newDocument = documentBuilder.newDocument(); Element newElement = newDocument.createElement("newNode"); try { vrMarshaller.marshal(vrObjectFactory.createVerificationReport(verificationReport), newElement); } catch (JAXBException e) { throw new RuntimeException("JAXB error: " + e.getMessage(), e); } Element verificationReportElement = (Element) newElement.getFirstChild(); optionalOutput.getAny().add(verificationReportElement); }
From source file:ching.icecreaming.action.ResourceDescriptors.java
private static String getTagValue(String tagName1, Element element1) { String tagValue1 = null;/*from w w w .ja va 2 s . c om*/ Node node1 = null; Element element2 = null; NodeList nodeList1 = element1.getElementsByTagName(tagName1); if (nodeList1 != null && nodeList1.getLength() > 0) { node1 = nodeList1.item(0); if (node1.hasChildNodes()) { if (node1.getNodeType() == Node.ELEMENT_NODE) { element2 = (Element) node1; tagValue1 = element2.getFirstChild().getNodeValue(); } } } return tagValue1; }
From source file:com.twinsoft.convertigo.engine.util.ProjectUtils.java
public static void getFullProjectDOM(Document document, String projectName, StreamSource xslFilter) throws TransformerFactoryConfigurationError, EngineException, TransformerException { Element root = document.getDocumentElement(); getFullProjectDOM(document, projectName); // transformation du dom Transformer xslt = TransformerFactory.newInstance().newTransformer(xslFilter); Element xsl = document.createElement("xsl"); xslt.transform(new DOMSource(document), new DOMResult(xsl)); root.replaceChild(xsl.getFirstChild(), root.getFirstChild()); }
From source file:com.fota.Link.sdpApi.java
public static String getNcnInfo(String CTN) throws JDOMException { String resultStr = ""; String logData = ""; try {/*from ww w. jav a2 s . c o m*/ String endPointUrl = PropUtil.getPropValue("sdp.oif516.url"); String strRequest = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' " + "xmlns:oas='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'" + " xmlns:sdp='http://kt.com/sdp'>" + " <soapenv:Header>" + " <oas:Security>" + " <oas:UsernameToken>" + " <oas:Username>" + PropUtil.getPropValue("sdp.id") + "</oas:Username>" + " <oas:Password>" + PropUtil.getPropValue("sdp.pw") + "</oas:Password>" + " </oas:UsernameToken>" + " </oas:Security>" + " </soapenv:Header>" + " <soapenv:Body>" + " <sdp:getBasicUserInfoAndMarketInfoRequest>" + " <!--You may enterthe following 6 items in any order-->" + " <sdp:CALL_CTN>" + CTN + "</sdp:CALL_CTN>" + " </sdp:getBasicUserInfoAndMarketInfoRequest>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>"; logData = "\r\n---------- Get Ncn Req Info start ----------\r\n"; logData += " get Ncn Req Info - endPointUrl : " + endPointUrl; logData += "\r\n get Ncn Req Info - Content-type : text/xml;charset=utf-8"; logData += "\r\n get Ncn Req Info - RequestMethod : POST"; logData += "\r\n get Ncn Req Info - xml : " + strRequest; logData += "\r\n---------- Get Ncn Req Info end ----------"; logger.info(logData); // connection URL url = new URL(endPointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-type", "text/xml;charset=utf-8"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); // output OutputStream os = connection.getOutputStream(); // os.write(strRequest.getBytes(), 0, strRequest.length()); os.write(strRequest.getBytes("utf-8")); os.flush(); os.close(); // input InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8")); String line = ""; String resValue = ""; String parseStr = ""; while ((line = br.readLine()) != null) { System.out.println(line); parseStr = line; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource temp = new InputSource(); temp.setCharacterStream(new StringReader(parseStr)); Document doc = builder.parse(temp); //xml? NodeList list = doc.getElementsByTagName("*"); int i = 0; Element element; String contents; String contractNum = ""; String customerId = ""; while (list.item(i) != null) { element = (Element) list.item(i); if (element.hasChildNodes()) { contents = element.getFirstChild().getNodeValue(); System.out.println(element.getNodeName() + " / " + element.getFirstChild().getNodeName()); if (element.getNodeName().equals("sdp:NS_CONTRACT_NUM")) { // resultStr = element.getFirstChild().getNodeValue(); contractNum = element.getFirstChild().getNodeValue(); } if (element.getNodeName().equals("sdp:NS_CUSTOMER_ID")) { customerId = element.getFirstChild().getNodeValue(); } // System.out.println(" >>>>> " + contents); } i++; } // System.out.println("contractNum : " + contractNum + " / cusomerId : " + customerId); resultStr = getNcnFromContractnumAndCustomerId(contractNum, customerId); // System.out.println("ncn : " + resultStr); //resultStr = resValue; // resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr"); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return resultStr; }
From source file:com.gargoylesoftware.htmlunit.html.HTMLParser.java
/** * Adds a body element to the current page, if necessary. Strictly speaking, this should * probably be done by NekoHTML. See the bug linked below. If and when that bug is fixed, * we may be able to get rid of this code. * * http://sourceforge.net/p/nekohtml/bugs/15/ * @param page/*from w ww . j a v a 2s .c om*/ * @param originalCall * @param checkInsideFrameOnly true if the original page had body that was removed by JavaScript */ private static void addBodyToPageIfNecessary(final HtmlPage page, final boolean originalCall, final boolean checkInsideFrameOnly) { // IE waits for the whole page to load before initializing bodies for frames. final boolean waitToLoad = page.hasFeature(PAGE_WAIT_LOAD_BEFORE_BODY); if (page.getEnclosingWindow() instanceof FrameWindow && originalCall && waitToLoad) { return; } // Find out if the document already has a body element (or frameset). final Element doc = page.getDocumentElement(); boolean hasBody = false; for (Node child = doc.getFirstChild(); child != null; child = child.getNextSibling()) { if (child instanceof HtmlBody || child instanceof HtmlFrameSet) { hasBody = true; break; } } // If the document does not have a body, add it. if (!hasBody && !checkInsideFrameOnly) { final HtmlBody body = new HtmlBody("body", page, null, false); doc.appendChild(body); } // If this is IE, we need to initialize the bodies of any frames, as well. // This will already have been done when emulating FF (see above). if (waitToLoad) { for (final FrameWindow frame : page.getFrames()) { final Page containedPage = frame.getEnclosedPage(); if (containedPage != null && containedPage.isHtmlPage()) { addBodyToPageIfNecessary((HtmlPage) containedPage, false, false); } } } }