Example usage for org.apache.commons.httpclient.methods GetMethod setQueryString

List of usage examples for org.apache.commons.httpclient.methods GetMethod setQueryString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod setQueryString.

Prototype

public void setQueryString(String queryString) 

Source Link

Usage

From source file:cuanto.api.CuantoConnector.java

/**
 * Gets TestOutcomes for the specified TestRun.
 *
 * @param testRun The TestRun for which to retrieve TestOutcomes.
 * @param offset Zero-based index of the first record to return
 * @param max The maximum number of records to return. You may request a maximum of 100 at a time.
 * @param sort The TestOutcome field on which to sort. Secondary sort will always be on the TestOutcome's fullName
 *        (asc) or if the fullName is the primary sort, secondary sort will be by dateCreated (asc).  
 * @param order The order in which to sort -- legal values are "asc" or "desc".
 * @return The TestOutcomes for the specified TestRun, in the order they were added to the server. If less than
 * <i>max</i> TestOutcomes are returned, the List will be the size of the number returned.
 * @throws IllegalArgumentException - if the max is > 100, order is an unknown value, or TestRun has no id.
 *//*from   w w  w  .ja  va 2s .  c  om*/
public List<TestOutcome> getTestOutcomesForTestRun(TestRun testRun, Integer offset, Integer max,
        TestOutcome.Sort sort, String order) throws IllegalArgumentException {
    if (testRun.id == null) {
        throw new IllegalArgumentException(
                "The TestRun has no id. Query for the TestRun before getting it's TestOutcomes.");
    }
    GetMethod get = (GetMethod) getHttpMethod(HTTP_GET, getCuantoUrl() + "/api/getTestOutcomes");
    TestOutcome.Sort secondarySort = sort == TestOutcome.Sort.FULL_NAME ? TestOutcome.Sort.DATE_CREATED
            : TestOutcome.Sort.FULL_NAME;

    final String realOrder = order.toLowerCase().trim();
    if (!realOrder.equals("asc") && !realOrder.equals("desc")) {
        throw new IllegalArgumentException("Unknown order: " + order);
    }

    if (max == null) {
        throw new NullPointerException("Null is not a valid value for max");
    } else if (max > 100) {
        throw new IllegalArgumentException("max must not exceed 100");
    }

    get.setQueryString(new NameValuePair[] { new NameValuePair("id", testRun.id.toString()),
            new NameValuePair("sort", sort.toString()), new NameValuePair("sort", secondarySort.toString()),
            new NameValuePair("order", realOrder), new NameValuePair("order", "asc"),
            new NameValuePair("max", max.toString()), new NameValuePair("offset", offset.toString()) });
    try {
        int httpStatus = getHttpClient().executeMethod(get);
        if (httpStatus == HttpStatus.SC_OK) {
            JSONObject jsonResponse = JSONObject.fromObject(getResponseBodyAsString(get));
            JSONArray jsonOutcomes = jsonResponse.getJSONArray("testOutcomes");
            List<TestOutcome> outcomesToReturn = new ArrayList<TestOutcome>(jsonOutcomes.size());
            for (Object obj : jsonOutcomes) {
                JSONObject jsonOutcome = (JSONObject) obj;
                outcomesToReturn.add(TestOutcome.fromJSON(jsonOutcome));
            }
            return outcomesToReturn;
        } else {
            throw new RuntimeException("Getting the TestOutcome failed with HTTP status code " + httpStatus
                    + ":\n" + getResponseBodyAsString(get));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Unable to parse JSON response: " + e.getMessage(), e);
    }
}

From source file:net.neurowork.cenatic.centraldir.workers.XMLRestWorker.java

private String getXmlToken() {
    String token = null;/*from  ww w .ja v  a2s.  c  om*/
    HttpClient httpclient = getHttpClient();
    GetMethod get = new GetMethod(restUrl.getTokenUrl());
    get.addRequestHeader("Accept", "application/xml");

    NameValuePair userParam = new NameValuePair(USERNAME_PARAM, satelite.getUser());
    NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, satelite.getPassword());
    NameValuePair[] params = new NameValuePair[] { userParam, passwordParam };

    get.setQueryString(params);
    try {
        int statusCode = httpclient.executeMethod(get);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: " + get.getStatusLine());
        }
        token = parseToken(get.getResponseBodyAsString());
    } catch (HttpException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        logger.error(e.getMessage());
    } catch (SAXException e) {
        logger.error(e.getMessage());
    } finally {
        get.releaseConnection();
    }

    return token;
}

