Example usage for javax.xml.xpath XPathConstants STRING

List of usage examples for javax.xml.xpath XPathConstants STRING

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants STRING.

Prototype

QName STRING

To view the source code for javax.xml.xpath XPathConstants STRING.

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:com.hin.hl7messaging.InvoiceSvgService.java

@Override
public void generatePdf(MessageVO messageVO) {
    List<Concept> serviceArray = new ArrayList<Concept>();
    String svgContent = "", address = "", exchangeRate = "";
    NodeList serviceFields = (NodeList) XMLHelper.read(messageVO.getMessageDocument(),
            "message/FIAB_MT020000HT02/pertinentInformation", XPathConstants.NODESET);
    int serviceSize = serviceFields.getLength();
    String patientId = (String) XMLHelper.read(messageVO.getMessageDocument(), participantXpath,
            XPathConstants.STRING);

    String organizationId = (String) XMLHelper.read(messageVO.getMessageDocument(), organizationXpath,
            XPathConstants.STRING);
    String organizationVersion = cassandraConnector.getColumnValue("COCT_MT150000HT04_ST", organizationId,
            "VERSION", organizationId);
    String organizationMessage = cassandraConnector.getColumnValue("COCT_MT150000HT04_ST", organizationId,
            organizationVersion, organizationId);

    Document organizationDocument = XMLHelper.getXMLDocument(organizationMessage);

    String organizationName = (String) XMLHelper.read(organizationDocument,
            "message/COCT_MT150000HT04/name/prefix", XPathConstants.STRING);
    String organizationTelecom = (String) XMLHelper.read(organizationDocument,
            "message/COCT_MT150000HT04/telecom/value", XPathConstants.STRING);

    String houseNumber = (String) XMLHelper.read(organizationDocument,
            "message/COCT_MT150000HT04/addr/houseNumber", XPathConstants.STRING);
    String city = (String) XMLHelper.read(organizationDocument, "message/COCT_MT150000HT04/addr/city",
            XPathConstants.STRING);
    String state = (String) XMLHelper.read(organizationDocument, "message/COCT_MT150000HT04/addr/state",
            XPathConstants.STRING);
    String country = (String) XMLHelper.read(organizationDocument, "message/COCT_MT150000HT04/addr/country",
            XPathConstants.STRING);

    if (houseNumber != null && !houseNumber.isEmpty()) {
        address = address + houseNumber + ", ";
    }//from w ww  . j av a2s .  c o m
    if (city != null && !city.isEmpty()) {
        address = address + city + ", ";
    }
    if (state != null && !state.isEmpty()) {
        address = address + state + ", ";
    }
    if (country != null && !country.isEmpty()) {
        address = address + country;
    }

    String licenseeId = getLicenseeId(organizationDocument);
    String licenseeVersion = cassandraConnector.getColumnValue("LICENSEE_ST", licenseeId, "VERSION",
            organizationId);
    String licenseeMessage = cassandraConnector.getColumnValue("LICENSEE_ST", licenseeId, licenseeVersion,
            organizationId);

    Document licenseeDocument = XMLHelper.getXMLDocument(licenseeMessage);
    String currenceyCode = (String) XMLHelper.read(licenseeDocument, "message/LICENSEE/currency/code/code",
            XPathConstants.STRING);

    Concept concept = new Concept();
    concept.setName(currenceyCode);
    try {
        Concept currenyConcept = conceptService.findByProperty("name", currenceyCode, Concept.class);
        List<ConceptAttribute> conceptAttributes = currenyConcept.getConceptAttributes();

        for (ConceptAttribute attribute : conceptAttributes) {
            if (attribute.getKey().equals("ExchangeRate")) {
                exchangeRate = attribute.getValue();
            }
        }

    } catch (Exception e1) {
        e1.printStackTrace();
    }

    File dir = new File(ATTACHMENT_DIR + "/" + patientId);
    dir.mkdirs();
    File file = new File(dir + "/" + messageVO.getId() + ".pdf");
    OutputStream out = null;

    for (int i = 1; i <= serviceSize; i++) {
        String serviceCode = (String) XMLHelper.read(messageVO.getMessageDocument(),
                "message/FIAB_MT020000HT02/pertinentInformation[" + i + "]/observationOrder/code/code",
                XPathConstants.STRING);
        serviceCode = serviceCode.replaceAll("\\n", "").trim();
        if (serviceCode != null && !serviceCode.isEmpty()) {
            serviceArray = conceptService.findAllConceptsByProperty("conceptClasses.name", serviceCode);
        }
        svgContent = createSvgDocument(messageVO.getMessageDocument(), serviceArray, organizationName,
                organizationTelecom, address, exchangeRate, currenceyCode);
    }

    Transcoder transcoder = new PDFTranscoder();
    java.io.InputStream in = null;

    try {
        in = IOUtils.toInputStream(svgContent, "UTF-8");
        TranscoderInput input = new TranscoderInput(in);
        // Setup output
        out = new FileOutputStream(file);
        out = new BufferedOutputStream(out);
        TranscoderOutput output = new TranscoderOutput(out);
        transcoder.transcode(input, output);
        System.out.println("File created");

    } catch (IOException e) {
        e.printStackTrace();
    } catch (TranscoderException e) {
        e.printStackTrace();
    }

}

