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:com.benfante.jslideshare.SlideShareConnectorImpl.java

public InputStream sendGetMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    HttpClient client = createHttpClient();
    GetMethod method = new GetMethod(url);
    NameValuePair[] params = new NameValuePair[parameters.size() + 3];
    int i = 0;//from   w  ww  .  j a v  a2s  .com
    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 = client.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:edu.unc.lib.dl.fedora.ManagementClient.java

public String getIrodsPath(String dsFedoraLocationToken) {
    log.debug("getting iRODS path for " + dsFedoraLocationToken);
    String result = null;//  www  .ja  v  a  2 s .  co m
    GetMethod get = null;
    try {
        String url = getFedoraContextUrl() + "/storagelocation";
        get = new GetMethod(url);
        get.setQueryString("pid=" + URLEncoder.encode(dsFedoraLocationToken, "utf-8"));
        int statusCode = httpClient.executeMethod(get);
        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("CDR storage location GET method failed: " + get.getStatusLine());
        } else {
            log.debug("CDR storage location GET method: " + get.getStatusLine());
            byte[] resultBytes = get.getResponseBody();
            result = new String(resultBytes, "utf-8");
            result = result.trim();
        }
    } catch (Exception e) {
        throw new ServiceException("Error while contacting iRODS location service with datastream location "
                + dsFedoraLocationToken, e);
    } finally {
        if (get != null)
            get.releaseConnection();
    }
    return result;
}