From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java

/**
 *
 *//*from w  w  w  .jav a  2s.c om*/
protected String sendGetRequest(String REQUEST, long since, long until) throws IOOperationException {

    String response = null;
    GetMethod method = null;
    try {
        if (log.isTraceEnabled()) {
            log.trace("\nREQUEST:" + REQUEST);
        }
        method = new GetMethod(REQUEST);
        HttpClient httpClient = new HttpClient();
        if (since != 0 && until != 0) {
            NameValuePair nvp_since = new NameValuePair();
            nvp_since.setName("since");
            nvp_since.setValue("" + since);
            NameValuePair nvp_until = new NameValuePair();
            nvp_until.setName("until");
            nvp_until.setValue("" + until);
            NameValuePair[] nvp = { nvp_since, nvp_until };
            method.setQueryString(nvp);
        }

        if (this.sessionid != null) {
            method.setRequestHeader("Authorization", this.sessionid);
        }

        printMethodParams(method);
        printHeaderFields(method.getRequestHeaders(), "REQUEST");

        int code = httpClient.executeMethod(method);

        response = method.getResponseBodyAsString();

        if (log.isTraceEnabled()) {
            log.trace("RESPONSE code: " + code);
        }
        printHeaderFields(method.getResponseHeaders(), "RESPONSE");

    } catch (Exception e) {
        throw new IOOperationException("Error GET Request ", e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return response;
}

From source file:net.neurowork.cenatic.centraldir.workers.XMLRestWorker.java

private void buscarOrganizacion(String token) {
    Organizacion organizacion = null;//from   w w w  . java2  s.com
    if (logger.isDebugEnabled())
        logger.debug("Buscando Organizaciones para Satelite: " + satelite);

    HttpClient httpclient = getHttpClient();

    GetMethod get = new GetMethod(restUrl.getOrganizacionUrl());
    get.addRequestHeader("Accept", "application/xml");
    NameValuePair tokenParam = new NameValuePair("token", token);
    int id = 0;
    //      if(satelite.getLastOrgId() != null) 
    //         id = satelite.getLastOrgId();

    int leap = idLeap;

    while (true) {
        id = id + 1;

        if (logger.isTraceEnabled()) {
            logger.trace("Buscando Organizacion con id: " + id + " en el Satelite: " + satelite);
        }

        NameValuePair passwordParam = new NameValuePair("id", String.valueOf(id));
        NameValuePair[] params = new NameValuePair[] { tokenParam, passwordParam };

        get.setQueryString(params);
        String queryString = get.getQueryString();

        int statusCode;
        try {
            if (logger.isTraceEnabled()) {
                logger.trace("Query String: " + queryString);
            }

            statusCode = httpclient.executeMethod(get);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + get.getStatusLine());
            } else {
                String xmlString = get.getResponseBodyAsString();
                if (logger.isInfoEnabled()) {
                    logger.info("Xml Received.");
                }

                String xmlHash = constructXmlHash(xmlString);

                organizacion = organizacionService.findByHash(xmlHash);
                if (organizacion == null) {
                    organizacion = parseOrganizacion(xmlString);
                    if (organizacion == null) {
                        leap--;
                        if (leap <= 0) {
                            logger.info("Se lleg al fin de las Organizaciones. Saliendo del Satelite: "
                                    + satelite);
                            break;
                        } else {
                            logger.info("Leap: " + leap);
                        }
                    } else {
                        if (organizacion.getSatelites() == null) {
                            organizacion.setSatelites(new HashSet<OrganizacionSatelite>());
                        }
                        boolean sateliteFound = false;
                        for (OrganizacionSatelite sat : organizacion.getSatelites()) {
                            if (sat.getSatelite().getName().equals(satelite.getName())) {
                                sateliteFound = true;
                                break;
                            }
                        }
                        if (!sateliteFound) {
                            OrganizacionSatelite newSat = new OrganizacionSatelite();
                            newSat.setSatelite(satelite);
                            newSat.setOrganizacion(organizacion);
                            organizacion.getSatelites().add(newSat);
                        }

                        organizacion.setXmlHash(xmlHash);
                        organizacionService.saveOrganization(organizacion);

                        int numEmpresas = 0;
                        if (satelite.getNumEmpresas() != null) {
                            numEmpresas = satelite.getNumEmpresas();
                        }
                        numEmpresas++;

                        Date now = new Date();
                        satelite.setNumEmpresas(numEmpresas);
                        satelite.setLastRetrieval(new Timestamp(now.getTime()));
                        satelite.setLastOrgId(id);
                        sateliteService.saveSatelite(satelite);
                    }
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("Organizacion with id: " + id + " already in centraldir");
                    }
                }
            }
        } catch (HttpException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } catch (ParserConfigurationException e) {
            logger.error(e.getMessage());
        } catch (SAXException e) {
            logger.error(e.getMessage());
        } catch (ServiceException e) {
            logger.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage());
        } finally {
            get.releaseConnection();
        }
    }

}

