List of usage examples for org.w3c.dom NamedNodeMap getNamedItem
public Node getNamedItem(String name);
From source file:edu.cornell.mannlib.semservices.service.impl.AgrovocService.java
protected String getConceptURIFromRDF(String rdf) { String conceptUri = new String(); try {/* ww w . jav a 2 s.c o m*/ Document doc = XMLUtils.parse(rdf); NodeList nodes = doc.getElementsByTagName("skos:Concept"); Node node = nodes.item(0); NamedNodeMap attrs = node.getAttributes(); Attr idAttr = (Attr) attrs.getNamedItem("rdf:about"); conceptUri = idAttr.getTextContent(); } catch (IOException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } catch (SAXException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } catch (ParserConfigurationException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } return conceptUri; }
From source file:edu.cornell.mannlib.semservices.service.impl.AgrovocService.java
protected List<String> getConceptURIsListFromRDF(String rdf) { List<String> conceptUris = new ArrayList<String>(); try {//from ww w. ja v a2 s . c o m Document doc = XMLUtils.parse(rdf); NodeList nodes = doc.getElementsByTagName("skos:Concept"); int numberNodes = nodes.getLength(); int n; for (n = 0; n < numberNodes; n++) { Node node = nodes.item(n); NamedNodeMap attrs = node.getAttributes(); Attr idAttr = (Attr) attrs.getNamedItem("rdf:about"); String conceptUri = idAttr.getTextContent(); conceptUris.add(conceptUri); } } catch (IOException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } catch (SAXException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } catch (ParserConfigurationException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } return conceptUris; }
From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java
public List<Configuration> getConfigObjFromXml(String featureManifestXml) throws PhrescoException { List<Configuration> configs = new ArrayList<Configuration>(); try {// w ww.jav a 2 s . com File featureManifestXmlFile = new File(featureManifestXml); Configuration config = null; if (featureManifestXmlFile.isFile()) { config = new Configuration(featureManifestXmlFile.getName(), FEATURES); } else { return Collections.emptyList(); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(featureManifestXmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(CONFIG_TAG); Properties properties = new Properties(); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); // get attributes if (nNode.hasAttributes()) { NamedNodeMap attributes = nNode.getAttributes(); Node name = attributes.getNamedItem(NAME); if (name != null) { Element eElement = (Element) nNode; String defaultValue = getTagValue(DEFAULT_VALUE, eElement); String currentValue = getTagValue(CURRENT_VALUE, eElement); String value = StringUtils.isNotEmpty(currentValue) ? currentValue : defaultValue; properties.put(name.getNodeValue(), value); } } } config.setProperties(properties); configs.add(config); } catch (Exception e) { throw new PhrescoException(e); } return configs; }
From source file:org.nema.medical.mint.dcm2mint.ProcessImportDir.java
private StudyQueryInfo doesStudyExist(final String studyInstanceUID, final String patientID) throws Exception { final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("studyInstanceUID", studyInstanceUID)); qparams.add(new BasicNameValuePair("patientID", patientID == null ? "" : patientID)); final String fullURI = queryURI + "?" + URLEncodedUtils.format(qparams, "UTF-8"); final HttpGet httpGet = new HttpGet(fullURI); final String response = httpClient.execute(httpGet, new BasicResponseHandler()); final NodeList nodeList; try {//from w ww . jav a 2 s . c o m final Document responseDoc = documentBuilder.parse(new ByteArrayInputStream(response.getBytes())); nodeList = (NodeList) xPath.evaluate("/studySearchResults/study", responseDoc, XPathConstants.NODESET); } catch (final Exception ex) { LOG.error("Querying for studyUID " + studyInstanceUID + ": unknown server response:\n" + response); throw ex; } final int uuidCount = nodeList.getLength(); switch (uuidCount) { case 0: return null; case 1: final Node node = nodeList.item(0); final StudyQueryInfo studyQueryInfo = new StudyQueryInfo(); final NamedNodeMap attrMap = node.getAttributes(); studyQueryInfo.studyUUID = attrMap.getNamedItem("studyUUID").getNodeValue(); studyQueryInfo.studyVersion = attrMap.getNamedItem("version").getNodeValue(); return studyQueryInfo; default: throw new Exception("Multiple matches for study UID " + studyInstanceUID); } }
From source file:com.konakart.actions.gateways.WorldPayXMLRedirectAction.java
public String execute() { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); // Create these outside of try / catch since they are needed in the case of a general // exception//w ww .j a v a 2 s .c o m IpnHistoryIf ipnHistory = new IpnHistory(); ipnHistory.setModuleCode(WorldPayXMLRedirect.WP_XML_REDIRECT_GATEWAY_CODE); KKAppEng kkAppEng = null; try { int custId; kkAppEng = this.getKKAppEng(request, response); custId = this.loggedIn(request, response, kkAppEng, "Checkout"); // Check to see whether the user is logged in if (custId < 0) { return KKLOGIN; } // Set the customer id for the IPN history object ipnHistory.setCustomerId(custId); // Ensure we are using the correct protocol. Redirect if not. String redirForward = checkSSL(kkAppEng, request, custId, /* forceSSL */false); if (redirForward != null) { setupResponseForSSLRedirect(response, redirForward); return null; } // Get the order OrderIf order = kkAppEng.getOrderMgr().getCheckoutOrder(); validateOrder(order, WorldPayXMLRedirect.WP_XML_REDIRECT_GATEWAY_CODE); // Set the order id for the ipnHistory object ipnHistory.setOrderId(order.getId()); PaymentDetailsIf pd = order.getPaymentDetails(); // Do the post String gatewayResp = null; try { gatewayResp = postData(pd, null); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Problem posting data to WorldPay: " + e.getMessage()); e.printStackTrace(); } // Save the ipnHistory ipnHistory.setGatewayFullResponse(e.getMessage()); ipnHistory.setKonakartResultDescription( getResultDescription("Problem posting data to WorldPay: " + e.getMessage())); ipnHistory.setKonakartResultId(RET4); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); // Redirect the user to an error screen return "CheckoutError"; } gatewayResp = URLDecoder.decode(gatewayResp, "UTF-8"); if (log.isDebugEnabled()) { log.debug("Unformatted GatewayResp = \n" + gatewayResp); } // Should look similar to: // <?xml version="1.0" encoding="UTF-8"?> // <!DOCTYPE paymentService PUBLIC "-//WorldPay//DTD WorldPay PaymentService v1//EN" // "http://dtd.worldpay.com/paymentService_v1.dtd"> // <paymentService version="1.4" merchantCode="MERCHANT"> // <reply> // <orderStatus orderCode="1315239998049"> // <reference id="123678374"> // https://secure-test.worldpay.com/jsp/shopper/SelectPaymentMethod.jsp?OrderKey=MERCHANT^1315239998049 // </reference> // </orderStatus> // </reply> // </paymentService> // Now process the XML response String redirectUrl = null; try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); ByteArrayInputStream bais = new ByteArrayInputStream(gatewayResp.getBytes()); Document doc = builder.parse(bais); // get all elements NodeList list = doc.getElementsByTagName("*"); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); String name = node.getNodeName(); if (name.equals("reference")) { Text textnode = (Text) node.getFirstChild(); String value = ""; if (textnode != null) { value = textnode.getNodeValue(); } redirectUrl = value; break; } else if (name.equals("error")) { String errorCode = ""; NamedNodeMap map = node.getAttributes(); Node attrNode = map.getNamedItem("code"); if (attrNode != null) { errorCode = attrNode.getNodeValue(); } Text textnode = (Text) node.getFirstChild(); String errorDesc = ""; if (textnode != null) { errorDesc = textnode.getNodeValue(); } // Save the ipnHistory ipnHistory.setGatewayFullResponse(gatewayResp); ipnHistory.setKonakartResultDescription(getResultDescription( "Error from WorldPay: Code = " + errorCode + " Desc = " + errorDesc)); ipnHistory.setKonakartResultId(RET4); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); // Redirect the user to an error screen return "CheckoutError"; } } if (redirectUrl != null) { HashMap<String, String> hp = hashParameters(pd, null); StringBuffer redirectUrlSb = new StringBuffer(redirectUrl); CustomerIf cust = kkAppEng.getCustomerMgr().getCurrentCustomer(); if (log.isDebugEnabled()) { log.debug("Customer Locale = " + cust.getLocale()); } if (cust.getLocale() != null && cust.getLocale().length() > 3 && cust.getLocale().charAt(2) == '_') { String langCode = cust.getLocale().substring(0, 2); redirectUrlSb.append("&language="); redirectUrlSb.append(langCode); } kkAppEng.getCustomerMgr().populateCurrentCustomerAddresses(/* force */false); if (cust.getAddresses() != null && cust.getAddresses().length > 0) { int countryId = cust.getAddresses()[0].getCountryId(); CountryIf country = kkAppEng.getEng().getCountry(countryId); if (country != null && country.getIsoCode2() != null) { redirectUrlSb.append("&country="); redirectUrlSb.append(country.getIsoCode2()); } } redirectUrlSb.append("&successURL="); redirectUrlSb.append(hp.get("responseUrl") + "?retCode=success"); redirectUrlSb.append("&pendingURL="); redirectUrlSb.append(hp.get("responseUrl") + "?retCode=pending"); redirectUrlSb.append("&failureURL="); redirectUrlSb.append(hp.get("responseUrl") + "?retCode=failure"); if (log.isDebugEnabled()) { log.debug("Redirecting customer to : " + redirectUrlSb.toString()); } this.url = redirectUrlSb.toString(); return "redirect"; } throw new KKAppException("Redirect URL is null"); } catch (Exception e) { // Problems parsing the XML if (log.isWarnEnabled()) { log.warn("Problem parsing the XML WorldPay response: " + ((gatewayResp != null) ? gatewayResp : "null")); e.printStackTrace(); } // Save the ipnHistory ipnHistory.setGatewayFullResponse(gatewayResp); ipnHistory.setKonakartResultDescription( getResultDescription("Problem parsing the XML WorldPay response: " + e.getMessage())); ipnHistory.setKonakartResultId(RET4); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); // Redirect the user to an error screen return "CheckoutError"; } } catch (Exception e) { try { ipnHistory.setKonakartResultDescription(getResultDescription(RET4_DESC + e.getMessage())); ipnHistory.setKonakartResultId(RET4); if (kkAppEng != null) { kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); } } catch (KKException e1) { return super.handleException(request, e1); } return super.handleException(request, e); } }
From source file:hoot.services.models.osm.Way.java
private long parseWayNode(org.w3c.dom.Node nodeXml) { NamedNodeMap nodeXmlAttributes = nodeXml.getAttributes(); long parsedNodeId = Long.parseLong(nodeXmlAttributes.getNamedItem("ref").getNodeValue()); wayNodeIdsCache.add(parsedNodeId);// w w w . j a va 2s .c o m Coordinates nodeCoords = new Coordinates(); Map<Long, Element> parsedNodes = parsedElementIdsToElementsByType.get(ElementType.Node); // if this is a node created within the same request that is referencing // this way, it won't exist in the database, but it will be in the element cache created // when parsing the node from the request if (parsedNodeId < 0) { if (!parsedNodes.containsKey(parsedNodeId)) { // TODO: add test for this throw new IllegalArgumentException("Created way references new node not " + "found in create request with ID: " + parsedNodeId); } } // The node is referenced somewhere else in this request, so get its // info from the request, not the database b/c the database either won't have it or will have // outdated info. Only get info from the request if the node is being created/modified, as if it is // being deleted, we can just get the info from the database since its coords won't be // changing and might not be in the request (not required). long actualNodeId; if (parsedNodes.containsKey(parsedNodeId) && (parsedNodes.get(parsedNodeId).getEntityChangeType() != EntityChangeType.DELETE)) { Node node = (Node) parsedElementIdsToElementsByType.get(ElementType.Node).get(parsedNodeId); CurrentNodes nodeRecord = (CurrentNodes) node.getRecord(); actualNodeId = nodeRecord.getId(); nodeCoords.setLat(nodeRecord.getLatitude()); nodeCoords.setLon(nodeRecord.getLongitude()); } else { // element not referenced in this request, so should already exist in // the db and its info be up to date actualNodeId = parsedNodeId; CurrentNodes existingNodeRecord = dbNodeCache.get(actualNodeId); if (existingNodeRecord == null) { throw new IllegalStateException("Node with ID: " + actualNodeId + " does not exist for way."); } if (!existingNodeRecord.getVisible()) { throw new IllegalStateException("Node with ID: " + actualNodeId + " is not visible for way."); } nodeCoords.setLat(existingNodeRecord.getLatitude()); nodeCoords.setLon(existingNodeRecord.getLongitude()); } nodeCoordsCollection.put(actualNodeId, nodeCoords); return actualNodeId; }
From source file:org.hdiv.config.xml.ConfigBeanDefinitionParser.java
private void processMapping(Node node, Map map) { NamedNodeMap attributes = node.getAttributes(); String url = attributes.getNamedItem("url").getTextContent(); String parameters = attributes.getNamedItem("parameters").getTextContent(); map.put(url, this.convertToList(parameters)); }
From source file:org.hdiv.config.xml.ConfigBeanDefinitionParser.java
private void processSessionExpired(Node node, RootBeanDefinition bean) { NamedNodeMap attributes = node.getAttributes(); String loginPage = attributes.getNamedItem("loginPage").getTextContent(); bean.getPropertyValues().addPropertyValue("sessionExpiredLoginPage", loginPage); String homePage = attributes.getNamedItem("homePage").getTextContent(); bean.getPropertyValues().addPropertyValue("sessionExpiredHomePage", homePage); }
From source file:org.ala.harvester.FlickrHarvester.java
/** * Retrieves a map of licences.// ww w . j a v a 2 s . com * * @return */ private Map<String, Licence> getLicencesMap() throws Exception { final String flickrMethodUri = "flickr.photos.licenses.getInfo"; String urlToSearch = this.flickrRestBaseUrl + "/" + "?method=" + flickrMethodUri + "&api_key=" + this.flickrApiKey; logger.info(urlToSearch); logger.debug("URL to search is: " + "`" + urlToSearch + "`" + "\n"); // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod(urlToSearch); // 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"); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { String errMsg = "HTTP GET to " + "`" + urlToSearch + "`" + " returned non HTTP OK code. Returned code " + statusCode + " and message " + method.getStatusLine() + "\n"; method.releaseConnection(); throw new Exception(errMsg); } //parse the response InputStream responseStream = method.getResponseBodyAsStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(responseStream); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); XPathExpression xe = xpath.compile("/rsp/licenses/license"); NodeList nodeSet = (NodeList) xe.evaluate(doc, XPathConstants.NODESET); Map<String, Licence> licencesMap = new HashMap<String, Licence>(); for (int i = 0; i < nodeSet.getLength(); i++) { NamedNodeMap map = nodeSet.item(i).getAttributes(); String id = map.getNamedItem("id").getNodeValue(); Licence licence = new Licence(); licence.setName(map.getNamedItem("name").getNodeValue()); licence.setUrl(map.getNamedItem("url").getNodeValue()); licencesMap.put(id, licence); } return licencesMap; } catch (Exception httpErr) { String errMsg = "HTTP GET to `" + urlToSearch + "` returned HTTP error."; throw new Exception(errMsg, httpErr); } finally { // Release the connection. method.releaseConnection(); } }
From source file:com.vimeo.VimeoUploadClient.java
@SuppressWarnings("serial") public void run() { // get a upload ticket try {/* w ww . jav a 2 s.c om*/ ResponseWrapper response = call("vimeo.videos.upload.getTicket", new HashMap<String, String>() { { put("upload_method", "streaming"); } }); NamedNodeMap nodeMap = ((Node) path(response.getResponse().getBody(), "//ticket", XPathConstants.NODE)) .getAttributes(); final String ticketId = nodeMap.getNamedItem("id").getNodeValue(); String endpoint = nodeMap.getNamedItem("endpoint").getNodeValue(); System.out.printf("%-30S: %s\n", "Ticket ID", ticketId); System.out.printf("%-30S: %s\n", "Endpoint", endpoint); // check ticket response = call("vimeo.videos.upload.checkTicket", new HashMap<String, String>() { { put("ticket_id", ticketId); } }); NamedNodeMap nodeMap1 = ((Node) path(response.getResponse().getBody(), "//ticket", XPathConstants.NODE)) .getAttributes(); System.out.printf("%-30S: %s\n", "Ticket VALID", nodeMap1.getNamedItem("valid").getNodeValue()); // TODO: send video doPut(endpoint); HashMap<String, String> hm = new HashMap<String, String>(); hm.put("filename", videoFile.getName()); hm.put("ticket_id", ticketId); // Complete the upload process. response = call("vimeo.videos.upload.complete", hm); NamedNodeMap nodeMap2 = ((Node) path(response.getResponse().getBody(), "//ticket", XPathConstants.NODE)) .getAttributes(); final String videoId = nodeMap2.getNamedItem("video_id").getNodeValue(); System.out.printf("%-30S: %s\n", "Video ID", videoId); // TODO: set title hm = new HashMap<String, String>(); hm.put("video_id", videoId); hm.put("title", videoTitle); response = call("vimeo.videos.setTitle", hm); NamedNodeMap nodeMap3 = ((Node) path(response.getResponse().getBody(), "//rsp", XPathConstants.NODE)) .getAttributes(); String stat = nodeMap3.getNamedItem("stat").getNodeValue(); System.out.printf("%-30S: %s\n", "set Title status", stat); // TODO: set description hm = new HashMap<String, String>(); hm.put("video_id", videoId); hm.put("description", description); response = call("vimeo.videos.setDescription", hm); NamedNodeMap nodeMap4 = ((Node) path(response.getResponse().getBody(), "//rsp", XPathConstants.NODE)) .getAttributes(); String stat2 = nodeMap4.getNamedItem("stat").getNodeValue(); System.out.printf("%-30S: %s\n", "set Description status", stat2); // TODO: set description hm = new HashMap<String, String>(); hm.put("video_id", videoId); hm.put("tags", keywords); response = call("vimeo.videos.addTags", hm); NamedNodeMap nodeMap5 = ((Node) path(response.getResponse().getBody(), "//rsp", XPathConstants.NODE)) .getAttributes(); String stat3 = nodeMap5.getNamedItem("stat").getNodeValue(); System.out.printf("%-30S: %s\n", "set Tags status", stat3); // TODO: set System.out.printf("DONE.\n\n"); } catch (APIException e) { System.out.println("Fail uploading " + videoTitle); e.setStackTrace(null); } uploading = false; }