From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public Recommendations askRecommendation(String modelSetId, String artifactId, String userId,
        String simulationSessionId) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/recommendation", DefaultRestResource.REST_URI,
            modelSetId);/*from   w w  w  .j  a  va2  s . c  o m*/

    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");

    boolean hasSimulationId = false;
    if ((simulationSessionId != null) && (!simulationSessionId.isEmpty())) {
        hasSimulationId = true;
    }

    int queryStringSize = 2;
    if (hasSimulationId) {
        queryStringSize = 3;
    }
    NameValuePair[] queryString = new NameValuePair[queryStringSize];
    queryString[0] = new NameValuePair("artifactid", artifactId);
    queryString[1] = new NameValuePair("userid", userId);
    if (hasSimulationId) {
        queryString[2] = new NameValuePair("simulationsessionid", simulationSessionId);
    }
    getMethod.setQueryString(queryString);

    Recommendations recommendations = null;

    try {
        httpClient.executeMethod(getMethod);

        InputStream recStream = getMethod.getResponseBodyAsStream();

        if (recStream != null) {
            JAXBContext jc = JAXBContext.newInstance(Recommendations.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            recommendations = (Recommendations) unmarshaller.unmarshal(recStream);
        }
    } catch (JAXBException | IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    return recommendations;
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

@Override
public String getMetaDataAsJSON(final int attachmentID) {
    String result = null;/*from   w  ww . j  av  a  2 s . c  o  m*/
    String fileName = BasicSQLUtils.querySingleObj(ATTACHMENT_URL + attachmentID);
    if (StringUtils.isNotEmpty(fileName) && StringUtils.isNotEmpty(fileGetMetaDataURLStr)) {
        GetMethod method = new GetMethod(fileGetMetaDataURLStr);
        fillValuesArray();
        method.setQueryString(new NameValuePair[] { new NameValuePair("dt", "json"),
                new NameValuePair("filename", fileName), new NameValuePair("token", generateToken(fileName)),
                new NameValuePair("coll", values[0]), new NameValuePair("disp", values[1]),
                new NameValuePair("div", values[2]), new NameValuePair("inst", values[3]) });

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        try {
            int status = client.executeMethod(method);
            updateServerTimeDelta(method);
            if (status == HttpStatus.SC_OK) {
                result = method.getResponseBodyAsString();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
    return result;
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

private void testKey() throws WebStoreAttachmentKeyException {
    if (testKeyURLStr == null)
        return; // skip test if there is not test url.

    GetMethod method = new GetMethod(testKeyURLStr);
    String r = "" + (new Random()).nextInt();
    method.setQueryString(new NameValuePair[] { new NameValuePair("random", r),
            new NameValuePair("token", generateToken(r)) });

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    try {//from  w  ww .  j ava 2  s.co m
        int status = client.executeMethod(method);
        updateServerTimeDelta(method);
        if (status == HttpStatus.SC_OK) {
            return;
        } else if (status == HttpStatus.SC_FORBIDDEN) {
            throw new WebStoreAttachmentKeyException("Attachment key is invalid.");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
    throw new WebStoreAttachmentKeyException("Problem verifying attachment key.");
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

@Override
public Calendar getFileEmbeddedDate(final int attachmentID) {
    String dateStr = null;// w  w  w  .j  av  a  2  s . co m
    String fileName = BasicSQLUtils.querySingleObj(ATTACHMENT_URL + attachmentID);
    if (StringUtils.isNotEmpty(fileName) && StringUtils.isNotEmpty(fileGetMetaDataURLStr)) {
        GetMethod method = new GetMethod(fileGetMetaDataURLStr);
        fillValuesArray();
        method.setQueryString(new NameValuePair[] { new NameValuePair("dt", "json"),
                new NameValuePair("filename", fileName), new NameValuePair("token", generateToken(fileName)),
                new NameValuePair("coll", values[0]), new NameValuePair("disp", values[1]),
                new NameValuePair("div", values[2]), new NameValuePair("inst", values[3]) });

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        try {
            int status = client.executeMethod(method);
            updateServerTimeDelta(method);
            if (status == HttpStatus.SC_OK) {
                dateStr = method.getResponseBodyAsString();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }

    if (dateStr != null && dateStr.length() == 10) {
        try {
            Date convertedDate = dateFormat.parse(dateStr);
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(convertedDate.getTime());
            return cal;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:net.neurowork.cenatic.centraldir.workers.xml.OrganizacionXmlImporter.java

public void buscarOrganizacion(String token) {
    Organizacion organizacion = null;//from ww w  .  jav a 2  s.  c  o  m
    if (logger.isDebugEnabled())
        logger.debug("Buscando Organizaciones para Satelite: " + satelite);

    HttpClient httpclient = XMLRestWorker.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 = XMLRestWorker.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:edu.ku.brc.util.WebStoreAttachmentMgr.java

/**
 * @param urlStr/*from ww w.j a  v  a 2 s .c o  m*/
 * @param tmpFile
 * @return
 * @throws IOException
 */

private File getFileFromWeb(final String attachLocation, final String mimeType, final Integer scale,
        final byte[] bytes) {
    File dlFile = getDLFileForName((scale == null) ? attachLocation : getScaledFileName(attachLocation, scale));
    try {
        dlFile.createNewFile();
        dlFile.deleteOnExit();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }

    boolean success = false;

    if (bytes == null) {
        System.out.println("bytes == null");
    }
    notifyListeners(1);

    GetMethod getMethod = new GetMethod(readURLStr);
    // type=<type>&filename=<fname>&coll=<coll>&disp=<disp>&div=<div>&inst=<inst>
    fillValuesArray();
    getMethod.setQueryString(new NameValuePair[] { new NameValuePair("type", (scale != null) ? "T" : "O"),
            new NameValuePair("scale", "" + scale), new NameValuePair("filename", attachLocation),
            new NameValuePair("token", generateToken(attachLocation)), new NameValuePair("coll", values[0]),
            new NameValuePair("disp", values[1]), new NameValuePair("div", values[2]),
            new NameValuePair("inst", values[3]) });

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    try {
        int status = client.executeMethod(getMethod);
        updateServerTimeDelta(getMethod);
        if (status == HttpStatus.SC_FORBIDDEN) {
            System.out.println(getMethod.getResponseBodyAsString());
        }
        if (status == HttpStatus.SC_OK) {
            InputStream inpStream = getMethod.getResponseBodyAsStream();
            if (inpStream != null) {
                BufferedInputStream in = new BufferedInputStream(inpStream);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dlFile));

                //long totBytes = 0;
                do {
                    int numBytes = in.read(bytes);
                    if (numBytes == -1) {
                        break;
                    }
                    //totBytes += numBytes;
                    bos.write(bytes, 0, numBytes);

                } while (true);
                //log.debug(String.format("Total Bytes for file: %d %d", totBytes, totBytes / 1024));
                in.close();
                bos.flush();
                bos.close();

                success = true;
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        getMethod.releaseConnection();
        notifyListeners(-1);
    }

    if (success) {
        return dlFile;
    } else {
        dlFile.delete();
        return null;
    }
}

From source file:com.gisgraphy.servlet.StreetServletTest.java

@Test
public void testLatLongOrNameIsRequired() {

    String url = streetServletUrl + STREET_SERVLET_CONTEXT + "/streetsearch";

    String result;//w w  w.  j a  va  2  s. c  o  m
    String queryString;
    OutputFormat format = OutputFormat.XML;
    GetMethod get = null;
    try {
        // wo lat/long/name
        HttpClient client = new HttpClient();
        get = new GetMethod(url);
        client.executeMethod(get);
        assertEquals("you could only set name ", 500, get.getStatusCode());
        result = get.getResponseBodyAsString().trim();
        String missingParameterErrorMessage = ResourceBundle.getBundle(Constants.BUNDLE_ERROR_KEY)
                .getString("error.emptyLatLong");
        FeedChecker.assertQ("The XML error is not correct", result,
                "//error[.='" + missingParameterErrorMessage + "']");
        if (get != null) {
            get.releaseConnection();
        }

        // only long
        queryString = StreetSearchQuery.LONG_PARAMETER + "=1";
        get = new GetMethod(url);
        get.setQueryString(queryString);
        client.executeMethod(get);
        assertEquals("only long should throws", 500, get.getStatusCode());
        result = get.getResponseBodyAsString().trim();
        FeedChecker.assertQ("The XML error is not correct", result,
                "//error[.='" + missingParameterErrorMessage + "']");
        if (get != null) {
            get.releaseConnection();
        }

        // only lat
        queryString = StreetSearchQuery.LAT_PARAMETER + "=1";
        get = new GetMethod(url);
        get.setQueryString(queryString);
        client.executeMethod(get);
        assertEquals("only lat should throws", 500, get.getStatusCode());
        result = get.getResponseBodyAsString().trim();
        FeedChecker.assertQ("The XML error is not correct", result,
                "//error[.='" + missingParameterErrorMessage + "']");
        if (get != null) {
            get.releaseConnection();
        }

        // only name
        queryString = StreetSearchQuery.NAME_PARAMETER + "=foo";
        get = new GetMethod(url);
        get.setQueryString(queryString);
        client.executeMethod(get);
        result = get.getResponseBodyAsString().trim();
        Assert.assertFalse(result.contains(missingParameterErrorMessage));
        // assertEquals("only name should not throws",200
        // ,get.getStatusCode());
        if (get != null) {
            get.releaseConnection();
        }

        // lat long
        queryString = StreetSearchQuery.LONG_PARAMETER + "=1&" + StreetSearchQuery.LAT_PARAMETER + "=1";
        get = new GetMethod(url);
        get.setQueryString(queryString);
        client.executeMethod(get);
        // assertEquals("only lat long should not throws",200
        // ,get.getStatusCode());
        result = get.getResponseBodyAsString().trim();
        Assert.assertFalse(result.contains(missingParameterErrorMessage));
        if (get != null) {
            get.releaseConnection();
        }

        // lat name
        queryString = StreetSearchQuery.LONG_PARAMETER + "=1&" + StreetSearchQuery.NAME_PARAMETER + "=foo";
        get = new GetMethod(url);
        get.setQueryString(queryString);
        client.executeMethod(get);
        // assertEquals("only lat long should not throws",200
        // ,get.getStatusCode());
        result = get.getResponseBodyAsString().trim();
        Assert.assertFalse(result.contains(missingParameterErrorMessage));

        if (get != null) {
            get.releaseConnection();
        }

    } catch (Exception e) {
        fail("An exception has occured " + e.getMessage());
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }

}

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

/**
 *
 *//*from  w  w w .jav  a 2  s.c o  m*/
protected String sendGetRequestWithNameValuePairs(String REQUEST, NameValuePair[] pairs)
        throws IOOperationException {

    String response = null;
    GetMethod method = null;
    try {
        if (log.isTraceEnabled()) {
            log.trace("\nREQUEST:" + REQUEST);
        }
        method = new GetMethod(REQUEST);
        HttpClient httpClient = new HttpClient();
        method.setQueryString(pairs);

        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;
}