List of usage examples for javax.xml.xpath XPathExpression evaluate
public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;
From source file:com.peter.mavenrunner.MavenRunnerTopComponent.java
void refreshTree(boolean showEmptyNode) { log("refreshTree"); try {//from w ww .j a v a 2 s .c o m root.removeAllChildren(); String searchString = searchTextField.getText().trim(); for (Project p : OpenProjects.getDefault().getOpenProjects()) { ProjectInformation projectInformation = p.getLookup().lookup(ProjectInformation.class); log(projectInformation.getDisplayName()); if (!new File(p.getProjectDirectory().getPath() + File.separator + "pom.xml").exists()) { continue; } MyTreeNode node = new MyTreeNode(projectInformation.getDisplayName(), null, null, null, false, "project", p, projectInformation); node.icon = projectInformation.getIcon(); // load goals from nbactions.xml if (!hideDefaultGoalButton.isSelected()) { if (new File(p.getProjectDirectory().getPath() + File.separator + "nbactions.xml").exists()) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder .parse(p.getProjectDirectory().getPath() + File.separator + "nbactions.xml"); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("//action"); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int x = 0; x < nl.getLength(); x++) { NodeList childs = nl.item(x).getChildNodes(); String displayName = null; String actionName = null; String goals = ""; String profiles = ""; List<String> properties = new ArrayList<String>(); boolean skipTest = false; for (int y = 0; y < childs.getLength(); y++) { //log(childs.item(y).getNodeName()); if (childs.item(y).getNodeName().equals("displayName")) { displayName = childs.item(y).getTextContent(); } else if (childs.item(y).getNodeName().equals("actionName")) { actionName = childs.item(y).getTextContent(); } else if (childs.item(y).getNodeName().equals("goals")) { NodeList goalNodes = childs.item(y).getChildNodes(); for (int z = 0; z < goalNodes.getLength(); z++) { if (goalNodes.item(z).getNodeName().equals("goal")) { goals += goalNodes.item(z).getTextContent() + " "; } } } else if (childs.item(y).getNodeName().equals("activatedProfiles")) { NodeList profileNodes = childs.item(y).getChildNodes(); for (int z = 0; z < profileNodes.getLength(); z++) { if (profileNodes.item(z).getNodeName().equals("activatedProfile")) { profiles += profileNodes.item(z).getTextContent() + " "; } } } else if (childs.item(y).getNodeName().equals("properties")) { NodeList profileNodes = childs.item(y).getChildNodes(); for (int z = 0; z < profileNodes.getLength(); z++) { if (!profileNodes.item(z).getNodeName().equals("#text")) { properties.add(">" + profileNodes.item(z).getNodeName() + "=" + profileNodes.item(z).getTextContent().trim()); if (profileNodes.item(z).getNodeName().equals("skipTests")) { skipTest = Boolean .parseBoolean(profileNodes.item(z).getTextContent().trim()); } } } } } // log(displayName == null ? actionName : displayName + "=" + goals + ", " + profiles + ", " + skipTest); // for (String pp : properties) { // log(" " + pp); // } // log("--------"); MyTreeNode goalNode = new MyTreeNode(displayName == null ? actionName : displayName, goals, profiles, properties, skipTest, "default goal", node.project, node.projectInformation); if ((searchString.equals("") || goalNode.name.toLowerCase().contains(searchString.toLowerCase())) && !goalNode.name.trim().equals("") && goalNode.type.equals("default goal")) { node.add(goalNode); goalNode.icon = (new javax.swing.ImageIcon( getClass().getResource("/com/peter/mavenrunner/star.png"))); } } } } // end load goals from nbactions.xml // load goals try { String key = node.projectInformation.getDisplayName(); String value = NbPreferences.forModule(this.getClass()).get("data", null); //log("value=" + value); data = fromString(value); if (data == null) { data = new Hashtable<String, ArrayList<PersistData>>(); //log(" create new data"); } if (data.get(key) == null) { data.put(key, new ArrayList<PersistData>()); //log(" add " + key + " to data"); } ArrayList<PersistData> persistData = data.get(key); if (persistData != null) { for (PersistData n : persistData) { if ((searchString.equals("") || n.name.toLowerCase().contains(searchString.toLowerCase())) && !n.name.trim().equals("") && n.type.equals("goal")) { node.add(new MyTreeNode(n.name, n.goals, n.profile, n.properties, n.skipTests, n.type, node.project, node.projectInformation)); } } } } catch (Exception ex) { log(ExceptionUtils.getStackTrace(ex)); // old version of data throws here data = new Hashtable<String, ArrayList<PersistData>>(); NbPreferences.forModule(this.getClass()).put("data", toString(data)); } // load goals end if (showEmptyNode || node.getChildCount() > 0) { root.add(node); } } } catch (Exception ex) { log(ExceptionUtils.getStackTrace(ex)); } treeModel.nodeStructureChanged(root); expandAll(projectTree, true); }
From source file:com.fluidops.iwb.provider.XMLProvider.java
/** * Requires the input to be a single node * //w ww . ja v a2 s .com * @param xpathOP * @param n * @return */ protected List<String> getHashValue(String xpathOP, Node context) { List<String> res = new ArrayList<String>(); Pattern p = Pattern.compile("^\\{([^\\}]*)\\}$"); Matcher m = p.matcher(xpathOP); if (m.matches()) { try { XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(ctx); XPathExpression xpathExp = xpath.compile(xpathOP.substring(1, xpathOP.length() - 1)); NodeList nl = (NodeList) xpathExp.evaluate(context, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); String s = XML.toFormattedString(n); res.add(SHA512.encrypt(s)); } } catch (Exception e) { logger.warn(e.getMessage()); } } return res; }
From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java
/** * /*www . j a va2 s. c om*/ * @param cADCommandObject * @param query * @param select * @param order * @return * @throws Exception */ private final ScribeCommandObject searchAllTypeOfObjects(final ScribeCommandObject cADCommandObject, final String query, final String select, final String order) throws Exception { logger.debug("----Inside searchAllTypeOfObjects query: " + query + " & select: " + select + " & order: " + order); GetMethod getMethod = null; try { String serviceURL = null; String serviceProtocol = null; String userId = null; String password = null; String sessionId = null; String crmPort = "80"; /* Check if CrmUserId is present in request */ if (cADCommandObject.getCrmUserId() != null) { /* Get agent from session manager */ final ScribeCacheObject agent = zDCRMSessionManager .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId()); /* Get CRM information from agent */ serviceURL = agent.getScribeMetaObject().getCrmServiceURL(); serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol(); userId = agent.getScribeMetaObject().getCrmUserId(); password = agent.getScribeMetaObject().getCrmPassword(); sessionId = agent.getScribeMetaObject().getCrmSessionId(); crmPort = agent.getScribeMetaObject().getCrmPort(); } /* Create Zen desk URL */ final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/search.xml"; logger.debug( "----Inside searchAllTypeOfObjects zenDeskURL: " + zenDeskURL + " & sessionId: " + sessionId); /* Instantiate get method */ getMethod = new GetMethod(zenDeskURL); /* Set request content type */ getMethod.addRequestHeader("Content-Type", "application/xml"); /* Cookie is required to be set in case of search */ getMethod.addRequestHeader("Cookie", sessionId); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)), new UsernamePasswordCredentials(userId, password)); /* Check if user has not provided a valid query */ if (ZDCRMMessageFormatUtils.validateQuery(query)) { getMethod.setQueryString(new NameValuePair[] { new NameValuePair("query", ZDCRMMessageFormatUtils.createZDQuery(query)) }); } /* Execute method */ int result = httpclient.executeMethod(getMethod); logger.debug("----Inside searchAllTypeOfObjects response code: " + result + " & body: " + getMethod.getResponseBodyAsString()); if (result == HttpStatus.SC_OK) { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(getMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing all nodes value */ final XPathExpression expr = xpath.compile("/records/record"); /* Get node list from resposne document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>(); /* Get select field list */ List<String> selectFieldList = null; /* Check if user is asking for all fields */ if (select != null && !select.equalsIgnoreCase(HTTPConstants.allCRMObjectFields)) { selectFieldList = ZDCRMMessageFormatUtils.createSelectFieldList(select); } /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Get node from node list */ final Node node = nodeList.item(i); /* Create new Scribe object */ final ScribeObject cADbject = new ScribeObject(); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* Create list of elements */ final List<Element> elementList = new ArrayList<Element>(); for (int j = 0; j < subNodeList.getLength(); j++) { /* Get all subnodes */ final Node subNode = subNodeList.item(j); /* This trick is to avoid empty nodes */ if (!subNode.getNodeName().contains("#text")) { if (selectFieldList != null) { /* Add only user requested fields */ if (selectFieldList.contains(subNode.getNodeName().trim().toUpperCase())) { /* Create element from response */ final Element element = ZDCRMMessageFormatUtils.createMessageElement( subNode.getNodeName(), subNode.getTextContent()); /* Add element in list */ elementList.add(element); } } else { /* Create element from response */ final Element element = ZDCRMMessageFormatUtils .createMessageElement(subNode.getNodeName(), subNode.getTextContent()); /* Add element in list */ elementList.add(element); } } } /* Add all CRM fields */ cADbject.setXmlContent(elementList); /* Add Scribe object in list */ cADbjectList.add(cADbject); } } /* Check if no record found */ if (cADbjectList.size() == 0) { throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk"); } /* Set the final object in command object */ cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()])); } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED || result == HttpStatus.SC_NOT_ACCEPTABLE) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : " + ZDCRMMessageFormatUtils.getErrorFromResponse(getMethod.getResponseBodyAsStream())); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM"); } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct"); } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } catch (final Exception e) { throw new ScribeException(ScribeResponseCodes._1000 + "Problem while communicating with Zendesk CRM", e); } finally { /* Release connection socket */ if (getMethod != null) { getMethod.releaseConnection(); } } return cADCommandObject; }
From source file:edu.umd.cs.guitar.replayer.Replayer.java
/** * Get container window corresponding to a given widget ID. * This function looks up the GUI structure to extract the * window title of the window containing the widget. * * @param sWidgetID Widget ID for which container window is required * @return String Window title of window containing sWidgetID *///from w ww . j ava 2s . c o m String getWindowName(String sWidgetID) { String sWindowName = null; XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr; Object result; NodeList nodes; try { String xpathExpression = "/GUIStructure/GUI[Container//Property[Name=\"" + GUITARConstants.ID_TAG_NAME + "\" and Value=\"" + sWidgetID + "\"]]/Window/Attributes/Property[Name=\"" + GUITARConstants.TITLE_TAG_NAME + "\"]/Value/text()"; GUITARLog.log.info("The xpath is " + xpathExpression); expr = xpath.compile(xpathExpression); result = expr.evaluate(docGUI, XPathConstants.NODESET); nodes = (NodeList) result; GUITARLog.log.info("There are " + nodes.getLength() + " matching " + "nodes"); if (nodes.getLength() > 0) { sWindowName = nodes.item(0).getNodeValue(); } } catch (XPathExpressionException e) { /* * Not propagating. Return value is set to NULL instead. Caller * must * check. */ GUITARLog.log.error("Error in XPath Expression", e); } log.info("Returning window name of " + sWindowName); return sWindowName; }
From source file:org.openmrs.module.sdmxhddataexport.web.controller.dataelement.DataElementController.java
@RequestMapping(value = "/module/sdmxhddataexport/listDataElement.form", method = RequestMethod.POST) public String deleteDataElement(@RequestParam(value = "ids", required = false) String[] ids, @RequestParam(value = "files", required = false) MultipartFile uploadItem, HttpServletRequest request, @RequestParam(value = "upload", required = false) String upload, @RequestParam(value = "IncludeQueries", required = false) String IncludeQueries, Object command, SessionStatus status) {//from w w w .j a v a2 s .co m String temp = ""; HttpSession httpSession = request.getSession(); Integer dataElementId = null; System.out.println(" done " + upload); if (upload != null) { System.out.println("1st part truly done"); //FileUpload file = uploadItem; String fileName = ""; if (uploadItem != null) { fileName = uploadItem.getOriginalFilename(); System.out.println("2nd part truly done " + fileName); byte[] byteArray = null; try { byteArray = uploadItem.getBytes(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Bad file name"); e.printStackTrace(); } String data = new String(byteArray); System.out.println("3rd part truly done " + data); XPath xpath = XPathFactory.newInstance().newXPath(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = domFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = null; try { doc = builder.parse(uploadItem.getInputStream()); } catch (SAXException e1) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Unsupported Document type is uploaded "); //or we can use httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "sdmxhddataexport.UploadedFile.Wrong" ); return "redirect:/module/sdmxhddataexport/listDataElement.form"; } catch (IOException e1) { // TODO Auto-generated catch block httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "error in reading Document type "); //e1.printStackTrace(); } XPathExpression expr = null; XPathExpression exprDesc = null; XPathExpression exprQuery = null; try { expr = xpath.compile( "//*[local-name(.)='CodeList' and @id='CL_DATAELEMENT']/*[local-name(.)='Code']"); exprDesc = xpath.compile("//[local-name(.)='Description']"); exprQuery = xpath.compile("//[local-name(.)='Query']"); } catch (XPathExpressionException e) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document "); } Object result = null; try { result = expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document "); // e.printStackTrace(); } NodeList nodes = (NodeList) result; ArrayList<DataElement> dataElements = new ArrayList<DataElement>(); for (int i = 0; i < nodes.getLength(); i++) { boolean putItIn = false; DataElement de = new DataElement(); System.out.println(nodes.item(i).getLocalName()); NamedNodeMap nmp = nodes.item(i).getAttributes(); System.out.println(nmp.getNamedItem("value").getNodeValue() + " hellooo.."); de.setCode(nmp.getNamedItem("value").getNodeValue()); //Node tempNode = (Node)nodes.item(i); NodeList innerNodeList = nodes.item(i).getChildNodes(); System.out.println("length: " + innerNodeList.getLength()); for (int j = 0; j < innerNodeList.getLength(); j++) { if (innerNodeList.item(j).getLocalName() != null) { System.out.println("hehe " + innerNodeList.item(j).getLocalName()); if (innerNodeList.item(j).getLocalName().equals(new String("Description"))) { System.out.println("Description: " + innerNodeList.item(j).getTextContent()); de.setName(innerNodeList.item(j).getTextContent()); putItIn = true; } if (innerNodeList.item(j).getLocalName().equals(new String("Query")) && IncludeQueries != null) { System.out.println("Query: " + innerNodeList.item(j).getTextContent()); de.setSqlQuery(innerNodeList.item(j).getTextContent()); } } } if (putItIn) { boolean bool; DataElementValidator valid = new DataElementValidator(); bool = valid.fileValidate(de); if (bool == true) dataElements.add(de); } } ListIterator<DataElement> li = dataElements.listIterator(); DataElement de; while (li.hasNext()) { de = (DataElement) li.next(); System.out.println("Element 1 = " + de.getName()); de.setCreatedOn(new java.util.Date()); de.setCreatedBy(Context.getAuthenticatedUser().getGivenName()); SDMXHDDataExportService sDMXHDDataExportService = Context .getService(SDMXHDDataExportService.class); sDMXHDDataExportService.saveDataElement(de); } status.setComplete(); } return "redirect:/module/sdmxhddataexport/listDataElement.form"; } try { SDMXHDDataExportService sDMXHDDataExportService = Context.getService(SDMXHDDataExportService.class); if (ids != null && ids.length > 0) { for (String sId : ids) { dataElementId = Integer.parseInt(sId); if (dataElementId != null && dataElementId > 0 && CollectionUtils.isEmpty( sDMXHDDataExportService.listReportDataElement(null, dataElementId, null, 0, 1))) { sDMXHDDataExportService .deleteDataElement(sDMXHDDataExportService.getDataElementById(dataElementId)); } else { //temp += "We can't delete store="+store.getName()+" because that store is using please check <br/>"; temp = "This dataElement cannot be deleted as it is in use"; } } } } catch (Exception e) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Can not delete dataElement "); log.error(e); } httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp); return "redirect:/module/sdmxhddataexport/listDataElement.form"; }
From source file:com.portfolio.data.attachment.XSLService.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { /**/*from ww w. jav a2 s . c o m*/ * Format demand: * <convert> * <portfolioid>{uuid}</portfolioid> * <portfolioid>{uuid}</portfolioid> * <nodeid>{uuid}</nodeid> * <nodeid>{uuid}</nodeid> * <documentid>{uuid}</documentid> * <xsl>{rpertoire}{fichier}</xsl> * <format>[pdf rtf xml ...]</format> * <parameters> * <maVar1>lala</maVar1> * ... * </parameters> * </convert> */ try { //On initialise le dataProvider Connection c = null; //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } String origin = request.getRequestURL().toString(); /// Variable stuff int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } /// TODO: A voire si un form get ne ferait pas l'affaire aussi /// On lis le xml /* BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while( (line = rd.readLine()) != null ) sb.append(line); DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document doc=null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); } catch( Exception e ) { e.printStackTrace(); } /// On lit les paramtres NodeList portfolioNode = doc.getElementsByTagName("portfolioid"); NodeList nodeNode = doc.getElementsByTagName("nodeid"); NodeList documentNode = doc.getElementsByTagName("documentid"); NodeList xslNode = doc.getElementsByTagName("xsl"); NodeList formatNode = doc.getElementsByTagName("format"); NodeList parametersNode = doc.getElementsByTagName("parameters"); //*/ // String xslfile = xslNode.item(0).getTextContent(); String xslfile = request.getParameter("xsl"); String format = request.getParameter("format"); // String format = formatNode.item(0).getTextContent(); String parameters = request.getParameter("parameters"); String documentid = request.getParameter("documentid"); String portfolios = request.getParameter("portfolioids"); String[] portfolioid = null; if (portfolios != null) portfolioid = portfolios.split(";"); String nodes = request.getParameter("nodeids"); String[] nodeid = null; if (nodes != null) nodeid = nodes.split(";"); System.out.println("PARAMETERS: "); System.out.println("xsl: " + xslfile); System.out.println("format: " + format); System.out.println("user: " + userId); System.out.println("portfolioids: " + portfolios); System.out.println("nodeids: " + nodes); System.out.println("parameters: " + parameters); boolean redirectDoc = false; if (documentid != null) { redirectDoc = true; System.out.println("documentid @ " + documentid); } boolean usefop = false; String ext = ""; if (MimeConstants.MIME_PDF.equals(format)) { usefop = true; ext = ".pdf"; } else if (MimeConstants.MIME_RTF.equals(format)) { usefop = true; ext = ".rtf"; } //// Paramtre portfolio-uuid et file-xsl // String uuid = request.getParameter("uuid"); // String xslfile = request.getParameter("xsl"); StringBuilder aggregate = new StringBuilder(); try { int portcount = 0; int nodecount = 0; // On aggrge les donnes if (portfolioid != null) { portcount = portfolioid.length; for (int i = 0; i < portfolioid.length; ++i) { String p = portfolioid[i]; String portfolioxml = dataProvider .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0) .toString(); aggregate.append(portfolioxml); } } if (nodeid != null) { nodecount = nodeid.length; for (int i = 0; i < nodeid.length; ++i) { String n = nodeid[i]; String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "") .toString(); aggregate.append(nodexml); } } // Est-ce qu'on a eu besoin d'aggrger les donnes? String input = aggregate.toString(); String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration input = input.replaceAll(pattern, ""); input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet [" + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \"" + servletDir + "xhtml-symbol.ent\">" + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters "<root>" + input + "</root>"; // System.out.println("INPUT WITH PROXY:"+ input); /// Rsolution des proxys DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(input)); Document doc = documentBuilder.parse(is); /// Proxy stuff XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//asmResource[@xsi_type='Proxy']"; String filterCode = "./code/text()"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); XPathExpression codeFilter = xPath.compile(filterCode); for (int i = 0; i < nodelist.getLength(); ++i) { Node res = nodelist.item(i); Node gp = res.getParentNode(); // resource -> context -> container Node ggp = gp.getParentNode(); Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE); /// Fetch node we want to replace String returnValue = dataProvider .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "") .toString(); Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue))); Element repNode = rep.getDocumentElement(); Node proxyNode = repNode.getFirstChild(); proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned // doc.replaceChild(proxyNode, gp); ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work. ggp.removeChild(gp); } try // Convert XML document to string { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); input = writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); } // System.out.println("INPUT DATA:"+ input); // Setup a buffer to obtain the content length ByteArrayOutputStream stageout = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); //// Setup Transformer (1st stage) /// Base path String basepath = xslfile.substring(0, xslfile.indexOf(File.separator)); String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator + "xsl" + File.separator + "html2xml.xsl"; System.out.println("FIRST: " + firstStage); Source xsltSrc1 = new StreamSource(new File(firstStage)); Transformer transformer1 = transFactory.newTransformer(xsltSrc1); StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes())); Result stageRes = new StreamResult(stageout); transformer1.transform(stageSource, stageRes); // Setup Transformer (2nd stage) String secondStage = baseDir + File.separator + xslfile; Source xsltSrc2 = new StreamSource(new File(secondStage)); Transformer transformer2 = transFactory.newTransformer(xsltSrc2); // Configure parameter from xml String[] table = parameters.split(";"); for (int i = 0; i < table.length; ++i) { String line = table[i]; int var = line.indexOf(":"); String par = line.substring(0, var); String val = line.substring(var + 1); transformer2.setParameter(par, val); } // Setup input StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes())); // StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") ); Result res = null; if (usefop) { /// FIXME: Might need to include the entity for html stuff? //Setup FOP //Make sure the XSL transformation's result is piped through to FOP Fop fop = fopFactory.newFop(format, out); res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } else { res = new StreamResult(out); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } if (redirectDoc) { // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String urlTarget = "http://" + server + "/resources/resource/file/" + documentid; System.out.println("Redirect @ " + urlTarget); HttpClientBuilder clientbuilder = HttpClientBuilder.create(); CloseableHttpClient client = clientbuilder.build(); HttpPost post = new HttpPost(urlTarget); post.addHeader("referer", origin); String sessionid = request.getSession().getId(); System.out.println("Session: " + sessionid); post.addHeader("Cookie", "JSESSIONID=" + sessionid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext); builder.addPart("uploadfile", body); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse ret = client.execute(post); String stringret = new BasicResponseHandler().handleResponse(ret); int code = ret.getStatusLine().getStatusCode(); response.setStatus(code); ServletOutputStream output = response.getOutputStream(); output.write(stringret.getBytes(), 0, stringret.length()); output.close(); client.close(); /* HttpURLConnection connection = CreateConnection( urlTarget, request ); /// Helping construct Json connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); RetrieveAnswer(connection, response, origin); //*/ } else { response.reset(); response.setHeader("Content-Disposition", "attachment; filename=generated" + ext); response.setContentType(format); response.setContentLength(out.size()); response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } } catch (Exception e) { String message = e.getMessage(); response.setStatus(500); response.getOutputStream().write(message.getBytes()); response.getOutputStream().close(); e.printStackTrace(); } finally { dataProvider.disconnect(); } }
From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java
@Override public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject) throws Exception { logger.debug("----Inside getObjects"); /* Check if all record types are to be searched */ if (cADCommandObject.getObjectType().trim().equalsIgnoreCase(HTTPConstants.anyObject)) { return this.searchAllTypeOfObjects(cADCommandObject, null, null, null); } else {//from ww w . j av a 2s .c o m GetMethod getMethod = null; try { String serviceURL = null; String serviceProtocol = null; String userId = null; String password = null; String crmPort = "80"; /* Check if agent is present in request */ if (cADCommandObject.getCrmUserId() != null) { /* Get agent from session manager */ final ScribeCacheObject cacheObject = zDCRMSessionManager .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId()); /* Get CRM information from agent */ serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL(); serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol(); userId = cacheObject.getScribeMetaObject().getCrmUserId(); password = cacheObject.getScribeMetaObject().getCrmPassword(); crmPort = cacheObject.getScribeMetaObject().getCrmPort(); } /* Create Zen desk URL */ final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType() + "s.xml"; logger.debug("----Inside getObjects zenDeskURL: " + zenDeskURL); /* Instantiate get method */ getMethod = new GetMethod(zenDeskURL); /* Set request content type */ getMethod.addRequestHeader("Content-Type", "application/xml"); getMethod.addRequestHeader("accept", "application/xml"); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)), new UsernamePasswordCredentials(userId, password)); /* Execute method */ int result = httpclient.executeMethod(getMethod); logger.debug("----Inside getObjects response code: " + result + " & body: " + getMethod.getResponseBodyAsString()); if (result == HttpStatus.SC_OK) { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(getMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing all nodes value */ final XPathExpression expr = xpath.compile( "/" + cADCommandObject.getObjectType() + "s/" + cADCommandObject.getObjectType()); /* Get node list from response document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); /* Create new Scribe object list */ final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>(); /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Create list of elements */ final List<Element> elementList = new ArrayList<Element>(); /* Get node from node list */ final Node node = nodeList.item(i); /* Create new Scribe object */ final ScribeObject cADbject = new ScribeObject(); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* Iterate over sub node list and create elements */ for (int j = 0; j < subNodeList.getLength(); j++) { final Node subNode = subNodeList.item(j); /* This trick is to avoid empty nodes */ if (!subNode.getNodeName().contains("#text")) { /* Create element from response */ final Element element = ZDCRMMessageFormatUtils .createMessageElement(subNode.getNodeName(), subNode.getTextContent()); /* Add element in list */ elementList.add(element); } } } /* Add all CRM fields */ cADbject.setXmlContent(elementList); /* Add Scribe object in list */ cADbjectList.add(cADbject); } /* Check if no record found */ if (cADbjectList.size() == 0) { throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk"); } /* Set the final object in command object */ cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()])); } else if (result == HttpStatus.SC_FORBIDDEN) { throw new ScribeException(ScribeResponseCodes._1020 + "Query is forbidden by Zendesk CRM"); } else if (result == HttpStatus.SC_BAD_REQUEST) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content"); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException( ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM"); } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (getMethod != null) { getMethod.releaseConnection(); } } return cADCommandObject; } }
From source file:org.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetriever.java
/** * Loads the portlet.xml file using the configured <tt>ResourceLoader</tt> and * parses the role-name elements from it, using these as the set of <tt>mappableAttributes</tt>. *///from w w w .ja v a 2s. c o m public void afterPropertiesSet() throws Exception { Resource portletXml = resourceLoader.getResource("/WEB-INF/portlet.xml"); Document doc = getDocument(portletXml.getInputStream()); final XPathExpression roleNamesExpression; if (portletConfig == null) { final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); roleNamesExpression = xPath.compile("/portlet-app/portlet/security-role-ref/role-name"); } else { final XPathFactory xPathFactory = XPathFactory.newInstance(); xPathFactory.setXPathVariableResolver(new XPathVariableResolver() { @Override public Object resolveVariable(QName variableName) { if ("portletName".equals(variableName.getLocalPart())) { return portletConfig.getPortletName(); } return null; } }); final XPath xPath = xPathFactory.newXPath(); roleNamesExpression = xPath .compile("/portlet-app/portlet[portlet-name=$portletName]/security-role-ref/role-name"); } final NodeList securityRoles = (NodeList) roleNamesExpression.evaluate(doc, XPathConstants.NODESET); final Set<String> roleNames = new HashSet<String>(); for (int i = 0; i < securityRoles.getLength(); i++) { Element secRoleElt = (Element) securityRoles.item(i); String roleName = secRoleElt.getTextContent().trim(); roleNames.add(roleName); logger.info("Retrieved role-name '" + roleName + "' from portlet.xml"); } if (roleNames.isEmpty()) { logger.info("No security-role-ref elements found in " + portletXml + (portletConfig == null ? "" : " for portlet " + portletConfig.getPortletName())); } mappableAttributes = Collections.unmodifiableSet(roleNames); }
From source file:erwins.util.repack.xml.XMLBuilder.java
/** * Return the result of evaluating an XPath query on the builder's DOM * using the given namespace. Returns null if the query finds nothing, * or finds a node that does not match the type specified by returnType. * * @param xpath// www . j ava2s . c o m * an XPath expression * @param type * the type the XPath is expected to resolve to, e.g: * {@link XPathConstants#NODE}, {@link XPathConstants#NODESET}, * {@link XPathConstants#STRING}. * @param nsContext * a mapping of prefixes to namespace URIs that allows the XPath expression * to use namespaces, or null for a non-namespaced document. * * @return * a builder node representing the first Element that matches the * XPath expression. * * @throws XPathExpressionException * If the XPath is invalid, or if does not resolve to at least one * {@link Node#ELEMENT_NODE}. */ public Object xpathQuery(String xpath, QName type, NamespaceContext nsContext) throws XPathExpressionException { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xPath = xpathFactory.newXPath(); if (nsContext != null) { xPath.setNamespaceContext(nsContext); } XPathExpression xpathExp = xPath.compile(xpath); try { return xpathExp.evaluate(this.xmlNode, type); } catch (IllegalArgumentException e) { // Thrown if item found does not match expected type return null; } }