/** * Takes an XML file containing parameterised queries + parameter queries and substitutes * parameters for values, then saves the resulting queries * * @param queryFileName the XML query file * @param queryMixFile * @param ignoreFile */ public void generateQueries(String queryFileName, String queryMixFile, String ignoreFile) { File queryFile = new File(queryFileName); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(queryFile); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("/queries/query"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; // for each query, generate a map of parameter names and values // then replace the parameters in the final query with the respective (randomly // selected) values for (int i = 0; i < nodes.getLength(); i++) { queryCount = i + 1; String completeQuery = generateCompleteQuery(nodes.item(i), doc); saveCompleteQuery(completeQuery); } saveHelperFiles(queryMixFile, ignoreFile); } catch (Exception e) { e.printStackTrace(); } }
public NodeList getOQasNodeList() throws SAXException, ParserConfigurationException, XPathExpressionException { NodeList result = null; if (oqUrl == null) { logger.warn("OQ.url not found. Synchronization impossible."); trace.append("Синхронизация невозможна: OQ.url не указан."); return result; } try { URLConnection oqc = oqUrl.openConnection(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(oqc.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("/root/projects/project"); result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } catch (IOException e) { // обрабатываем только IOException - остальные выбрасываем наверх logger.error("oq project sync error: ", e); trace .append( "Синхронизация прервана из-за ошибки ввода/вывода при попытке получить и прочитать файл " + "синхронизации: ") .append(e.getMessage()) .append("\n"); } return result; }
public boolean equals(Object o) { if (o instanceof XPathBinaryOpExpr) { XPathBinaryOpExpr x = (XPathBinaryOpExpr) o; return a.equals(x.a) && b.equals(x.b); } else { return false; } }
/** * Checks if there is a servlet element with specified Servlet name. * * @param servletName Servlet name to check. * @return <code>true</code> if servle with specified name is present, <code>false</code> * otherwise. */ public boolean isAppletDefined(String appletAID) { try { XPathExpression xPression = xPath.compile("/applet-app/applet/applet-AID[text()='" + appletAID + "']"); // NOI18N return (Boolean) xPression.evaluate(doc, XPathConstants.BOOLEAN); } catch (XPathExpressionException ex) { return false; } }
private String getNodeValue(XPathFactory factory, Document doc, String xpathStr) throws XPathExpressionException { XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xpathStr); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList results = (NodeList) result; if (results.getLength() > 0 && null != results.item(0)) return results.item(0).getNodeValue(); return null; }
/** * Retrieves mapping service URL from ontology URI. * * @param ontologyURI ontology URI * @return mapping service URL for the ontology * @throws ParserConfigurationException * @throws IOException * @throws SAXException * @throws XPathExpressionException */ public static String getMappingServiceURL(String ontologyURI) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { log.debug("Checking mapping service URL for ontology {}", ontologyURI); Document doc = getDocumentBuilder().parse(ontologyURI); XPathExpression indexExpression = getXPathExpression("/rdf:RDF/mappingService"); final String indexURL = (String) indexExpression.evaluate(doc, XPathConstants.STRING); log.debug("Mapping service URL: {}", indexURL); return indexURL; }
private String getConfigValue(String setting, String name, Document doc) throws XPathExpressionException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression userExpr = xpath.compile( "wikipediaminer/setting[@name=\"" + setting + "\"]/param[@name=\"" + name + "\"]/@value"); return userExpr.evaluate(doc); }
private Object getDOMFromFile( final String fileName, final String xPathExpression, final QName qName) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document document = dBuilder.parse(IWSNOverlayManagerTest.class.getClassLoader().getResourceAsStream(fileName)); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression expression = xPath.compile(xPathExpression); return expression.evaluate(document, qName); }
private PageManifestDef loadRootPageDefinition(String manifestPathOrPath) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException { PageManifestDef pmd = new PageManifestDef(); Document document = readPageDefinitionFile(manifestPathOrPath, pmd); pmd.setSelectorStrategy(selectorExpr.evaluate(document)); return pmd; }
public NodeList getAppletClassElements() { try { return (NodeList) appletClassXPression.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException ex) { return null; } }
private static NodeList selectNodeList( Node contextNode, String xpathString, NamespaceContext nsContext, String... args) throws XPathException { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); xpath.setNamespaceContext(nsContext); xpathString = replacePlaceholders(xpathString, args); XPathExpression xpathExpr = xpath.compile(xpathString); NodeList nodes = (NodeList) xpathExpr.evaluate(contextNode, XPathConstants.NODESET); return nodes; }
public NodeList xpathRealQuery(String doc, String query) { log.debug("xpathRealQuery(String doc, String query)"); XPathFactory xpathFact = XPathFactory.newInstance(); XPath xpath = xpathFact.newXPath(); XPathExpression expr = null; NodeList res = null; try { expr = xpath.compile(query); Object result = expr.evaluate(doc, XPathConstants.STRING); res = (NodeList) result; } catch (XPathExpressionException e) { log.debug(e.getMessage()); return null; } return res; }
/** * Removes empty #text nodes from a document. From James Murty on this StackOverflow post: * http://stackoverflow.com/questions/978810/how-to-strip-whitespace-only-text-nodes-from-a-dom-before-serialization * * @param doc The document to remove empty text nodes from. */ private static void removeEmptyTextNodes(Document doc) { try { XPathFactory xpathFactory = XPathFactory.newInstance(); // XPath to find empty text nodes. XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']"); NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyTextNodes.getLength(); i++) { Node emptyTextNode = emptyTextNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } } catch (Exception ex) { ex.printStackTrace(); } }
public boolean equals(Object o) { if (o instanceof XPathConditional) { XPathConditional cond = (XPathConditional) o; return expr.equals(cond.expr); } else { return false; } }
public double measureMetric(Document document) { double count = 0; XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { XPathExpression expression = xpath.compile(XPATH_QUERY); count = (Double) expression.evaluate(document, XPathConstants.NUMBER); } catch (XPathExpressionException e) { e.printStackTrace(); } return count; // Para retornar so 0 ou 1 usar o seguinte: // return (count > 0.0) ? 1.0 : 0.0; }
/** * Splits the given NTCIR query file into individual queries, converts each query into an XQuery * using XQueryGenerator, and returns the result as a list of NtcirPatterns for each individual * query. * * @return List of NtcirPatterns for each query * @throws XPathExpressionException Thrown if xpaths fail to compile or fail to evaluate + */ public final List<NtcirPattern> extractPatterns() throws XPathExpressionException { final XPath xpath = XMLHelper.namespaceAwareXpath("t", NS_NII); final XPathExpression xNum = xpath.compile("./t:num"); final XPathExpression xFormula = xpath.compile("./t:query/t:formula"); final NonWhitespaceNodeList topicList = new NonWhitespaceNodeList(topics.getElementsByTagNameNS(NS_NII, "topic")); for (final Node node : topicList) { final String num = xNum.evaluate(node); final NonWhitespaceNodeList formulae = new NonWhitespaceNodeList((NodeList) xFormula.evaluate(node, XPathConstants.NODESET)); for (final Node formula : formulae) { final String id = formula.getAttributes().getNamedItem("id").getTextContent(); final Node mathMLNode = getFirstChild(formula); queryGenerator.setMainElement(getFirstChild(mathMLNode)); patterns.add(new NtcirPattern(num, id, queryGenerator.toString(), mathMLNode)); } } return patterns; }
private NodeList findNodes(Document doc, Node operation) { List<Node> xpaths = getChildNodes(operation, "xpath"); if (xpaths.isEmpty()) { return null; } String xpathExpression = xpaths.get(0).getTextContent(); if (xpathExpression == null) { return null; } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList nl = null; try { XPathExpression expr = xpath.compile(xpathExpression); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException ex) { Utils.onError(new Error.WrongXpathExpression(xpathExpression)); } return nl; }
private SignatureData createSignatureDataFromXmlDigSig(String signature) throws SignatureException { // Start with setting some fields that are known directly SignatureData signatureData = new SignatureData(); signatureData.setClientType(new ELegType("test", "test", PkiClient.NEXUS_PERSONAL_4X)); signatureData.setSignature(new String(Base64.encode(signature.getBytes()))); // For the rest we need to parse the XML try { Document document = createDocument(new ByteArrayInputStream(signature.getBytes()), false); // nonce and tbs XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xpath.compile("/Signature/Object/bankIdSignedData/srvInfo/nonce/text()"); String encodedNonce = (String) expression.evaluate(document, XPathConstants.STRING); String decodedNonce = new String(Base64.decode(encodedNonce)); // will be re-encoded again before it is sent signatureData.setNonce(decodedNonce); expression = xpath.compile("/Signature/Object/bankIdSignedData/usrVisibleData/text()"); String encodedTbs = (String) expression.evaluate(document, XPathConstants.STRING); String decodedTbs = new String(Base64.decode(encodedTbs)); // this will be re-encoded again before it is sent signatureData.setEncodedTbs(encodedTbs); signatureData.setTbs(decodedTbs); } catch (XPathExpressionException e) { throw new SignatureException(e); } catch (ParserConfigurationException e) { throw new SignatureException(e); } catch (SAXException e) { throw new SignatureException(e); } catch (IOException e) { throw new SignatureException(e); } return signatureData; }
public Object pivot( FormInstance model, EvaluationContext evalContext, List<Object> pivots, Object sentinal) throws UnpivotableExpressionException { // Pivot both args Object aval = a.pivot(model, evalContext, pivots, sentinal); Object bval = b.pivot(model, evalContext, pivots, sentinal); // If either is the sentinal, we don't have a good way to represent the resulting expression, so // fail if (aval == sentinal || bval == sentinal) { throw new UnpivotableExpressionException(); } // If either has added a pivot, this expression can't produce any more pivots, so signal that if (aval == null || bval == null) { return null; } // Otherwise, return the value return this.eval(model, evalContext); }
/** * extract the XPath from the content. the return value type is passed in input using one of the * {@link XPathConstants}. See also {@link XPathExpression#evaluate(Object item, QName * returnType)} ; * * @param ns * @param xpathExpression * @param content * @param returnType * @param charset * @return the result */ public static Object extractXPath( Map<String, String> ns, String xpathExpression, String content, QName returnType, String charset) { if (null == ns) { ns = new HashMap<String, String>(); } String ch = charset; if (ch == null) { ch = Charset.defaultCharset().name(); } Document doc = toDocument(content, charset); XPathExpression expr = toExpression(ns, xpathExpression); try { Object o = expr.evaluate(doc, returnType); return o; } catch (XPathExpressionException e) { throw new IllegalArgumentException("xPath expression cannot be executed: " + xpathExpression); } }
public Collection<String> getAllAppletAIDs() { Set<String> names = new HashSet<String>(); try { NodeList nodes = (NodeList) appletAIDXPression.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { names.add(nodes.item(i).getNodeValue()); } } catch (XPathExpressionException ex) { Exceptions.printStackTrace(ex); } return names; }
public Credentials authenticate() throws Exception { HttpURLConnection urlConnection = new ConnBuilder(authUrl) .addHeader(HttpHeaders.CONTENT_TYPE_HEADER, "application/json") .addHeader(HttpHeaders.ACCEPT_HEADER, "application/xml") .getConnection(); StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder .append("{\"auth\": {\"tenantName\": \"") .append(tenant) .append("\", \"passwordCredentials\": {\"username\": \"") .append(username) .append("\", \"password\": \"") .append(password) .append("\"}}}"); HttpResponse response = Utils.doOperation(urlConnection, jsonBuilder.toString().getBytes(), true); if (response.isSuccessCode()) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(response.payload)); String authToken = (String) tokenIdExpression.evaluate(doc, XPathConstants.STRING); String storageUrl = (String) publicUrlExpression.evaluate(doc, XPathConstants.STRING); log.trace("Authentication successful"); return new Credentials(authToken, storageUrl); } else { throw new IllegalStateException( "Error authenticating to the service. Please check your credentials. Code = " + response.code); } }
/** * Gets Xpath results * * @param contextNode * @param xpathValue * @return * @throws XPathExpressionException */ private NodeList getXPathResults(Node contextNode, String xpathValue) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // see if the request root is in a namespace String namespace = contextNode.getNamespaceURI(); // name spaces are used, so we need to lookup the correct // prefix to use in the search string NamedNodeMap namedNodeMap = contextNode.getAttributes(); Map<String, String> nsMap = new HashMap<String, String>(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Node n = namedNodeMap.item(i); // we found the matching namespace, so get the prefix // and then break out String prefix = DOMHelper.getLocalName(n); String nodeValue = n.getNodeValue(); nsMap.put(prefix, nodeValue); } // if there is not any namespace is defined for content element, default XACML request // name space would be there. if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) { nsMap.put("xacml", namespace); } NamespaceContext namespaceContext = new DefaultNamespaceContext(nsMap); xpath.setNamespaceContext(namespaceContext); XPathExpression expression = xpath.compile(xpathValue); return (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET); }
void serialize(OutputContext c) throws XProcException { boolean bRead = false; if (select == null || select.isEmpty()) { // If this input is the default input and its parent is the same, then dont add // an xread if (!step && !c.isDerivedInput(this)) { c.addPreamble("xread " + getPortVariable()); bRead = true; } } else { c.addPreamble("xpath " + XProcUtil.quote(select.xpath) + " >{" + getPortVariable() + "}"); bRead = true; } if (!Util.isEqual(port, "source")) c.addPreamble("<(" + port + ")"); bindings.serialize(c); c.addPreambleLine(""); // if(! bindings.hasInputs() ) if (bRead) c.addBody(" <{" + getPortVariable() + "}"); }
private List<Room> getRooms() { String body = get("rooms.xml"); List<Room> rooms; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); StringReader reader = new StringReader(body); InputSource inputSource = new InputSource(reader); Document doc = builder.parse(inputSource); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression roomExpr = xpath.compile("//room"); XPathExpression nameExpr = xpath.compile(".//name"); XPathExpression idExpr = xpath.compile(".//id"); NodeList roomNodeList = (NodeList) roomExpr.evaluate(doc, XPathConstants.NODESET); rooms = new ArrayList<Room>(); for (int i = 0; i < roomNodeList.getLength(); i++) { Node roomNode = roomNodeList.item(i); String name = ((NodeList) nameExpr.evaluate(roomNode, XPathConstants.NODESET)) .item(0) .getFirstChild() .getNodeValue(); String id = ((NodeList) idExpr.evaluate(roomNode, XPathConstants.NODESET)) .item(0) .getFirstChild() .getNodeValue(); rooms.add(new Room(this, name.trim(), id.trim())); } } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (XPathExpressionException e) { throw new RuntimeException(e); } return rooms; }
/** * generates a complete query from a parameterised query + parameter queries * * @param namedQuery the current query * @param doc the XML file containing the queries * @return a complete query * @throws XPathExpressionException */ protected String generateCompleteQuery(Node namedQuery, Document doc) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); String queryName = namedQuery.getAttributes().getNamedItem("id").getTextContent(); currentQueryName = queryName; System.out.println("* Generating query: " + currentQueryName); // get the parameterised query Node queryStringNode = namedQuery.getChildNodes().item(1); // TODO: get it by name String queryString = queryStringNode.getTextContent(); // this returns all paramquery nodes XPathExpression xGetParamNode = xpath.compile("//query[@id='" + queryName + "']/parameter"); NodeList paramQueries = (NodeList) xGetParamNode.evaluate(doc, XPathConstants.NODESET); Map<String, String> paramMap = new HashMap<String, String>(); for (int j = 0; j < paramQueries.getLength(); j++) { // this is one parameter query item Node paramNode = paramQueries.item(j); // get the list of parameter names for which we query XPathExpression xGetParamNames = xpath.compile("paramname"); NodeList paramNames = (NodeList) xGetParamNames.evaluate(paramNode, XPathConstants.NODESET); XPathExpression xGetParamQueryNodes = xpath.compile("paramvaluesquery"); NodeList paramQueryNodes = (NodeList) xGetParamQueryNodes.evaluate(paramNode, XPathConstants.NODESET); // the query to obtain the parameters String paramQueryString = paramQueryNodes.item(0).getTextContent(); populateParamMap(paramMap, paramNames, paramQueryString); } return substituteQueryParameters(queryString, paramMap); }
public Object evalRaw(FormInstance model, EvaluationContext evalContext) { return XPathFuncExpr.unpack(expr.eval(model, evalContext)); }
public void parseStartup(File file) { Logger.getLogger(com.bombdiggity.amazon.ec2.install.Installer.class) .info((new StringBuilder("InstallParser.parseStartup: ")).append(file).toString()); try { Document doc = loadFile(file); if (doc != null) { XPathFactory factory = XMLUtils.newXPathFactory(); XPath xpath = factory.newXPath(); String rootXPath = "/Startup/Commands/*"; Element root = doc.getDocumentElement(); XPathExpression rootExp = xpath.compile(rootXPath); NodeList streamList = (NodeList) rootExp.evaluate(root, XPathConstants.NODESET); if (streamList != null) { for (int i = 0; i < streamList.getLength(); i++) { Node streamNode = streamList.item(i); Element streamElem = (Element) streamNode; if (streamElem.getNodeName().toLowerCase().equals("install")) { String packageName = null; String folderPath = null; for (Node child = streamNode.getFirstChild(); child != null; child = child.getNextSibling()) if (child.getNodeName().toLowerCase().equals("package")) packageName = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("folder")) folderPath = XMLUtils.getNodeValue(child).trim(); if (packageName != null) InstallCommands.installPackage(session, packageName); else if (folderPath != null) InstallCommands.installFolder(session, folderPath); else Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class) .error("StartupParser.loadFile: <Install>: <Package> or <Folder> required"); } else if (streamElem.getNodeName().toLowerCase().equals("download")) { String url = null; String method = "get"; String data = null; String destination = "/opt"; String action = null; List headers = new ArrayList(); for (Node child = streamNode.getFirstChild(); child != null; child = child.getNextSibling()) if (child.getNodeName().toLowerCase().equals("url")) url = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("method")) method = XMLUtils.getNodeValue(child).toLowerCase().trim(); else if (child.getNodeName().toLowerCase().equals("data")) data = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("destination")) destination = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("action")) action = XMLUtils.getNodeValue(child).toLowerCase().trim(); else if (child.getNodeName().toLowerCase().equals("header")) { Node nameNode = XMLUtils.getNodeByTagName((Element) child, "Name"); Node valueNode = XMLUtils.getNodeByTagName((Element) child, "Value"); if (nameNode != null && valueNode != null) { Map namePair = new HashMap(); namePair.put( XMLUtils.getNodeValue(nameNode).trim(), XMLUtils.getNodeValue(valueNode).trim()); headers.add(namePair); } else { Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class) .error( "StartupParser.loadFile: <Download/Header>: <Name> and <Value> required"); } } if (url != null && destination != null) InstallCommands.downloadFile( session, url, method, data, headers, destination, action); else Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class) .error("StartupParser.loadFile: <Download>: <URL> and <Destination> required"); } else if (streamElem.getNodeName().toLowerCase().equals("s3fetch")) { String awsAccessKeyId = null; String awsSecretAccessKey = null; String bucket = null; String key = null; String destination = null; String action = null; for (Node child = streamNode.getFirstChild(); child != null; child = child.getNextSibling()) if (child.getNodeName().toLowerCase().equals("awsaccesskeyid")) awsAccessKeyId = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("awssecretaccesskey")) awsSecretAccessKey = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("bucket")) bucket = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("key")) key = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("destination")) destination = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("action")) action = XMLUtils.getNodeValue(child).toLowerCase().trim(); if (awsAccessKeyId != null && awsSecretAccessKey != null && bucket != null && key != null && destination != null) InstallCommands.fetchFile( session, awsAccessKeyId, awsSecretAccessKey, bucket, key, destination, action); else Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class) .error( "StartupParser.loadFile: <Fetch>: <AWSAccessKeyId>, <AWSSecretAccessKey>, <Bucket>, <Key> and <Destination> required"); } else if (streamElem.getNodeName().toLowerCase().equals("runscript")) { String script = null; List params = new ArrayList(); for (Node child = streamNode.getFirstChild(); child != null; child = child.getNextSibling()) if (child.getNodeName().toLowerCase().equals("script")) script = XMLUtils.getNodeValue(child).trim(); else if (child.getNodeName().toLowerCase().equals("param")) { String param = XMLUtils.getNodeValue(child).trim(); params.add(param); } if (script != null) InstallCommands.runScript(session, script, params); else Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class) .error("StartupParser.loadFile: <RunScript>: <Script> required"); } } } } } catch (Exception e) { Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class) .error( (new StringBuilder("InstallParser.parseStartup: ")).append(e.toString()).toString()); e.printStackTrace(); } }
public static void main(String[] args) { try { DocumentBuilderFactory db = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = db.newDocumentBuilder(); Document dom = builder.parse("data/geographic-area-data.html"); XPathFactory xpath = XPathFactory.newInstance(); XPath path = xpath.newXPath(); XPathExpression table = path.compile("//div[@id='mw-content-text']/table[contains(@class,'wikitable')]/tr"); NodeList wikiData = (NodeList) table.evaluate(dom, XPathConstants.NODESET); NodeList children; String currentData, cleanData; /* Open output stream */ FileWriter fstream = new FileWriter("data/parsed.yaml"); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < wikiData.getLength(); i++) { if (i == 0) { continue; } out.write(new Integer(i).toString() + ":\n"); children = wikiData.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { currentData = (String) children.item(j).getTextContent(); switch (j) { case 0: /* Current Data is empty */ break; case 1: cleanData = decompose(currentData).trim().replaceAll("[^a-zA-Z\\s]+", ""); out.write("\t\"Geographic entity\": \"" + cleanData + "\"\n"); break; case 2: /* Current Data is empty */ break; case 3: cleanData = decompose(currentData).trim().replaceAll(",", ""); out.write("\t\"Area\": \"" + cleanData + "\"\n"); break; case 4: /* Current Data is empty */ break; case 5: cleanData = decompose(currentData).trim(); out.write("\t\"Notes\": \"" + cleanData + "\"\n"); break; case 6: /* Current Data is empty */ break; default: /* System.out.println("[" + j + "] Hit default case statement. Current Data is: " + currentData); */ break; } } } /* Close output stream */ out.close(); } catch (Exception e) { System.out.println(e); } }
private void checkValues() { try { // Get payload of the message Map payload = getCalloutMediatorMessage().getPayload(); // Try to get the message key String key = null; Iterator it = payload.keySet().iterator(); while (it.hasNext()) { key = (String) it.next(); } Element payloadElement = (Element) payload.get(key); try { if (li.getLogMessageFlag() != null && li.getLogMessageFlag().trim().equals("Y")) { MsgWriter writer = new MsgWriter(); writer.setPayload(payloadElement); writer.setLi(li); writer.setEntry(entry); writer.setSoaLogger(soaLogger); writer.run(); /* This code is moved to another thread LogMsgTo msg = new LogMsgTo(); msg.setBase64Flag(li.getApplyBase64()); msg.setEnv(li.getEnvironmentFlag()); msg.setInstanceId(entry.getIntegrationInstanceId()); msg.setInterfaceName(li.getLogInterfaceName()); msg.setLogMsg(msgString); int retval = soaLogger.addLogMessage(msg); if (retval != 0) { logger.severe("Writing message to web service did not succeed: " + retval); } */ } } catch (Exception expp) { expp.printStackTrace(); logger.severe("Exception writing message to web service : " + expp.toString()); } List<LogFieldTo> lfs = null; try { lfs = soaLogger.getInterfaceFields(li); if (lfs != null) { ArrayList<EntryValueTo> values = new ArrayList<EntryValueTo>(); for (LogFieldTo field : lfs) { if (field.getXmlXpath() != null) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(field.getXmlXpath()); String xpathResult = (String) expr.evaluate(payloadElement, XPathConstants.STRING); EntryValueTo value = new EntryValueTo(); value.setValueName(field.getLogFieldName()); value.setValueId(random.nextInt()); value.setEntryValue(xpathResult); values.add(value); } catch (Exception exp) { logger.severe("Exception parsing Xpath : " + exp.toString()); } } else { NodeList nl = payloadElement.getElementsByTagNameNS("*", field.getElementName()); for (int i = 0; i < nl.getLength(); i++) { Element valEl = (Element) nl.item(i); List<String> elementValues = MessageProcesser.getStringFromElement(valEl); for (String elementValue : elementValues) { EntryValueTo value = new EntryValueTo(); value.setValueName(field.getLogFieldName()); value.setValueId(random.nextInt()); value.setEntryValue(elementValue); values.add(value); } } } } entry.setEntryValuesList(values); ArrayList<LogEntryTo> logEntries = new ArrayList<LogEntryTo>(); logEntries.add(entry); soaLogger.addLogEntryValues(logEntries); } } catch (Exception ex) { logger.severe("Exception occurred adding logfield value: " + ex.toString()); } } catch (Exception eexp) { eexp.printStackTrace(); logger.severe("Exception occurred in preRouting : " + eexp.toString()); } }