List of usage examples for org.w3c.dom Element getFirstChild
public Node getFirstChild();
From source file:ua.kiev.doctorvera.utils.SMSGateway.java
@SuppressWarnings("deprecation") public ArrayList<String> send(String phone, String sms) { ArrayList<String> result = new ArrayList<String>(); final String MESSAGE = "<message><service id='single' source='" + FROM + "'/><to>" + phone + "</to><body content-type='text/plain'>" + sms + "</body></message>"; @SuppressWarnings("resource") HttpClient httpclient = new DefaultHttpClient(); String xml = null;//from www. java2 s.c om try { HttpPost httpPost = new HttpPost(SMS_SEND_URL); StringEntity entity = new StringEntity(MESSAGE, "UTF-8"); entity.setContentType("text/xml"); entity.setChunked(true); httpPost.setEntity(entity); httpPost.addHeader( BasicScheme.authenticate(new UsernamePasswordCredentials(LOGIN, PASS), "UTF-8", false)); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); LOG.info("Sending SMS: " + (response.getStatusLine().getStatusCode() == 200)); xml = EntityUtils.toString(resEntity); } catch (Exception e) { LOG.severe("" + e.getStackTrace()); } finally { httpclient.getConnectionManager().shutdown(); } //parsing xml result Document doc = loadXMLFromString(xml); NodeList nl = doc.getElementsByTagName("status"); Element status = (Element) nl.item(0); result.add(0, status.getAttribute("id").toString()); //tracking id at position 0 result.add(1, status.getAttribute("date").toString()); //date at position 1 result.add(2, getElementValue(status.getFirstChild())); //state at position 2 return result; }
From source file:com.amazonaws.mturk.service.axis.AWSService.java
/** * //from w ww .jav a2s .com * @param m - Message structure which contains the details for making wsdl operation call * @return Reply structure containing results and errors from the wsdl operation call * @throws ServiceException */ public Reply executeRequestMessage(Message m) throws ServiceException { String axisMethodName = m.getMethodName(); Object requests = m.getRequests(); String credential = m.getCredential(); String resultAccessorName = m.getResultAccessorName(); try { Class bodyClass; Class responseClass; Class requestClass; Object body; // Construct the request body bodyClass = Class.forName(getPackagePrefix() + axisMethodName); body = bodyClass.newInstance(); responseClass = Class.forName(getPackagePrefix() + axisMethodName + RESPONSE_SUFFIX); requestClass = Class.forName(getPackagePrefix() + axisMethodName + REQUEST_SUFFIX); Class requestArrayClass = Array.newInstance(requestClass, 0).getClass(); Object requestArray = requestArrayClass.cast(requests); Method setRequest = bodyClass.getMethod(SET_REQUEST_METHOD_NAME, new Class[] { requestArrayClass }); setRequest.invoke(body, requestArray); Calendar now = null; String signature = null; synchronized (AWSService.class) { Method setAWSAccessKeyId = bodyClass.getMethod(SET_AWS_ACCESS_KEY_ID_METHOD_NAME, STRING_CLASS_ARRAY); setAWSAccessKeyId.invoke(body, getAWSAccessKeyId()); Method setValidate = bodyClass.getMethod(SET_VALIDATE_METHOD_NAME, STRING_CLASS_ARRAY); setValidate.invoke(body, (Object) null); if (credential != null && credential.length() > 0) { Method setCredential = bodyClass.getMethod(SET_CREDENTIAL_METHOD_NAME, STRING_CLASS_ARRAY); setCredential.invoke(body, credential); } Method setTimestamp = bodyClass.getMethod(SET_TIMESTAMP_METHOD_NAME, CALENDAR_CLASS_ARRAY); now = Calendar.getInstance(); setTimestamp.invoke(body, now); // Create the signature Method setSignature = bodyClass.getMethod(SET_SIGNATURE_METHOD_NAME, STRING_CLASS_ARRAY); signature = getSigner().sign(getServiceName(), axisMethodName, now); setSignature.invoke(body, signature); } Object response = responseClass.newInstance(); String axisClassMethodName = axisMethodName.substring(0, 1).toLowerCase() + axisMethodName.substring(1); Method axisMethod = getPort().getClass().getMethod(axisClassMethodName, new Class[] { bodyClass }); try { // Execute the request and get a response response = axisMethod.invoke(getPort(), body); } catch (InvocationTargetException e) { if (e.getCause() instanceof AxisFault) { //errors due to throttling are inside AxisFault. Get those if present AxisFault fault = (AxisFault) e.getCause(); String httpResponse = fault.getFaultCode().getLocalPart(); List<String> errorCodes = new ArrayList<String>(); errorCodes.add(httpResponse); // When Axis encounters networking errors, it sets the fault code to // {http://xml.apache.org/axis/}HTTP // In this case it sets the error code from the http response in // the "HttpErrorCode" element of the fault details // If this is the case, add it to the error codes so the SDK // can be configured to retry for specific response codes if (AXIS_HTTP_FAULT.equals(fault.getFaultCode())) { Element faultElement = fault.lookupFaultDetail(AXIS_HTTP_ERROR_CODE); if (faultElement != null && faultElement.getFirstChild() != null) { errorCodes.add(faultElement.getFirstChild().getNodeValue()); } } throw new InternalServiceException(e.getCause(), errorCodes); } throw new ServiceException(e.getCause()); } // Extract the Operation Request Method getOperationRequest = responseClass.getMethod(GET_OPERATION_REQUEST_METHOD_NAME); Object operationRequest = getOperationRequest.invoke(response); // Extract the Errors Method getErrors = operationRequest.getClass().getMethod(GET_ERRORS_METHOD_NAME); Object errors = getErrors.invoke(operationRequest); Object[] results = null; if (errors != null) { return new Reply(results, errors, getRequestId(operationRequest)); } Method getResult = responseClass.getMethod(GET_PREFIX + resultAccessorName); results = (Object[]) getResult.invoke(response); if (results == null || results.length == 0) { throw new ServiceException("Empty result, unknown error."); } for (int i = 0; i < results.length; i++) { Object result = results[i]; Method getRequest = result.getClass().getMethod(GET_REQUEST_METHOD_NAME); Object request = getRequest.invoke(result); getErrors = request.getClass().getMethod(GET_ERRORS_METHOD_NAME); errors = getErrors.invoke(request); if (errors != null) { break; //get only the first error } } return new Reply(results, errors, getRequestId(operationRequest)); } catch (ClassNotFoundException e) { throw new ServiceException(e); } catch (IllegalAccessException e) { throw new ServiceException(e); } catch (InstantiationException e) { throw new ServiceException(e); } catch (NoSuchMethodException e) { throw new ServiceException(e); } catch (InvocationTargetException e) { throw new ServiceException(e.getCause()); } }
From source file:ca.inverse.sogo.engine.source.SOGoPropertyConverter.java
private String getSifValue(Element rootElement, String propertyName) { NodeList nodeList = rootElement.getElementsByTagName(propertyName); if (nodeList.getLength() > 0) { Element propertyElement = (Element) nodeList.item(0); Text propertyText = (Text) propertyElement.getFirstChild(); if (propertyText != null) return propertyText.getNodeValue(); else// ww w . j a v a2s .c om return null; } else { return null; } }
From source file:com.krawler.esp.utils.ConfigReader.java
private void loadResource(Properties properties, Object name, boolean quietFail) { try {/*from w ww .jav a 2 s . c o m*/ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = null; if (name instanceof String) { // a CLASSPATH resource String path = getResourceAsString((String) name); LOG.debug("Path is " + path); if (path != null) { doc = builder.parse(path); } } else if (name instanceof File) { // a file resource File file = (File) name; if (file.exists()) { doc = builder.parse(file); } } if (doc == null) { if (quietFail) return; throw new RuntimeException(name + " not found"); } Element root = doc.getDocumentElement(); if (!"krawler-conf".equals(root.getTagName())) System.err.print("bad conf file: top-level element not <krawler-conf>"); NodeList props = root.getChildNodes(); for (int i = 0; i < props.getLength(); i++) { Node propNode = props.item(i); if (!(propNode instanceof Element)) continue; Element prop = (Element) propNode; if (!"property".equals(prop.getTagName())) System.err.print("bad conf file: element not <property>"); NodeList fields = prop.getChildNodes(); String attr = null; String value = null; for (int j = 0; j < fields.getLength(); j++) { Node fieldNode = fields.item(j); if (!(fieldNode instanceof Element)) continue; Element field = (Element) fieldNode; if ("name".equals(field.getTagName())) attr = ((Text) field.getFirstChild()).getData(); if ("value".equals(field.getTagName()) && field.hasChildNodes()) value = ((Text) field.getFirstChild()).getData(); } if (attr != null && value != null) properties.setProperty(attr, value); } } catch (Exception e) { System.err.print("error parsing conf file: " + e); throw new RuntimeException(e); } }
From source file:edu.lternet.pasta.client.ReservationsManager.java
/** * Return the number of subscriptions for a given user. * // ww w . java 2 s . com * @return the number of subscriptions for this user. */ public int numberOfReservations() throws Exception { int numberOfReservations = 0; if (this.uid != null && !this.uid.equals("public")) { String xmlString = listActiveReservations(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList reservations = documentElement.getElementsByTagName("reservation"); int nReservations = reservations.getLength(); for (int i = 0; i < nReservations; i++) { Node reservationNode = reservations.item(i); NodeList reservationChildren = reservationNode.getChildNodes(); String principal = ""; for (int j = 0; j < reservationChildren.getLength(); j++) { Node childNode = reservationChildren.item(j); if (childNode instanceof Element) { Element reservationElement = (Element) childNode; if (reservationElement.getTagName().equals("principal")) { Text text = (Text) reservationElement.getFirstChild(); if (text != null) { principal = text.getData().trim(); if (principal.startsWith(this.uid)) { numberOfReservations++; } } } } } } } catch (Exception e) { logger.error("Exception:\n" + e.getMessage()); e.printStackTrace(); throw new PastaEventException(e.getMessage()); } } return numberOfReservations; }
From source file:org.opencastproject.remotetest.server.ComposerRestEndpointTest.java
/** * Gets the mediapackage element from a job polling response * // w w w . ja v a 2 s . c o m * @param jobXml * the job as xml * @return the mediapackage elemet as an xml string */ protected long getDurationFromJob(String jobXml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(jobXml, "UTF-8")); String payload = (String) XPathFactory.newInstance().newXPath().compile("//*[local-name() = 'payload']") .evaluate(doc, XPathConstants.STRING); Document payloadDoc = builder.parse(IOUtils.toInputStream(payload, "UTF-8")); Element element = ((Element) XPathFactory.newInstance().newXPath() .compile("//*[local-name() = 'duration'][1]").evaluate(payloadDoc, XPathConstants.NODE)); if (element == null) throw new IllegalStateException("Track doesn't contain a duration"); return Long.parseLong(element.getFirstChild().getNodeValue()); }
From source file:ca.inverse.sogo.engine.source.SOGoPropertyConverter.java
/** * This method converts DOM element to Property instance. Multiple SIF properties may map * into one iCalendar property, so some of the properties just 'skipped' when conversion is performed, * because they should be used only in conjunction with other properties. When SIF property is skipped, * implementation will return <b>null</b>. * * @param o instance of org.w3c.dom.Element representing SIF property * @return Cal4j Property instance if conversion was successful and SIF element was not skipped *//*w w w .ja v a 2s . co m*/ public Property convertDataToProperty(Object o) throws ConversionException { if (!(o instanceof Element)) throw new IllegalArgumentException("argument must be instance of org.w3c.Element"); String sifPropertyValue; String sifPropertyName; String iCalPropertyName; String iCalPropertyValue; Element sifElement = (Element) o; Node sifValueNode = sifElement.getFirstChild(); sifPropertyName = sifElement.getTagName(); if (sifValueNode != null && (sifValueNode instanceof Text)) { Text textNode = (Text) sifValueNode; sifPropertyValue = textNode.getNodeValue(); if (sifPropertyMappedDirectly(sifPropertyName)) { /* perform appropriate mapping of property name & value */ String keyName = this.componentType + '.' + PROP_PREFIX + sifPropertyName; String valName = this.componentType + '.' + VAL_PREFIX + sifPropertyName + "." + sifPropertyValue; iCalPropertyName = (String) this.sif2ICalDirectMappings.get(keyName); iCalPropertyValue = (String) this.sif2ICalDirectMappings.get(valName); if (iCalPropertyValue == null) iCalPropertyValue = sifPropertyValue; return new Property(iCalPropertyName, iCalPropertyValue); } else if (sifPropertyHasDependencies(sifPropertyName)) { /* process this property and all dependent properties */ try { String methodName = "_convert" + sifPropertyName; Method[] methods = getClass().getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(methodName)) { methods[i].setAccessible(true); return (Property) methods[i].invoke(this, new Object[] { sifElement }); } } return null; } catch (IllegalAccessException e) { throw new ConversionException(e); } catch (InvocationTargetException e) { throw new ConversionException(e.getTargetException()); } } else if (sifPropertyIsDependent(sifPropertyName)) { /* skip property */ return null; } else { /* create x-property */ iCalPropertyName = DEFAULT_X_PREFIX + sifPropertyName; iCalPropertyValue = sifPropertyValue; return new Property(iCalPropertyName, iCalPropertyValue); } } else { return null; } }
From source file:edu.lternet.pasta.client.ReservationsManager.java
/** * Builds an options list for the number of reservations the end user is * requesting with a single button click. * /*w ww. j av a 2s.co m*/ * @return the options HTML to be inserted into the <select> element * @throws PastaEventException */ public String reservationsDeleteOptionsHTML() throws Exception { String html; StringBuilder sb = new StringBuilder(""); if (this.uid != null && !this.uid.equals("public")) { String xmlString = listActiveReservations(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList reservations = documentElement.getElementsByTagName("reservation"); int nReservations = reservations.getLength(); for (int i = 0; i < nReservations; i++) { Node reservationNode = reservations.item(i); NodeList reservationChildren = reservationNode.getChildNodes(); String docid = ""; String principal = ""; boolean include = false; for (int j = 0; j < reservationChildren.getLength(); j++) { Node childNode = reservationChildren.item(j); if (childNode instanceof Element) { Element reservationElement = (Element) childNode; if (reservationElement.getTagName().equals("principal")) { Text text = (Text) reservationElement.getFirstChild(); if (text != null) { principal = text.getData().trim(); if (principal.startsWith(this.uid)) { include = true; } } } else if (reservationElement.getTagName().equals("docid")) { Text text = (Text) reservationElement.getFirstChild(); if (text != null) { docid = text.getData().trim(); } } } } if (include) { sb.append(String.format(" <option value=\"%s\">%s</option>\n", docid, docid)); } } } catch (Exception e) { logger.error("Exception:\n" + e.getMessage()); e.printStackTrace(); throw new PastaEventException(e.getMessage()); } } html = sb.toString(); return html; }
From source file:com.amalto.core.util.Util.java
/** * Executes a BeforeDeleting process if any * // w w w . j a v a 2 s . co m * @param clusterName A data cluster name * @param concept A concept/type name * @param ids Id of the document being deleted * @throws Exception If something went wrong */ @SuppressWarnings("unchecked") public static BeforeDeleteResult beforeDeleting(String clusterName, String concept, String[] ids, String operationType) throws Exception { // check before deleting transformer boolean isBeforeDeletingTransformerExist = false; Collection<TransformerV2POJOPK> transformers = getTransformerV2CtrlLocal().getTransformerPKs("*"); for (TransformerV2POJOPK id : transformers) { if (id.getIds()[0].equals("beforeDeleting_" + concept)) { isBeforeDeletingTransformerExist = true; break; } } if (isBeforeDeletingTransformerExist) { try { // call before deleting transformer // load the item ItemPOJOPK itemPk = new ItemPOJOPK(new DataClusterPOJOPK(clusterName), concept, ids); ItemPOJO pojo = ItemPOJO.load(itemPk); String xml = null; if (pojo == null) {// load from recycle bin DroppedItemPOJOPK droppedItemPk = new DroppedItemPOJOPK(itemPk, "/");//$NON-NLS-1$ DroppedItemPOJO droppedItem = Util.getDroppedItemCtrlLocal().loadDroppedItem(droppedItemPk); if (droppedItem != null) { xml = droppedItem.getProjection(); Document doc = Util.parse(xml); Node item = (Node) XPathFactory.newInstance().newXPath().evaluate("//ii/p", doc, //$NON-NLS-1$ XPathConstants.NODE); if (item != null && item instanceof Element) { NodeList list = item.getChildNodes(); Node node = null; for (int i = 0; i < list.getLength(); i++) { if (list.item(i) instanceof Element) { node = list.item(i); break; } } if (node != null) { xml = Util.nodeToString(node); } } } } else { xml = pojo.getProjectionAsString(); } // Create before deleting update report String username; try { username = LocalUser.getLocalUser().getUsername(); } catch (Exception e1) { LOGGER.error(e1); throw e1; } String key = ""; if (ids != null) { for (int i = 0; i < ids.length; i++) { key += ids[i]; if (i != ids.length - 1) { key += "."; } } } String resultUpdateReport = "" + "<Update>" + "<UserName>" + username + "</UserName>" + "<Source>" + UpdateReportPOJO.GENERIC_UI_SOURCE + "</Source>" + "<TimeInMillis>" + System.currentTimeMillis() + "</TimeInMillis>" + "<OperationType>" + StringEscapeUtils.escapeXml(operationType) + "</OperationType>" + "<DataCluster>" + clusterName + "</DataCluster>" + "<DataModel>" + StringUtils.EMPTY + "</DataModel>" + "<Concept>" + StringEscapeUtils.escapeXml(concept) + "</Concept>" + "<Key>" + StringEscapeUtils.escapeXml(key) + "</Key>"; resultUpdateReport += "</Update>"; // Proceed with execution String exchangeData = mergeExchangeData(xml, resultUpdateReport); final String runningKey = "XtentisWSBean.executeTransformerV2.beforeDeleting.running"; TransformerContext context = new TransformerContext( new TransformerV2POJOPK("beforeDeleting_" + concept)); context.put(runningKey, Boolean.TRUE); com.amalto.core.server.api.Transformer ctrl = getTransformerV2CtrlLocal(); TypedContent wsTypedContent = new TypedContent(exchangeData.getBytes("UTF-8"), "text/xml; charset=utf-8"); ctrl.execute(context, wsTypedContent, new TransformerCallBack() { @Override public void contentIsReady(TransformerContext context) throws XtentisException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("XtentisWSBean.executeTransformerV2.beforeDeleting.contentIsReady() "); } } @Override public void done(TransformerContext context) throws XtentisException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("XtentisWSBean.executeTransformerV2.beforeDeleting.done() "); } context.put(runningKey, Boolean.FALSE); } }); while ((Boolean) context.get(runningKey)) { // TODO Poor-man synchronization here Thread.sleep(100); } // TODO process no plug-in issue String outputErrorMessage = null; // Scan the entries - in priority, aka the content of the 'output_error_message' entry. for (Entry<String, TypedContent> entry : context.getPipelineClone().entrySet()) { if (ITransformerConstants.VARIABLE_OUTPUT_OF_BEFORESAVINGTRANFORMER.equals(entry.getKey())) { outputErrorMessage = new String(entry.getValue().getContentBytes(), "UTF-8"); break; } } // handle error message BeforeDeleteResult result = new BeforeDeleteResult(); if (outputErrorMessage == null) { LOGGER.warn("No message generated by before delete process."); result.type = "info"; //$NON-NLS-1$ result.message = StringUtils.EMPTY; } else { if (outputErrorMessage.length() > 0) { Document doc = Util.parse(outputErrorMessage); // TODO what if multiple error nodes ? String xpath = "//report/message"; //$NON-NLS-1$ Node errorNode = (Node) XPathFactory.newInstance().newXPath().evaluate(xpath, doc, XPathConstants.NODE); if (errorNode instanceof Element) { Element errorElement = (Element) errorNode; result.type = errorElement.getAttribute("type"); //$NON-NLS-1$ Node child = errorElement.getFirstChild(); if (child instanceof Text) { result.message = child.getTextContent(); } } } else { result.type = "error"; //$NON-NLS-1$ result.message = "<report><message type=\"error\"/></report>"; //$NON-NLS-1$ } } return result; } catch (Exception e) { LOGGER.error(e); throw e; } } return null; }
From source file:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java
@Override public boolean handleMessage(SOAPMessageContext context) { if (null == this.sessionKey) { return true; }/*from w ww . j a v a2s . c o m*/ if (null == this.prototypeKeyBindingId) { return true; } Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (false == outboundProperty) { return true; } LOG.debug("adding proof of possession signature"); SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); NodeList registerRequestNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "Register"); Element registerRequestElement = (Element) registerRequestNodeList.item(0); Document xkmsDocument; try { xkmsDocument = copyDocument(registerRequestElement); } catch (ParserConfigurationException e) { LOG.error("error copying XKMS request: " + e.getMessage(), e); return false; } NodeList proofOfPossessionNodeList = xkmsDocument.getElementsByTagNameNS(XKMS_NAMESPACE, "ProofOfPossession"); Element proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0); try { prepareDocument(xkmsDocument); addSignature(proofOfPossessionElement); } catch (Exception e) { LOG.error("error adding proof signature: " + e.getMessage(), e); return false; } Node signatureNode = soapPart.importNode(proofOfPossessionElement.getFirstChild(), true); proofOfPossessionNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "ProofOfPossession"); proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0); proofOfPossessionElement.appendChild(signatureNode); return true; }