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:org.n52.oxf.util.IOHelper.java

public static InputStream sendGetMessage(String serviceURL, String queryString) throws IOException {
    InputStream is = null;// w  w  w .j  a v a2 s  . c o  m

    HttpClient httpClient = new HttpClient();
    httpClient.setHostConfiguration(getHostConfiguration(new URL(serviceURL)));
    GetMethod method = new GetMethod(serviceURL);

    method.setQueryString(queryString);

    httpClient.executeMethod(method);

    LOGGER.info("GET-method sended to: " + method.getURI());

    is = method.getResponseBodyAsStream();

    return is;
}

From source file:org.olat.admin.registration.SystemRegistrationManager.java

String getLocationCoordinates(final String textLocation) {
    String csvCoordinates = null;

    if (textLocation == null || textLocation.length() == 0) {
        return null;
    }/* w  w w  .  ja v a 2s. co m*/

    final HttpClient client = HttpClientFactory.getHttpClientInstance();
    final String url = "http://maps.google.com/maps/geo";
    final NameValuePair[] nvps = new NameValuePair[5];
    nvps[0] = new NameValuePair("q", textLocation);
    nvps[1] = new NameValuePair("output", "csv");
    nvps[2] = new NameValuePair("oe", "utf8");
    nvps[3] = new NameValuePair("sensor", "false");
    nvps[4] = new NameValuePair("key",
            "ABQIAAAAq5BZJrKbG-xh--W4MrciXRQZTOqTGVCcmpRMgrUbtlJvJ3buAhSfG7H7hgE66BCW17_gLyhitMNP4A");

    final GetMethod getCall = new GetMethod(url);
    getCall.setQueryString(nvps);

    try {
        client.executeMethod(getCall);
        String resp = null;
        if (getCall.getStatusCode() == 200) {
            resp = getCall.getResponseBodyAsString();
            final String[] split = resp.split(",");
            csvCoordinates = split[2] + "," + split[3];
        }
    } catch (final HttpException e) {
        //
    } catch (final IOException e) {
        //
    }

    return csvCoordinates;
}

From source file:org.olat.modules.tu.IframeTunnelController.java

/**
 * Constructor for a tunnel component wrapper controller
 * //from  ww w.j ava 2  s. com
 * @param ureq the userrequest
 * @param wControl the windowcontrol
 * @param config the module configuration
 */
