List of usage examples for javax.xml.xpath XPathFactory newXPath
public abstract XPath newXPath();
Return a new XPath
using the underlying object model determined when the XPathFactory was instantiated.
From source file:com.dwdesign.tweetings.activity.ComposeActivity.java
private String uploadTwitlonger(String text) { String finalUrl = "http://www.twitlonger.com/api_post/"; final String atext = parseString(mEditText.getText()); String screen_name = null;//from w ww .ja v a2 s .c om if (mAccountIds != null && mAccountIds.length > 0) { screen_name = getAccountUsername(this, mAccountIds[0]); } try { HttpClient httpclient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(finalUrl); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("username", new StringBody(screen_name)); reqEntity.addPart("application", new StringBody(TWIT_LONGER_USER)); reqEntity.addPart("api_key", new StringBody(TWIT_LONGER_API_KEY)); reqEntity.addPart("message", new StringBody(atext, Charset.forName("UTF-8"))); postRequest.setEntity(reqEntity); HttpResponse response = httpclient.execute(postRequest); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(response.getEntity().getContent()); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr; expr = xpath.compile("//twitlonger/post/content/text()"); Object result = expr.evaluate(doc, XPathConstants.STRING); Log.d("ComposeActivity.uploadTwitlonger", "path: " + atext + " " + result.toString()); return result.toString(); } catch (Exception e) { //Toast.makeText(getApplicationContext(), "Network exception" + e.getMessage(), Toast.LENGTH_SHORT).show(); } return null; }
From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java
@Test public void testNameIDUnset() throws Exception { new SamlClientBuilder().navigateTo(employee2ServletPage.toString()).processSamlResponse(Binding.POST) .build().login().user(bburkeUser).build().processSamlResponse(Binding.POST) .transformDocument(responseDoc -> { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("//*[local-name()='NameID']"); NodeList nodeList = (NodeList) expr.evaluate(responseDoc, XPathConstants.NODESET); Assert.assertThat(nodeList.getLength(), is(1)); final Node nameIdNode = nodeList.item(0); nameIdNode.getParentNode().removeChild(nameIdNode); return responseDoc; }).build()/*from ww w. j a v a 2s . c o m*/ .navigateTo(employee2ServletPage.toString()) .execute(r -> { Assert.assertThat(r, statusCodeIsHC(Response.Status.OK)); Assert.assertThat(r, bodyHC(allOf(containsString("principal="), not(containsString("500"))))); }); }
From source file:com.novartis.opensource.yada.test.ServiceTest.java
/** * Validation method for XML response/*from ww w. j a v a 2 s . co m*/ * * @param result the query result * @return {@code true} if result complies with expected output spec * @throws YADAResponseException when the test result is invalid */ public boolean validateXMLResult(String result) throws YADAResponseException { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader(result))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression resultSets = xpath.compile("/RESULTSETS"); XPathExpression nestedTotal = xpath.compile("//RESULTSET/@total[1]"); XPathExpression resultSet = xpath.compile("/RESULTSET"); XPathExpression colCase = xpath.compile("//" + COL_STRING + "[1]"); String evalSets = resultSets.evaluate(doc); String evalSet = resultSet.evaluate(doc); XPathExpression colInt = xpath.compile("//" + COL_INTEGER + "[1]"); XPathExpression colNum = xpath.compile("//" + COL_NUMBER + "[1]"); XPathExpression colDat = xpath.compile("//" + COL_DATE + "[1]"); XPathExpression colTim = xpath.compile("//" + COL_TIME + "[1]"); if ((evalSets != null && evalSets.length() > 0) || (evalSet != null && evalSet.length() > 0)) { String eval = nestedTotal.evaluate(doc); if (eval != null && eval.length() > 0 && Integer.parseInt(eval) > 0) { logMarkupResult(result); String evalCol = colCase.evaluate(doc); if (evalCol == null || evalCol.length() == 0) { colInt = xpath.compile("//" + COL_INTEGER_LC + "[1]"); colNum = xpath.compile("//" + COL_NUMBER_LC + "[1]"); colDat = xpath.compile("//" + COL_DATE_LC + "[1]"); colTim = xpath.compile("//" + COL_TIME_LC + "[1]"); } try { return validateInteger(colInt.evaluate(doc)) && validateNumber(colNum.evaluate(doc)) && validateDate(colDat.evaluate(doc)) && validateTime(colTim.evaluate(doc)); } catch (NumberFormatException e) { String msg = "Unable to validate result content."; throw new YADAResponseException(msg, e); } catch (ParseException e) { String msg = "Unable to validate result content."; throw new YADAResponseException(msg, e); } } } } catch (ParserConfigurationException e) { throw new YADAResponseException("XML Document creation failed.", e); } catch (SAXException e) { throw new YADAResponseException("XML Document creation failed.", e); } catch (IOException e) { throw new YADAResponseException("XML Document creation failed.", e); } catch (XPathExpressionException e) { throw new YADAResponseException("Results do not contain expected XML content", e); } return true; }
From source file:it.imtech.metadata.MetaUtility.java
public void findLastClassification(String panelname) { try {// w w w . ja v a 2 s . c om int tmpseq; last_classification = 0; DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; File s = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); String expression = "//*[@ID='22']"; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); doc = dBuilder.parse(s.getAbsolutePath()); NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength() && nodeList.getLength() > 1; i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); tmpseq = Integer.parseInt(nodeAttr.getNodeValue()); if (tmpseq > last_classification) { last_classification = tmpseq; } } } catch (SAXException ex) { Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex); } catch (XPathExpressionException ex) { Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(MetaUtility.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:it.imtech.metadata.MetaUtility.java
public void setSessionMetadataFile(String filetoparse, String panelname) { try {// w w w . ja v a 2s . c o m DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; File f = new File(Globals.BACKUP_METADATA); File s = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); FileUtils.copyFile(f, s); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); File impmetadata = new File(filetoparse); doc = dBuilder.parse(impmetadata); String expression = "//*[local-name()='contribute']"; NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength() - 1; i++) { addContributorToMetadata(panelname); } expression = "//*[local-name()='taxonpath']"; nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength() - 1; i++) { addClassificationToMetadata(panelname); } } catch (ParserConfigurationException ex) { logger.error(ex.getMessage()); } catch (XPathExpressionException ex) { logger.error(ex.getMessage()); } catch (SAXException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } }
From source file:it.imtech.metadata.MetaUtility.java
public void findLastContribute(String panelname) { try {//from w ww. ja va 2 s. c o m int tmpseq; last_contribute = 0; DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; File s = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); String expression = "//*[@ID='11']"; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); doc = dBuilder.parse(s.getAbsolutePath()); NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength() && nodeList.getLength() > 1; i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); tmpseq = Integer.parseInt(nodeAttr.getNodeValue()); System.out.println("contribute sequence: " + tmpseq); if (tmpseq > last_contribute) { last_contribute = tmpseq; } } } catch (SAXException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } catch (XPathExpressionException ex) { logger.error(ex.getMessage()); } catch (ParserConfigurationException ex) { logger.error(ex.getMessage()); } }
From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java
@Override public Boolean addNewPlugin(String newPluginName, String xmlSourcePath, String jarSourcePath) throws UIException { LOGGER.info("Saving the new plugin with following details:\n Plugin Name:\t" + newPluginName + "\n Plugin Xml Path:\t" + xmlSourcePath + "\n Plugin Jar path:\t" + jarSourcePath); PluginXmlDTO pluginXmlDTO = null;/*from ww w .j av a2s . co m*/ boolean pluginAdded = false; // Parse the data from xmlSourcePath file XPathFactory xFactory = new org.apache.xpath.jaxp.XPathFactoryImpl(); XPath xpath = xFactory.newXPath(); org.w3c.dom.Document pluginXmlDoc = null; try { pluginXmlDoc = XMLUtil .createDocumentFrom(FileUtils.getInputStreamFromZip(newPluginName, xmlSourcePath)); } catch (Exception e) { String errorMsg = "Invalid xml content. Please try again."; LOGGER.error(errorMsg + e.getMessage(), e); throw new UIException(errorMsg); } if (pluginXmlDoc != null) { // correct syntax NodeList pluginNodeList = null; try { pluginNodeList = (NodeList) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_EXPR, pluginXmlDoc, XPathConstants.NODESET); } catch (XPathExpressionException e) { String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE; LOGGER.error(errorMsg + e.getMessage(), e); throw new UIException(errorMsg); } if (pluginNodeList != null && pluginNodeList.getLength() == 1) { LOGGER.info("Reading the Xml contents"); String backUpFileName = SystemConfigSharedConstants.EMPTY_STRING; String jarName = SystemConfigSharedConstants.EMPTY_STRING; String methodName = SystemConfigSharedConstants.EMPTY_STRING; String description = SystemConfigSharedConstants.EMPTY_STRING; String pluginName = SystemConfigSharedConstants.EMPTY_STRING; String workflowName = SystemConfigSharedConstants.EMPTY_STRING; String scriptFileName = SystemConfigSharedConstants.EMPTY_STRING; String serviceName = SystemConfigSharedConstants.EMPTY_STRING; String pluginApplicationContextPath = SystemConfigSharedConstants.EMPTY_STRING; boolean isScriptingPlugin = false; boolean overrideExisting = false; try { backUpFileName = (String) xpath.evaluate(SystemConfigSharedConstants.BACK_UP_FILE_NAME_EXPR, pluginNodeList.item(0), XPathConstants.STRING); jarName = (String) xpath.evaluate(SystemConfigSharedConstants.JAR_NAME_EXPR, pluginNodeList.item(0), XPathConstants.STRING); methodName = (String) xpath.evaluate(SystemConfigSharedConstants.METHOD_NAME_EXPR, pluginNodeList.item(0), XPathConstants.STRING); description = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_DESC_EXPR, pluginNodeList.item(0), XPathConstants.STRING); pluginName = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_NAME_EXPR, pluginNodeList.item(0), XPathConstants.STRING); workflowName = (String) xpath.evaluate(SystemConfigSharedConstants.PLUGIN_WORKFLOW_NAME_EXPR, pluginNodeList.item(0), XPathConstants.STRING); scriptFileName = (String) xpath.evaluate(SystemConfigSharedConstants.SCRIPT_FILE_NAME_EXPR, pluginNodeList.item(0), XPathConstants.STRING); serviceName = (String) xpath.evaluate(SystemConfigSharedConstants.SERVICE_NAME_EXPR, pluginNodeList.item(0), XPathConstants.STRING); isScriptingPlugin = Boolean .parseBoolean((String) xpath.evaluate(SystemConfigSharedConstants.IS_SCRIPT_PLUGIN_EXPR, pluginNodeList.item(0), XPathConstants.STRING)); pluginApplicationContextPath = (String) xpath.evaluate( SystemConfigSharedConstants.APPLICATION_CONTEXT_PATH, pluginNodeList.item(0), XPathConstants.STRING); overrideExisting = Boolean .parseBoolean((String) xpath.evaluate(SystemConfigSharedConstants.OVERRIDE_EXISTING, pluginNodeList.item(0), XPathConstants.STRING)); } catch (Exception e) { String errorMsg = "Error in xml content. A mandatory tag is missing or invalid."; LOGGER.error(errorMsg + e.getMessage(), e); throw new UIException(errorMsg); } LOGGER.info("Back Up File Name: " + backUpFileName); LOGGER.info("Jar Name" + jarName); LOGGER.info("Method Name" + methodName); LOGGER.info("Description: " + description); LOGGER.info("Name: " + pluginName); LOGGER.info("Workflow Name" + workflowName); LOGGER.info("Script file Name" + scriptFileName); LOGGER.info("Service Name" + serviceName); LOGGER.info("Is scripting Plugin:" + isScriptingPlugin); LOGGER.info("Plugin application context path: " + pluginApplicationContextPath); if (!backUpFileName.isEmpty() && !jarName.isEmpty() && !methodName.isEmpty() && !description.isEmpty() && !pluginName.isEmpty() && !workflowName.isEmpty() && !serviceName.isEmpty() && !pluginApplicationContextPath.isEmpty()) { if (isScriptingPlugin && scriptFileName.isEmpty()) { String errorMsg = "Error in xml content. A mandatory field is missing."; LOGGER.error(errorMsg); throw new UIException(errorMsg); } pluginXmlDTO = setPluginInfo(backUpFileName, jarName, methodName, description, pluginName, workflowName, scriptFileName, serviceName, pluginApplicationContextPath, isScriptingPlugin, overrideExisting); extractPluginConfigs(pluginXmlDTO, xpath, pluginNodeList); extractPluginDependenciesFromXml(pluginXmlDTO, xpath, pluginNodeList); boolean pluginAlreadyExists = !checkIfPluginExists(pluginName); saveOrUpdatePluginToDB(pluginXmlDTO); createAndDeployPluginProcessDefinition(pluginXmlDTO); copyJarToLib(newPluginName, jarSourcePath); if (pluginAlreadyExists) { addPathToApplicationContext(pluginXmlDTO.getApplicationContextPath()); } pluginAdded = true; LOGGER.info("Plugin added successfully."); } else { String errorMsg = SystemConfigSharedConstants.INVALID_XML_CONTENT_MESSAGE; LOGGER.error(errorMsg); throw new UIException(errorMsg); } } else { String errorMsg = "Invalid xml content. Number of plugins expected is one."; LOGGER.error(errorMsg); throw new UIException(errorMsg); } } return pluginAdded; }
From source file:it.imtech.metadata.MetaUtility.java
private void addContributorToMetadata(String panelname) { try {/*w w w . jav a 2s . c o m*/ DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); //File backupmetadata = new File(Globals.SESSION_METADATA); doc = dBuilder.parse(backupmetadata); String expression = "//*[@ID='11']"; NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); int maxseq = 0; int tmpseq = 0; for (int i = 0; i < nodeList.getLength(); i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); tmpseq = Integer.parseInt(nodeAttr.getNodeValue()); if (tmpseq > maxseq) { maxseq = tmpseq; } } maxseq++; Node newNode = nodeList.item(0).cloneNode(true); Element nodetocopy = (Element) newNode; NamedNodeMap attr = nodeList.item(0).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); nodeAttr.setTextContent(Integer.toString(maxseq)); Node copyOfn = doc.importNode(nodetocopy, true); nodeList.item(0).getParentNode().appendChild(copyOfn); XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); } catch (ParserConfigurationException ex) { logger.error(ex.getMessage()); } catch (SAXException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } catch (XPathExpressionException ex) { logger.error(ex.getMessage()); } }
From source file:it.imtech.metadata.MetaUtility.java
private void removeContributorToMetadata(String panelname) { try {/*from ww w .ja v a 2 s.c o m*/ DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); //File backupmetadata = new File(Globals.SESSION_METADATA); doc = dBuilder.parse(backupmetadata); String expression = "//*[@ID='11']"; NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); int maxseq = 0; int tmpseq = 0; for (int i = 0; i < nodeList.getLength(); i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); tmpseq = Integer.parseInt(nodeAttr.getNodeValue()); if (tmpseq > maxseq) { maxseq = tmpseq; } } //maxseq++; int nLast, idLast, counter = 0; for (int i = 0; i < nodeList.getLength(); i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); if (maxseq == Integer.parseInt(nodeAttr.getNodeValue())) { nLast = counter; nodeAttr = attr.getNamedItem("ID"); idLast = Integer.parseInt(nodeAttr.getNodeValue()); nodeList.item(i).getParentNode().removeChild(nodeList.item(i)); } counter++; } XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); } catch (ParserConfigurationException ex) { logger.error(ex.getMessage()); } catch (SAXException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } catch (XPathExpressionException ex) { logger.error(ex.getMessage()); } }
From source file:it.imtech.metadata.MetaUtility.java
private void addClassificationToMetadata(String panelname) { try {/* w w w.j ava 2 s . c o m*/ DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); //File backupmetadata = new File(Globals.SESSION_METADATA); File backupmetadata = new File(Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); doc = dBuilder.parse(backupmetadata); String expression = "//*[@ID='22']"; NodeList nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); int maxseq = 0; int tmpseq; for (int i = 0; i < nodeList.getLength(); i++) { NamedNodeMap attr = nodeList.item(i).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); tmpseq = Integer.parseInt(nodeAttr.getNodeValue()); if (tmpseq > maxseq) { maxseq = tmpseq; } } maxseq++; Node newNode = nodeList.item(0).cloneNode(true); Element nodetocopy = (Element) newNode; NamedNodeMap attr = nodeList.item(0).getAttributes(); Node nodeAttr = attr.getNamedItem("sequence"); nodeAttr.setTextContent(Integer.toString(maxseq)); Node copyOfn = doc.importNode(nodetocopy, true); nodeList.item(0).getParentNode().appendChild(copyOfn); Element root = doc.getDocumentElement(); NodeList firstlevelnodes = root.getChildNodes(); for (int i = 0; i < firstlevelnodes.getLength(); i++) { if (firstlevelnodes.item(i).getNodeType() == Node.ELEMENT_NODE) { Element node = (Element) firstlevelnodes.item(i); Integer sequence = Integer.parseInt(node.getAttribute("sequence")); if (!node.getAttribute("ID").equals("22") && sequence >= maxseq) { node.setAttribute("sequence", Integer.toString(sequence + 1)); } } } XMLUtil.xmlWriter(doc, Globals.DUPLICATION_FOLDER_SEP + "session" + panelname); } catch (ParserConfigurationException ex) { logger.error(ex.getMessage()); } catch (SAXException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } catch (XPathExpressionException ex) { logger.error(ex.getMessage()); } }