List of usage examples for org.dom4j.io SAXReader read
public Document read(InputSource in) throws DocumentException
Reads a Document from the given InputSource
using SAX
From source file:com.cladonia.xml.HTMLUtilities.java
License:Open Source License
/** * Cleans up HTML, makes HTML well formed etc * * @param text The HTML/*from w ww .j a v a 2 s .c o m*/ * @param encoding The encoding */ public static String cleanUpHTML(String text) throws UnsupportedEncodingException, IOException, SAXNotRecognizedException, SAXNotSupportedException, DocumentException { // set the paser to use Neko HTML configuration SAXParser parser = new SAXParser(new HTMLConfiguration()); parser.setFeature(NOTIFY_CHAR_REFS, true); parser.setFeature(NOTIFY_HTML_BUILTIN_REFS, true); parser.setFeature(IGNORE_SPECIFIED_CHARSET, true); // set the parser to use lower case parser.setProperty(ELEMENT_CASE, "lower"); parser.setProperty(ATTR_CASE, "lower"); parser.setProperty(ENCODING_PROPERTY, "UTF-8"); // create a dom4j SaxReader SAXReader reader = new SAXReader(parser); // get the bytes from the input text ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes("UTF-8")); // using sax read the stream into a dom4j dom XDocument doc = (XDocument) reader.read(stream); // write the new dom return XMLUtilities.write(doc, new ExchangerOutputFormat("", false, "UTF-8")); }
From source file:com.cladonia.xml.XMLUtilities.java
License:Open Source License
/** * Validates the document for this URL.//from w w w . j a va 2 s .com * * @param url the URL of the document. * * @return the Dom4J document. */ public static synchronized void validate(URL url) throws IOException, SAXParseException { if (DEBUG) System.out.println("XMLUtilities.validate( " + url + ")"); try { SAXReader reader = getReader(true); reader.read(url); } catch (DocumentException e) { Exception x = (Exception) e.getNestedException(); if (x instanceof SAXParseException) { SAXParseException spe = (SAXParseException) x; Exception ex = spe.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (SAXParseException) x; } } else if (x instanceof IOException) { throw (IOException) x; } } }
From source file:com.cladonia.xml.XMLUtilities.java
License:Open Source License
/** * Resolves all XIncludes/*w ww. j a v a 2 s .com*/ * * @param text The XML which may contain XIncludes * @param encoding The encoding * @param encoding The url of the file which can be used as a base identifier * * @return the XML with any XIncludes resolved */ public static String resolveXIncludes(String text, String encoding, URL url, ExchangerOutputFormat format) throws DocumentException, IOException { // set the paser to use XInclude configuration SAXParser parser = new SAXParser(new XIncludeParserConfiguration()); // create a dom4j SaxReader SAXReader reader = new SAXReader(parser); // if no encoding given then use UTF-8 if (encoding == null) { encoding = "UTF-8"; } // get the bytes from the input text ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes(mapXMLEncodingToJava(encoding))); InputStreamReader isReader = new InputStreamReader(stream, mapXMLEncodingToJava(encoding)); InputSource source = new InputSource(isReader); if (url != null) { source.setSystemId(url.toString()); } // using sax read the stream into a dom4j dom XDocument doc = (XDocument) reader.read(source); // write the new dom return write(doc, format, true); }
From source file:com.cn.servlet.DataInterface.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. j av a2 s. co m * * @param request servlet request * @param response servlet response * @param params * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response, String params) throws ServletException, IOException { String uri = request.getRequestURI(); String subUri = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf(".")); String json = null; CommonController commonController = new CommonController(); InterfaceController interfaceController = new InterfaceController(); DatabaseOpt opt = new DatabaseOpt(); //logger.info(Units.getIpAddress(request) + "accept:" + subUri + ",time:" + (new Date().getTime())); try { logger.info(subUri + ",params:" + params); JSONObject paramsJson = JSONObject.parseObject(params); //logger.info("send:" + subUri + ",time:" + paramsJson.getString("timestamp")); String module = paramsJson.getString("module"); String operation = paramsJson.getString("operation"); String rely = (paramsJson.getString("rely") == null) ? ("{}") : (paramsJson.getString("rely")); String target = paramsJson.getString("target"); String datas = (paramsJson.getString("datas") == null) ? ("") : paramsJson.getString("datas"); String update = paramsJson.getString("update"); String add = paramsJson.getString("add"); String delete = paramsJson.getString("del"); String item = paramsJson.getString("item"); String details = paramsJson.getString("details"); String detail = paramsJson.getString("detail"); String fileName = paramsJson.getString("fileName"); String operateType = paramsJson.getString("type"); String start = paramsJson.getString("start"); String end = paramsJson.getString("end"); int isHistory = paramsJson.getIntValue("isHistory"); int pageIndex = paramsJson.getIntValue("pageIndex"); int pageSize = paramsJson.getIntValue("pageSize"); HttpSession session = request.getSession(); String path = this.getClass().getClassLoader().getResource("/").getPath().replaceAll("%20", " "); String importPath = getServletContext().getRealPath("/").replace("\\", "/") + "excelFile/"; /*??*/ if (!"userLogin".equals(module) && (session.getAttribute("user") == null || session.getAttribute("loginType") == null || session.getAttribute("employee") == null)) { session.invalidate(); json = Units.objectToJson(-99, "", null); PrintWriter out = response.getWriter(); try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); out.print(json); } finally { out.close(); } return; } Employee curEmployee = null; Customer curCustomer = null; if (session.getAttribute("employee") != null && session.getAttribute("loginType").toString().compareTo("employeeLogin") == 0) { curEmployee = (Employee) session.getAttribute("employee"); } if (session.getAttribute("employee") != null && session.getAttribute("loginType").toString().compareTo("customerLogin") == 0) { curCustomer = (Customer) session.getAttribute("employee"); } switch (module) { //<editor-fold desc="?"> case "userLogin": { switch (operation) { //<editor-fold desc=""> case "employeeLogin": { String whereSql = "EmployeeName = '" + paramsJson.getString("username") + "'"; List<Object> res = commonController.dataBaseQuery("table", "com.cn.bean.", "Employee", "*", whereSql, 1, 1, "EmployeeName", 1, DatabaseOpt.DATA); String type = paramsJson.getString("type"); if (res != null && res.size() > 0) { Employee employee = (Employee) res.get(0); if (employee.getEmployeePassword().compareTo(paramsJson.getString("password")) == 0) { session.setAttribute("user", paramsJson.getString("username")); session.setAttribute("loginType", "employeeLogin"); session.setAttribute("employee", employee); //session.setAttribute("customer", null); String whereCase = "RoleCode in ('" + employee.getEmployeeTypeCode() + "')"; List<Object> roleRight = commonController.dataBaseQuery("table", "com.cn.bean.", "PlatformRoleRight", "*", whereCase, Integer.MAX_VALUE, 1, "RoleCode", 0, DatabaseOpt.BASE); if (roleRight != null && roleRight.size() > 0) { ArrayList<String> roleRightList = new ArrayList<>(); roleRight.stream().map((obj) -> (PlatformRoleRight) obj).forEach((right) -> { roleRightList.add(right.getRightCode()); }); if (type.compareTo("pc") == 0) { /*???????*/ String menuJson = "{"; SAXReader reader = new SAXReader(); Document document = reader.read(new File(path + "menu.xml")); Element root = document.getRootElement(); Iterator<Element> iterator = root.elementIterator(); while (iterator.hasNext()) { menuJson += commonController.hasRight(iterator.next(), roleRightList); } if (menuJson.length() <= 1) { menuJson = null; json = Units.objectToJson(-1, "???!", menuJson); } else { menuJson = menuJson.substring(0, menuJson.length() - 1) + "}"; json = Units.objectToJson(0, "?!", menuJson); } } if (type.compareTo("app") == 0) { /*???????*/ String menuJson = "{"; SAXReader reader = new SAXReader(); Document document = reader.read(new File(path + "menu.xml")); Element root = document.getRootElement(); Iterator<Element> iterator = root.elementIterator(); while (iterator.hasNext()) { menuJson += commonController.hasAppRight(iterator.next(), roleRightList); } if (menuJson.length() <= 1) { menuJson = null; json = Units.objectToJson(-1, "???!", menuJson); } else { menuJson = menuJson.substring(0, menuJson.length() - 1) + "}"; JSONObject object = new JSONObject(); object.put("menuJson", menuJson); object.put("employee", employee); json = Units.objectToJson(0, "?!", object); } } } else { json = Units.objectToJson(-1, "???!", null); } } else { json = Units.objectToJson(-1, "????!", null); } } else { json = Units.objectToJson(-1, "???!", null); } break; } //</editor-fold> //<editor-fold desc="?"> case "login": { String type = paramsJson.getString("type"); PlatformUserInfoController controller = new PlatformUserInfoController(); int result = controller.userLogin(paramsJson.getString("username"), paramsJson.getString("password")); switch (result) { case 0: session.setAttribute("user", paramsJson.getString("username")); session.setAttribute("loginType", "login"); //session.setAttribute("customer", null); session.setAttribute("employee", null); /*??*/ String whereCase = "UserLoginAccount = '" + paramsJson.getString("username") + "'"; List<Object> userRole = commonController.dataBaseQuery("table", "com.cn.bean.", "PlatformUserRole", "*", whereCase, Integer.MAX_VALUE, 1, "UserLoginAccount", 0, DatabaseOpt.BASE); if (userRole != null) { /*?????*/ whereCase = "RoleCode in ("; for (Object obj : userRole) { PlatformUserRole role = (PlatformUserRole) obj; whereCase += "'" + role.getRoleCode() + "',"; } whereCase = whereCase.substring(0, whereCase.length() - 1); whereCase += ")"; List<Object> roleRight = commonController.dataBaseQuery("table", "com.cn.bean.", "PlatformRoleRight", "*", whereCase, Integer.MAX_VALUE, 1, "RoleCode", 0, DatabaseOpt.BASE); ArrayList<String> roleRightList = new ArrayList<>(); roleRight.stream().map((obj) -> (PlatformRoleRight) obj).forEach((right) -> { roleRightList.add(right.getRightCode()); }); /*???????*/ String menuJson = "{"; SAXReader reader = new SAXReader(); Document document = reader.read(new File(path + "menu.xml")); Element root = document.getRootElement(); Iterator<Element> iterator = root.elementIterator(); while (iterator.hasNext()) { menuJson += commonController.hasRight(iterator.next(), roleRightList); } menuJson = menuJson.substring(0, menuJson.length() - 1) + "}"; if (type.compareTo("pc") == 0) { json = Units.objectToJson(result, "?!", menuJson); } if (type.compareTo("app") == 0) { json = Units.objectToJson(result, "?!", roleRightList); } } else { json = Units.objectToJson(-1, "?!", null); } break; case 1: json = Units.objectToJson(result, "???!", null); break; case 2: json = Units.objectToJson(result, "???!", null); break; case -1: json = Units.objectToJson(result, "!", null); break; default: json = Units.objectToJson(result, "?!", null); break; } break; } //</editor-fold> //<editor-fold desc=""> case "customerLogin": { String whereSql = "CustomerID = '" + paramsJson.getString("username") + "'"; List<Object> res = commonController.dataBaseQuery("view", "com.cn.bean.", "Customer", "*", whereSql, 1, 1, "CustomerID", 1, DatabaseOpt.DATA); String type = paramsJson.getString("type"); if (res != null && res.size() > 0) { Customer customer = (Customer) res.get(0); if (customer.getCustomerPassword().compareTo(paramsJson.getString("password")) == 0) { session.setAttribute("user", paramsJson.getString("username")); session.setAttribute("loginType", "customerLogin"); //session.setAttribute("customer", customer); session.setAttribute("employee", customer); String whereCase = "RoleCode in ('" + customer.getCustomerRoleCode() + "')"; List<Object> roleRight = commonController.dataBaseQuery("table", "com.cn.bean.", "PlatformRoleRight", "*", whereCase, Integer.MAX_VALUE, 1, "RoleCode", 0, DatabaseOpt.BASE); if (roleRight != null && roleRight.size() > 0) { ArrayList<String> roleRightList = new ArrayList<>(); roleRight.stream().map((obj) -> (PlatformRoleRight) obj).forEach((right) -> { roleRightList.add(right.getRightCode()); }); if (type.compareTo("pc") == 0) { /*???????*/ String menuJson = "{"; SAXReader reader = new SAXReader(); Document document = reader.read(new File(path + "menu.xml")); Element root = document.getRootElement(); Iterator<Element> iterator = root.elementIterator(); while (iterator.hasNext()) { menuJson += commonController.hasRight(iterator.next(), roleRightList); } if (menuJson.length() <= 1) { menuJson = null; json = Units.objectToJson(-1, "???!", menuJson); } else { menuJson = menuJson.substring(0, menuJson.length() - 1) + "}"; json = Units.objectToJson(0, "?!", menuJson); } } if (type.compareTo("app") == 0) { /*???????*/ String menuJson = "{"; SAXReader reader = new SAXReader(); Document document = reader.read(new File(path + "menu.xml")); Element root = document.getRootElement(); Iterator<Element> iterator = root.elementIterator(); while (iterator.hasNext()) { menuJson += commonController.hasAppRight(iterator.next(), roleRightList); } if (menuJson.length() <= 1) { menuJson = null; json = Units.objectToJson(-1, "???!", menuJson); } else { menuJson = menuJson.substring(0, menuJson.length() - 1) + "}"; JSONObject object = new JSONObject(); object.put("menuJson", menuJson); object.put("employee", customer); json = Units.objectToJson(0, "?!", object); } } } else { json = Units.objectToJson(-1, "???!", null); } } else { json = Units.objectToJson(-1, "????!", null); } } else { json = Units.objectToJson(-1, "???!", null); } break; } //</editor-fold> } break; } //</editor-fold> //<editor-fold desc="?"> case "?": { String oldPassword = paramsJson.getString("oldPassword"); String newPassword = paramsJson.getString("newPassword"); switch (session.getAttribute("loginType").toString()) { case "employeeLogin": { if (curEmployee != null && curEmployee.getEmployeePassword().compareTo(oldPassword) == 0) { JSONArray updateParams = new JSONArray(); JSONObject setObj = new JSONObject(); setObj.put("employeePassword", newPassword); updateParams.add(setObj); JSONObject whereObj = new JSONObject(); whereObj.put("employeeName", curEmployee.getEmployeeName()); updateParams.add(whereObj); ArrayList<Integer> updateResult = commonController.dataBaseOperate( updateParams.toJSONString(), "com.cn.bean.", "Employee", "update", DatabaseOpt.DATA); if (updateResult.get(0) == 0) { json = Units.objectToJson(0, "??!", null); } else { json = Units.objectToJson(-1, "?!", null); } } else { json = Units.objectToJson(-1, "??!", null); } break; } case "customerLogin": { if (curCustomer != null && curCustomer.getCustomerPassword().compareTo(oldPassword) == 0) { JSONArray updateParams = new JSONArray(); JSONObject setObj = new JSONObject(); setObj.put("customerPassword", newPassword); updateParams.add(setObj); JSONObject whereObj = new JSONObject(); whereObj.put("customerID", curCustomer.getCustomerID()); updateParams.add(whereObj); ArrayList<Integer> updateResult = commonController.dataBaseOperate( updateParams.toJSONString(), "com.cn.bean.", "Customer", "update", DatabaseOpt.DATA); if (updateResult.get(0) == 0) { json = Units.objectToJson(0, "??!", null); } else { json = Units.objectToJson(-1, "?!", null); } } else { json = Units.objectToJson(-1, "??!", null); } break; } case "login": { break; } } break; } //</editor-fold> //<editor-fold desc="?"> case "?": { if (curEmployee != null && curEmployee.getEmployeeName().compareTo("?") == 0) { CommonOperate operate = new CommonOperate(); json = operate.dataMoveToHistory(curEmployee.getEmployeeName()); } else { json = Units.objectToJson(-1, "???", null); } break; } //</editor-fold> //<editor-fold desc=""> case "": { List<Object> res = commonController.dataBaseQuery("table", "com.cn.bean.", "DataJZ", "*", "", Integer.MAX_VALUE, 1, "JZYMonth", 1, DatabaseOpt.DATA); if (res != null && res.size() > 0) { json = Units.objectToJson(0, "", res); } else { json = Units.objectToJson(-1, "?!", null); } break; } //</editor-fold> /** * ***************************************?************************************** */ //<editor-fold desc="?"> //<editor-fold desc=""> case "": { switch (operation) { case "create": { json = interfaceController.createOperate(20, "table", "com/cn/json/plan/", "com.cn.bean.plan.", "DHPlan", "DHPlanID", DatabaseOpt.DATA); json = Units.insertStr(json, "\\\"??\\", ",@DHJH_" + Units.getNowTimeNoSeparator()); break; } case "request_table": { if (target.compareToIgnoreCase("supplierID") == 0) { String[] keys = { "supplierID", "supplierName" }; String[] keysName = { "?", "??" }; int[] keysWidth = { 50, 50 }; String[] fieldsName = { "customerID", "customerName" }; json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "Customer", "CustomerID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys, keysName, keysWidth, fieldsName); } if (target.compareToIgnoreCase("partCode") == 0) { String[] keys = { "partCode", "partID", "partName", "partUnit", "cfAddress" }; String[] keysName = { "??", "??", "???", "???", "?" }; int[] keysWidth = { 20, 20, 20, 20, 20 }; String[] fieldsName = { "partCode", "partID", "partName", "partUnit", "psAddress1" }; json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "PartBaseInfo", "PartCode", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys, keysName, keysWidth, fieldsName); } break; } case "request_detail": { json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "DHPlanList", "DHPlanID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex); break; } case "request_page": { json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "DHPlan", "DHPlanID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex); break; } case "submit": { int result = commonController.dataBaseOperate("[" + item + "]", "com.cn.bean.plan.", "DHPlan", "add", DatabaseOpt.DATA).get(0); if (result == 0) { result = commonController.dataBaseOperate(details, "com.cn.bean.plan.", "DHPlanList", "add", DatabaseOpt.DATA).get(0); if (result == 0) { json = Units.objectToJson(0, "??!", null); } else { json = Units.objectToJson(-1, "!", null); commonController.dataBaseOperate("[" + item + "]", "com.cn.bean.plan.", "DHPlan", "delete", DatabaseOpt.DATA); } } else { json = Units.objectToJson(-1, "?!", null); } break; } } break; } //</editor-fold> //<editor-fold desc="?"> case "?": { switch (operation) { case "create": { json = interfaceController.createOperate(20, "table", "com/cn/json/plan/", "com.cn.bean.plan.", "SHPlan", "SHPlanID", DatabaseOpt.DATA); json = Units.insertStr(json, "\\\"???\\", ",@SHJH_" + Units.getNowTimeNoSeparator()); break; } case "request_table": { if (target.compareToIgnoreCase("dhPlanID") == 0) { String[] keys = { "dhPlanID" }; String[] keysName = { "??" }; int[] keysWidth = { 100, 50 }; String[] fieldsName = { "dhPlanID" }; json = interfaceController.queryOperate(target, "com.cn.bean.plan.", "table", "DHPlan", "DHPlanID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys, keysName, keysWidth, fieldsName); } if (target.compareToIgnoreCase("supplierID") == 0) { String[] keys = { "supplierID", "supplierName" }; String[] keysName = { "?", "??" }; int[] keysWidth = { 50, 50 }; String[] fieldsName = { "customerID", "customerName" }; json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "Customer", "CustomerID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys, keysName, keysWidth, fieldsName); } if (target.compareToIgnoreCase("partCode") == 0) { String[] keys = { "partCode", "partID", "partName", "partUnit", "cfAddress" }; String[] keysName = { "??", "??", "???", "???", "?" }; int[] keysWidth = { 20, 20, 20, 20, 20 }; String[] fieldsName = { "partCode", "partID", "partName", "partUnit", "psAddress1" }; json = interfaceController.queryOperate(target, "com.cn.bean.", "table", "PartBaseInfo", "PartCode", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex, keys, keysName, keysWidth, fieldsName); } break; } case "request_detail": { json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "SHPlanList", "SHPlanID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex); break; } case "request_page": { json = interfaceController.queryOperate("com.cn.bean.plan.", "table", "SHPlan", "SHPlanID", datas, rely, true, DatabaseOpt.DATA, pageSize, pageIndex); break; } case "submit": { int result = commonController.dataBaseOperate("[" + item + "]", "com.cn.bean.plan.", "SHPlan", "add", DatabaseOpt.DATA).get(0); if (result == 0) { result = commonController.dataBaseOperate(details, "com.cn.bean.plan.", "SHPlanList", "add", DatabaseOpt.DATA).get(0); if (result == 0) { json = Units.objectToJson(0, "??!", null); } else { json = Units.objectToJson(-1, "!", null); } } else { json = Units.objectToJson(-1, "?!", null); } break; } } break; } //</editor-fold> //</editor-fold> } } catch (Exception e) { logger.info(subUri); logger.error("?:" + e.getMessage(), e); json = Units.objectToJson(-1, "?!", e.toString()); } //logger.info(Units.getIpAddress(request) + "response:" + subUri + ",time:" + (new Date().getTime())); PrintWriter out = response.getWriter(); try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); out.print(json); } finally { if (out != null) { out.close(); } } }
From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java
License:Open Source License
/** * Tries to load the XSLT from the file defined in the properties * //w ww . j a v a 2 s .c o m * @throws ValidationException * if the XSLT file is not defined in the properties, the file * cannot be found or there was an error parsing it */ private List<Transformer> loadXSLT(File xsltFile, Element element) { List<Transformer> transformerList = new ArrayList<Transformer>(); if (xsltFile == null) { String cause = "xsltFile property not set"; log.error(cause); XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE, GenericArtifact.ERROR_TRANSFORMER_FILE); throw new CCFRuntimeException(cause); } try { Source source = null; if (isOnlyAllowWhiteListedJavaFunctionCalls()) { SAXReader reader = new SAXReader(); Document originalDocument = reader.read(xsltFile); Document clonedDocument = (Document) originalDocument.clone(); Element clonedRootElement = clonedDocument.getRootElement(); // replace white listed Java functions in XPath expressions with // "." for (String functionCall : getWhiteListedJavaFunctionCalls()) { List<Element> nodes = findFunctionCalls(clonedRootElement, functionCall); for (Element e : nodes) { e.addAttribute("select", "."); } } Transformer secureTransform = secureFactory.newTransformer(new DocumentSource(clonedDocument)); secureTransform.setErrorListener(new XsltValidationErrorListener()); log.debug("Loaded sanitized version of XSLT [" + xsltFile + "] successfully"); transformerList.add(secureTransform); source = new DocumentSource(originalDocument); } else { source = new StreamSource(xsltFile); } Transformer transform = factory.newTransformer(source); log.debug("Loaded original XSLT [" + xsltFile + "] successfully"); transformerList.add(transform); } catch (Exception e) { String cause = "Failed to load XSLT: [" + xsltFile + " ]" + e.getMessage(); log.error(cause, e); XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE, GenericArtifact.ERROR_TRANSFORMER_FILE); throw new CCFRuntimeException(cause, e); } return transformerList; }
From source file:com.controlj.addon.weather.util.HTTPHelper.java
License:Open Source License
public Document readDocument(String scheme, String host, int port, String path, Map<String, Object> params) throws IOException, URISyntaxException { URI uri = URIUtils.createURI(scheme, host, port, path, encodeParams(params), null); return httpclient.execute(new HttpGet(uri), new ResponseHandler<Document>() { //@Override public Document handleResponse(HttpResponse response) throws IOException { if (response.getStatusLine().getStatusCode() != 200) throw new IOException(response.getStatusLine().getReasonPhrase()); HttpEntity entity = response.getEntity(); if (entity != null) { String responseString = EntityUtils.toString(entity); try { SAXReader reader = new SAXReader(); return reader.read(new StringReader(responseString)); } catch (DocumentException e) { throw (IOException) new IOException("Service returned \"" + responseString + '"') .initCause(e); }//from w ww . j a v a2s.c o m } throw new IOException("No response"); } }); }
From source file:com.cwctravel.hudson.plugins.suitegroupedtests.junit.SuiteResult.java
License:Open Source License
/** * Parses the JUnit XML file into {@link SuiteResult}s. This method returns a collection, as a single XML may have multiple <testsuite> * elements wrapped into the top-level <testsuites>. *///from w w w .j a va2 s . c o m static List<SuiteResult> parse(File xmlReport, boolean keepLongStdio) throws DocumentException, IOException { List<SuiteResult> r = new ArrayList<SuiteResult>(); // parse into DOM SAXReader saxReader = new SAXReader(); // install EntityResolver for resolving DTDs, which are in files created by TestNG. // (see https://hudson.dev.java.net/servlets/ReadMsg?listName=users&msgNo=5530) XMLEntityResolver resolver = new XMLEntityResolver(); saxReader.setEntityResolver(resolver); Document result = saxReader.read(xmlReport); Element root = result.getRootElement(); if (root.getName().equals("testsuites")) { // multi-suite file for (Element suite : (List<Element>) root.elements("testsuite")) r.add(new SuiteResult(xmlReport, suite, keepLongStdio)); } else { // single suite file r.add(new SuiteResult(xmlReport, root, keepLongStdio)); } return r; }
From source file:com.delmar.station.service.impl.WFDetailServiceImpl.java
public String updateDcmsFcrDate(EDIResponseInfo edirInfo, String trustFileCode) { String resultMessage = "success"; Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); String currentDate = sf.format(date); try {/*from w w w . j a v a 2 s .c om*/ date = sf.parse(edirInfo.getInDate()); currentDate = sf.format(date); } catch (ParseException e1) { e1.printStackTrace(); } try { EDIResponseInfo resultEDIResponseInfo = ediResponseInfoService.getEDIRByTrustFileCode(trustFileCode); // Booking IDCargoProDcms????bookingID if (StringUtil.isNotEmpty(resultEDIResponseInfo.getCsReferenceNo())) { Map<String, String> params = new HashMap<String, String>(); params.put("id", resultEDIResponseInfo.getCsReferenceNo()); params.put("fcrDate", currentDate); params.put("remark", edirInfo.getResponseDesc()); HttpClient httpClient = null; httpClient.getParams().setAuthenticationPreemptive(true); // ? Credentials credentials = new UsernamePasswordCredentials("wsuserchina", "ws1sGreat"); httpClient.getState().setCredentials(AuthScope.ANY, credentials); HttpMethod method = buildPostMethod( "https://www.delmarcargo.com/cms/api/bookingservice/updateBookingFcrDate", params); int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new HttpException(method.getStatusText()); } String xmlResult = method.getResponseBodyAsString(); method.releaseConnection(); // StringReader xmlReader = new StringReader(xmlResult); // ?SAX ? InputSource ?? XML InputSource xmlSource = new InputSource(xmlReader); // SAXBuilder SAXReader builder = new SAXReader(); // ?SAXDocument Document doc = builder.read(xmlSource); // Element root = doc.getRootElement(); // BODY Element resultStatusCode = root.element("ServiceResponse").element("statusCode"); // ???? if ("200".equals(resultStatusCode.getText())) { // add edirInfo.setEdiType("DCMS_FCRDATE"); edirInfo.setEdiStatus("1"); edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id edirInfo.setEdiAction("NEW"); edirInfo.setEdiStatus("1"); edirInfo.setBatchNo("0"); edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); edirInfo.setBeUse(0); ediResponseInfoService.saveOrUpdate(edirInfo); ediResponseInfoService.updateTrustFileInfoFCRDate(currentDate, edirInfo.getTrustFileCode()); } else if ("405".equals(resultStatusCode.getText())) { Element resultText = root.element("ServiceResponse").element("description"); resultMessage = resultText.getText(); // add edirInfo.setEdiType("DCMS_FCRDATE"); edirInfo.setEdiStatus("11"); edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id edirInfo.setEdiAction("NEW"); edirInfo.setEdiStatus("1"); edirInfo.setBatchNo("0"); edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); edirInfo.setBeUse(0); ediResponseInfoService.saveOrUpdate(edirInfo); } else { Element resultText = root.element("ServiceResponse").element("description"); resultMessage = resultText.getText(); } } else { resultMessage = "Booking IDCargoProDcms?"; } } catch (Exception e) { e.printStackTrace(); resultMessage = "Modify Dcms Fcr Date have Exception"; return resultMessage; } return resultMessage; }
From source file:com.devoteam.srit.xmlloader.asn1.ASNInitializer.java
License:Open Source License
public static Document getDocumentXML(final String xmlFileName) { Document document = null;// ww w .ja v a2s . c o m SAXReader reader = new SAXReader(); try { document = reader.read(xmlFileName); } catch (DocumentException ex) { GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, ex, "Wrong ASN1 file : "); } return document; }
From source file:com.devoteam.srit.xmlloader.core.operations.basic.operators.PluggableParameterOperatorFile.java
License:Open Source License
@Override public Parameter operate(Runner runner, Map<String, Parameter> operands, String name, String resultant) throws Exception { normalizeParameters(operands);/*from w w w . ja va 2 s .c o m*/ Parameter path = assertAndGetParameter(operands, "value", "path"); Parameter result = new Parameter(); if (path.length() > 0) { URI filePathURI = URIRegistry.MTS_TEST_HOME.resolve(path.get(0).toString()); if (name.equals(NAME_B_WRITE) || name.equals(NAME_S_WRITE)) { Parameter data = assertAndGetParameter(operands, "value2", "data"); if (data.length() != 0) { String fileData = data.get(0).toString(); File file = new File(filePathURI); if (!file.exists()) file.createNewFile(); OutputStream out = new FileOutputStream(file, true); Array array; if (name.equals(NAME_B_WRITE)) { array = Array.fromHexString(fileData); } else { array = new DefaultArray(fileData.getBytes()); } out.write(array.getBytes()); out.close(); } result = null; } else if (name.equals(NAME_B_READ) || name.equals(NAME_S_READ)) { File file = new File(filePathURI); byte[] bytes = new byte[(int) file.length()]; InputStream in = new FileInputStream(file); in.read(bytes); in.close(); if (name.equals(NAME_B_READ)) { result.add(Array.toHexString(new DefaultArray(bytes))); } else { result.add(new String(bytes)); } } else if (name.equals(NAME_CREATE)) { File file = new File(filePathURI); if (file.exists()) file.delete(); file.createNewFile(); result = null; } else if (name.equals(NAME_REMOVE)) { new File(filePathURI).delete(); result = null; } else if (name.equals(NAME_EXISTS)) { result.add(new File(filePathURI).exists()); } else if (name.equals(NAME_READPROPERTY)) { normalizeParameters(operands); Parameter config = path; Parameter property = PluggableParameterOperatorList.assertAndGetParameter(operands, "value2"); String configName = ""; String propertyName = ""; configName = config.get(0).toString(); propertyName = property.get(0).toString(); result.add(Config.getConfigByName(configName).getString(propertyName)); } else if (name.equals(NAME_LISTPROPERTYKEYS)) { normalizeParameters(operands); Parameter config = path; String configName = ""; configName = config.get(0).toString(); Vector<String> names = Config.getConfigByName(configName).getPropertiesEnhanced() .getNameOfAllParameters(); for (String key : names) { result.add(key); } } else if (name.equals(NAME_READCSV)) { Parameter csvCol = PluggableParameterOperatorList.assertAndGetParameter(operands, "value2"); String comment = Config.getConfigByName("tester.properties") .getString("operations.CSV_COMMENT_CHAR", "#"); String separator = Config.getConfigByName("tester.properties") .getString("operations.CSV_SEPARATOR_CHAR", ";"); String escape = Config.getConfigByName("tester.properties").getString("operations.CSV_ESCAPE_CHAR", "\""); CSVReader csvReader = new CSVReader(comment, separator, escape + escape); String var2 = csvCol.get(0).toString(); int column = -1; List<String> listData = null; if (Utils.isInteger(var2)) { column = Integer.parseInt(var2); listData = csvReader.loadData(filePathURI, column, false); } else { // get the header line to retrieve the column number String[] listHeader = csvReader.loadHeader(filePathURI); for (int j = 0; j < listHeader.length; j++) { if (listHeader[j].equals(var2.trim())) { column = j; break; } } if (column >= 0) { listData = csvReader.loadData(filePathURI, column, true); } } if (listData != null) { result.addAll(listData); } } else if (name.equals(NAME_READMEDIA)) { String resultantUnbracketed = ParameterPool.unbracket(resultant); Parameter payloadList = new Parameter(resultantUnbracketed + ".payload"); Parameter timestampList = new Parameter(resultantUnbracketed + ".timestampList"); Parameter seqList = new Parameter(resultantUnbracketed + ".seqList"); Parameter payloadType = new Parameter(resultantUnbracketed + ".payloadType"); Parameter deltaTime = new Parameter(resultantUnbracketed + ".deltaTime"); Parameter markList = new Parameter(resultantUnbracketed + ".markList"); boolean isPayloadTypeSet = false; long timestamp = 0; long oldTimestamp = 0; long diffTimestamp = 0; String value = null; Element node = null; InputStream in = null; Document document = null; try { SAXReader reader = new SAXReader(); in = SingletonFSInterface.instance().getInputStream(filePathURI); document = reader.read(in); in.close(); } catch (Exception e) { if (in != null) in.close(); throw e; } //parsing du fichier List listNode = document.selectNodes( "//proto[@name='geninfo' or @name='rtp']/field[@name='timestamp' or @name='rtp.payload' or @name='rtp.seq' or @name='rtp.timestamp' or @name='rtp.p_type' or @name='rtp.marker']");//5s for 50000 for (int j = 0; j < listNode.size(); j++)//parse all rtp message { node = (Element) listNode.get(j); value = node.attributeValue("name"); if (value.equalsIgnoreCase("rtp.payload")) { value = node.attributeValue("value");//get payload in hexa string payloadList.add(value); } else if (value.equalsIgnoreCase("rtp.timestamp")) { value = node.attributeValue("show");//get timestamp timestampList.add(Long.parseLong(value)); } else if (value.equalsIgnoreCase("rtp.seq")) { value = node.attributeValue("show");//get seqnum seqList.add(Long.parseLong(value)); } else if (value.equalsIgnoreCase("rtp.marker")) { value = node.attributeValue("show");//get mark header markList.add((Integer) Integer.parseInt(value)); } else if (!isPayloadTypeSet && value.equalsIgnoreCase("rtp.p_type")) { value = node.attributeValue("show");//get payloadType payloadType.add((Integer) Integer.parseInt(value)); isPayloadTypeSet = true; } else if (value.equalsIgnoreCase("timestamp"))//get arrival time, useful to calculate deltaTime between each packet { value = node.attributeValue("value");//get capture timestamp timestamp = (long) (Double.parseDouble(value) * 1000);//convert in ms if (oldTimestamp != 0)//for all messages except the first received { diffTimestamp = timestamp - oldTimestamp; } oldTimestamp = timestamp; deltaTime.add(diffTimestamp); } } runner.getParameterPool().set("[" + resultantUnbracketed + ".payload" + "]", payloadList); runner.getParameterPool().set("[" + resultantUnbracketed + ".timestamp" + "]", timestampList); runner.getParameterPool().set("[" + resultantUnbracketed + ".seq" + "]", seqList); runner.getParameterPool().set("[" + resultantUnbracketed + ".payloadType" + "]", payloadType); runner.getParameterPool().set("[" + resultantUnbracketed + ".deltaTime" + "]", deltaTime); runner.getParameterPool().set("[" + resultantUnbracketed + ".markList" + "]", markList); result.add(resultantUnbracketed + ".payload"); result.add(resultantUnbracketed + ".timestamp"); result.add(resultantUnbracketed + ".seq"); result.add(resultantUnbracketed + ".payloadType"); result.add(resultantUnbracketed + ".deltaTime"); result.add(resultantUnbracketed + ".markList"); } else if (name.equals(NAME_READWAVE)) { String resultantUnbracketed = ParameterPool.unbracket(resultant); Parameter payloadList = new Parameter(resultantUnbracketed + ".payload"); Parameter payloadType = new Parameter(resultantUnbracketed + ".payloadType"); Parameter bitRate = new Parameter(resultantUnbracketed + ".bitRate"); InputStream in = null; WAVReader waveFileReader = null; AudioFileFormat format = null; try { in = SingletonFSInterface.instance().getInputStream(filePathURI); if (in == null) { Exception e = new FileNotFoundException(filePathURI.toString() + " file is not found."); throw e; } waveFileReader = new WAVReader(); format = waveFileReader.getAudioFileFormat(in); in.close(); } catch (Exception e) { if (in != null) in.close(); throw e; } if (format != null) { byte[] payload = waveFileReader.getPayload(); //recuperation du nombre de paquets par ech a partir du fichier xml Parameter paraDeltaTimeMilliSec = PluggableParameterOperatorList.assertAndGetParameter(operands, "value2"); String strDeltaTimeMilliSec = paraDeltaTimeMilliSec.get(0).toString(); int deltaTimeMilliSec = Integer.parseInt(strDeltaTimeMilliSec); int nbEchPerPacket = deltaTimeMilliSec * waveFileReader.getBitRate() / 8; //recuperation du nombre totale de paquets int nbPacket = payload.length / nbEchPerPacket; int nbFullPacket = nbPacket; int nbEchInLastPacket = 0; if (payload.length % nbEchPerPacket != 0) { //si la division a un reste, un rajoute un paquet qui ne sera pas plein nbEchInLastPacket = payload.length - nbEchPerPacket * nbPacket; nbPacket++; } //recuperation et decoupage du payload byte[] val; for (int j = 0; j < payload.length; j += nbEchPerPacket) { DefaultArray temp; if (j < nbFullPacket * nbEchPerPacket) { val = new byte[nbEchPerPacket]; for (int k = j; k < j + nbEchPerPacket; k++) { val[k - j] = payload[k]; } temp = new DefaultArray(val); payloadList.add(Array.toHexString(temp)); } else { val = new byte[nbEchInLastPacket]; //on ajoute le dernier paquet qui ne sera pas plein for (int k = j; k < j + nbEchInLastPacket; k++) { val[k - j] = payload[k]; } temp = new DefaultArray(val); payloadList.add(Array.toHexString(temp)); } } int payloadTypeInt = waveFileReader.getPayloadType(); if (!(payloadTypeInt != 0) && !(payloadTypeInt != 8)) { throw new ParameterException("The codec is not supported : " + payloadTypeInt); } payloadType.add(payloadTypeInt); bitRate.add(waveFileReader.getBitRate()); runner.getParameterPool().set("[" + resultantUnbracketed + ".payload" + "]", payloadList); runner.getParameterPool().set("[" + resultantUnbracketed + ".payloadType" + "]", payloadType); runner.getParameterPool().set("[" + resultantUnbracketed + ".bitRate" + "]", bitRate); result.add(resultantUnbracketed + ".payload"); result.add(resultantUnbracketed + ".payloadType"); result.add(resultantUnbracketed + ".bitRate"); } } else if (name.equals(NAME_WRITEWAVE)) { byte[] chunkID = "RIFF".getBytes(); byte[] chunkSize; byte[] format = "WAVE".getBytes(); byte[] subChunk1ID = "fmt ".getBytes(); byte[] subChunk1Size; byte[] audioFormat; byte[] numberChannels; byte[] sampleRate; byte[] byteRate; byte[] blockAlign; byte[] bitsPerSample; byte[] subChunkFactID = "fact".getBytes(); byte[] subChunkFactSize; byte[] fact; byte[] subChunk2ID = "data".getBytes(); byte[] subChunk2Size; byte[] payload; CodecDictionary dico = new CodecDictionary(); Parameter paraPayloadType = PluggableParameterOperatorList.assertAndGetParameter(operands, "value2"); String strPayloadType = paraPayloadType.get(0).toString(); int payloadType = Integer.parseInt(strPayloadType); if (payloadType != 0 && payloadType != 8) { throw new Exception("Payload Type not supported yet"); } Protocol protocol = dico.getProtocol(payloadType); int formatAudio; if (protocol == null) { formatAudio = 6;//default value for PCMA } else { formatAudio = protocol.getCompressionCode(); } if (formatAudio < 0) { formatAudio = 6; } audioFormat = Utils.convertFromIntegerToByte(formatAudio, 2); audioFormat = Utils.convertToLittleEndian(audioFormat); Parameter paraNbChannel = PluggableParameterOperatorList.getParameter(operands, "value6"); int nbChannels; if (paraNbChannel != null && paraNbChannel.length() > 0) { String strNbChannel = paraNbChannel.get(0).toString(); nbChannels = Integer.parseInt(strNbChannel); } else { if (protocol == null) { nbChannels = 1; } else { nbChannels = protocol.getNbChannel(); } if (nbChannels <= 0) { nbChannels = 1; } } numberChannels = Utils.convertFromIntegerToByte(nbChannels, 2); numberChannels = Utils.convertToLittleEndian(numberChannels); Parameter paraSampleRate = PluggableParameterOperatorList.getParameter(operands, "value5"); int rateSample; if (paraSampleRate != null && paraSampleRate.length() > 0) { String strSampleRate = paraSampleRate.get(0).toString(); rateSample = Integer.parseInt(strSampleRate); } else { if (protocol == null) { rateSample = 8000;//8000 default value for PCMA/PCMU } else { rateSample = protocol.getClockRate(); } if (rateSample <= 0) { rateSample = 8000; } } sampleRate = Utils.convertFromIntegerToByte(rateSample, 4); sampleRate = Utils.convertToLittleEndian(sampleRate); Parameter paraBitsPerSample = PluggableParameterOperatorList.getParameter(operands, "value4"); int bitsSample; if (paraBitsPerSample != null && paraBitsPerSample.length() > 0) { String strBitsPerSample = paraBitsPerSample.get(0).toString(); bitsSample = Integer.parseInt(strBitsPerSample); } else { bitsSample = 8;//8 par defaut } bitsPerSample = Utils.convertFromIntegerToByte(bitsSample, 2); bitsPerSample = Utils.convertToLittleEndian(bitsPerSample); int alignBlock = bitsSample * nbChannels / 8; blockAlign = Utils.convertFromIntegerToByte(alignBlock, 2); blockAlign = Utils.convertToLittleEndian(blockAlign); int rateByte = bitsSample * nbChannels * rateSample / 8; byteRate = Utils.convertFromIntegerToByte(rateByte, 4); byteRate = Utils.convertToLittleEndian(byteRate); Parameter paraPayloadBinary = PluggableParameterOperatorList.assertAndGetParameter(operands, "value3"); SupArray concat = new SupArray(); String temp; for (int k = 0; k < paraPayloadBinary.length(); k++) { temp = (String) paraPayloadBinary.get(k); concat.addLast(Array.fromHexString(temp)); } payload = concat.getBytes(); subChunk2Size = Utils.convertFromIntegerToByte(payload.length, 4); subChunk2Size = Utils.convertToLittleEndian(subChunk2Size); int sub1 = 28;//16 (same for all) + 12 (for PCMA: "fact" field) subChunk1Size = Utils.convertFromIntegerToByte(sub1, 4); subChunk1Size = Utils.convertToLittleEndian(subChunk1Size); int sub0 = 4 + (8 + sub1) + (8 + payload.length); chunkSize = Utils.convertFromIntegerToByte(sub0, 4); chunkSize = Utils.convertToLittleEndian(chunkSize); int subFact = 4; subChunkFactSize = Utils.convertFromIntegerToByte(subFact, 4); subChunkFactSize = Utils.convertToLittleEndian(subChunkFactSize); fact = subChunk2Size; int totalLength = chunkID.length + chunkSize.length + format.length + subChunk1ID.length + subChunk1Size.length + audioFormat.length + numberChannels.length + sampleRate.length + byteRate.length + blockAlign.length + bitsPerSample.length + subChunkFactID.length + subChunkFactSize.length + fact.length + subChunk2ID.length + subChunk2Size.length + payload.length; byte[] buf = new byte[totalLength]; System.arraycopy(chunkID, 0, buf, 0, 4); System.arraycopy(chunkSize, 0, buf, 4, 4); System.arraycopy(format, 0, buf, 8, 4); System.arraycopy(subChunk1ID, 0, buf, 12, 4); System.arraycopy(subChunk1Size, 0, buf, 16, 4); System.arraycopy(audioFormat, 0, buf, 20, 2); System.arraycopy(numberChannels, 0, buf, 22, 2); System.arraycopy(sampleRate, 0, buf, 24, 4); System.arraycopy(byteRate, 0, buf, 28, 4); System.arraycopy(blockAlign, 0, buf, 32, 2); System.arraycopy(bitsPerSample, 0, buf, 34, 2); System.arraycopy(subChunkFactID, 0, buf, 36, 4); System.arraycopy(subChunkFactSize, 0, buf, 40, 4); System.arraycopy(fact, 0, buf, 44, 4); System.arraycopy(subChunk2ID, 0, buf, 48, 4); System.arraycopy(subChunk2Size, 0, buf, 52, 4); System.arraycopy(payload, 0, buf, 56, payload.length); File myFile = new File(filePathURI); if (myFile.exists()) { myFile.delete(); } if (buf.length > 0) { OutputStream out = null; try { out = SingletonFSInterface.instance().getOutputStream(filePathURI); out.write(buf); out.close(); } catch (Exception e) { if (out != null) out.close(); throw e; } } result = null; } else { throw new RuntimeException("unsupported operation " + name); } } return result; }