public IframeTunnelController(final UserRequest ureq, final WindowControl wControl,
        final ModuleConfiguration config) {
    super(ureq, wControl);
    // use iframe translator for generic iframe title text
    setTranslator(Util.createPackageTranslator(IFrameDisplayController.class, ureq.getLocale()));
    this.config = config;

    // configuration....
    final int configVersion = config.getConfigurationVersion();
    // since config version 1
    final String proto = (String) config.get(TUConfigForm.CONFIGKEY_PROTO);
    final String host = (String) config.get(TUConfigForm.CONFIGKEY_HOST);
    final Integer port = (Integer) config.get(TUConfigForm.CONFIGKEY_PORT);
    final String user = (String) config.get(TUConfigForm.CONFIGKEY_USER);
    final String startUri = (String) config.get(TUConfigForm.CONFIGKEY_URI);
    final String pass = (String) config.get(TUConfigForm.CONFIGKEY_PASS);
    String firstQueryString = null;
    if (configVersion == 2) {
        // query string is available since config version 2
        firstQueryString = (String) config.get(TUConfigForm.CONFIGKEY_QUERY);
    }

    final boolean usetunnel = config.getBooleanSafe(TUConfigForm.CONFIG_TUNNEL);
    myContent = createVelocityContainer("iframe_index");
    if (!usetunnel) { // display content directly
        final String rawurl = TUConfigForm.getFullURL(proto, host, port, startUri, firstQueryString).toString();
        myContent.contextPut("url", rawurl);
    } else { // tunnel
        final Identity ident = ureq.getIdentity();

        if (user != null && user.length() > 0) {
            httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, user,
                    pass);
        } else {
            httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, null,
                    null);
        }

        final Locale loc = ureq.getLocale();
        final Mapper mapper = new Mapper() {
            @Override
            public MediaResource handle(final String relPath, final HttpServletRequest hreq) {
                MediaResource mr = null;
                final String method = hreq.getMethod();
                String uri = relPath;
                HttpMethod meth = null;

                if (uri == null) {
                    uri = (startUri == null) ? "" : startUri;
                }
                if (uri.length() > 0 && uri.charAt(0) != '/') {
                    uri = "/" + uri;
                }

                // String contentType = hreq.getContentType();

                // if (allowedToSendPersonalHeaders) {
                final String userName = ident.getName();
                final User u = ident.getUser();
                final String lastName = u.getProperty(UserConstants.LASTNAME, loc);
                final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc);
                final String email = u.getProperty(UserConstants.EMAIL, loc);

                if (method.equals("GET")) {
                    final GetMethod cmeth = new GetMethod(uri);
                    final String queryString = hreq.getQueryString();
                    if (queryString != null) {
                        cmeth.setQueryString(queryString);
                    }
                    meth = cmeth;
                    // if response is a redirect, follow it
                    if (meth == null) {
                        return null;
                    }
                    meth.setFollowRedirects(true);

                } else if (method.equals("POST")) {
                    // if (contentType == null || contentType.equals("application/x-www-form-urlencoded")) {
                    // regular post, no file upload
                    // }
                    final Map params = hreq.getParameterMap();
                    final PostMethod pmeth = new PostMethod(uri);
                    final Set postKeys = params.keySet();
                    for (final Iterator iter = postKeys.iterator(); iter.hasNext();) {
                        final String key = (String) iter.next();
                        final String vals[] = (String[]) params.get(key);
                        for (int i = 0; i < vals.length; i++) {
                            pmeth.addParameter(key, vals[i]);
                        }
                        meth = pmeth;
                    }
                    if (meth == null) {
                        return null;
                        // Redirects are not supported when using POST method!
                        // See RFC 2616, section 10.3.3, page 62
                    }

                }

                // Add olat specific headers to the request, can be used by external
                // applications to identify user and to get other params
                // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
                meth.addRequestHeader("X-OLAT-USERNAME", userName);
                meth.addRequestHeader("X-OLAT-LASTNAME", lastName);
                meth.addRequestHeader("X-OLAT-FIRSTNAME", firstName);
                meth.addRequestHeader("X-OLAT-EMAIL", email);

                boolean ok = false;
                try {
                    httpClientInstance.executeMethod(meth);
                    ok = true;
                } catch (final Exception e) {
                    // handle error later
                }

                if (!ok) {
                    // error
                    meth.releaseConnection();
                    return new NotFoundMediaResource(relPath);
                }

                // get or post successfully
                final Header responseHeader = meth.getResponseHeader("Content-Type");
                if (responseHeader == null) {
                    // error
                    return new NotFoundMediaResource(relPath);
                }
                mr = new HttpRequestMediaResource(meth);
                return mr;
            }
        };

        final String amapPath = registerMapper(mapper);
        String alluri = amapPath + startUri;
        if (firstQueryString != null) {
            alluri += "?" + firstQueryString;
        }
        myContent.contextPut("url", alluri);
    }

    final String frameId = "ifdc" + hashCode(); // for e.g. js use
    myContent.contextPut("frameId", frameId);

    putInitialPanel(myContent);
}

From source file:org.olat.modules.tu.TunnelComponent.java

/**
 * @param tuReq//  ww  w.ja v a2  s . co  m
 * @param client
 * @return HttpMethod
 */
public HttpMethod fetch(final TURequest tuReq, final HttpClient client) {

    final String modulePath = tuReq.getUri();

    HttpMethod meth = null;
    final String method = tuReq.getMethod();
    if (method.equals("GET")) {
        final GetMethod cmeth = new GetMethod(modulePath);
        final String queryString = tuReq.getQueryString();
        if (queryString != null) {
            cmeth.setQueryString(queryString);
        }
        meth = cmeth;
        if (meth == null) {
            return null;
        }
        // if response is a redirect, follow it
        meth.setFollowRedirects(true);

    } else if (method.equals("POST")) {
        final String type = tuReq.getContentType();
        if (type == null || type.equals("application/x-www-form-urlencoded")) {
            // regular post, no file upload
        }

        final PostMethod pmeth = new PostMethod(modulePath);
        final Set postKeys = tuReq.getParameterMap().keySet();
        for (final Iterator iter = postKeys.iterator(); iter.hasNext();) {
            final String key = (String) iter.next();
            final String vals[] = (String[]) tuReq.getParameterMap().get(key);
            for (int i = 0; i < vals.length; i++) {
                pmeth.addParameter(key, vals[i]);
            }
            meth = pmeth;
        }
        if (meth == null) {
            return null;
            // Redirects are not supported when using POST method!
            // See RFC 2616, section 10.3.3, page 62
        }
    }

    // Add olat specific headers to the request, can be used by external
    // applications to identify user and to get other params
    // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
    meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName());
    meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName());
    meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName());
    meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail());

    try {
        client.executeMethod(meth);
        return meth;
    } catch (final Exception e) {
        meth.releaseConnection();
    }
    return null;
}

