List of usage examples for org.w3c.dom Node getFirstChild
public Node getFirstChild();
From source file:com.intuit.karate.Script.java
public static void evalXmlEmbeddedExpressions(Node node, ScriptContext context) { if (node.getNodeType() == Node.DOCUMENT_NODE) { node = node.getFirstChild(); }/*from w w w .j a v a2s .c o m*/ NamedNodeMap attribs = node.getAttributes(); int attribCount = attribs.getLength(); for (int i = 0; i < attribCount; i++) { Attr attrib = (Attr) attribs.item(i); String value = attrib.getValue(); value = StringUtils.trimToEmpty(value); if (isEmbeddedExpression(value)) { try { ScriptValue sv = evalInNashorn(value.substring(1), context); attrib.setValue(sv.getAsString()); } catch (Exception e) { logger.warn("embedded xml-attribute script eval failed: {}", e.getMessage()); } } } NodeList nodes = node.getChildNodes(); int childCount = nodes.getLength(); for (int i = 0; i < childCount; i++) { Node child = nodes.item(i); String value = child.getNodeValue(); if (value != null) { value = StringUtils.trimToEmpty(value); if (isEmbeddedExpression(value)) { try { ScriptValue sv = evalInNashorn(value.substring(1), context); child.setNodeValue(sv.getAsString()); } catch (Exception e) { logger.warn("embedded xml-text script eval failed: {}", e.getMessage()); } } } else if (child.hasChildNodes()) { evalXmlEmbeddedExpressions(child, context); } } }
From source file:cz.incad.cdk.cdkharvester.PidsRetriever.java
private void getDocs() throws Exception { String urlStr = harvestUrl + URIUtil.encodeQuery(actual_date); logger.log(Level.INFO, "urlStr: {0}", urlStr); org.w3c.dom.Document solrDom = solrResults(urlStr); String xPathStr = "/response/result/@numFound"; expr = xpath.compile(xPathStr);// w w w .j av a 2s .c om int numDocs = Integer.parseInt((String) expr.evaluate(solrDom, XPathConstants.STRING)); logger.log(Level.INFO, "numDocs: {0}", numDocs); if (numDocs > 0) { xPathStr = "/response/result/doc/str[@name='PID']"; expr = xpath.compile(xPathStr); NodeList nodes = (NodeList) expr.evaluate(solrDom, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String pid = node.getFirstChild().getNodeValue(); String to = node.getNextSibling().getFirstChild().getNodeValue(); qe.add(new DocEntry(pid, to)); } } }
From source file:fi.vrk.xroad.catalog.lister.WsdlCdataInterceptor.java
@Override public boolean handleResponse(MessageContext messageContext, Object o) throws Exception { WebServiceMessage response = messageContext.getResponse(); SaajSoapMessage saajSoapMessage = (SaajSoapMessage) response; SOAPMessage soapMessage = saajSoapMessage.getSaajMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); Iterator responses = body// w w w. ja v a2 s. c om .getChildElements(new QName("http://xroad.vrk.fi/xroad-catalog-lister", "GetWsdlResponse")); while (responses.hasNext()) { Node wsdlResponse = (Node) responses.next(); NodeList children = wsdlResponse.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getLocalName().equals("wsdl")) { CDATASection cdat = soapPart.createCDATASection(child.getFirstChild().getNodeValue()); child.removeChild(child.getFirstChild()); child.appendChild(cdat); } } } return true; }
From source file:com.cloud.bridge.auth.ec2.AuthenticationHandler.java
/** * For EC2 SOAP calls this function's goal is to extract the X509 certificate that is * part of the WS-Security wrapped SOAP request. We need the cert in order to * map it to the user's Cloud API key and Cloud Secret Key. *///from w w w .j a v a2s . c om public InvocationResponse invoke(MessageContext msgContext) throws AxisFault { // -> the certificate we want is embedded into the soap header try { SOAPEnvelope soapEnvelope = msgContext.getEnvelope(); String xmlHeader = soapEnvelope.toString(); //System.out.println( "entire request: " + xmlHeader ); InputStream is = new ByteArrayInputStream(xmlHeader.getBytes("UTF-8")); DocumentBuilder db = dbf.newDocumentBuilder(); Document request = db.parse(is); NodeList certs = request.getElementsByTagNameNS( "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "BinarySecurityToken"); if (0 < certs.getLength()) { Node item = certs.item(0); String result = new String(item.getFirstChild().getNodeValue()); byte[] certBytes = Base64.decodeBase64(result.getBytes()); Certificate userCert = null; CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bs = new ByteArrayInputStream(certBytes); while (bs.available() > 0) userCert = cf.generateCertificate(bs); //System.out.println( "cert: " + userCert.toString()); String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert); logger.debug("X509 cert's uniqueId: " + uniqueId); // -> find the Cloud API key and the secret key from the cert's uniqueId /* UserCredentialsDao credentialDao = new UserCredentialsDao(); UserCredentials cloudKeys = credentialDao.getByCertUniqueId( uniqueId ); */ UserCredentialsVO cloudKeys = ucDao.getByCertUniqueId(uniqueId); if (null == cloudKeys) { logger.error("Cert does not map to Cloud API keys: " + uniqueId); throw new AxisFault("User not properly registered: Certificate does not map to Cloud API Keys", "Client.Blocked"); } else UserContext.current().initContext(cloudKeys.getAccessKey(), cloudKeys.getSecretKey(), cloudKeys.getAccessKey(), "SOAP Request", null); //System.out.println( "end of cert match: " + UserContext.current().getSecretKey()); } } catch (AxisFault e) { throw e; } catch (Exception e) { logger.error("EC2 Authentication Handler: ", e); throw new AxisFault("An unknown error occurred.", "Server.InternalError"); } return InvocationResponse.CONTINUE; }
From source file:no.digipost.api.SdpMeldingSigner.java
public Document sign(final StandardBusinessDocument sbd) { try {/*from w w w .j a v a 2s .com*/ PrivateKey privateKey = keystoreInfo.getPrivateKey(); X509Certificate certificate = keystoreInfo.getCertificate(); DOMResult result = new DOMResult(); Marshalling.marshal(marshaller, sbd, result); Document doc = (Document) result.getNode(); Marshalling.trimNamespaces(doc); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(Constants.RSA_SHA256, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data xd = kif.newX509Data(Collections.singletonList(certificate)); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = fac.newXMLSignature(si, ki); Node digitalPostNode = doc.getDocumentElement().getFirstChild().getNextSibling(); Node avsenderNode = digitalPostNode.getFirstChild(); DOMSignContext dsc = new DOMSignContext(privateKey, digitalPostNode, avsenderNode); signature.sign(dsc); doc.normalizeDocument(); return doc; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnrecoverableKeyException e) { throw new RuntimeException(e); } catch (XMLSignatureException e) { throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (MarshalException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.jereksel.rommanager.XMLParser.java
/** * Getting node value/* w ww . jav a 2s . co m*/ * * @param elem element */ public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); } } } } return ""; }
From source file:org.cleverbus.core.common.exception.AbstractSoapExceptionFilter.java
/** * Gets first child element (node with type {@link Node#ELEMENT_NODE}. * * @param node the node/* w ww . j a v a 2s . c o m*/ * @return element */ protected Node getFirstElm(Node node) { node = node.getFirstChild(); while (node.getNodeType() != Node.ELEMENT_NODE) { node = node.getNextSibling(); } return node; }
From source file:com.krawler.esp.fileparser.wordparser.DocxParser.java
public String extractText(String filepath) { StringBuilder sb = new StringBuilder(); ZipFile docxfile = null;// w w w .j av a 2 s.c o m try { docxfile = new ZipFile(filepath); } catch (Exception e) { // file corrupt or otherwise could not be found logger.warn(e.getMessage(), e); return sb.toString(); } InputStream in = null; try { ZipEntry ze = docxfile.getEntry("word/document.xml"); in = docxfile.getInputStream(ze); } catch (NullPointerException nulle) { System.err.println("Expected entry word/document.xml does not exist"); logger.warn(nulle.getMessage(), nulle); return sb.toString(); } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); return sb.toString(); } Document document = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(in); } catch (ParserConfigurationException pce) { logger.warn(pce.getMessage(), pce); return sb.toString(); } catch (SAXException sex) { sex.printStackTrace(); return sb.toString(); } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); return sb.toString(); } finally { try { docxfile.close(); } catch (IOException ioe) { System.err.println("Exception closing file."); logger.warn(ioe.getMessage(), ioe); } } NodeList list = document.getElementsByTagName("w:t"); List<String> content = new ArrayList<String>(); for (int i = 0; i < list.getLength(); i++) { Node aNode = list.item(i); content.add(aNode.getFirstChild().getNodeValue()); } for (String s : content) { sb.append(s); } return sb.toString(); }
From source file:Main.java
public static int getAllChildrenString(Node start, int offset) { //String spacers = " "; String tagOpen = "<"; String tagClose = ">"; String tagEndOpen = "</"; String tagEndClose = ">"; String tagName = start.getNodeName(); String tagValue = (start.getNodeValue() == null ? "" : start.getNodeValue()); if (start.getNodeName().trim().equals("#text")) { tagOpen = ""; tagClose = ""; tagName = ""; tagEndOpen = ""; tagEndClose = ""; }//from www. j a v a 2s . c o m if (offset == 0) HTMLString = ""; else { HTMLString += //spacers.substring(0, offset) + tagOpen + tagName; if (start.getNodeType() == Element.ELEMENT_NODE) { NamedNodeMap startAttr = start.getAttributes(); for (int i = 0; i < startAttr.getLength(); i++) { Node attr = startAttr.item(i); HTMLString += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""; } } HTMLString += tagClose + tagValue; } for (Node child = start.getFirstChild(); child != null; child = child.getNextSibling()) { getAllChildrenString(child, offset + 1); } if (offset > 0 && tagName.length() > 0) { HTMLString += //spacers.substring(0, offset) + tagEndOpen + tagName + tagEndClose; } return ++offset; }
From source file:playground.jbischoff.carsharing.data.VBBRouteCatcher.java
private void run(Coord from, Coord to, long departureTime) { Locale locale = new Locale("en", "UK"); String pattern = "###.000000"; DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale); df.applyPattern(pattern);/*w w w .ja va 2 s . co m*/ // Construct data //X&Y coordinates must be exactly 8 digits, otherwise no proper result is given. They are swapped (x = long, y = lat) //Verbindungen 1-n bekommen; Laufweg, Reisezeit & Umstiege ermitteln String text = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<ReqC accessId=\"JBischoff2486b558356fa9b81b1rzum\" ver=\"1.1\" requestId=\"7\" prod=\"SPA\" lang=\"DE\">" + "<ConReq>" + "<ReqT date=\"" + VBBDAY.format(departureTime) + "\" time=\"" + VBBTIME.format(departureTime) + "\">" + "</ReqT>" + "<RFlags b=\"0\" f=\"1\" >" + "</RFlags>" + "<Start>" + "<Coord name=\"START\" x=\"" + df.format(from.getY()).replace(".", "") + "\" y=\"" + df.format(from.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "<Prod prod=\"1111000000000000\" direct=\"0\" sleeper=\"0\" couchette=\"0\" bike=\"0\"/>" + "</Start>" + "<Dest>" + "<Coord name=\"ZIEL\" x=\"" + df.format(to.getY()).replace(".", "") + "\" y=\"" + df.format(to.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "</Dest>" + "</ConReq>" + "</ReqC>"; PostMethod post = new PostMethod("http://demo.hafas.de/bin/pub/vbb/extxml.exe/"); post.setRequestBody(text); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); // Display status code // System.out.println("Response status code: " + result); // Display response // System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(post.getResponseBodyAsStream()); if (writeOutput) { BufferedWriter writer = IOUtils.getBufferedWriter(filename); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with File object to save to file StreamResult res = new StreamResult(writer); DOMSource source = new DOMSource(document); transformer.transform(source, res); writer.flush(); writer.close(); } Node connectionList = document.getFirstChild().getFirstChild().getFirstChild(); NodeList connections = connectionList.getChildNodes(); int amount = connections.getLength(); for (int i = 0; i < amount; i++) { Node connection = connections.item(i); Node overview = connection.getFirstChild(); ; while (!overview.getNodeName().equals("Overview")) { overview = overview.getNextSibling(); } System.out.println(overview.getChildNodes().item(3).getTextContent()); int transfers = Integer.parseInt(overview.getChildNodes().item(3).getTextContent()); String time = overview.getChildNodes().item(4).getFirstChild().getTextContent().substring(3); System.out.println(time); Date rideTime = VBBDATE.parse(time); int seconds = rideTime.getHours() * 3600 + rideTime.getMinutes() * 60 + rideTime.getSeconds(); System.out.println(seconds + "s; transfers: " + transfers); if (seconds < this.bestRideTime) { this.bestRideTime = seconds; this.bestTransfers = transfers; } } } catch (Exception e) { this.bestRideTime = -1; this.bestTransfers = -1; } finally { // Release current connection to the connection pool // once you are done post.releaseConnection(); post.abort(); } }