List of usage examples for org.dom4j XPath evaluate
Object evaluate(Object context);
evaluate
evaluates an XPath expression and returns the result as an Object . From source file:bio2rdf.datahub_get_stats_0_1.datahub_get_stats.java
License:Apache License
public void tHttpRequest_1Process(final java.util.Map<String, Object> globalMap) throws TalendException { globalMap.put("tHttpRequest_1_SUBPROCESS_STATE", 0); final boolean execStat = this.execStat; String iterateId = ""; int iterateLoop = 0; String currentComponent = ""; java.util.Map<String, Object> resourceMap = new java.util.HashMap<String, Object>(); try {//from w w w . j av a2 s .co m String currentMethodName = new java.lang.Exception().getStackTrace()[0].getMethodName(); boolean resumeIt = currentMethodName.equals(resumeEntryMethodName); if (resumeEntryMethodName == null || resumeIt || globalResumeTicket) {// start // the // resume globalResumeTicket = true; row6Struct row6 = new row6Struct(); row7Struct row7 = new row7Struct(); row8Struct row8 = new row8Struct(); row9Struct row9 = new row9Struct(); row10Struct row10 = new row10Struct(); row10Struct row5 = row10; /** * [tBufferOutput_1 begin ] start */ ok_Hash.put("tBufferOutput_1", false); start_Hash.put("tBufferOutput_1", System.currentTimeMillis()); currentComponent = "tBufferOutput_1"; int tos_count_tBufferOutput_1 = 0; /** * [tBufferOutput_1 begin ] stop */ /** * [tLogRow_2 begin ] start */ ok_Hash.put("tLogRow_2", false); start_Hash.put("tLogRow_2", System.currentTimeMillis()); currentComponent = "tLogRow_2"; int tos_count_tLogRow_2 = 0; /** * [tLogRow_2 begin ] stop */ /** * [tFilterRow_1 begin ] start */ ok_Hash.put("tFilterRow_1", false); start_Hash.put("tFilterRow_1", System.currentTimeMillis()); currentComponent = "tFilterRow_1"; int tos_count_tFilterRow_1 = 0; int nb_line_tFilterRow_1 = 0; int nb_line_ok_tFilterRow_1 = 0; int nb_line_reject_tFilterRow_1 = 0; class Operator_tFilterRow_1 { private String sErrorMsg = ""; private boolean bMatchFlag = true; private String sUnionFlag = "&&"; public Operator_tFilterRow_1(String unionFlag) { sUnionFlag = unionFlag; bMatchFlag = "||".equals(unionFlag) ? false : true; } public String getErrorMsg() { if (sErrorMsg != null && sErrorMsg.length() > 1) return sErrorMsg.substring(1); else return null; } public boolean getMatchFlag() { return bMatchFlag; } public void matches(boolean partMatched, String reason) { // no need to care about the next judgement if ("||".equals(sUnionFlag) && bMatchFlag) { return; } if (!partMatched) { sErrorMsg += "|" + reason; } if ("||".equals(sUnionFlag)) bMatchFlag = bMatchFlag || partMatched; else bMatchFlag = bMatchFlag && partMatched; } } /** * [tFilterRow_1 begin ] stop */ /** * [tJavaRow_2 begin ] start */ ok_Hash.put("tJavaRow_2", false); start_Hash.put("tJavaRow_2", System.currentTimeMillis()); currentComponent = "tJavaRow_2"; int tos_count_tJavaRow_2 = 0; int nb_line_tJavaRow_2 = 0; /** * [tJavaRow_2 begin ] stop */ /** * [tExtractRegexFields_1 begin ] start */ ok_Hash.put("tExtractRegexFields_1", false); start_Hash.put("tExtractRegexFields_1", System.currentTimeMillis()); currentComponent = "tExtractRegexFields_1"; int tos_count_tExtractRegexFields_1 = 0; java.util.regex.Pattern pattern_tExtractRegexFields_1 = java.util.regex.Pattern .compile("http:\\/\\/bio2rdf.org\\/(.*)_vocabulary:Resource"); /** * [tExtractRegexFields_1 begin ] stop */ /** * [tExtractJSONFields_1 begin ] start */ ok_Hash.put("tExtractJSONFields_1", false); start_Hash.put("tExtractJSONFields_1", System.currentTimeMillis()); currentComponent = "tExtractJSONFields_1"; int tos_count_tExtractJSONFields_1 = 0; int nb_line_tExtractJSONFields_1 = 0; class ConvertJSONString_tExtractJSONFields_1 { final static int Brace = 0; // { final static int Bracket = 1; // [ private int barceType = -1; private String originalJsonString = ""; private String originalLoopString = ""; private String jsonString4XML = null; private String loopString4XML = null; private String additionRoot = null; public void barceType() { for (int c = 0; c < originalJsonString.length(); ++c) { if (originalJsonString.charAt(c) == '{') { barceType = Brace; break; } else if (originalJsonString.charAt(c) == '[') { barceType = Bracket; break; } } } public void setJsonString(String originalJsonString) { this.originalJsonString = originalJsonString; } public void setLoopString(String originalLoopString) { this.originalLoopString = originalLoopString; } public String getJsonString4XML() { return jsonString4XML; } public String getLoopString4XML() { if (loopString4XML.length() > 1 && loopString4XML.endsWith("/")) { loopString4XML = loopString4XML.substring(0, loopString4XML.length() - 1); } return loopString4XML; } public void setAdditionRoot(String additionRoot) { this.additionRoot = additionRoot; } public String getAdditionRoot() { return additionRoot; } public void generate() { barceType(); jsonString4XML = originalJsonString; loopString4XML = originalLoopString; if (Brace == barceType) { if (isNeedAddRoot(originalJsonString)) { jsonString4XML = "{ \"root\": " + originalJsonString + " }"; loopString4XML = "root" + originalLoopString; setAdditionRoot("root"); } } else if (Bracket == barceType) { jsonString4XML = "{ \"root\" : { \"object\": " + originalJsonString + " } }"; loopString4XML = "root/object" + originalLoopString; setAdditionRoot("object"); } } public boolean isNeedAddRoot(String originalJsonString) { boolean isNeedAddRoot = false; net.sf.json.JSONObject jso = net.sf.json.JSONObject.fromObject(originalJsonString); String jsonKey = ""; Object firstObject = null; if (jso.names().size() == 1) { jsonKey = jso.names().get(0).toString(); firstObject = jso.get(jsonKey); } if (jso.size() > 1 || (firstObject != null && firstObject instanceof net.sf.json.JSONArray && ((net.sf.json.JSONArray) firstObject).size() > 1)) { isNeedAddRoot = true; } return isNeedAddRoot; } } ConvertJSONString_tExtractJSONFields_1 cjs_tExtractJSONFields_1 = new ConvertJSONString_tExtractJSONFields_1(); de.odysseus.staxon.json.JsonXMLConfig config_tExtractJSONFields_1 = new de.odysseus.staxon.json.JsonXMLConfigBuilder() .multiplePI(false).build(); de.odysseus.staxon.json.JsonXMLInputFactory jsonXMLInputFactory_tExtractJSONFields_1 = new de.odysseus.staxon.json.JsonXMLInputFactory( config_tExtractJSONFields_1); javax.xml.stream.XMLOutputFactory xmlOutputFactory_tExtractJSONFields_1 = javax.xml.stream.XMLOutputFactory .newInstance(); boolean isGetWholeJson_tExtractJSONFields_1 = false; class OriginalJSONString_tExtractJSONFields_1 { } OriginalJSONString_tExtractJSONFields_1 originalJSONString_tExtractJSONFields_1 = new OriginalJSONString_tExtractJSONFields_1(); class XML_API_tExtractJSONFields_1 { public boolean isDefNull(org.dom4j.Node node) throws javax.xml.transform.TransformerException { if (node != null && node instanceof org.dom4j.Element) { org.dom4j.Attribute attri = ((org.dom4j.Element) node).attribute("nil"); if (attri != null && ("true").equals(attri.getText())) { return true; } } return false; } public boolean isMissing(org.dom4j.Node node) throws javax.xml.transform.TransformerException { return node == null ? true : false; } public boolean isEmpty(org.dom4j.Node node) throws javax.xml.transform.TransformerException { if (node != null) { return node.getText().length() == 0; } return false; } } String jsonStr_tExtractJSONFields_1 = ""; String xmlStr_tExtractJSONFields_1 = ""; XML_API_tExtractJSONFields_1 xml_api_tExtractJSONFields_1 = new XML_API_tExtractJSONFields_1(); /** * [tExtractJSONFields_1 begin ] stop */ /** * [tHttpRequest_1 begin ] start */ ok_Hash.put("tHttpRequest_1", false); start_Hash.put("tHttpRequest_1", System.currentTimeMillis()); currentComponent = "tHttpRequest_1"; int tos_count_tHttpRequest_1 = 0; /** * [tHttpRequest_1 begin ] stop */ /** * [tHttpRequest_1 main ] start */ currentComponent = "tHttpRequest_1"; java.net.URL url_tHttpRequest_1 = new java.net.URL("http://" + context.endpoint_namespace + ".bio2rdf.org/sparql?default-graph-uri=&query=PREFIX+void%3A+%3Chttp%3A%2F%2Frdfs.org%2Fns%2Fvoid%23%3E%0D%0APREFIX+ds%3A+%3Chttp%3A%2F%2Fbio2rdf.org%2Fbio2rdf.dataset_vocabulary%3A%3E%0D%0A%0D%0ASELECT+*%0D%0A+%7B+%5B%5D+void%3Asubset+%5B%0D%0A+++++++a+ds%3ADataset-Type-Count%3B%0D%0A+++++++void%3Aclass+%3Flink%3B%0D%0A+++++++void%3AdistinctEntities+%3FdistinctCount%3B%0D%0A+++%5D%0D%0A+++FILTER+regex%28str%28%3Flink%29%2C+%27.*bio2rdf.org%5C%5C%2F.*_vocabulary%3AResource%27%2C+%27i%27%29%0D%0A+%7D&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on"); java.net.HttpURLConnection urlConn_tHttpRequest_1 = (java.net.HttpURLConnection) url_tHttpRequest_1 .openConnection(); urlConn_tHttpRequest_1.setRequestMethod("GET"); urlConn_tHttpRequest_1.setDoOutput(true); urlConn_tHttpRequest_1.setDoInput(true); urlConn_tHttpRequest_1.setUseCaches(false); urlConn_tHttpRequest_1.connect(); byte[] buffer_tHttpRequest_1 = new byte[1024]; int bos_buffer_tHttpRequest_1 = 0; StringBuilder sb_tHttpRequest_1 = new StringBuilder(); if (java.net.HttpURLConnection.HTTP_OK == (urlConn_tHttpRequest_1.getResponseCode())) { java.io.InputStream bis_tHttpRequest_1 = new java.io.BufferedInputStream( urlConn_tHttpRequest_1.getInputStream()); while ((bos_buffer_tHttpRequest_1 = bis_tHttpRequest_1.read(buffer_tHttpRequest_1)) != -1) { sb_tHttpRequest_1.append(new String(buffer_tHttpRequest_1, 0, bos_buffer_tHttpRequest_1)); } bis_tHttpRequest_1.close(); } else { System.err.println(urlConn_tHttpRequest_1.getResponseCode() + " " + urlConn_tHttpRequest_1.getResponseMessage()); } row6.ResponseContent = sb_tHttpRequest_1.toString(); urlConn_tHttpRequest_1.disconnect(); tos_count_tHttpRequest_1++; /** * [tHttpRequest_1 main ] stop */ /** * [tExtractJSONFields_1 main ] start */ currentComponent = "tExtractJSONFields_1"; if (row6.ResponseContent != null) {// C_01 jsonStr_tExtractJSONFields_1 = row6.ResponseContent.toString(); row7 = null; org.dom4j.io.SAXReader reader_tExtractJSONFields_1 = new org.dom4j.io.SAXReader(); org.dom4j.Document doc_tExtractJSONFields_1 = null; java.util.HashMap xmlNameSpaceMap_tExtractJSONFields_1 = new java.util.HashMap<String, String>(); org.dom4j.XPath x_tExtractJSONFields_1 = null; java.util.List<org.dom4j.tree.AbstractNode> nodeList_tExtractJSONFields_1 = null; boolean isStructError_tExtractJSONFields_1 = true; String loopQuery_tExtractJSONFields_1 = "/results/bindings"; String oraginalJsonStr_tExtractJSONFields_1 = jsonStr_tExtractJSONFields_1; cjs_tExtractJSONFields_1.setJsonString(jsonStr_tExtractJSONFields_1); cjs_tExtractJSONFields_1.setLoopString(loopQuery_tExtractJSONFields_1); java.io.ByteArrayInputStream bais_tExtractJSONFields_1 = null; java.io.ByteArrayOutputStream baos_tExtractJSONFields_1 = new java.io.ByteArrayOutputStream(); try { cjs_tExtractJSONFields_1.generate(); jsonStr_tExtractJSONFields_1 = cjs_tExtractJSONFields_1.getJsonString4XML(); loopQuery_tExtractJSONFields_1 = cjs_tExtractJSONFields_1.getLoopString4XML(); bais_tExtractJSONFields_1 = new ByteArrayInputStream( jsonStr_tExtractJSONFields_1.getBytes("UTF-8")); javax.xml.stream.XMLEventReader xmlEventReader_tExtractJSONFields_1 = jsonXMLInputFactory_tExtractJSONFields_1 .createXMLEventReader(bais_tExtractJSONFields_1); javax.xml.stream.XMLEventWriter xmLEventWriter_tExtractJSONFields_1 = xmlOutputFactory_tExtractJSONFields_1 .createXMLEventWriter(baos_tExtractJSONFields_1, "UTF-8"); xmLEventWriter_tExtractJSONFields_1.add(xmlEventReader_tExtractJSONFields_1); // convert json string to xml xmlStr_tExtractJSONFields_1 = baos_tExtractJSONFields_1.toString(); xmLEventWriter_tExtractJSONFields_1.close(); xmlEventReader_tExtractJSONFields_1.close(); doc_tExtractJSONFields_1 = reader_tExtractJSONFields_1 .read(new java.io.StringReader(xmlStr_tExtractJSONFields_1)); x_tExtractJSONFields_1 = doc_tExtractJSONFields_1 .createXPath(loopQuery_tExtractJSONFields_1); x_tExtractJSONFields_1.setNamespaceURIs(xmlNameSpaceMap_tExtractJSONFields_1); nodeList_tExtractJSONFields_1 = (java.util.List<org.dom4j.tree.AbstractNode>) x_tExtractJSONFields_1 .selectNodes(doc_tExtractJSONFields_1); isStructError_tExtractJSONFields_1 = false; } catch (java.lang.Exception ex_tExtractJSONFields_1) { System.err.println(ex_tExtractJSONFields_1.getMessage()); } finally { baos_tExtractJSONFields_1.close(); if (bais_tExtractJSONFields_1 != null) { bais_tExtractJSONFields_1.close(); } } org.dom4j.Node node_tExtractJSONFields_1 = null; String str_tExtractJSONFields_1 = ""; for (int i_tExtractJSONFields_1 = 0; isStructError_tExtractJSONFields_1 || (nodeList_tExtractJSONFields_1 != null && i_tExtractJSONFields_1 < nodeList_tExtractJSONFields_1 .size()); i_tExtractJSONFields_1++) { if (!isStructError_tExtractJSONFields_1) { row7 = null; row7 = new row7Struct(); org.dom4j.tree.AbstractNode temp_tExtractJSONFields_1 = nodeList_tExtractJSONFields_1 .get(i_tExtractJSONFields_1); nb_line_tExtractJSONFields_1++; try { org.dom4j.XPath xTmp0_tExtractJSONFields_1 = temp_tExtractJSONFields_1 .createXPath("link/value"); xTmp0_tExtractJSONFields_1.setNamespaceURIs(xmlNameSpaceMap_tExtractJSONFields_1); Object obj0_tExtractJSONFields_1 = xTmp0_tExtractJSONFields_1 .evaluate(temp_tExtractJSONFields_1); if (obj0_tExtractJSONFields_1 instanceof String || obj0_tExtractJSONFields_1 instanceof Number) { node_tExtractJSONFields_1 = temp_tExtractJSONFields_1; str_tExtractJSONFields_1 = String.valueOf(obj0_tExtractJSONFields_1); } else { node_tExtractJSONFields_1 = xTmp0_tExtractJSONFields_1 .selectSingleNode(temp_tExtractJSONFields_1); str_tExtractJSONFields_1 = xTmp0_tExtractJSONFields_1 .valueOf(temp_tExtractJSONFields_1); } if (xml_api_tExtractJSONFields_1.isDefNull(node_tExtractJSONFields_1)) { row7.link = null; } else if (xml_api_tExtractJSONFields_1.isEmpty(node_tExtractJSONFields_1)) { row7.link = ""; } else if (xml_api_tExtractJSONFields_1.isMissing(node_tExtractJSONFields_1)) { row7.link = null; } else { row7.link = str_tExtractJSONFields_1; } org.dom4j.XPath xTmp1_tExtractJSONFields_1 = temp_tExtractJSONFields_1 .createXPath("distinctCount/value"); xTmp1_tExtractJSONFields_1.setNamespaceURIs(xmlNameSpaceMap_tExtractJSONFields_1); Object obj1_tExtractJSONFields_1 = xTmp1_tExtractJSONFields_1 .evaluate(temp_tExtractJSONFields_1); if (obj1_tExtractJSONFields_1 instanceof String || obj1_tExtractJSONFields_1 instanceof Number) { node_tExtractJSONFields_1 = temp_tExtractJSONFields_1; str_tExtractJSONFields_1 = String.valueOf(obj1_tExtractJSONFields_1); } else { node_tExtractJSONFields_1 = xTmp1_tExtractJSONFields_1 .selectSingleNode(temp_tExtractJSONFields_1); str_tExtractJSONFields_1 = xTmp1_tExtractJSONFields_1 .valueOf(temp_tExtractJSONFields_1); } if (xml_api_tExtractJSONFields_1.isDefNull(node_tExtractJSONFields_1)) { row7.count = null; } else if (xml_api_tExtractJSONFields_1.isEmpty(node_tExtractJSONFields_1)) { row7.count = ""; } else if (xml_api_tExtractJSONFields_1.isMissing(node_tExtractJSONFields_1)) { row7.count = null; } else { row7.count = str_tExtractJSONFields_1; } } catch (java.lang.Exception ex_tExtractJSONFields_1) { System.err.println(ex_tExtractJSONFields_1.getMessage()); row7 = null; } } isStructError_tExtractJSONFields_1 = false; tos_count_tExtractJSONFields_1++; /** * [tExtractJSONFields_1 main ] stop */ // Start of branch "row7" if (row7 != null) { /** * [tExtractRegexFields_1 main ] start */ currentComponent = "tExtractRegexFields_1"; row8 = null; if (row7.link != null) {// C_01 java.util.regex.Matcher matcher_tExtractRegexFields_1 = pattern_tExtractRegexFields_1 .matcher(row7.link); int groupCount_tExtractRegexFields_1 = matcher_tExtractRegexFields_1.groupCount(); while (matcher_tExtractRegexFields_1.find()) { try { row8 = new row8Struct(); row8.count = row7.count; String temp_tExtractRegexFields_1 = null; row8.linkNamespace = groupCount_tExtractRegexFields_1 <= 0 ? "" : matcher_tExtractRegexFields_1.group(1); } catch (java.lang.Exception ex_tExtractRegexFields_1) { throw (ex_tExtractRegexFields_1); } tos_count_tExtractRegexFields_1++; /** * [tExtractRegexFields_1 main ] stop */ // Start of branch "row8" if (row8 != null) { /** * [tJavaRow_2 main ] start */ currentComponent = "tJavaRow_2"; // Code gnr selon le schmas d'entre // et de sortie row9.link = row8.linkNamespace; row9.stat = row8.count; nb_line_tJavaRow_2++; tos_count_tJavaRow_2++; /** * [tJavaRow_2 main ] stop */ /** * [tFilterRow_1 main ] start */ currentComponent = "tFilterRow_1"; row10 = null; Operator_tFilterRow_1 ope_tFilterRow_1 = new Operator_tFilterRow_1("&&"); ope_tFilterRow_1.matches((// code sample : use // row9 to define // the condition. // row9.columnName1.equals("foo") // ||!(row9.columnName2.equals("bar")) // replace the following // expression by your // own filter condition !row9.link.contains(".") && !row9.link.contains(" ") && !row9.link.equals(context.endpoint_namespace)), "advanced condition failed"); if (ope_tFilterRow_1.getMatchFlag()) { if (row10 == null) { row10 = new row10Struct(); } row10.link = row9.link; row10.stat = row9.stat; nb_line_ok_tFilterRow_1++; } else { nb_line_reject_tFilterRow_1++; } nb_line_tFilterRow_1++; tos_count_tFilterRow_1++; /** * [tFilterRow_1 main ] stop */ // Start of branch "row10" if (row10 != null) { /** * [tLogRow_2 main ] start */ currentComponent = "tLogRow_2"; row5 = row10; tos_count_tLogRow_2++; /** * [tLogRow_2 main ] stop */ /** * [tBufferOutput_1 main ] start */ currentComponent = "tBufferOutput_1"; String[] row_tBufferOutput_1 = new String[] { "", "", }; if (row5.link != null) { row_tBufferOutput_1[0] = row5.link; } else { row_tBufferOutput_1[0] = null; } if (row5.stat != null) { row_tBufferOutput_1[1] = row5.stat; } else { row_tBufferOutput_1[1] = null; } globalBuffer.add(row_tBufferOutput_1); tos_count_tBufferOutput_1++; /** * [tBufferOutput_1 main ] stop */ } // End of branch "row10" } // End of branch "row8" // end for } } // C_01 } // End of branch "row7" // end for } } // C_01 /** * [tHttpRequest_1 end ] start */ currentComponent = "tHttpRequest_1"; ok_Hash.put("tHttpRequest_1", true); end_Hash.put("tHttpRequest_1", System.currentTimeMillis()); /** * [tHttpRequest_1 end ] stop */ /** * [tExtractJSONFields_1 end ] start */ currentComponent = "tExtractJSONFields_1"; globalMap.put("tExtractJSONFields_1_NB_LINE", nb_line_tExtractJSONFields_1); ok_Hash.put("tExtractJSONFields_1", true); end_Hash.put("tExtractJSONFields_1", System.currentTimeMillis()); /** * [tExtractJSONFields_1 end ] stop */ /** * [tExtractRegexFields_1 end ] start */ currentComponent = "tExtractRegexFields_1"; ok_Hash.put("tExtractRegexFields_1", true); end_Hash.put("tExtractRegexFields_1", System.currentTimeMillis()); /** * [tExtractRegexFields_1 end ] stop */ /** * [tJavaRow_2 end ] start */ currentComponent = "tJavaRow_2"; globalMap.put("tJavaRow_2_NB_LINE", nb_line_tJavaRow_2); ok_Hash.put("tJavaRow_2", true); end_Hash.put("tJavaRow_2", System.currentTimeMillis()); /** * [tJavaRow_2 end ] stop */ /** * [tFilterRow_1 end ] start */ currentComponent = "tFilterRow_1"; globalMap.put("tFilterRow_1_NB_LINE", nb_line_tFilterRow_1); globalMap.put("tFilterRow_1_NB_LINE_OK", nb_line_ok_tFilterRow_1); globalMap.put("tFilterRow_1_NB_LINE_REJECT", nb_line_reject_tFilterRow_1); ok_Hash.put("tFilterRow_1", true); end_Hash.put("tFilterRow_1", System.currentTimeMillis()); /** * [tFilterRow_1 end ] stop */ /** * [tLogRow_2 end ] start */ currentComponent = "tLogRow_2"; ok_Hash.put("tLogRow_2", true); end_Hash.put("tLogRow_2", System.currentTimeMillis()); /** * [tLogRow_2 end ] stop */ /** * [tBufferOutput_1 end ] start */ currentComponent = "tBufferOutput_1"; ok_Hash.put("tBufferOutput_1", true); end_Hash.put("tBufferOutput_1", System.currentTimeMillis()); /** * [tBufferOutput_1 end ] stop */ } // end the resume } catch (java.lang.Exception e) { TalendException te = new TalendException(e, currentComponent, globalMap); throw te; } catch (java.lang.Error error) { throw error; } finally { try { /** * [tHttpRequest_1 finally ] start */ currentComponent = "tHttpRequest_1"; /** * [tHttpRequest_1 finally ] stop */ /** * [tExtractJSONFields_1 finally ] start */ currentComponent = "tExtractJSONFields_1"; /** * [tExtractJSONFields_1 finally ] stop */ /** * [tExtractRegexFields_1 finally ] start */ currentComponent = "tExtractRegexFields_1"; /** * [tExtractRegexFields_1 finally ] stop */ /** * [tJavaRow_2 finally ] start */ currentComponent = "tJavaRow_2"; /** * [tJavaRow_2 finally ] stop */ /** * [tFilterRow_1 finally ] start */ currentComponent = "tFilterRow_1"; /** * [tFilterRow_1 finally ] stop */ /** * [tLogRow_2 finally ] start */ currentComponent = "tLogRow_2"; /** * [tLogRow_2 finally ] stop */ /** * [tBufferOutput_1 finally ] start */ currentComponent = "tBufferOutput_1"; /** * [tBufferOutput_1 finally ] stop */ } catch (java.lang.Exception e) { // ignore } catch (java.lang.Error error) { // ignore } resourceMap = null; } globalMap.put("tHttpRequest_1_SUBPROCESS_STATE", 1); }
From source file:bio2rdf.upload_all_datasets_0_1.upload_all_datasets.java
License:Apache License
public void tFileList_3Process(final java.util.Map<String, Object> globalMap) throws TalendException { globalMap.put("tFileList_3_SUBPROCESS_STATE", 0); final boolean execStat = this.execStat; String iterateId = ""; int iterateLoop = 0; String currentComponent = ""; java.util.Map<String, Object> resourceMap = new java.util.HashMap<String, Object>(); try {/*from w w w. ja v a 2 s. c o m*/ String currentMethodName = new java.lang.Exception().getStackTrace()[0].getMethodName(); boolean resumeIt = currentMethodName.equals(resumeEntryMethodName); if (resumeEntryMethodName == null || resumeIt || globalResumeTicket) {// start // the // resume globalResumeTicket = true; row6Struct row6 = new row6Struct(); row4Struct row4 = new row4Struct(); row7Struct row7 = new row7Struct(); /** * [tFileList_3 begin ] start */ int NB_ITERATE_tHttpRequest_4 = 0; // for statistics ok_Hash.put("tFileList_3", false); start_Hash.put("tFileList_3", System.currentTimeMillis()); currentComponent = "tFileList_3"; int tos_count_tFileList_3 = 0; String directory_tFileList_3 = context.workspace; final java.util.List<String> maskList_tFileList_3 = new java.util.ArrayList<String>(); final java.util.List<java.util.regex.Pattern> patternList_tFileList_3 = new java.util.ArrayList<java.util.regex.Pattern>(); maskList_tFileList_3.add("datahub_import_*.json"); for (final String filemask_tFileList_3 : maskList_tFileList_3) { String filemask_compile_tFileList_3 = filemask_tFileList_3; filemask_compile_tFileList_3 = org.apache.oro.text.GlobCompiler.globToPerl5( filemask_tFileList_3.toCharArray(), org.apache.oro.text.GlobCompiler.DEFAULT_MASK); java.util.regex.Pattern fileNamePattern_tFileList_3 = java.util.regex.Pattern .compile(filemask_compile_tFileList_3); patternList_tFileList_3.add(fileNamePattern_tFileList_3); } int NB_FILEtFileList_3 = 0; final boolean case_sensitive_tFileList_3 = true; final java.util.List<java.io.File> list_tFileList_3 = new java.util.ArrayList<java.io.File>(); final java.util.List<String> filePath_tFileList_3 = new java.util.ArrayList<String>(); java.io.File file_tFileList_3 = new java.io.File(directory_tFileList_3); file_tFileList_3.listFiles(new java.io.FilenameFilter() { public boolean accept(java.io.File dir, String name) { java.io.File file = new java.io.File(dir, name); if (!file.isDirectory()) { String fileName_tFileList_3 = file.getName(); for (final java.util.regex.Pattern fileNamePattern_tFileList_3 : patternList_tFileList_3) { if (fileNamePattern_tFileList_3.matcher(fileName_tFileList_3).matches()) { if (!filePath_tFileList_3.contains(file.getAbsolutePath())) { list_tFileList_3.add(file); filePath_tFileList_3.add(file.getAbsolutePath()); } } } } return true; } }); java.util.Collections.sort(list_tFileList_3); for (int i_tFileList_3 = 0; i_tFileList_3 < list_tFileList_3.size(); i_tFileList_3++) { java.io.File files_tFileList_3 = list_tFileList_3.get(i_tFileList_3); String fileName_tFileList_3 = files_tFileList_3.getName(); String currentFileName_tFileList_3 = files_tFileList_3.getName(); String currentFilePath_tFileList_3 = files_tFileList_3.getAbsolutePath(); String currentFileDirectory_tFileList_3 = files_tFileList_3.getParent(); String currentFileExtension_tFileList_3 = null; if (files_tFileList_3.getName().contains(".") && files_tFileList_3.isFile()) { currentFileExtension_tFileList_3 = files_tFileList_3.getName() .substring(files_tFileList_3.getName().lastIndexOf(".") + 1); } else { currentFileExtension_tFileList_3 = ""; } NB_FILEtFileList_3++; globalMap.put("tFileList_3_CURRENT_FILE", currentFileName_tFileList_3); globalMap.put("tFileList_3_CURRENT_FILEPATH", currentFilePath_tFileList_3); globalMap.put("tFileList_3_CURRENT_FILEDIRECTORY", currentFileDirectory_tFileList_3); globalMap.put("tFileList_3_CURRENT_FILEEXTENSION", currentFileExtension_tFileList_3); globalMap.put("tFileList_3_NB_FILE", NB_FILEtFileList_3); /** * [tFileList_3 begin ] stop */ /** * [tFileList_3 main ] start */ currentComponent = "tFileList_3"; tos_count_tFileList_3++; /** * [tFileList_3 main ] stop */ NB_ITERATE_tHttpRequest_4++; iterateLoop++; /** * [tLogRow_4 begin ] start */ ok_Hash.put("tLogRow_4", false); start_Hash.put("tLogRow_4", System.currentTimeMillis()); currentComponent = "tLogRow_4"; int tos_count_tLogRow_4 = 0; // ///////////////////// final String OUTPUT_FIELD_SEPARATOR_tLogRow_4 = "|"; java.io.PrintStream consoleOut_tLogRow_4 = null; StringBuilder strBuffer_tLogRow_4 = null; int nb_line_tLogRow_4 = 0; // ///////////////////// /** * [tLogRow_4 begin ] stop */ /** * [tExtractJSONFields_3 begin ] start */ ok_Hash.put("tExtractJSONFields_3", false); start_Hash.put("tExtractJSONFields_3", System.currentTimeMillis()); currentComponent = "tExtractJSONFields_3"; int tos_count_tExtractJSONFields_3 = 0; int nb_line_tExtractJSONFields_3 = 0; class ConvertJSONString_tExtractJSONFields_3 { final static int Brace = 0; // { final static int Bracket = 1; // [ private int barceType = -1; private String originalJsonString = ""; private String originalLoopString = ""; private String jsonString4XML = null; private String loopString4XML = null; private String additionRoot = null; public void barceType() { for (int c = 0; c < originalJsonString.length(); ++c) { if (originalJsonString.charAt(c) == '{') { barceType = Brace; break; } else if (originalJsonString.charAt(c) == '[') { barceType = Bracket; break; } } } public void setJsonString(String originalJsonString) { this.originalJsonString = originalJsonString; } public void setLoopString(String originalLoopString) { this.originalLoopString = originalLoopString; } public String getJsonString4XML() { return jsonString4XML; } public String getLoopString4XML() { if (loopString4XML.length() > 1 && loopString4XML.endsWith("/")) { loopString4XML = loopString4XML.substring(0, loopString4XML.length() - 1); } return loopString4XML; } public void setAdditionRoot(String additionRoot) { this.additionRoot = additionRoot; } public String getAdditionRoot() { return additionRoot; } public void generate() { barceType(); jsonString4XML = originalJsonString; loopString4XML = originalLoopString; if (Brace == barceType) { if (isNeedAddRoot(originalJsonString)) { jsonString4XML = "{ \"root\": " + originalJsonString + " }"; loopString4XML = "root" + originalLoopString; setAdditionRoot("root"); } } else if (Bracket == barceType) { jsonString4XML = "{ \"root\" : { \"object\": " + originalJsonString + " } }"; loopString4XML = "root/object" + originalLoopString; setAdditionRoot("object"); } } public boolean isNeedAddRoot(String originalJsonString) { boolean isNeedAddRoot = false; net.sf.json.JSONObject jso = net.sf.json.JSONObject.fromObject(originalJsonString); String jsonKey = ""; Object firstObject = null; if (jso.names().size() == 1) { jsonKey = jso.names().get(0).toString(); firstObject = jso.get(jsonKey); } if (jso.size() > 1 || (firstObject != null && firstObject instanceof net.sf.json.JSONArray && ((net.sf.json.JSONArray) firstObject).size() > 1)) { isNeedAddRoot = true; } return isNeedAddRoot; } } ConvertJSONString_tExtractJSONFields_3 cjs_tExtractJSONFields_3 = new ConvertJSONString_tExtractJSONFields_3(); de.odysseus.staxon.json.JsonXMLConfig config_tExtractJSONFields_3 = new de.odysseus.staxon.json.JsonXMLConfigBuilder() .multiplePI(false).build(); de.odysseus.staxon.json.JsonXMLInputFactory jsonXMLInputFactory_tExtractJSONFields_3 = new de.odysseus.staxon.json.JsonXMLInputFactory( config_tExtractJSONFields_3); javax.xml.stream.XMLOutputFactory xmlOutputFactory_tExtractJSONFields_3 = javax.xml.stream.XMLOutputFactory .newInstance(); boolean isGetWholeJson_tExtractJSONFields_3 = false; class OriginalJSONString_tExtractJSONFields_3 { } OriginalJSONString_tExtractJSONFields_3 originalJSONString_tExtractJSONFields_3 = new OriginalJSONString_tExtractJSONFields_3(); class XML_API_tExtractJSONFields_3 { public boolean isDefNull(org.dom4j.Node node) throws javax.xml.transform.TransformerException { if (node != null && node instanceof org.dom4j.Element) { org.dom4j.Attribute attri = ((org.dom4j.Element) node).attribute("nil"); if (attri != null && ("true").equals(attri.getText())) { return true; } } return false; } public boolean isMissing(org.dom4j.Node node) throws javax.xml.transform.TransformerException { return node == null ? true : false; } public boolean isEmpty(org.dom4j.Node node) throws javax.xml.transform.TransformerException { if (node != null) { return node.getText().length() == 0; } return false; } } String jsonStr_tExtractJSONFields_3 = ""; String xmlStr_tExtractJSONFields_3 = ""; XML_API_tExtractJSONFields_3 xml_api_tExtractJSONFields_3 = new XML_API_tExtractJSONFields_3(); /** * [tExtractJSONFields_3 begin ] stop */ /** * [tReplicate_1 begin ] start */ ok_Hash.put("tReplicate_1", false); start_Hash.put("tReplicate_1", System.currentTimeMillis()); currentComponent = "tReplicate_1"; int tos_count_tReplicate_1 = 0; /** * [tReplicate_1 begin ] stop */ /** * [tHttpRequest_4 begin ] start */ ok_Hash.put("tHttpRequest_4", false); start_Hash.put("tHttpRequest_4", System.currentTimeMillis()); currentComponent = "tHttpRequest_4"; int tos_count_tHttpRequest_4 = 0; /** * [tHttpRequest_4 begin ] stop */ /** * [tHttpRequest_4 main ] start */ currentComponent = "tHttpRequest_4"; java.net.URL url_tHttpRequest_4 = new java.net.URL( "http://datahub.io/api/action/package_update"); java.net.HttpURLConnection urlConn_tHttpRequest_4 = (java.net.HttpURLConnection) url_tHttpRequest_4 .openConnection(); urlConn_tHttpRequest_4.setRequestMethod("POST"); urlConn_tHttpRequest_4.setDoOutput(true); urlConn_tHttpRequest_4.setDoInput(true); urlConn_tHttpRequest_4.setUseCaches(false); urlConn_tHttpRequest_4.setRequestProperty("Authorization", context.authorizationKey); urlConn_tHttpRequest_4.connect(); byte[] buffer_tHttpRequest_4 = new byte[1024]; int bos_buffer_tHttpRequest_4 = 0; StringBuilder sb_tHttpRequest_4 = new StringBuilder(); java.io.InputStream bisParam_tHttpRequest_4 = new java.io.BufferedInputStream( new java.io.FileInputStream(((String) globalMap.get("tFileList_3_CURRENT_FILEPATH")))); java.io.OutputStream bosParam_tHttpRequest_4 = new java.io.BufferedOutputStream( urlConn_tHttpRequest_4.getOutputStream()); while ((bos_buffer_tHttpRequest_4 = bisParam_tHttpRequest_4 .read(buffer_tHttpRequest_4)) != -1) { bosParam_tHttpRequest_4.write(buffer_tHttpRequest_4, 0, bos_buffer_tHttpRequest_4); } bosParam_tHttpRequest_4.flush(); bosParam_tHttpRequest_4.close(); bisParam_tHttpRequest_4.close(); if (java.net.HttpURLConnection.HTTP_OK == (urlConn_tHttpRequest_4.getResponseCode())) { java.io.InputStream bis_tHttpRequest_4 = new java.io.BufferedInputStream( urlConn_tHttpRequest_4.getInputStream()); while ((bos_buffer_tHttpRequest_4 = bis_tHttpRequest_4.read(buffer_tHttpRequest_4)) != -1) { sb_tHttpRequest_4 .append(new String(buffer_tHttpRequest_4, 0, bos_buffer_tHttpRequest_4)); } bis_tHttpRequest_4.close(); } else { System.err.println(urlConn_tHttpRequest_4.getResponseCode() + " " + urlConn_tHttpRequest_4.getResponseMessage()); } row6.ResponseContent = sb_tHttpRequest_4.toString(); urlConn_tHttpRequest_4.disconnect(); tos_count_tHttpRequest_4++; /** * [tHttpRequest_4 main ] stop */ /** * [tReplicate_1 main ] start */ currentComponent = "tReplicate_1"; row4 = new row4Struct(); row4.ResponseContent = row6.ResponseContent; tos_count_tReplicate_1++; /** * [tReplicate_1 main ] stop */ /** * [tExtractJSONFields_3 main ] start */ currentComponent = "tExtractJSONFields_3"; if (row4.ResponseContent != null) {// C_01 jsonStr_tExtractJSONFields_3 = row4.ResponseContent.toString(); row7 = null; org.dom4j.io.SAXReader reader_tExtractJSONFields_3 = new org.dom4j.io.SAXReader(); org.dom4j.Document doc_tExtractJSONFields_3 = null; java.util.HashMap xmlNameSpaceMap_tExtractJSONFields_3 = new java.util.HashMap<String, String>(); org.dom4j.XPath x_tExtractJSONFields_3 = null; java.util.List<org.dom4j.tree.AbstractNode> nodeList_tExtractJSONFields_3 = null; boolean isStructError_tExtractJSONFields_3 = true; String loopQuery_tExtractJSONFields_3 = "/result"; String oraginalJsonStr_tExtractJSONFields_3 = jsonStr_tExtractJSONFields_3; cjs_tExtractJSONFields_3.setJsonString(jsonStr_tExtractJSONFields_3); cjs_tExtractJSONFields_3.setLoopString(loopQuery_tExtractJSONFields_3); java.io.ByteArrayInputStream bais_tExtractJSONFields_3 = null; java.io.ByteArrayOutputStream baos_tExtractJSONFields_3 = new java.io.ByteArrayOutputStream(); try { cjs_tExtractJSONFields_3.generate(); jsonStr_tExtractJSONFields_3 = cjs_tExtractJSONFields_3.getJsonString4XML(); loopQuery_tExtractJSONFields_3 = cjs_tExtractJSONFields_3.getLoopString4XML(); bais_tExtractJSONFields_3 = new ByteArrayInputStream( jsonStr_tExtractJSONFields_3.getBytes("UTF-8")); javax.xml.stream.XMLEventReader xmlEventReader_tExtractJSONFields_3 = jsonXMLInputFactory_tExtractJSONFields_3 .createXMLEventReader(bais_tExtractJSONFields_3); javax.xml.stream.XMLEventWriter xmLEventWriter_tExtractJSONFields_3 = xmlOutputFactory_tExtractJSONFields_3 .createXMLEventWriter(baos_tExtractJSONFields_3, "UTF-8"); xmLEventWriter_tExtractJSONFields_3.add(xmlEventReader_tExtractJSONFields_3); // convert json string to xml xmlStr_tExtractJSONFields_3 = baos_tExtractJSONFields_3.toString(); xmLEventWriter_tExtractJSONFields_3.close(); xmlEventReader_tExtractJSONFields_3.close(); doc_tExtractJSONFields_3 = reader_tExtractJSONFields_3 .read(new java.io.StringReader(xmlStr_tExtractJSONFields_3)); x_tExtractJSONFields_3 = doc_tExtractJSONFields_3 .createXPath(loopQuery_tExtractJSONFields_3); x_tExtractJSONFields_3.setNamespaceURIs(xmlNameSpaceMap_tExtractJSONFields_3); nodeList_tExtractJSONFields_3 = (java.util.List<org.dom4j.tree.AbstractNode>) x_tExtractJSONFields_3 .selectNodes(doc_tExtractJSONFields_3); isStructError_tExtractJSONFields_3 = false; } catch (java.lang.Exception ex_tExtractJSONFields_3) { System.err.println(ex_tExtractJSONFields_3.getMessage()); } finally { baos_tExtractJSONFields_3.close(); if (bais_tExtractJSONFields_3 != null) { bais_tExtractJSONFields_3.close(); } } org.dom4j.Node node_tExtractJSONFields_3 = null; String str_tExtractJSONFields_3 = ""; for (int i_tExtractJSONFields_3 = 0; isStructError_tExtractJSONFields_3 || (nodeList_tExtractJSONFields_3 != null && i_tExtractJSONFields_3 < nodeList_tExtractJSONFields_3 .size()); i_tExtractJSONFields_3++) { if (!isStructError_tExtractJSONFields_3) { row7 = null; row7 = new row7Struct(); org.dom4j.tree.AbstractNode temp_tExtractJSONFields_3 = nodeList_tExtractJSONFields_3 .get(i_tExtractJSONFields_3); nb_line_tExtractJSONFields_3++; try { org.dom4j.XPath xTmp0_tExtractJSONFields_3 = temp_tExtractJSONFields_3 .createXPath("name"); xTmp0_tExtractJSONFields_3 .setNamespaceURIs(xmlNameSpaceMap_tExtractJSONFields_3); Object obj0_tExtractJSONFields_3 = xTmp0_tExtractJSONFields_3 .evaluate(temp_tExtractJSONFields_3); if (obj0_tExtractJSONFields_3 instanceof String || obj0_tExtractJSONFields_3 instanceof Number) { node_tExtractJSONFields_3 = temp_tExtractJSONFields_3; str_tExtractJSONFields_3 = String.valueOf(obj0_tExtractJSONFields_3); } else { node_tExtractJSONFields_3 = xTmp0_tExtractJSONFields_3 .selectSingleNode(temp_tExtractJSONFields_3); str_tExtractJSONFields_3 = xTmp0_tExtractJSONFields_3 .valueOf(temp_tExtractJSONFields_3); } if (xml_api_tExtractJSONFields_3.isDefNull(node_tExtractJSONFields_3)) { row7.ResponseContent = null; } else if (xml_api_tExtractJSONFields_3.isEmpty(node_tExtractJSONFields_3)) { row7.ResponseContent = ""; } else if (xml_api_tExtractJSONFields_3.isMissing(node_tExtractJSONFields_3)) { row7.ResponseContent = null; } else { row7.ResponseContent = str_tExtractJSONFields_3; } } catch (java.lang.Exception ex_tExtractJSONFields_3) { System.err.println(ex_tExtractJSONFields_3.getMessage()); row7 = null; } } isStructError_tExtractJSONFields_3 = false; tos_count_tExtractJSONFields_3++; /** * [tExtractJSONFields_3 main ] stop */ // Start of branch "row7" if (row7 != null) { /** * [tLogRow_4 main ] start */ currentComponent = "tLogRow_4"; // ///////////////////// strBuffer_tLogRow_4 = new StringBuilder(); if (row7.ResponseContent != null) { // strBuffer_tLogRow_4.append(String.valueOf(row7.ResponseContent)); } // if (globalMap.get("tLogRow_CONSOLE") != null) { consoleOut_tLogRow_4 = (java.io.PrintStream) globalMap.get("tLogRow_CONSOLE"); } else { consoleOut_tLogRow_4 = new java.io.PrintStream( new java.io.BufferedOutputStream(System.out)); globalMap.put("tLogRow_CONSOLE", consoleOut_tLogRow_4); } consoleOut_tLogRow_4.println(strBuffer_tLogRow_4.toString()); consoleOut_tLogRow_4.flush(); nb_line_tLogRow_4++; // //// // //// // ///////////////////// tos_count_tLogRow_4++; /** * [tLogRow_4 main ] stop */ } // End of branch "row7" // end for } } // C_01 /** * [tHttpRequest_4 end ] start */ currentComponent = "tHttpRequest_4"; ok_Hash.put("tHttpRequest_4", true); end_Hash.put("tHttpRequest_4", System.currentTimeMillis()); /** * [tHttpRequest_4 end ] stop */ /** * [tReplicate_1 end ] start */ currentComponent = "tReplicate_1"; ok_Hash.put("tReplicate_1", true); end_Hash.put("tReplicate_1", System.currentTimeMillis()); /** * [tReplicate_1 end ] stop */ /** * [tExtractJSONFields_3 end ] start */ currentComponent = "tExtractJSONFields_3"; globalMap.put("tExtractJSONFields_1_NB_LINE", nb_line_tExtractJSONFields_3); ok_Hash.put("tExtractJSONFields_3", true); end_Hash.put("tExtractJSONFields_3", System.currentTimeMillis()); /** * [tExtractJSONFields_3 end ] stop */ /** * [tLogRow_4 end ] start */ currentComponent = "tLogRow_4"; // //// // //// globalMap.put("tLogRow_4_NB_LINE", nb_line_tLogRow_4); // ///////////////////// ok_Hash.put("tLogRow_4", true); end_Hash.put("tLogRow_4", System.currentTimeMillis()); /** * [tLogRow_4 end ] stop */ /** * [tFileList_3 end ] start */ currentComponent = "tFileList_3"; } globalMap.put("tFileList_3_NB_FILE", NB_FILEtFileList_3); ok_Hash.put("tFileList_3", true); end_Hash.put("tFileList_3", System.currentTimeMillis()); /** * [tFileList_3 end ] stop */ } // end the resume } catch (java.lang.Exception e) { TalendException te = new TalendException(e, currentComponent, globalMap); throw te; } catch (java.lang.Error error) { throw error; } finally { try { /** * [tFileList_3 finally ] start */ currentComponent = "tFileList_3"; /** * [tFileList_3 finally ] stop */ /** * [tHttpRequest_4 finally ] start */ currentComponent = "tHttpRequest_4"; /** * [tHttpRequest_4 finally ] stop */ /** * [tReplicate_1 finally ] start */ currentComponent = "tReplicate_1"; /** * [tReplicate_1 finally ] stop */ /** * [tExtractJSONFields_3 finally ] start */ currentComponent = "tExtractJSONFields_3"; /** * [tExtractJSONFields_3 finally ] stop */ /** * [tLogRow_4 finally ] start */ currentComponent = "tLogRow_4"; /** * [tLogRow_4 finally ] stop */ } catch (java.lang.Exception e) { // ignore } catch (java.lang.Error error) { // ignore } resourceMap = null; } globalMap.put("tFileList_3_SUBPROCESS_STATE", 1); }
From source file:com.devoteam.srit.xmlloader.core.Parameter.java
License:Open Source License
public void applyXPath(String xml, String xpath, boolean deleteNS) throws Exception { // remove beginning to '<' character int iPosBegin = xml.indexOf('<'); if (iPosBegin > 0) { xml = xml.substring(iPosBegin);/*from w w w . ja v a2s . c om*/ } // remove from '>' character to the end int iPosEnd = xml.lastIndexOf('>'); if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1)) { xml = xml.substring(0, iPosEnd + 1); } int iPosXMLLine = xml.indexOf("<?xml"); if (iPosXMLLine < 0) { xml = "<?xml version='1.0'?>" + xml; } // remove the namespace because the parser does not support them if there are not declare in the root node if (deleteNS) { xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<"); xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</"); } // remove doctype information (dtd files for the XML syntax) xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", ""); InputStream input = new ByteArrayInputStream(xml.getBytes()); SAXReader reader = new SAXReader(false); reader.setEntityResolver(new XMLLoaderEntityResolver()); Document document = reader.read(input); XPath xpathObject = document.createXPath(xpath); Object obj = xpathObject.evaluate(document.getRootElement()); if (obj instanceof List) { List<Node> list = (List<Node>) obj; for (Node node : list) { add(node.asXML()); } } else if (obj instanceof DefaultElement) { Node node = (Node) obj; add(node.asXML()); } else if (obj instanceof DefaultAttribute) { Node node = (Node) obj; add(node.getStringValue()); } else if (obj instanceof DefaultText) { Node node = (Node) obj; add(node.getText()); } else { add(obj.toString()); } }
From source file:de.codecentric.multitool.xml.XmlLibrary.java
License:Apache License
/** * Ersetzt den Text-Inhalt des Xpath Elements/Attributs durch den angegeben Wert. * Wenn mehrere Elemente oder Attribute gefunden werden, wird der Wert mehrfach ersetzt. * //w w w .j a v a2 s. c om * Beispiel: * | Replace Xml Element Value | ${xmlDoc} | //Row[@orderid="2"]/Column[@name="TRADE_ID"] | 12345 | */ public void replaceXmlElementValue(Document document, String expression, String value) { if (!isXPathEpression(expression)) { throw new IllegalArgumentException("Unbekannter selector: " + expression); } XPath path = document.createXPath(getXPath(expression)); Object result = path.evaluate(document); if (result instanceof List) { for (Object o : (List<?>) result) { if (o instanceof DefaultAttribute) { replaceAttributeValue((DefaultAttribute) o, value); } if (o instanceof DefaultElement) { replaceElementValue((DefaultElement) o, value); } } } if (result instanceof DefaultElement) { replaceElementValue((DefaultElement) result, value); } if (result instanceof DefaultAttribute) { replaceAttributeValue((DefaultAttribute) result, value); } }
From source file:de.codecentric.multitool.xml.XmlLibrary.java
License:Apache License
/** * Liefert ein Xml - Knoten als String/* w w w . j a v a 2 s. c o m*/ * * Beispiel: * | ${xmlFragment} = | Get Xml Node | ${xmlDoc} | //Row[@orderid="2"] | */ public String getXmlNode(Document document, String expression) { XPath path = document.createXPath(expression); Object result = path.evaluate(document); if (result instanceof DefaultElement) { return ((DefaultElement) result).asXML(); } else { throw new RuntimeException("Der Xpath Ausdruck liefert keinen XML Knoten!"); } }
From source file:de.innovationgate.wga.server.api.Xml.java
License:Open Source License
/** * Executes an XPath expression on some XML text or JavaBean * This function always returns single values. If the xpath expression matches multiple values it will only return the first one. To retrieve lists of values use {@link #xpathList(Object, String)}. * The given object to parse as XML is either a dom4j branch object (mostly document or element), a String containing XML text or a JavaBean. In the last case this function uses JXPath functionality to find a bean property value. * This uses the Apache library JXPath under the hood. See their documentation for details how XPath is used to browser JavaBeans. * @param object Object to inspect/*w w w . jav a2 s .c o m*/ * @param xpath XPath expression * @param ns Map of namespace prefix declarations used in the XPath. Keys are prefixes, values are namespace URIs. * @return Returned value * @throws DocumentException */ public Object xpath(Object object, String xpath, Map<String, String> ns) throws WGException, DocumentException { Object result; if (object instanceof String || object instanceof Branch) { Branch branch = retrieveBranch(object); XPath xpathObj = createXPath(xpath, branch, ns); result = xpathObj.evaluate(branch); } // Do JXPath on Bean else { JXPathContext jxContext = JXPathContext.newContext(object); jxContext.setLenient(true); result = jxContext.getValue(xpath); } return convertXMLObjects(result, false); }
From source file:org.apache.archiva.xml.XMLReader.java
License:Apache License
@SuppressWarnings("unchecked") public List<Element> getElementList(String xpathExpr) throws XMLException { XPath xpath = createXPath(xpathExpr); Object evaluated = xpath.evaluate(document); if (evaluated == null) { return null; }// w w w . ja va 2 s . com /* The xpath.evaluate(Context) method can return: * 1) A Collection or List of dom4j Nodes. * 2) A single dom4j Node. */ if (evaluated instanceof List) { return (List<Element>) evaluated; } else if (evaluated instanceof Node) { List<Element> ret = new ArrayList<>(); ret.add((Element) evaluated); return ret; } else { // Unknown evaluated type. throw new XMLException(".getElementList( Expr: " + xpathExpr + " ) resulted in non-List type -> (" + evaluated.getClass().getName() + ") " + evaluated); } }
From source file:org.mule.module.xml.transformer.JXPathExtractor.java
License:Open Source License
/** * Evaluate the expression in the context of the given object and returns the * result. If the given object is a string, it assumes it is an valid xml and * parses it before evaluating the xpath expression. *//*from www . j ava 2s. c o m*/ @Override public Object doTransform(Object src, String encoding) throws TransformerException { try { Object result = null; if (src instanceof String) { Document doc = DocumentHelper.parseText((String) src); XPath xpath = doc.createXPath(expression); if (namespaces != null) { xpath.setNamespaceURIs(namespaces); } // This is the way we always did it before, so keep doing it that way // as xpath.evaluate() will return non-string results (like Doubles) // for some scenarios. if (outputType == null && singleResult) { return xpath.valueOf(doc); } // TODO handle non-list cases, see //http://www.dom4j.org/apidocs/org/dom4j/XPath.html#evaluate(java.lang.Object) Object obj = xpath.evaluate(doc); if (obj instanceof List) { for (int i = 0; i < ((List) obj).size(); i++) { final Node node = (Node) ((List) obj).get(i); result = add(result, node); if (singleResult) { break; } } } else { result = add(result, obj); } } else { JXPathContext context = JXPathContext.newContext(src); result = context.getValue(expression); } return result; } catch (Exception e) { throw new TransformerException(this, e); } }
From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java
License:Open Source License
/** * Evaluates an XPath expression//from w ww . ja v a 2 s.c o m */ public static Object evaluate(final URIResolver uriResolver, Object context, final VariableContextImpl variableContext, final DocumentContext documentContext, final LocationData locationData, String select, NamespaceContext namespaceContext) { FunctionContext functionContext = new FunctionContext() { public org.jaxen.Function getFunction(final String namespaceURI, final String prefix, final String localName) { // Override document() and doc() if (/*namespaceURI == null &&*/ ("document".equals(localName) || "doc".equals(localName))) { return new org.jaxen.Function() { public Object call(Context jaxenContext, List args) { try { String url = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0)); Document result = documentContext.getDocument(url); if (result == null) { Source source = uriResolver.resolve(url, locationData.getSystemID()); if (!(source instanceof SAXSource)) throw new ValidationException("Unsupported source type", locationData); XMLReader xmlReader = ((SAXSource) source).getXMLReader(); LocationSAXContentHandler contentHandler = new LocationSAXContentHandler(); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource()); result = contentHandler.getDocument(); documentContext.addDocument(url, result); } return result; } catch (Exception e) { throw new ValidationException(e, locationData); } } }; } else if (/*namespaceURI == null &&*/ "get-namespace-uri-for-prefix".equals(localName)) { return new org.jaxen.Function() { public Object call(Context jaxenContext, List args) { String prefix = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0)); Element element = null; if (args.get(1) instanceof List) { List list = (List) args.get(1); if (list.size() == 1) element = (Element) list.get(0); } else if (args.get(1) instanceof Element) { element = (Element) args.get(1); } if (element == null) throw new ValidationException("An element is expected as the second argument " + "in get-namespace-uri-for-prefix()", locationData); return element.getNamespaceForPrefix(prefix); } }; } else if (/*namespaceURI == null &&*/ "distinct-values".equals(localName)) { return new org.jaxen.Function() { public Object call(Context jaxenContext, List args) { List originalList = args.get(0) instanceof List ? (List) args.get(0) : Collections.singletonList(args.get(0)); List resultList = new ArrayList(); XPath stringXPath = Dom4jUtils.createXPath("string(.)"); for (Iterator i = originalList.iterator(); i.hasNext();) { Object item = (Object) i.next(); String itemString = (String) stringXPath.evaluate(item); if (!resultList.contains(itemString)) resultList.add(itemString); } return resultList; } }; } else if (/*namespaceURI == null &&*/ "evaluate".equals(localName)) { return new org.jaxen.Function() { public Object call(Context jaxenContext, List args) { try { if (args.size() != 3) { try { return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix, localName); } catch (UnresolvableException e) { throw new ValidationException(e, locationData); } } else { String xpathString = (String) Dom4jUtils.createXPath("string(.)") .evaluate(args.get(0)); XPath xpath = Dom4jUtils.createXPath(xpathString); Map namespaceURIs = new HashMap(); List namespaces = (List) args.get(1); for (Iterator i = namespaces.iterator(); i.hasNext();) { org.dom4j.Namespace namespace = (org.dom4j.Namespace) i.next(); namespaceURIs.put(namespace.getPrefix(), namespace.getURI()); } xpath.setNamespaceURIs(namespaceURIs); return xpath.evaluate(args.get(2)); } } catch (InvalidXPathException e) { throw new ValidationException(e, locationData); } } }; } else if (/*namespaceURI == null &&*/ "tokenize".equals(localName)) { return new org.jaxen.Function() { public Object call(Context jaxenContext, List args) { try { String input = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0)); String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1)); List result = new ArrayList(); while (input.length() != 0) { int position = input.indexOf(pattern); if (position != -1) { result.add(input.substring(0, position)); input = input.substring(position + 1); } else { result.add(input); input = ""; } } return result; } catch (InvalidXPathException e) { throw new ValidationException(e, locationData); } } }; } else if (/*namespaceURI == null &&*/ "string-join".equals(localName)) { return new org.jaxen.Function() { public Object call(Context jaxenContext, List args) { try { List strings = (List) args.get(0); String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1)); StringBuilder result = new StringBuilder(); boolean isFirst = true; for (Iterator i = strings.iterator(); i.hasNext();) { if (!isFirst) result.append(pattern); else isFirst = false; String item = (String) (String) Dom4jUtils.createXPath("string(.)") .evaluate(i.next()); result.append(item); } return result.toString(); } catch (InvalidXPathException e) { throw new ValidationException(e, locationData); } } }; } else if (/*namespaceURI == null &&*/ "reverse".equals(localName)) { return new org.jaxen.Function() { public Object call(Context jaxenContext, List args) { try { List result = new ArrayList((List) args.get(0)); Collections.reverse(result); return result; } catch (InvalidXPathException e) { throw new ValidationException(e, locationData); } } }; } else { try { // Go through standard XPath functions return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix, localName); } catch (UnresolvableException e) { // User-defined function try { final Closure closure = findClosure( variableContext.getVariableValue(namespaceURI, prefix, localName)); if (closure == null) throw new ValidationException( "'" + qualifiedName(prefix, localName) + "' is not a function", locationData); return new org.jaxen.Function() { public Object call(Context context, List args) { return closure.execute(args); } }; } catch (UnresolvableException e2) { throw new ValidationException("Cannot invoke function '" + qualifiedName(prefix, localName) + "', no such function", locationData); } } } } private Closure findClosure(Object xpathObject) { if (xpathObject instanceof Closure) { return (Closure) xpathObject; } else if (xpathObject instanceof List) { for (Iterator i = ((List) xpathObject).iterator(); i.hasNext();) { Closure closure = findClosure(i.next()); if (closure != null) return closure; } return null; } else { return null; } } }; try { // Create XPath XPath xpath = Dom4jUtils.createXPath(select); // Set variable, namespace, and function context if (context instanceof Context) { // Create a new context, as Jaxen may modify the current node in the context (is this a bug?) Context currentContext = (Context) context; Context newContext = new Context(new ContextSupport(namespaceContext, functionContext, variableContext, DocumentNavigator.getInstance())); newContext.setNodeSet(currentContext.getNodeSet()); newContext.setSize(currentContext.getSize()); newContext.setPosition(currentContext.getPosition()); context = newContext; } else { xpath.setVariableContext(variableContext); xpath.setNamespaceContext(namespaceContext); xpath.setFunctionContext(functionContext); } // Execute XPath return xpath.evaluate(context); } catch (Exception e) { throw new ValidationException(e, locationData); } }
From source file:org.orbeon.oxf.xml.XPathUtils.java
License:Open Source License
public static Object selectObjectValue(org.dom4j.Node node, String expr, Map prefixes, VariableContext variableContext, FunctionContext functionContext) { try {// w w w .j av a2 s .com org.dom4j.XPath path = node.createXPath(expr); hookupPath(path, prefixes, variableContext, functionContext); return path.evaluate(node); } catch (InvalidXPathException e) { throw new OXFException(e); } }