From source file:org.olat.restapi.UserMgmtTest.java

@Test
public void testFindUsersByLogin() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("login", "administrator"),
            new NameValuePair("authProvider", "OLAT") });
    final int code = c.executeMethod(method);
    assertEquals(code, 200);//from  w ww. java 2  s  .  co  m
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);
    final String[] authProviders = new String[] { "OLAT" };
    final List<Identity> identities = BaseSecurityManager.getInstance().getIdentitiesByPowerSearch(
            "administrator", null, true, null, null, authProviders, null, null, null, null,
            Identity.STATUS_VISIBLE_LIMIT);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    assertEquals(vos.size(), identities.size());
    boolean onlyLikeAdmin = true;
    for (final UserVO vo : vos) {
        if (!vo.getLogin().startsWith("administrator")) {
            onlyLikeAdmin = false;
        }
    }
    assertTrue(onlyLikeAdmin);
}

From source file:org.olat.restapi.UserMgmtTest.java

@Test
public void testFindUsersByProperty() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("telMobile", "39847592"),
            new NameValuePair("gender", "Female"), new NameValuePair("birthDay", "12/12/2009") });
    method.addRequestHeader("Accept-Language", "en");
    final int code = c.executeMethod(method);
    assertEquals(code, 200);//from   w  w w . ja  va  2 s.  co  m
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
}

From source file:org.olat.restapi.UserMgmtTest.java

@Test
public void testFindAdminByAuth() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("authUsername", "administrator"),
            new NameValuePair("authProvider", "OLAT") });
    final int code = c.executeMethod(method);
    assertEquals(code, 200);/*from  w  ww. ja v  a2 s  .c o m*/
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    assertEquals(1, vos.size());
    assertEquals("administrator", vos.get(0).getLogin());
}

From source file:org.openlaszlo.servlets.HistoryServlet.java

private void doSendHistory(HttpServletRequest req, HttpServletResponse res, Document doc) {
    mLogger.info("doSendHistory");
    Element el = doc.getRootElement().getChild("root").getChild("history");

    ServletOutputStream out = null;//from  w w  w  .  ja  va2  s.  c o  m
    GetMethod request = null;
    String status = null;
    String body = null;
    try {
        out = res.getOutputStream();

        request = new MyGetMethod();

        String url = mURL + "?lzt=agentmessage" + "&url=" + URLEncoder.encode(mAgentURL) + "&group="
                + mAgentGroup + "&to=*&range=user" + "&dset=" + mClientDataset + "&msg="
                + URLEncoder.encode(getXMLHistory());

        mLogger.debug("url: " + url);
        URI uri = new URI(url.toCharArray());
        HostConfiguration hcfg = new HostConfiguration();
        hcfg.setHost(uri);

        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();

        mLogger.debug("path: " + path);
        mLogger.debug("query: " + query);

        request.setPath(path);
        request.setQueryString(query);

        HttpClient htc = new HttpClient(mConnectionMgr);
        htc.setHostConfiguration(hcfg);
        int rc = htc.executeMethod(hcfg, request);

        status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug("remote response status: " + status);

        body = request.getResponseBodyAsString();

        mLogger.debug("response body: " + body);
    } catch (HttpRecoverableException e) {
        mLogger.debug("HttpRecoverableException: " + e.getMessage());
        sendError(out, "<status message=\"HttpRecoverableException " + e.getMessage() + "\" />");
    } catch (HttpException e) {
        mLogger.debug("HttpException: " + e.getMessage());
        sendError(out, "<status message=\"HttpException " + e.getMessage() + "\" />");
    } catch (IOException e) {
        mLogger.debug("IOException: " + e.getMessage());
        sendError(out, "<status message=\"IOException " + e.getMessage() + "\" />");
    } finally {
        if (request != null) {
            request.releaseConnection();
        }
    }

    try {
        if (status != null && status.equals("OK")) {
            out.println("<status message=\"ok\">" + (body != null ? body : "") + "</status>");
        } else {
            out.println("<status message=\"" + mURL + "?lzt=agentmessage" + " " + status + "\" />");
        }
        out.flush();
    } catch (IOException e) {
        mLogger.debug("Client IOException");
        // ignore client ioexception
    } finally {
        close(out);
    }
}