From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

/**
 * /*w  ww . j  av  a 2s.co m*/
 * @param cADCommandObject
 * @param query
 * @param select
 * @param order
 * @return
 * @throws Exception
 */
private final ScribeCommandObject searchAllTypeOfObjects(final ScribeCommandObject cADCommandObject,
        final String query, final String select, final String order) throws Exception {
    logger.debug("----Inside searchAllTypeOfObjects query: " + query + " & select: " + select + " & order: "
            + order);
    GetMethod getMethod = null;
    try {

        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Check if CrmUserId is present in request */
        if (cADCommandObject.getCrmUserId() != null) {

            /* Get agent from session manager */
            final ScribeCacheObject agent = zDCRMSessionManager
                    .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

            /* Get CRM information from agent */
            serviceURL = agent.getScribeMetaObject().getCrmServiceURL();
            serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol();
            userId = agent.getScribeMetaObject().getCrmUserId();
            password = agent.getScribeMetaObject().getCrmPassword();
            sessionId = agent.getScribeMetaObject().getCrmSessionId();
            crmPort = agent.getScribeMetaObject().getCrmPort();
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/search.xml";

        logger.debug(
                "----Inside searchAllTypeOfObjects zenDeskURL: " + zenDeskURL + " & sessionId: " + sessionId);

        /* Instantiate get method */
        getMethod = new GetMethod(zenDeskURL);

        /* Set request content type */
        getMethod.addRequestHeader("Content-Type", "application/xml");

        /* Cookie is required to be set in case of search */
        getMethod.addRequestHeader("Cookie", sessionId);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Check if user has not provided a valid query */
        if (ZDCRMMessageFormatUtils.validateQuery(query)) {
            getMethod.setQueryString(new NameValuePair[] {
                    new NameValuePair("query", ZDCRMMessageFormatUtils.createZDQuery(query)) });
        }

        /* Execute method */
        int result = httpclient.executeMethod(getMethod);
        logger.debug("----Inside searchAllTypeOfObjects response code: " + result + " & body: "
                + getMethod.getResponseBodyAsString());

        if (result == HttpStatus.SC_OK) {
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(getMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing all nodes value */
            final XPathExpression expr = xpath.compile("/records/record");

            /* Get node list from resposne document */
            final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

            final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

            /* Get select field list */
            List<String> selectFieldList = null;

            /* Check if user is asking for all fields */
            if (select != null && !select.equalsIgnoreCase(HTTPConstants.allCRMObjectFields)) {
                selectFieldList = ZDCRMMessageFormatUtils.createSelectFieldList(select);
            }

            /* Iterate over node list */
            for (int i = 0; i < nodeList.getLength(); i++) {

                /* Get node from node list */
                final Node node = nodeList.item(i);

                /* Create new Scribe object */
                final ScribeObject cADbject = new ScribeObject();

                /* Check if node has child nodes */
                if (node.hasChildNodes()) {

                    final NodeList subNodeList = node.getChildNodes();

                    /* Create list of elements */
                    final List<Element> elementList = new ArrayList<Element>();

                    for (int j = 0; j < subNodeList.getLength(); j++) {

                        /* Get all subnodes */
                        final Node subNode = subNodeList.item(j);

                        /* This trick is to avoid empty nodes */
                        if (!subNode.getNodeName().contains("#text")) {
                            if (selectFieldList != null) {
                                /* Add only user requested fields */
                                if (selectFieldList.contains(subNode.getNodeName().trim().toUpperCase())) {
                                    /* Create element from response */
                                    final Element element = ZDCRMMessageFormatUtils.createMessageElement(
                                            subNode.getNodeName(), subNode.getTextContent());

                                    /* Add element in list */
                                    elementList.add(element);
                                }
                            } else {
                                /* Create element from response */
                                final Element element = ZDCRMMessageFormatUtils
                                        .createMessageElement(subNode.getNodeName(), subNode.getTextContent());

                                /* Add element in list */
                                elementList.add(element);
                            }
                        }
                    }

                    /* Add all CRM fields */
                    cADbject.setXmlContent(elementList);

                    /* Add Scribe object in list */
                    cADbjectList.add(cADbject);
                }
            }
            /* Check if no record found */
            if (cADbjectList.size() == 0) {
                throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk");
            }

            /* Set the final object in command object */
            cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(getMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } catch (final Exception e) {
        throw new ScribeException(ScribeResponseCodes._1000 + "Problem while communicating with Zendesk CRM",
                e);
    } finally {
        /* Release connection socket */
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.inbravo.scribe.rest.service.crm.zd.ZDV2RESTCRMService.java

/**
 * //w  ww.  jav a 2s  .  c o  m
 * @param cADCommandObject
 * @param query
 * @param select
 * @param order
 * @return
 * @throws Exception
 */
private final ScribeCommandObject searchAllTypeOfObjects(final ScribeCommandObject cADCommandObject,
        final String query, final String select, final String order) throws Exception {

    if (logger.isDebugEnabled()) {
        logger.debug("----Inside searchAllTypeOfObjects query: " + query + " & select: " + select + " & order: "
                + order);
    }
    GetMethod getMethod = null;
    try {

        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Get agent from session manager */
        final ScribeCacheObject cacheObject = zDCRMSessionManager
                .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

        /* Get CRM information from agent */
        serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL();
        serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol();
        userId = cacheObject.getScribeMetaObject().getCrmUserId();
        password = cacheObject.getScribeMetaObject().getCrmPassword();
        crmPort = cacheObject.getScribeMetaObject().getCrmPort();

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + zdAPISubPath + "search.json";

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside searchAllTypeOfObjects zenDeskURL: " + zenDeskURL + " & sessionId: "
                    + sessionId);
        }

        /* Instantiate get method */
        getMethod = new GetMethod(zenDeskURL);

        /* Set request content type */
        getMethod.addRequestHeader("Content-Type", "application/json");

        /* Cookie is required to be set in case of search */
        getMethod.addRequestHeader("Cookie", sessionId);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Check if user has not provided a valid query */
        if (ZDCRMMessageFormatUtils.validateQuery(query)) {
            getMethod.setQueryString(new NameValuePair[] {
                    new NameValuePair("query", ZDCRMMessageFormatUtils.createZDQuery(query)) });
        }

        /* Execute method */
        int result = httpclient.executeMethod(getMethod);

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside searchAllTypeOfObjects response code: " + result + " & body: "
                    + getMethod.getResponseBodyAsString());
        }

        if (result == HttpStatus.SC_OK) {

            /* Create JSON object from response */
            final JSONObject jObj = new JSONObject(getMethod.getResponseBodyAsString());

            /* Create new Scribe object list */
            final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

            /* Get select field list */
            List<String> selectFieldList = null;

            /* Check if user is asking for all fields */
            if (select != null && !select.equalsIgnoreCase(HTTPConstants.allCRMObjectFields)) {

                /* Create select field list */
                selectFieldList = ZDCRMMessageFormatUtils.createSelectFieldList(select);
            }

            /* Get all keys */
            @SuppressWarnings("rawtypes")
            final Iterator itr = jObj.keys();

            /* Iterate over user json object list */
            while (itr.hasNext()) {

                /* Get key name */
                final String key = (String) itr.next();

                /* Get array value */
                if (jObj.get(key).getClass().isAssignableFrom(JSONArray.class)) {

                    /* Get array object */
                    final JSONArray arrObj = (JSONArray) jObj.get(key);

                    /* Run over all JSON objects */
                    for (int i = 0; i < arrObj.length(); i++) {

                        /* Get individual object */
                        final JSONObject subObj = (JSONObject) arrObj.get(i);

                        /* Create list of elements */
                        final List<Element> elementList = new ArrayList<Element>();

                        /* Create new Scribe object */
                        final ScribeObject cADbject = new ScribeObject();

                        /* Get all keys */
                        @SuppressWarnings("rawtypes")
                        final Iterator subItr = subObj.keys();

                        /* Loop over each user in list */
                        while (subItr.hasNext()) {

                            /* Get key name */
                            final String subKey = (String) subItr.next();

                            /* Get value */
                            final Object value = subObj.get(subKey);

                            if (selectFieldList != null) {

                                /* Add only user requested fields */
                                if (selectFieldList.contains(subKey.trim().toUpperCase())) {

                                    /* Add element in list */
                                    elementList
                                            .add(ZDCRMMessageFormatUtils.createMessageElement(subKey, value));
                                }
                            } else {

                                /* Add element in list */
                                elementList.add(ZDCRMMessageFormatUtils.createMessageElement(subKey, value));
                            }

                            /* Set Scribe object type */
                            if (subKey.equalsIgnoreCase("result_type")) {

                                cADbject.setObjectType("" + value);
                            }

                            if (logger.isDebugEnabled()) {
                                logger.debug("----Inside searchAllTypeOfObjects key : " + subKey + " & value: "
                                        + value);
                            }
                        }

                        /* Add all CRM fields */
                        cADbject.setXmlContent(elementList);

                        /* Add Scribe object in list */
                        cADbjectList.add(cADbject);
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "----Inside searchAllTypeOfObjects unexpected JSON object type in response : "
                                        + jObj);
                    }
                }
            }

            /* Check if no record found */
            if (cADbjectList.size() == 0) {

                /* Throw user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk");
            }

            /* Set the final object in command object */
            cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));

        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE || result == HttpStatus.SC_UNPROCESSABLE_ENTITY) {

            /* Throw user error */
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(getMethod.getResponseBodyAsString()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {

            /* Throw user error */
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {

            /* Throw user error */
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested record not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {

            /* Throw user error */
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final JSONException e) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                e);
    } catch (final ParserConfigurationException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final IOException exception) {

        /* Throw user error */
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } catch (final Exception e) {
        throw new ScribeException(ScribeResponseCodes._1000 + "Problem while communicating with Zendesk CRM",
                e);
    } finally {

        /* Release connection socket */
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:net.sourceforge.tagsea.instrumentation.network.RegisterWithProgress.java

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    GetMethod getUidMethod = new GetMethod(NetworkUtilities.REGISTER_SCRIPT);
    getUidMethod.setQueryString(new NameValuePair[] { new NameValuePair("firstName", firstName),
            new NameValuePair("lastName", lastName), new NameValuePair("email", email),
            new NameValuePair("jobFunction", job), new NameValuePair("company", company),
            new NameValuePair("companySize", companySize), new NameValuePair("companyBusiness", fieldOfWork),
            new NameValuePair("anonymous", Boolean.toString(anonymous)) });
    monitor.beginTask("Get User Id", 1);
    HttpClient client = new HttpClient();

    try {//www. j  a  v  a  2 s . co  m
        status = client.executeMethod(getUidMethod);

        response = NetworkUtilities.readInputAsString(getUidMethod.getResponseBodyAsStream());
    } catch (HttpException e) {
        //there was a problem with the file upload so throw up
        // an error
        // dialog to inform the user and log the exception
        status = 500;
        response = e.getMessage();
        throw new InvocationTargetException(e, response);
    } catch (IOException e) {
        //there was a problem with the file upload so throw up
        // an error
        // dialog to inform the user and log the exception
        status = 500;
        response = e.getMessage();
        throw new InvocationTargetException(e, response);
    } finally {
        //             release the connection to the server
        getUidMethod.releaseConnection();
    }

    if (status != 200) {
    } else {
        String uidString = response.substring(response.indexOf(":") + 1).trim();
        userID = Integer.parseInt(uidString);
        InstrumentationPreferences.setAnonymous(anonymous);
        InstrumentationPreferences.setAskForRegistration(false);
        InstrumentationPreferences.setCompany(company);
        InstrumentationPreferences.setCompanySize(companySize);
        InstrumentationPreferences.setEmail(email);
        InstrumentationPreferences.setFieldOfWork(fieldOfWork);
        InstrumentationPreferences.setFirstName(firstName);
        InstrumentationPreferences.setJob(job);
        InstrumentationPreferences.setLastName(lastName);
        InstrumentationPreferences.setUID(userID);
        InstrumentationPreferences.setMonitoringEnabled(true);
        InstrumentationPreferences.setUploadInterval(1);
    }

    monitor.worked(1);
    monitor.done();
}

From source file:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendGetMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    GetMethod method = new GetMethod(url);
    NameValuePair[] params = new NameValuePair[parameters.size() + 3];
    int i = 0;//ww  w .j  ava  2  s .  c o  m
    params[i++] = new NameValuePair("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        params[i++] = new NameValuePair(entry.getKey(), entry.getValue());
    }
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    params[i++] = new NameValuePair("ts", ts);
    params[i++] = new NameValuePair("hash", hash);
    method.setQueryString(params);
    logger.debug("Sending GET message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(params));
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:org.alfresco.repo.urlshortening.BitlyUrlShortenerImpl.java

@Override
public String shortenUrl(String longUrl) {
    if (log.isDebugEnabled()) {
        log.debug("Shortening URL: " + longUrl);
    }//  w  w w.j a  v  a  2s  .c  o  m
    String shortUrl = longUrl;
    if (longUrl.length() > urlLength) {
        GetMethod getMethod = new GetMethod();
        getMethod.setPath("/v3/shorten");

        List<NameValuePair> args = new ArrayList<NameValuePair>();
        args.add(new NameValuePair("login", username));
        args.add(new NameValuePair("apiKey", apiKey));
        args.add(new NameValuePair("longUrl", longUrl));
        args.add(new NameValuePair("format", "txt"));
        getMethod.setQueryString(args.toArray(new NameValuePair[args.size()]));

        try {
            int resultCode = httpClient.executeMethod(getMethod);
            if (resultCode == 200) {
                shortUrl = getMethod.getResponseBodyAsString();
            } else {
                log.warn("Failed to shorten URL " + longUrl + "  - response code == " + resultCode);
                log.warn(getMethod.getResponseBodyAsString());
            }
        } catch (Exception ex) {
            log.error("Failed to shorten URL " + longUrl, ex);
        }
        if (log.isDebugEnabled()) {
            log.debug("URL " + longUrl + " has been shortened to " + shortUrl);
        }
    }
    return shortUrl.trim();
}

From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java

GetMethod getGETMethod(String servicePath, List<WebscriptParam> params) {
    GetMethod getMethod = new GetMethod(this.baseUrl + servicePath);

    if (params != null) {
        List<NameValuePair> args = new ArrayList<NameValuePair>();
        for (WebscriptParam param : params) {
            args.add(new NameValuePair(param.getName(), param.getValue()));
        }//w w w . ja va  2 s .  co  m
        getMethod.setQueryString(args.toArray(new NameValuePair[args.size()]));
    }
    return getMethod;
}