From source file:com.hin.hl7messaging.InvoiceSvgService.java

private String getLicenseeId(Document messageDocument) {
    String value = (String) XMLHelper.read(messageDocument, LicenseeXPath, XPathConstants.STRING);
    return value;
}

From source file:dk.statsbiblioteket.doms.central.CentralWebserviceImpl.java

@Override
public SearchResultList findObjects(@WebParam(name = "query", targetNamespace = "") String query,
        @WebParam(name = "offset", targetNamespace = "") int offset,
        @WebParam(name = "pageSize", targetNamespace = "") int pageSize) throws MethodFailedException {
    try {//from   w  w  w .j a va  2  s .  c  o  m
        log.trace("Entering findObjects with param query=" + query + ", offset=" + offset + ", pageSize="
                + pageSize);

        JSONObject jsonQuery = new JSONObject();
        jsonQuery.put("search.document.resultfields", "recordID, domsshortrecord");
        jsonQuery.put("search.document.query", query);
        jsonQuery.put("search.document.startindex", offset);
        jsonQuery.put("search.document.maxrecords", pageSize);

        SearchWS summaSearch = getSearchWSService();
        String searchResultString = summaSearch.directJSON(jsonQuery.toString());

        Document searchResultDOM = DOM.stringToDOM(searchResultString);
        XPath xPath = XPathFactory.newInstance().newXPath();

        NodeList nodeList = (NodeList) xPath.evaluate("//responsecollection/response/documentresult/record",
                searchResultDOM.getDocumentElement(), XPathConstants.NODESET);

        java.lang.Long hitCount = java.lang.Long
                .parseLong((String) (xPath.evaluate("//responsecollection/response/documentresult/@hitCount",
                        searchResultDOM.getDocumentElement(), XPathConstants.STRING)));

        SearchResultList searchResultList = new SearchResultList();
        searchResultList.setHitCount(hitCount);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            SearchResult searchResult = new SearchResult();

            Node shortRecordNode = (Node) xPath.evaluate("field[@name='domsshortrecord']", node,
                    XPathConstants.NODE);

            if (shortRecordNode != null) {
                Node shortRecord = DOM.stringToDOM(shortRecordNode.getTextContent()).getDocumentElement();
                String pid = xPath.evaluate("pid", shortRecord);
                String title = xPath.evaluate("title", shortRecord);
                searchResult.setPid(pid);
                if (title != null && !title.equals("")) {
                    searchResult.setTitle(title);
                } else {
                    searchResult.setTitle(pid);
                }
                searchResult.setType(xPath.evaluate("type", shortRecord));
                searchResult.setSource(xPath.evaluate("source", shortRecord));
                searchResult.setTime(xPath.evaluate("time", shortRecord));
                searchResult.setDescription(xPath.evaluate("description", shortRecord));
                searchResult.setState(xPath.evaluate("state", shortRecord));

                try {
                    searchResult.setCreatedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("createdDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
                try {
                    searchResult.setModifiedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("modifiedDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
            } else {
                String pid = xPath.evaluate("field[@name='recordID']/text()", node);
                pid = pid.substring(pid.indexOf(':') + 1);
                searchResult.setPid(pid);
                searchResult.setTitle(pid);
                searchResult.setDescription("");
                searchResult.setSource("");
                searchResult.setState("");
                searchResult.setTime("");
                searchResult.setType("");
            }

            searchResultList.getSearchResult().add(searchResult);
        }

        return searchResultList;

    } catch (XPathExpressionException e) {
        log.warn("Failed to execute method", e);
        throw new MethodFailedException("Method failed to execute", "Method failed to execute", e);
    } catch (Exception e) {
        log.warn("Caught Unknown Exception", e);
        throw new MethodFailedException("Server error", "Server error", e);
    }
}

From source file:com.dwdesign.tweetings.activity.ComposeActivity.java

private String uploadTwitlonger(String text) {
    String finalUrl = "http://www.twitlonger.com/api_post/";

    final String atext = parseString(mEditText.getText());
    String screen_name = null;//from ww w .ja va 2 s.c o  m
    if (mAccountIds != null && mAccountIds.length > 0) {
        screen_name = getAccountUsername(this, mAccountIds[0]);
    }

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(finalUrl);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("username", new StringBody(screen_name));
        reqEntity.addPart("application", new StringBody(TWIT_LONGER_USER));
        reqEntity.addPart("api_key", new StringBody(TWIT_LONGER_API_KEY));
        reqEntity.addPart("message", new StringBody(atext, Charset.forName("UTF-8")));
        postRequest.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(postRequest);

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(response.getEntity().getContent());

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr;
        expr = xpath.compile("//twitlonger/post/content/text()");

        Object result = expr.evaluate(doc, XPathConstants.STRING);
        Log.d("ComposeActivity.uploadTwitlonger", "path: " + atext + " " + result.toString());

        return result.toString();
    } catch (Exception e) {

        //Toast.makeText(getApplicationContext(), "Network exception" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    return null;
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private String requestWithPolling(PaloAltoMethod method, Map<String, String> params) throws ExecutionException {
    String job_id;/*from  w ww.java2  s.co m*/
    String job_response = request(method, params);
    Document doc = getDocument(job_response);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']/result/job/text()");
        job_id = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }
    if (job_id.length() > 0) {
        boolean finished = false;
        Map<String, String> job_params = new HashMap<String, String>();
        job_params.put("type", "op");
        job_params.put("cmd", "<show><jobs><id>" + job_id + "</id></jobs></show>");

        while (!finished) {
            String job_status;
            String response = request(PaloAltoMethod.GET, job_params);
            Document job_doc = getDocument(response);
            XPath job_xpath = XPathFactory.newInstance().newXPath();
            try {
                XPathExpression expr = job_xpath
                        .compile("/response[@status='success']/result/job/status/text()");
                job_status = (String) expr.evaluate(job_doc, XPathConstants.STRING);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }
            if (job_status.equals("FIN")) {
                finished = true;
                String job_result;
                try {
                    XPathExpression expr = job_xpath
                            .compile("/response[@status='success']/result/job/result/text()");
                    job_result = (String) expr.evaluate(job_doc, XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
                if (!job_result.equals("OK")) {
                    NodeList job_details;
                    try {
                        XPathExpression expr = job_xpath
                                .compile("/response[@status='success']/result/job/details/line");
                        job_details = (NodeList) expr.evaluate(job_doc, XPathConstants.NODESET);
                    } catch (XPathExpressionException e) {
                        throw new ExecutionException(e.getCause().getMessage());
                    }
                    String error = "";
                    for (int i = 0; i < job_details.getLength(); i++) {
                        error = error + job_details.item(i).getTextContent() + "\n";
                    }
                    throw new ExecutionException(error);
                }
                return response;
            } else {
                try {
                    Thread.sleep(2000); // poll periodically for the status of the async job...
                } catch (InterruptedException e) { /* do nothing */
                }
            }
        }
    } else {
        return job_response;
    }
    return null;
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private synchronized boolean requestWithCommit(ArrayList<IPaloAltoCommand> commandList)
        throws ExecutionException {
    boolean result = true;

    if (commandList.size() > 0) {
        // CHECK IF THERE IS PENDING CHANGES THAT HAVE NOT BEEN COMMITTED...
        String pending_changes;/*ww w  .  j a  v  a 2 s .  co m*/
        Map<String, String> check_params = new HashMap<String, String>();
        check_params.put("type", "op");
        check_params.put("cmd", "<check><pending-changes></pending-changes></check>");
        String check_response = request(PaloAltoMethod.GET, check_params);
        Document check_doc = getDocument(check_response);
        XPath check_xpath = XPathFactory.newInstance().newXPath();
        try {
            XPathExpression expr = check_xpath.compile("/response[@status='success']/result/text()");
            pending_changes = (String) expr.evaluate(check_doc, XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            throw new ExecutionException(e.getCause().getMessage());
        }
        if (pending_changes.equals("yes")) {
            throw new ExecutionException(
                    "The Palo Alto has uncommited changes, so no changes can be made.  Try again later or contact your administrator.");
        } else {
            // ADD A CONFIG LOCK TO CAPTURE THE PALO ALTO RESOURCE
            String add_lock_status;
            Map<String, String> add_lock_params = new HashMap<String, String>();
            add_lock_params.put("type", "op");
            add_lock_params.put("cmd", "<request><config-lock><add></add></config-lock></request>");
            String add_lock_response = request(PaloAltoMethod.GET, add_lock_params);
            Document add_lock_doc = getDocument(add_lock_response);
            XPath add_lock_xpath = XPathFactory.newInstance().newXPath();
            try {
                XPathExpression expr = add_lock_xpath.compile("/response[@status='success']/result/text()");
                add_lock_status = (String) expr.evaluate(add_lock_doc, XPathConstants.STRING);
            } catch (XPathExpressionException e) {
                throw new ExecutionException(e.getCause().getMessage());
            }
            if (add_lock_status.length() == 0) {
                throw new ExecutionException("The Palo Alto is locked, no changes can be made at this time.");
            }

            try {
                // RUN THE SEQUENCE OF COMMANDS
                for (IPaloAltoCommand command : commandList) {
                    result = (result && command.execute()); // run commands and modify result boolean
                }

                // COMMIT THE CHANGES (ALSO REMOVES CONFIG LOCK)
                String commit_job_id;
                Map<String, String> commit_params = new HashMap<String, String>();
                commit_params.put("type", "commit");
                commit_params.put("cmd", "<commit></commit>");
                String commit_response = requestWithPolling(PaloAltoMethod.GET, commit_params);
                Document commit_doc = getDocument(commit_response);
                XPath commit_xpath = XPathFactory.newInstance().newXPath();
                try {
                    XPathExpression expr = commit_xpath
                            .compile("/response[@status='success']/result/job/id/text()");
                    commit_job_id = (String) expr.evaluate(commit_doc, XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
                if (commit_job_id.length() == 0) { // no commit was done, so release the lock...
                    // REMOVE THE CONFIG LOCK TO RELEASE THE PALO ALTO RESOURCE
                    String remove_lock_status;
                    Map<String, String> remove_lock_params = new HashMap<String, String>();
                    remove_lock_params.put("type", "op");
                    remove_lock_params.put("cmd",
                            "<request><config-lock><remove></remove></config-lock></request>");
                    String remove_lock_response = request(PaloAltoMethod.GET, remove_lock_params);
                    Document remove_lock_doc = getDocument(remove_lock_response);
                    XPath remove_lock_xpath = XPathFactory.newInstance().newXPath();
                    try {
                        XPathExpression expr = remove_lock_xpath
                                .compile("/response[@status='success']/result/text()");
                        remove_lock_status = (String) expr.evaluate(remove_lock_doc, XPathConstants.STRING);
                    } catch (XPathExpressionException e) {
                        throw new ExecutionException(e.getCause().getMessage());
                    }
                    if (remove_lock_status.length() == 0) {
                        throw new ExecutionException(
                                "Could not release the Palo Alto device.  Please notify an administrator!");
                    }
                }

            } catch (ExecutionException ex) {
                // REVERT TO RUNNING
                String revert_job_id;
                Map<String, String> revert_params = new HashMap<String, String>();
                revert_params.put("type", "op");
                revert_params.put("cmd", "<load><config><from>running-config.xml</from></config></load>");
                requestWithPolling(PaloAltoMethod.GET, revert_params);

                // REMOVE THE CONFIG LOCK TO RELEASE THE PALO ALTO RESOURCE
                String remove_lock_status;
                Map<String, String> remove_lock_params = new HashMap<String, String>();
                remove_lock_params.put("type", "op");
                remove_lock_params.put("cmd",
                        "<request><config-lock><remove></remove></config-lock></request>");
                String remove_lock_response = request(PaloAltoMethod.GET, remove_lock_params);
                Document remove_lock_doc = getDocument(remove_lock_response);
                XPath remove_lock_xpath = XPathFactory.newInstance().newXPath();
                try {
                    XPathExpression expr = remove_lock_xpath
                            .compile("/response[@status='success']/result/text()");
                    remove_lock_status = (String) expr.evaluate(remove_lock_doc, XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    throw new ExecutionException(e.getCause().getMessage());
                }
                if (remove_lock_status.length() == 0) {
                    throw new ExecutionException(
                            "Could not release the Palo Alto device.  Please notify an administrator!");
                }

                throw ex; // Bubble up the reason we reverted...
            }

            return result;
        }
    } else {
        return true; // nothing to do
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

/**
 * http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-proxy.txt
 * This is an Apple standard implemented by Apple Mac OSX at least up to Yosemite and offers a fairly simple
 * sharing model for calendars.  The model is simpler than Zimbra's native model and there are mismatches,
 * for instance Zimbra requires the proposed delegate to accept shares.
 *///from   w  w w. ja  v  a  2  s.  c  o  m
@Test
public void testAppleCaldavProxyFunctions() throws ServiceException, IOException {
    Account sharer = users[3].create();
    Account sharee1 = users[1].create();
    Account sharee2 = users[2].create();
    ZMailbox mboxSharer = TestUtil.getZMailbox(sharer.getName());
    ZMailbox mboxSharee1 = TestUtil.getZMailbox(sharee1.getName());
    ZMailbox mboxSharee2 = TestUtil.getZMailbox(sharee2.getName());
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharer, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee1, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee2, true);
    // Test PROPPATCH to "calendar-proxy-read" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyReadUrl(sharer), sharer, sharee2);
    // Test PROPPATCH to "calendar-proxy-write" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyWriteUrl(sharer), sharer, sharee1);

    // verify that adding new members to groups triggered notification messages
    List<ZMessage> msgs = TestUtil.waitForMessages(mboxSharee1,
            "in:inbox subject:\"Share Created: Calendar shared by \"", 1, 10000);
    assertNotNull(String.format("Notification msgs for %s", sharee1.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee1.getName()), 1, msgs.size());

    msgs = TestUtil.waitForMessages(mboxSharee2, "in:inbox subject:\"Share Created: Calendar shared by \"", 1,
            10000);
    assertNotNull(String.format("Notification msgs for %s", sharee2.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee2.getName()), 1, msgs.size());
    // Simulate acceptance of the shares (would normally need to be done in ZWC
    createCalendarMountPoint(mboxSharee1, sharer);
    createCalendarMountPoint(mboxSharee2, sharer);
    Document doc = delegateForExpandProperty(sharee1);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;
    try {
        String xpathS = "/D:multistatus/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        NodeList result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        String text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for account owner", UrlNamespace.getPrincipalUrl(sharee1).replaceAll("@", "%40"),
                text);

        xpathS = "/D:multistatus/D:response/D:propstat/D:prop/CS:calendar-proxy-write-for/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for sharer", UrlNamespace.getPrincipalUrl(sharer).replaceAll("@", "%40"), text);
    } catch (XPathExpressionException e1) {
        ZimbraLog.test.debug("xpath problem", e1);
    }
    // Check that proxy write has sharee1 in it
    doc = groupMemberSetExpandProperty(sharer, sharee1, true);
    // Check that proxy read has sharee2 in it
    doc = groupMemberSetExpandProperty(sharer, sharee2, false);
    String davBaseName = "notAllowed@There";
    String url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            davBaseName);
    HttpMethodExecutor exe = doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_MOVED_TEMPORARILY);
    String location = null;
    for (Header hdr : exe.respHeaders) {
        if ("Location".equals(hdr.getName())) {
            location = hdr.getValue();
        }
    }
    assertNotNull("Location Header not returned when creating", location);
    url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            location.substring(location.lastIndexOf('/') + 1));
    doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_CREATED);
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

public static Document groupMemberSetExpandProperty(Account acct, Account member, boolean proxyWrite)
        throws IOException, ServiceException {
    String url = proxyWrite ? TestCalDav.getCalendarProxyWriteUrl(acct)
            : TestCalDav.getCalendarProxyReadUrl(acct);
    url = url.replaceAll("@", "%40");
    String href = proxyWrite ? UrlNamespace.getCalendarProxyWriteUrl(acct, acct)
            : UrlNamespace.getCalendarProxyReadUrl(acct, acct);
    href = href.replaceAll("@", "%40");
    ReportMethod method = new ReportMethod(url);
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(new ByteArrayRequestEntity(TestCalDav.expandPropertyGroupMemberSet.getBytes(),
            MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;/*  w ww.j  ava  2s . c om*/
    try {
        String xpathS = "/D:multistatus/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        String text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for response", href, text);

        xpathS = "/D:multistatus/D:response/D:propstat/D:prop/D:group-member-set/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for sharee", UrlNamespace.getPrincipalUrl(member).replaceAll("@", "%40"), text);
    } catch (XPathExpressionException e1) {
        ZimbraLog.test.debug("xpath problem", e1);
    }
    return doc;
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

private void createBooking(String rq, Reservation reservation, long timestamp, Map<String, String> result)
        throws Throwable {
    String rs = getConnection(rq);
    LOG.debug("\nBookResponse rs: \n" + rs + "\n");
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    InputSource inputSource = new InputSource(new StringReader(rs.toString()));
    String bookID = (String) xpath.evaluate("//BookID", inputSource, XPathConstants.STRING);
    if (bookID.isEmpty()) {
        throw new ServiceException(Error.reservation_api, reservation.getId());
    } else {/* w  w w  .  j a v  a 2 s  .c o  m*/
        reservation.setAltid(bookID);
        reservation.setAltpartyid(getAltpartyid());
        reservation.setMessage(reservation.getMessage());
        reservation.setVersion(new Date(timestamp));
        reservation.setState(Reservation.State.Confirmed.name());
        result.put(GatewayHandler.STATE, GatewayHandler.ACCEPTED);
    }
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

private static Reservation readPrice(SqlSession sqlSession, Reservation reservation, String productAltId) {
    StringBuilder sb = new StringBuilder();
    Date now = new Date();
    long time = now.getTime();
    String SenderSessionID = time + "bookingnetS";
    String ReceiverSessionID = time + "bookingnetR";
    String rq;/*from w  ww  .  j  a  v  a  2  s  .co m*/
    String rs = null;

    try {
        sb.append("<?xml version='1.0' ?>");
        sb.append("<TravelMessage VersionID='1.8N'>");
        sb.append(" <Control Language='NL' Test='nee'>");
        sb.append("    <SenderSessionID>" + SenderSessionID + "</SenderSessionID>");
        sb.append("    <ReceiverSessionID>" + ReceiverSessionID + "</ReceiverSessionID>");
        sb.append("    <Date>" + DF.format(new Date()) + "</Date>");
        sb.append("    <Time Reliability='zeker'>" + TF.format(new Date()) + "</Time>");
        sb.append("   <MessageSequence>1</MessageSequence>");
        sb.append("   <SenderID>" + SENDERID + "</SenderID>");
        sb.append("  <ReceiverID>NPS001</ReceiverID>");
        sb.append("   <RequestID>AvailabilitybookingnetRequest</RequestID>");
        sb.append("   <ResponseID>AvailabilitybookingnetResponse</ResponseID>");
        sb.append(" </Control>");
        sb.append("  <TRequest>");
        sb.append("    <AvailabilitybookingnetRequest>");
        sb.append("      <PackageDetails WaitListCheck='ja'>");
        sb.append("          <AccommodationID>" + "A" + productAltId + "</AccommodationID>");
        sb.append("          <ArrivalDate>" + DF.format(reservation.getFromdate()) + "</ArrivalDate>");
        sb.append("        <Duration DurationType='dagen'>" + reservation.getDuration(Time.DAY).intValue()
                + "</Duration>");
        sb.append("     </PackageDetails>");
        sb.append("   </AvailabilitybookingnetRequest>");
        sb.append("  </TRequest>");
        sb.append("</TravelMessage>");

        rq = sb.toString();
        rs = getConnection(rq); // fix code have better support. gettting errors when deploying with tomcat.

        LOG.debug("computePrice rq: \n" + rq + "\n");
        LOG.debug("computePrice rs: \n" + rs + "\n");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        InputSource inputSource = new InputSource(new StringReader(rs.toString()));
        Double price = (Double) xpath.evaluate("//Price", inputSource, XPathConstants.NUMBER);
        if (Double.isNaN(price)) {
            throw new ServiceException(Error.product_not_available);
        }

        price = price / 100.00; //price is a whole number

        factory = XPathFactory.newInstance();
        xpath = factory.newXPath();
        inputSource = new InputSource(new StringReader(rs.toString()));
        String fromCurrency = (String) xpath.evaluate("//Price/@Currency", inputSource, XPathConstants.STRING);
        if ("".equals(fromCurrency)) {
            throw new ServiceException(Error.price_missing, reservation.getId() + " State = "
                    + reservation.getState() + " currency = " + reservation.getCurrency());
        }
        String tocurrency = reservation.getCurrency();
        if (!fromCurrency.equalsIgnoreCase(tocurrency)) {
            // Double rate = OpenExchangeRates.getExchangeRate(currency,rescurrency);
            Double rate = WebService.getRate(sqlSession, fromCurrency, tocurrency, new Date());
            price = rate * price;
        }

        LOG.debug("price = " + price);
        reservation.setPrice(price);
        reservation.setQuote(price);
    } catch (Throwable e) {
        LOG.error(e.getMessage());
        reservation.setPrice(0.00);
    }
    return reservation;
}