From source file:org.openlaszlo.servlets.responders.ResponderCompile.java

/**
 * @return File name for temporary LZX file that is the
 *         result of this http pre-processing; null for a bad request
 * @param req request/*www  .  ja v  a2s  . co  m*/
 * @param fileName file name associated with request
 */
private String doPreProcessing(HttpServletRequest req, String fileName) throws IOException {
    // Do an http request for this and see what we get back.
    //
    StringBuffer s = req.getRequestURL();
    int len = s.length();
    // Remove the .lzx from the end of the URL
    if (len <= 4) {
        return null;
    }
    s.delete(len - 4, len);

    // FIXME [2002-12-15 bloch] does any/all of this need to be synchronized on session?

    // First get the temporary file name for this session
    HttpSession session = req.getSession();
    String sid = session.getId();
    String tempFileName = getTempFileName(fileName, sid);
    File tempFile = new File(tempFileName);

    tempFile.deleteOnExit();

    // Now pre-process the request and copy the data to
    // the temporary file that is unique to this session

    // FIXME: query string processing

    String surl = s.toString();

    URL url = new URL(surl);
    mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="Preprocessing request at " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(), "051018-263",
                    new Object[] { surl }));
    GetMethod getRequest = new LZGetMethod();
    getRequest.setPath(url.getPath());
    //getRequest.setQueryString(url.getQuery());
    getRequest.setQueryString(req.getQueryString());

    // Copy headers to request
    LZHttpUtils.proxyRequestHeaders(req, getRequest);
    // Mention the last modified time, if the file exists
    if (tempFile.exists()) {
        long lastModified = tempFile.lastModified();
        getRequest.addRequestHeader("If-Modified-Since", LZHttpUtils.getDateString(lastModified));
    } else {
        // Otherwise, create a listener that will clean up the tempfile
        // Note: web server administrators must make sure that their servers are killed
        // gracefully or temporary files will not be handled by the LZBindingListener.
        // Add a binding listener for this session that
        // will remove our temporary files
        LZBindingListener listener = (LZBindingListener) session.getAttribute("tmpl");
        if (listener == null) {
            listener = new LZBindingListener(tempFileName);
            session.setAttribute("tmpl", listener);
        } else {
            listener.addTempFile(tempFileName);
        }
    }

    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(url.getHost(), url.getPort(), url.getProtocol());

    HttpClient htc = new HttpClient();
    htc.setHostConfiguration(hostConfig);

    int rc = htc.executeMethod(getRequest);
    mLogger.debug("Response Status: " + rc);
    if (rc >= 400) {
        // respondWithError(req, res, "HTTP Status code: " + rc + " for url " + surl, rc);
        return null;
    }
    if (rc != HttpServletResponse.SC_NOT_MODIFIED) {
        FileOutputStream output = new FileOutputStream(tempFile);
        try {
            // FIXME:[2002-12-17 bloch] verify that the response body is XML
            FileUtils.sendToStream(getRequest.getResponseBodyAsStream(), output);
            // TODO: [2002-12-15 bloch] What to do with response headers?
        } catch (FileUtils.StreamWritingException e) {
            mLogger.warn(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="StreamWritingException while sending error: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(),
                            "051018-313", new Object[] { e.getMessage() }));
        } finally {
            FileUtils.close(output);
        }
    }

    return tempFileName;
}

From source file:org.openmrs.module.openconceptlab.client.OclClient.java

public OclResponse fetchUpdates(String url, String token, Date updatedSince) throws IOException {
    totalBytesToDownload = -1; //unknown yet
    bytesDownloaded = 0;//from   w ww  . j a v  a  2  s  .  com

    GetMethod get = new GetMethod(url);
    if (!StringUtils.isBlank(token)) {
        get.addRequestHeader("Authorization", "Token " + token);
        get.addRequestHeader("Compress", "true");
    }

    List<NameValuePair> query = new ArrayList<NameValuePair>();
    query.add(new NameValuePair("includeMappings", "true"));
    query.add(new NameValuePair("includeConcepts", "true"));
    query.add(new NameValuePair("includeRetired", "true"));
    query.add(new NameValuePair("limit", "100000"));

    if (updatedSince != null) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        query.add(new NameValuePair("updatedSince", dateFormat.format(updatedSince)));
    }

    get.setQueryString(query.toArray(new NameValuePair[0]));

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_IN_MS);
    client.executeMethod(get);

    if (get.getStatusCode() != 200) {
        throw new IOException(get.getStatusLine().toString());
    }

    return extractResponse(get);
}