List of usage examples for javax.xml.xpath XPathConstants STRING
QName STRING
To view the source code for javax.xml.xpath XPathConstants STRING.
Click Source Link
The XPath 1.0 string data type.
Maps to Java String .
From source file:eu.europa.esig.dss.DSSXMLUtils.java
/** * Returns the String value of the corresponding to the XPath query. * * @param xmlNode The node where the search should be performed. * @param xPathString XPath query string * @return string value of the XPath query * @throws XPathExpressionException//from w w w .ja va2 s .c o m */ public static String getValue(final Node xmlNode, final String xPathString) { try { final XPathExpression xPathExpression = createXPathExpression(xPathString); final String string = (String) xPathExpression.evaluate(xmlNode, XPathConstants.STRING); return string.trim(); } catch (XPathExpressionException e) { throw new DSSException(e); } }
From source file:com.esri.gpt.server.openls.provider.services.route.DetermineRouteProvider.java
/** * /*w w w . j a v a 2 s .c o m*/ * @param context * @param ndReq * @param xpath * @throws Exception */ private void parseRequest(OperationContext context, Node ndReq, XPath xpath) throws Exception { DetermineRouteParams routeParams = new DetermineRouteParams(); Node ndRoutePlan = (Node) xpath.evaluate("xls:RoutePlan", ndReq, XPathConstants.NODE); if (ndRoutePlan != null) { RoutePlan routePlan = new RoutePlan(); Node ndRoutePreference = (Node) xpath.evaluate("xls:RoutePreference", ndRoutePlan, XPathConstants.NODE); if (ndRoutePreference != null) { routePlan.setRoutePreference(ndRoutePreference.getTextContent()); } Node ndWayPointList = (Node) xpath.evaluate("xls:WayPointList", ndRoutePlan, XPathConstants.NODE); if (ndWayPointList != null) { HashMap<String, Point> wayPointList = new HashMap<String, Point>(); Node ndStartPoint = (Node) xpath.evaluate("xls:StartPoint", ndWayPointList, XPathConstants.NODE); if (ndStartPoint != null) { Node ndStartPOI = (Node) xpath.evaluate("xls:POI", ndStartPoint, XPathConstants.NODE); if (ndStartPOI != null) { ndStartPoint = ndStartPOI; } Node ndStartPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndStartPoint, XPathConstants.NODE); Point point = new Point(); if (ndStartPos != null) { String[] coords = ndStartPos.getTextContent().split(" "); point.setX(coords[0]); point.setY(coords[1]); } else { geocode(context, ndStartPoint, xpath, point); } wayPointList.put("start", point); } Node ndViaPoint = (Node) xpath.evaluate("xls:ViaPoint", ndWayPointList, XPathConstants.NODE); if (ndViaPoint != null) { Node ndViaPOI = (Node) xpath.evaluate("xls:POI", ndStartPoint, XPathConstants.NODE); if (ndViaPOI != null) { ndViaPoint = ndViaPOI; } Point point = new Point(); Node ndViaPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndViaPoint, XPathConstants.NODE); if (ndViaPos != null) { String[] coords = ndViaPos.getTextContent().split(" "); point.setX(coords[0]); point.setY(coords[1]); } else { geocode(context, ndViaPoint, xpath, point); } wayPointList.put("via", point); } Node ndEndPoint = (Node) xpath.evaluate("xls:EndPoint", ndWayPointList, XPathConstants.NODE); if (ndEndPoint != null) { Node ndEndPOI = (Node) xpath.evaluate("xls:POI", ndEndPoint, XPathConstants.NODE); if (ndEndPOI != null) { ndEndPoint = ndEndPOI; } Node ndEndPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndEndPoint, XPathConstants.NODE); Point point = new Point(); if (ndEndPos != null) { String[] coords = ndEndPos.getTextContent().split(" "); point.setX(coords[0]); point.setY(coords[1]); } else { geocode(context, ndEndPoint, xpath, point); } wayPointList.put("end", point); } routePlan.setWayPointList(wayPointList); } Node ndAvoidList = (Node) xpath.evaluate("xls:AvoidList", ndRoutePlan, XPathConstants.NODE); if (ndAvoidList != null) { Node ndAvoidPOI = (Node) xpath.evaluate("xls:POI", ndAvoidList, XPathConstants.NODE); if (ndAvoidPOI != null) { ndAvoidList = ndAvoidPOI; } HashMap<String, Point> avoidPointList = new HashMap<String, Point>(); Node ndStartPos = (Node) xpath.evaluate("xls:Position/gml:Point/gml:pos", ndAvoidList, XPathConstants.NODE); Point point = new Point(); if (ndStartPos != null) { String[] coords = ndStartPos.getTextContent().split(" "); point.setX(coords[0]); point.setY(coords[1]); } else { geocode(context, ndAvoidList, xpath, point); } avoidPointList.put("avoid", point); routePlan.setAvoidPointList(avoidPointList); } routeParams.setRoutePlan(routePlan); } Node ndRouteInst = (Node) xpath.evaluate("xls:RouteInstructionsRequest", ndReq, XPathConstants.NODE); if (ndRouteInst != null) { RouteInstructionsRequest routeInst = new RouteInstructionsRequest(); String format = (String) xpath.evaluate("@format", ndRouteInst, XPathConstants.STRING); String provideGeometry = (String) xpath.evaluate("@provideGeometry", ndRouteInst, XPathConstants.STRING); routeInst.setFormat(format); routeInst.setProvideGeometry(provideGeometry); routeParams.setRouteInstructions(routeInst); } Node ndRouteMap = (Node) xpath.evaluate("xls:RouteMapRequest", ndReq, XPathConstants.NODE); if (ndRouteMap != null) { RouteMap routeMap = new RouteMap(); Node ndOutput = (Node) xpath.evaluate("xls:Output", ndRouteMap, XPathConstants.NODE); if (ndOutput != null) { ImageOutput imgOutput = new ImageOutput(); Output output = new Output(); String format = (String) xpath.evaluate("@format", ndOutput, XPathConstants.STRING); String width = (String) xpath.evaluate("@width", ndOutput, XPathConstants.STRING); String height = (String) xpath.evaluate("@height", ndOutput, XPathConstants.STRING); output.setFormat(format); output.setWidth(width); output.setHeight(height); imgOutput.setOutput(output); routeMap.setImageOutput(imgOutput); } routeParams.setRouteMap(routeMap); } context.getRequestOptions().setDetermineRouteParams(routeParams); }
From source file:com.espertech.esper.regression.event.TestNoSchemaXMLEvent.java
public void testNestedXMLDOMGetter() throws Exception { Configuration configuration = SupportConfigFactory.getConfiguration(); ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM(); xmlDOMEventTypeDesc.setRootElementName("a"); xmlDOMEventTypeDesc.addXPathProperty("element1", "/a/b/c", XPathConstants.STRING); configuration.addEventType("AEvent", xmlDOMEventTypeDesc); epService = EPServiceProviderManager.getDefaultProvider(configuration); epService.initialize();/*w w w. j av a 2 s . c o m*/ updateListener = new SupportUpdateListener(); String stmt = "select b.c as type, element1, result1 from AEvent"; EPStatement joinView = epService.getEPAdministrator().createEPL(stmt); joinView.addListener(updateListener); sendXMLEvent("<a><b><c></c></b></a>"); EventBean theEvent = updateListener.assertOneGetNewAndReset(); assertEquals("", theEvent.get("type")); assertEquals("", theEvent.get("element1")); sendXMLEvent("<a><b></b></a>"); theEvent = updateListener.assertOneGetNewAndReset(); assertEquals(null, theEvent.get("type")); assertEquals("", theEvent.get("element1")); sendXMLEvent("<a><b><c>text</c></b></a>"); theEvent = updateListener.assertOneGetNewAndReset(); assertEquals("text", theEvent.get("type")); assertEquals("text", theEvent.get("element1")); }
From source file:com.mnxfst.testing.client.TSClientPlanResultCollectCallable.java
/** * Parses the long value referenced by the given query * @param rootNode/* ww w. j a va2 s. co m*/ * @param query * @param xpath * @return * @throws TSClientExecutionException */ protected long parseLongValue(Node rootNode, String query, XPath xpath) throws TSClientExecutionException { String tmp = null; try { tmp = (String) xpath.evaluate(query, rootNode, XPathConstants.STRING); } catch (XPathExpressionException e) { throw new TSClientExecutionException("Failed to parse out value for '" + query + "' from document received from " + httpHost.getHostName()); } if (tmp != null && !tmp.isEmpty()) { try { return Long.parseLong(tmp); } catch (NumberFormatException e) { throw new TSClientExecutionException("Failed to parse the string '" + tmp + "' into a valid numerical value received through query '" + query + "'. Returning host: " + httpHost.getHostName()); } } throw new TSClientExecutionException( "No valid value found for '" + query + "' from document received from " + httpHost.getHostName()); }
From source file:de.bayern.gdi.services.CatalogService.java
private String getServiceURL(Node serviceNode) { String onLineExpr = "gmd:distributionInfo" + "/gmd:MD_Distribution" + "/gmd:transferOptions" + "/gmd:MD_DigitalTransferOptions" + "/gmd:onLine"; NodeList onlineNL = (NodeList) XML.xpath(serviceNode, onLineExpr, XPathConstants.NODESET, context); for (int j = 0; j < onlineNL.getLength(); j++) { Node onlineN = onlineNL.item(j); String urlExpr = "gmd:CI_OnlineResource" + GMD_LINKAGE + GMD_URL; String onLineserviceURL = (String) XML.xpath(onlineN, urlExpr, XPathConstants.STRING, context); String applicationprofileExpr = "gmd:CI_OnlineResource" + "/gmd:applicationProfile" + GCO_CHARACTER_STRING;//from ww w.j a va 2 s . com String applicationProfile = (String) XML.xpath(onlineN, applicationprofileExpr, XPathConstants.STRING, context); applicationProfile = applicationProfile.toLowerCase(); if (applicationProfile.equals("wfs-url") || applicationProfile.equals("feed-url") || applicationProfile.equals("dienste-url") || applicationProfile.equals("download")) { return onLineserviceURL; } } String operationMetaDataExpr = GMD_IDENTIFICATION_INFO + SRV_SV_SERVICE_IDENTIFICATION + "/srv:containsOperations"; NodeList operationsMetadataNL = (NodeList) XML.xpath(serviceNode, operationMetaDataExpr, XPathConstants.NODESET, context); Node firstNode = null; for (int j = 0; j < operationsMetadataNL.getLength(); j++) { Node operationMetadataNode = operationsMetadataNL.item(j); if (j == 0) { firstNode = operationMetadataNode; } String operationsNameExpr = SV_OPERATION_METADATA + "/srv:operationName" + GCO_CHARACTER_STRING; String applicationProfile = (String) XML.xpath(operationMetadataNode, operationsNameExpr, XPathConstants.STRING, context); if (applicationProfile.equalsIgnoreCase("getcapabilities")) { String operationsURLExpr = SV_OPERATION_METADATA + "/srv:connectPoint" + "/gmd:CI_OnlineResource" + GMD_LINKAGE + GMD_URL; String operationsURL = (String) XML.xpath(operationMetadataNode, operationsURLExpr, XPathConstants.STRING, context); if (!operationsURL.isEmpty()) { return operationsURL; } } } if (firstNode != null) { String operationsURLExpr = SV_OPERATION_METADATA + "/srv:connectPoint" + "/gmd:CI_OnlineResource" + GMD_LINKAGE + GMD_URL; return (String) XML.xpath(firstNode, operationsURLExpr, XPathConstants.STRING, context); } return null; }
From source file:hudson.plugins.plot.XMLSeries.java
/** * Convert a given object into a String. * //from w w w. jav a 2 s . co m * @param obj * Xpath Object * @return String representation of the node */ private String nodeToString(Object obj) { String ret = null; if (nodeType == XPathConstants.BOOLEAN) { return (((Boolean) obj)) ? "1" : "0"; } if (nodeType == XPathConstants.NUMBER) return ((Double) obj).toString().trim(); if (nodeType == XPathConstants.NODE || nodeType == XPathConstants.NODESET) { if (obj instanceof String) { ret = ((String) obj).trim(); } else { if (null == obj) { return null; } Node node = (Node) obj; NamedNodeMap nodeMap = node.getAttributes(); if ((null != nodeMap) && (null != nodeMap.getNamedItem("time"))) { ret = nodeMap.getNamedItem("time").getTextContent(); } if (null == ret) { ret = node.getTextContent().trim(); } } } if (nodeType == XPathConstants.STRING) ret = ((String) obj).trim(); // for Node/String/NodeSet, try and parse it as a double. // we don't store a double, so just throw away the result. Scanner scanner = new Scanner(ret); if (scanner.hasNextDouble()) { return String.valueOf(scanner.nextDouble()); } return null; }
From source file:org.ala.harvester.FlickrHarvester.java
/** * Process a single image, do the document mapping etc * /* w w w . ja va 2 s .co m*/ * @param infosourceId * @param imageIndex * @param currentResDom * @throws Exception */ private boolean processSingleImage(int infosourceId, int imageIndex, Document currentResDom) throws Exception { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); String xPathToPhotoId = "/rsp/photos/photo[" + imageIndex + "]/@id"; String photoId = (String) xpath.evaluate(xPathToPhotoId, currentResDom, XPathConstants.STRING); logger.info("Handling photo ID: " + photoId); final String flickrMethod = "flickr.photos.getInfo"; // Calls the Flickr's Photo Info API to determine whether the photo // comes from Australia or not. String photoInfoFlickrUrl = this.flickrRestBaseUrl + "/" + "?method=" + flickrMethod + "&" + "api_key=" + this.flickrApiKey + "&" + "photo_id=" + photoId; System.out.println("PHOTO URL:" + photoInfoFlickrUrl); org.w3c.dom.Document photoInfoDom = null; // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod(photoInfoFlickrUrl); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); method.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "UTF-8"); method.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8"); logger.debug( "Fetching info. for photo with ID " + photoId + " from " + "`" + photoInfoFlickrUrl + "`" + "\n"); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { String errMsg = "HTTP GET to " + "`" + photoInfoFlickrUrl + "`" + " returned non HTTP OK code. " + "Returned code " + statusCode + " and message " + method.getStatusLine() + "\n"; method.releaseConnection(); logger.error(errMsg); throw new Exception(errMsg); } InputStream responseStream = method.getResponseBodyAsStream(); // Instantiates a DOM builder to create a DOM of the response. DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); photoInfoDom = domBuilder.parse(responseStream); } catch (Exception domCreationErr) { throw new Exception("Failed to create DOM representation of GET response.", domCreationErr); } finally { // Release the connection. method.releaseConnection(); } // Check for Flickr's error. if (!isDocExtractionSuccessful(photoInfoDom)) { throw new Exception("Flickr error response for fetching single image information."); } if (System.getProperty("overwrite") != null && "false".equals(System.getProperty("overwrite"))) { String photoPageUrl = (String) xpath.evaluate("/rsp/photo/urls/url[@type=\"photopage\"]/text()", photoInfoDom, XPathConstants.STRING); logger.debug("photo page URL: " + photoPageUrl); org.ala.model.Document doc = this.repository.getDocumentByGuid(photoPageUrl); if (doc != null) { logger.debug("Document with URI already harvested. Skipping: " + photoPageUrl); return true; } } // Determines whether photo has geo-coded tag from Australia. // If so, pass onto DocumentMapper. if (isPhotoFromAustralia(photoInfoDom)) { try { String document = (DOMUtils.domToString(photoInfoDom)); // FIXME flickr GUID ??? List<ParsedDocument> parsedDocs = documentMapper.map("", document.getBytes()); for (ParsedDocument parsedDoc : parsedDocs) { this.repository.storeDocument(infosourceId, parsedDoc); debugParsedDoc(parsedDoc); } return false; } catch (Exception docMapperErr) { // Skipping over errors here and proceeding to next document. logger.error("Problem processing image. " + docMapperErr.toString() + ", Problem processing: " + photoInfoFlickrUrl, docMapperErr); } } else { logger.debug("Photo is unAustralian: " + photoInfoFlickrUrl); } return false; }
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 www . jav a 2 s . c o 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:org.ala.harvester.WikipediaImageHarvester.java
private String getSingleXPathValue(Document currentResDom, String xpathAsString) throws Exception { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); return (String) xpath.evaluate(xpathAsString, currentResDom, XPathConstants.STRING); }
From source file:com.amalto.core.util.Util.java
public static String[] getKeyValuesFromItem(Element item, Collection<FieldMetadata> keyFields) throws TransformerException { XPath xPath = XPathFactory.newInstance().newXPath(); String[] ids = new String[keyFields.size()]; int i = 0;/*from w w w . j av a 2 s. com*/ for (FieldMetadata keyField : keyFields) { try { ids[i++] = (String) xPath.compile(keyField.getPath()).evaluate(item, XPathConstants.STRING); } catch (XPathExpressionException e) { throw new RuntimeException("Unable to find key value in '" + keyField.getPath() + "'.", e); } } return ids; }