/** * Creates a new XMLReader instance. * * @param stream XML source stream * @throws DocumentException if the XML could not be parsed */ public XMLReader(InputStream stream) throws DocumentException { try { saxReader.read(stream); } catch (org.dom4j.DocumentException e) { throw new DocumentException(e.getMessage()); } }
/** * Creates a new XMLReader instance. * * @param reader XML source reader * @throws DocumentException if the XML could not be parsed */ public XMLReader(Reader reader) throws DocumentException { try { saxReader.read(reader); } catch (org.dom4j.DocumentException e) { throw new DocumentException(e.getMessage()); } }
public ModelAndView updateProject(HttpServletRequest request, HttpServletResponse response) throws Exception { Project project = (Project) BeanUtil.createBean(request, Project.class); Map<String, String> result = new HashMap<String, String>(); boolean success = true; try { projectService.updateProject(project); } catch (ProjectExistException e) { logger.error("项目已经存在"); result.put("errorMsg", "项目已经存在"); success = false; } catch (ProjectNotExistException e) { logger.error("项目不存在"); result.put("errorMsg", "项目不存在"); success = false; } catch (DocumentException e) { logger.error(e.getMessage()); result.put("errorMsg", "项目文件无法读取!"); success = false; } catch (IOException e) { logger.error(e.getMessage()); result.put("errorMsg", "项目文件无法写入!"); success = false; } result.put("success", String.valueOf(success)); return new ModelAndView(getView(request), result); }
/** * 修改xml某节点的值 * * @param inputXml 原xml文件 * @param nodes 要修改的节点 * @param attributename 属性名称 * @param value 新值 * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件 */ public static void modifyDocument( File inputXml, String nodes, String attributename, String value, String outXml) { try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(inputXml); List list = document.selectNodes(nodes); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attribute = (Attribute) iter.next(); if (attribute.getName().equals(attributename)) attribute.setValue(value); } XMLWriter output; if (outXml != null) { // 指定输出文件 output = new XMLWriter(new FileWriter(new File(outXml))); } else { // 输出文件为原文件 output = new XMLWriter(new FileWriter(inputXml)); } output.write(document); output.close(); } catch (DocumentException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } }
/** 解析xml */ public void parseXml() { try { Document document = this.saxReader.read(new File(this.xmlPath)); Element root = document.getRootElement(); this.parseConsumers(root); } catch (DocumentException e) { e.printStackTrace(); logger.error("rocket.xml解析异常,error=" + e.getMessage()); } }
public Document getValue() { try { SAXReader reader = new SAXReader(); GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(getData())); Document document = reader.read(gzipInput); gzipInput.close(); return document; } catch (IOException e) { throw new HibernateException(e.getMessage(), e); } catch (DocumentException e) { throw new HibernateException(e.getMessage(), e); } }
/** 使用Dom4j验证Jaxb所生成XML的正确性. */ private static void assertXmlByDom4j(String xml) { Document doc = null; try { doc = DocumentHelper.parseText(xml); } catch (DocumentException e) { fail(e.getMessage()); } Element user = doc.getRootElement(); assertThat(user.attribute("id").getValue()).isEqualTo("1"); Element interests = (Element) doc.selectSingleNode("//interests"); assertThat(interests.elements()).hasSize(2); assertThat(((Element) interests.elements().get(0)).getText()).isEqualTo("movie"); }
public void parserXml(String fileName) { File inputXml = new File(fileName); SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(inputXml); Element employees = document.getRootElement(); for (Iterator i = employees.elementIterator(); i.hasNext(); ) { Element employee = (Element) i.next(); for (Iterator j = employee.elementIterator(); j.hasNext(); ) { Element node = (Element) j.next(); System.out.println(node.getName() + ":" + node.getText()); } } } catch (DocumentException e) { System.out.println(e.getMessage()); } System.out.println("dom4j parserXml"); }
/** * Simple parsing and display of the response. This method uses dom4j for parsing XML, feel free * to use anything that comes handy. */ @SuppressWarnings("unchecked") private static void displayResults(InputStream results) throws IOException { try { final SAXReader reader = new SAXReader(); final Document document = reader.read(results); final Iterator<Element> i = document.getRootElement().elementIterator("group"); while (i.hasNext()) { final Element group = i.next(); display(group, 1); } System.out.println(); } catch (DocumentException e) { throw new IOException("Could not parse response: " + e.getMessage()); } finally { if (results != null) { results.close(); } } }
/** * 功能描述:根据响应节点 获取结果hash * * @return 返回值 * @throw 异常描述 * @see 需要参见的其它内容 */ public static Map<String, Object> getResponseData(String node, String msg) { Map<String, Object> result = null; StringBuffer startNode = new StringBuffer("<"); startNode.append(node).append(">"); StringBuffer endNode = new StringBuffer("</"); endNode.append(node).append(">"); String resultMsg = msg.substring( msg.lastIndexOf(startNode.toString()) + startNode.toString().length(), msg.lastIndexOf(endNode.toString())); try { parseXml2Object.createDocument(resultMsg); result = parseXml2Object.getMsgData(); } catch (DocumentException e) { logger.debug("parse xml to object occur error" + e.getMessage()); } return result; }
// parse the XML model data to PTNet private void ParseModelToPTNet(Model model) { if (this.model == null) return; else { ByteArrayInputStream stream; SAXReader reader = new SAXReader(); Document document; Element root = null; try { stream = new ByteArrayInputStream(model.XMLContent.getBytes()); reader.setEncoding("utf-8"); document = reader.read(stream); root = document.getRootElement(); } catch (DocumentException e) { Log.getLogger(Config.FLOW).error(e.getMessage()); e.printStackTrace(); } ForwardPlace sp = (ForwardPlace) newPlace("ForwardPlace"); new Parser().parse(this, sp, root, null, false); Log.getLogger(Config.FLOW).debug(getPtnet()); } }
public Document read(URL url, boolean validate) throws DocumentException { ClassLoader classLoader = getClass().getClassLoader(); Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); try { if (contextClassLoader != classLoader) { currentThread.setContextClassLoader(classLoader); } org.dom4j.io.SAXReader saxReader = getSAXReader(validate); return new DocumentImpl(saxReader.read(url)); } catch (org.dom4j.DocumentException de) { throw new DocumentException(de.getMessage(), de); } finally { if (contextClassLoader != classLoader) { currentThread.setContextClassLoader(contextClassLoader); } } }
private void wmiLaunch(final EC2Computer computer, final TaskListener listener) throws IOException, InterruptedException, JIException { try { final PrintStream logger = listener.getLogger(); final String name = host; logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingTo(name)); InetAddress host = InetAddress.getByName(name); try { Socket s = new Socket(); s.connect(new InetSocketAddress(host, 135), 5000); s.close(); } catch (IOException e) { logger.println( "Failed to connect to port 135 of " + name + ". Is Windows firewall blocking this port? Or did you disable DCOM service?"); // again, let it continue. } JIDefaultAuthInfoImpl auth = createAuth(); JISession session = JISession.createSession(auth); session.setGlobalSocketTimeout(60000); SWbemServices services = WMI.connect(session, name); String path = computer.getNode().getRemoteFS(); if (path.indexOf(':') == -1) throw new IOException( "Remote file system root path of the slave needs to be absolute: " + path); SmbFile remoteRoot = new SmbFile( "smb://" + name + "/" + path.replace('\\', '/').replace(':', '$') + "/", createSmbAuth()); if (!remoteRoot.exists()) remoteRoot.mkdirs(); try { // does Java exist? logger.println("Checking if Java exists"); WindowsRemoteProcessLauncher wrpl = new WindowsRemoteProcessLauncher(name, auth); Process proc = wrpl.launch("%JAVA_HOME%\\bin\\java -fullversion", "c:\\"); proc.getOutputStream().close(); IOUtils.copy(proc.getInputStream(), logger); proc.getInputStream().close(); int exitCode = proc.waitFor(); if (exitCode == 1) { // we'll get this error code if Java is not found logger.println("No Java found. Downloading JDK"); JDKInstaller jdki = new JDKInstaller("jdk-6u16-oth-JPR@CDS-CDS_Developer", true); URL jdk = jdki.locate(listener, Platform.WINDOWS, CPU.i386); listener.getLogger().println("Installing JDK"); copyStreamAndClose( jdk.openStream(), new SmbFile(remoteRoot, "jdk.exe").getOutputStream()); String javaDir = path + "\\jdk"; // this is where we install Java to WindowsRemoteFileSystem fs = new WindowsRemoteFileSystem(name, createSmbAuth()); fs.mkdirs(javaDir); jdki.install( new WindowsRemoteLauncher(listener, wrpl), Platform.WINDOWS, fs, listener, javaDir, path + "\\jdk.exe"); } } catch (Exception e) { e.printStackTrace(listener.error("Failed to prepare Java")); } String id = generateServiceId(path); Win32Service slaveService = services.getService(id); if (slaveService == null) { logger.println(Messages.ManagedWindowsServiceLauncher_InstallingSlaveService()); if (!DotNet.isInstalled(2, 0, name, auth)) { // abort the launch logger.println(Messages.ManagedWindowsServiceLauncher_DotNetRequired()); return; } // copy exe logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveExe()); copyStreamAndClose( getClass().getResource("/windows-service/jenkins.exe").openStream(), new SmbFile(remoteRoot, "jenkins-slave.exe").getOutputStream()); copySlaveJar(logger, remoteRoot); // copy jenkins-slave.xml logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveXml()); String nodeNameEncoded = java.net.URLEncoder.encode(nodeName, "UTF-8").replace("+", "%20"); String xml = generateSlaveXml( id, "\"%JAVA_HOME%\\bin\\java\"", " -jnlpUrl " + Hudson.getInstance().getRootUrl() + "computer/" + nodeNameEncoded + "/slave-agent.jnlp"); copyStreamAndClose( new ByteArrayInputStream(xml.getBytes("UTF-8")), new SmbFile(remoteRoot, "jenkins-slave.xml").getOutputStream()); // install it as a service logger.println(Messages.ManagedWindowsServiceLauncher_RegisteringService()); Document dom = new SAXReader().read(new StringReader(xml)); Win32Service svc = services.Get("Win32_Service").cast(Win32Service.class); int r = svc.Create( id, dom.selectSingleNode("/service/name").getText() + " at " + path, path + "\\jenkins-slave.exe", Win32OwnProcess, 0, "Manual", true); if (r != 0) { throw new JIException(-1, ("Failed to create a service: " + svc.getErrorMessage(r))); } slaveService = services.getService(id); } else { copySlaveJar(logger, remoteRoot); } logger.println(Messages.ManagedWindowsServiceLauncher_StartingService()); slaveService.start(); // wait until we see the port.txt, but don't do so forever logger.println(Messages.ManagedWindowsServiceLauncher_WaitingForService()); SmbFile portFile = new SmbFile(remoteRoot, "port.txt"); for (int i = 0; !portFile.exists(); i++) { if (i >= 30) { throw new JIException(-1, Messages.ManagedWindowsServiceLauncher_ServiceDidntRespond()); } Thread.sleep(1000); } int p = readSmbFile(portFile); // connect logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingToPort(p)); final Socket s = new Socket(name, p); // ready computer.setChannel( new BufferedInputStream(new SocketInputStream(s)), new BufferedOutputStream(new SocketOutputStream(s)), listener.getLogger(), new Listener() { @Override public void onClosed(Channel channel, IOException cause) { afterDisconnect(computer, listener); } }); // destroy session to free the socket JISession.destroySession(session); } catch (SmbException e) { e.printStackTrace(listener.error(e.getMessage())); } catch (DocumentException e) { e.printStackTrace(listener.error(e.getMessage())); } }
private boolean accept(Object obj) { if (obj == null) { logger.warn("Applying JXPathFilter to null object."); return false; } if (pattern == null) { logger.warn("Expression for JXPathFilter is not set."); return false; } if (expectedValue == null) { // Handle the special case where the expected value really is null. if (pattern.endsWith("= null") || pattern.endsWith("=null")) { expectedValue = "null"; pattern = pattern.substring(0, pattern.lastIndexOf("=")); } else { if (logger.isInfoEnabled()) { logger.info("Expected value for JXPathFilter is not set, using 'true' by default"); } expectedValue = Boolean.TRUE.toString(); } } Object xpathResult = null; boolean accept = false; // Payload is a DOM Document if (obj instanceof Document) { if (namespaces == null) { // no namespace defined, let's perform a direct evaluation xpathResult = ((Document) obj).valueOf(pattern); } else { // create an xpath expression with namespaces and evaluate it XPath xpath = DocumentHelper.createXPath(pattern); xpath.setNamespaceURIs(namespaces); xpathResult = xpath.valueOf(obj); } } // Payload is a String of XML else if (obj instanceof String) { try { return accept(DocumentHelper.parseText((String) obj)); } catch (DocumentException e) { logger.warn("JXPathFilter unable to parse XML document: " + e.getMessage(), e); if (logger.isDebugEnabled()) logger.debug("XML = " + StringMessageUtils.truncate((String) obj, 200, false)); return false; } } // Payload is a Java object else { if (logger.isDebugEnabled()) { logger.debug("Passing object of type " + obj.getClass().getName() + " to JXPathContext"); } JXPathContext context = JXPathContext.newContext(obj); initialise(context); xpathResult = context.getValue(pattern); } if (logger.isDebugEnabled()) { logger.debug( "JXPathFilter Expression result = '" + xpathResult + "' - Expected value = '" + expectedValue + "'"); } // Compare the XPath result with the expected result. if (xpathResult != null) { accept = xpathResult.toString().equals(expectedValue); } else { // A null result was actually expected. if (expectedValue.equals("null")) { accept = true; } // A null result was not expected, something probably went wrong. else { logger.warn("JXPathFilter expression evaluates to null: " + pattern); } } if (logger.isDebugEnabled()) { logger.debug("JXPathFilter accept object : " + accept); } return accept; }
private void parseXML(URL url) { /* Here I am parsing from an XML File, using Dom4J framework. the file (test.xml) is setup so it holds info for the current game On parsing from the file I will populate the fields for: Teams, scores, goals scored and players who scored. Running tight on time, this will be fully implemented next week. This file will not be a local file, but a downloaded stream from server */ String team1G = "", team2G = ""; try { SAXReader reader = new SAXReader(); Document document = reader.read(url); Element rootElement = document.getRootElement(); System.out.println("Root Element: " + rootElement.getName()); for (Iterator i = rootElement.elementIterator(); i.hasNext(); ) { Element element = (Element) i.next(); System.out.println(element.getName()); for (Iterator i2 = element.elementIterator(); i2.hasNext(); ) { Element element2 = (Element) i2.next(); // Node is a game - parse game if ("isLive".equals(element2.getName())) { if ("false".equals((String) element2.getData())) { // If its not live dont show System.out.println("Game is not live, revert to Sim"); revertToSimulation(); break; } } if ("team1".equals(element2.getName())) { // Node is Team 1 - parse info for (Iterator team1Iterator = element2.elementIterator(); team1Iterator.hasNext(); ) { Element team1 = (Element) team1Iterator.next(); if ("name".equals((String) team1.getName())) { Team1Name.setText((String) team1.getData()); } if ("score".equals((String) team1.getName())) { teamOneScore.setText((String) team1.getData()); } if ("goals".equals((String) team1.getName())) { /* Parse the goals scored by this team */ for (Iterator team1GoalsIterator = team1.elementIterator(); team1GoalsIterator.hasNext(); ) { Element goals = (Element) team1GoalsIterator.next(); if ("goal".equals((String) goals.getName())) { for (Iterator t1gIgoalIterator = goals.elementIterator(); t1gIgoalIterator.hasNext(); ) { Element goal = (Element) t1gIgoalIterator.next(); if ("player".equals((String) goal.getName())) { // Parse the Player team1G = team1G + (String) goal.getData(); } if ("time".equals((String) goal.getName())) { // Parse the Time of Score team1G = team1G + " : " + (String) goal.getData() + "\n"; } } } } } } } if ("team2".equals(element2.getName())) { // Node is Team 2 - parse info for (Iterator team2Iterator = element2.elementIterator(); team2Iterator.hasNext(); ) { Element team2 = (Element) team2Iterator.next(); if ("name".equals((String) team2.getName())) { Team2Name.setText((String) team2.getData()); } if ("score".equals((String) team2.getName())) { teamTwoScore.setText((String) team2.getData()); } if ("goals".equals((String) team2.getName())) { /* Parse the goals scored by thie team */ for (Iterator team2GoalsIterator = team2.elementIterator(); team2GoalsIterator.hasNext(); ) { Element goals = (Element) team2GoalsIterator.next(); if ("goal".equals((String) goals.getName())) { /* Parse a Goal */ for (Iterator t2gIgoalIterator = goals.elementIterator(); t2gIgoalIterator.hasNext(); ) { Element goal = (Element) t2gIgoalIterator.next(); if ("player".equals((String) goal.getName())) { /* Parse the Player */ team2G = team2G + (String) goal.getData(); } if ("time".equals((String) goal.getName())) { /* Parse the time of score */ team2G = team2G + " : " + (String) goal.getData() + "\n"; } } } } } } } } } } catch (DocumentException e) { System.out.print(e.getMessage()); } team1GoalsArea.setText(team1G); team2GoalsArea.setText(team2G); }
/** * 功能描述:封装soap报文信息 * * @return 返回值 * @throw 异常描述 * @see 需要参见的其它内容 */ public static String mergeSoapMessage( Map<String, Object> nodeHash, Map<String, Object> paramHash) { String soapMsg = ""; if (StringUtil.isNullOrEmpty(nodeHash) || StringUtil.isNullOrEmpty(paramHash)) { return soapMsg; } if (!nodeHash.containsKey("operationName")) { return soapMsg; } if (!nodeHash.containsKey("namespace")) { return soapMsg; } if (!nodeHash.containsKey("serviceCode")) { return soapMsg; } // 操作名称 String operationName = nodeHash.get("operationName").toString(); // 命名空间 String namespace = nodeHash.get("namespace").toString(); // Esb提供交易码 String serviceCode = nodeHash.get("serviceCode").toString(); Document doc = DocumentHelper.createDocument(); if (null != doc) { Element root = doc.addElement("SOAP-ENV:Envelope", "http://schemas.xmlsoap.org/soap/envelope/"); root.addNamespace("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"); root.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); root.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); Element body = root.addElement("SOAP-ENV:Body"); Element operation = body.addElement("m:" + operationName, namespace); Element input = operation.addElement("input1"); Element head = input.addElement("MbfHeader"); head.addElement("MBServiceCode").addText(serviceCode); Element pbody = input.addElement("MbfBody"); pbody.setText("test"); XMLWriter xmlWriter = null; StringWriter writer = new StringWriter(); xmlWriter = new XMLWriter(writer); try { xmlWriter.write(doc); parseObject2Xml.parser(paramHash); String replaceStr = parseObject2Xml.getMsg() + "</MbfBody></input1></m:" + operationName + "></SOAP-ENV:Body></SOAP-ENV:Envelope>"; soapMsg = writer .toString() .replace( "test</MbfBody></input1></m:" + operationName + "></SOAP-ENV:Body></SOAP-ENV:Envelope>", replaceStr.substring(38, replaceStr.length())); } catch (IOException e) { logger.error("io handler occur error" + e.getMessage()); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (DocumentException e) { logger.debug("parse object to xml occur error" + e.getMessage()); } return soapMsg; } return soapMsg; }