Example usage for org.apache.http.client.utils URIBuilder addParameter

List of usage examples for org.apache.http.client.utils URIBuilder addParameter

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder addParameter.

Prototype

public URIBuilder addParameter(final String param, final String value) 

Source Link

Document

Adds parameter to URI query.

Usage

From source file:org.loklak.api.search.TweetScraper.java

protected String prepareSearchUrl(String type) {
    URIBuilder url = null;
    String typeMedia = "tweets";
    String midUrl = "search/";

    if (this.since != null) {
        this.query = this.query + " " + "since:" + this.since;
    }//from w ww  . ja v a2  s  . co  m
    if (this.until != null) {
        this.query = this.query + " " + "until:" + this.until;
    }

    if (this.filterList.contains("video") && this.filterList.size() == 1) {
        typeMedia = "video";
    }

    try {
        url = new URIBuilder(this.baseUrl + midUrl);
        switch (type) {
        case "user":
            typeMedia = "users";
            break;
        case "tweet":
            typeMedia = "tweets";
            break;
        case "image":
            typeMedia = "images";
            break;
        case "video":
            typeMedia = "videos";
            break;
        default:
            typeMedia = "tweets";
            break;
        }

        url.addParameter("f", typeMedia);
        url.addParameter("q", this.query);
        url.addParameter("vertical", "default");
        url.addParameter("src", "typd");
    } catch (URISyntaxException e) {
        DAO.log("Invalid Url: baseUrl = " + this.baseUrl + ", mid-URL = " + midUrl + ", query = " + this.query
                + ", type = " + type);
    }
    return url.toString();
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }//ww  w  . j  a  v a2 s .  com

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

String addCAToURL(String url) throws URISyntaxException, MalformedURLException {
    URIBuilder uri = new URIBuilder(url);
    if (caName != null) {
        uri.addParameter("ca", caName);
    }/*from   w  ww  .j a v  a 2s  . c  om*/
    return uri.build().toURL().toString();
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

String getURL(String endpoint, Map<String, String> queryMap)
        throws URISyntaxException, MalformedURLException, InvalidArgumentException {
    setUpSSL();/* w  ww.  j  a va 2s. c om*/
    String url = addCAToURL(this.url + endpoint);
    URIBuilder uri = new URIBuilder(url);
    if (queryMap != null) {
        for (Map.Entry<String, String> param : queryMap.entrySet()) {
            if (!Utils.isNullOrEmpty(param.getValue())) {
                uri.addParameter(param.getKey(), param.getValue());
            }
        }
    }
    return uri.build().toURL().toString();
}

From source file:servlets.Samples_servlets.java

/**
 * *//from w  ww.  j a va 2s .c o  m
 * This function retrieves the registered samples for a given LIMS. The
 * function requires a valid LIMS type, the URL for the service, and the
 * user credentials.
 *
 * @param request
 * @param response
 * @throws IOException
 */
private void get_external_samples_list(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    JsonArray samples = new JsonArray();

    try {
        /**
         * *******************************************************
         * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF ERROR
         * --> throws exception if not valid session, GO TO STEP 5b ELSE -->
         * GO TO STEP 2
         * *******************************************************
         */
        Map<String, Cookie> cookies = this.getCookies(request);
        String loggedUser = cookies.get("loggedUser").getValue();
        String sessionToken = cookies.get("sessionToken").getValue();

        if (!checkAccessPermissions(loggedUser, sessionToken)) {
            throw new AccessControlException("Your session is invalid. User or session token not allowed.");
        }

        //Read the JSON file
        String external_sample_type = request.getParameter("external_sample_type");
        File file = new File(DATA_LOCATION + File.separator + "extensions" + File.separator + "external_sources"
                + File.separator + external_sample_type);
        JsonObject lims_data;
        if (file.isFile()) {
            lims_data = new JsonParser().parse(new BufferedReader(new FileReader(file))).getAsJsonObject();
        } else {
            throw new FileNotFoundException(
                    "JSON file for selected LIMS cannot be found. File name is " + external_sample_type);
        }

        String get_all_url = lims_data.get("get_all_url").getAsString();
        String human_readable_url = lims_data.get("human_readable_url").getAsString();
        String id_field = lims_data.get("id_field").getAsString();
        String name_field = lims_data.get("name_field").getAsString();
        String list_samples_field = lims_data.get("list_samples_field").getAsString();
        String apikey_param = "";
        if (lims_data.get("apikey_param") != null) {
            apikey_param = lims_data.get("apikey_param").getAsString();
        }

        //Request the list of samples for the selected LIMS
        String external_sample_url = request.getParameter("external_sample_url");
        //Adapt URL
        if (!(external_sample_url.startsWith("http://") || external_sample_url.startsWith("https://"))) {
            external_sample_url = "http://" + external_sample_url;
        }
        if (external_sample_url.endsWith("/")) {
            external_sample_url = external_sample_url.substring(0, external_sample_url.length() - 1);
        }

        get_all_url = get_all_url.replace("$${APP_URL}", external_sample_url);
        human_readable_url = human_readable_url.replace("$${APP_URL}", external_sample_url);

        //Prepare request
        HttpClient client = new DefaultHttpClient();
        HttpGet _request = new HttpGet(get_all_url);
        // Set LIMS credentials
        if (request.getParameter("credentials") != null) {
            _request.setHeader("Authorization", "Basic " + request.getParameter("credentials"));
        } else if (request.getParameter("apikey") != null) {
            URIBuilder uri = new URIBuilder(get_all_url);
            uri.addParameter(apikey_param, request.getParameter("apikey"));
            _request = new HttpGet(uri.build());
        }

        //Send request
        HttpResponse _response = client.execute(_request);
        JsonElement json_response = new JsonParser().parse(EntityUtils.toString(_response.getEntity()));

        if (json_response.isJsonObject()) {
            JsonArray sample_list = json_response.getAsJsonObject().get(list_samples_field).getAsJsonArray();
            JsonObject object;
            for (JsonElement element : sample_list) {
                object = new JsonObject();
                object.add("id", element.getAsJsonObject().get(id_field));
                object.add("name", element.getAsJsonObject().get(name_field));
                object.add("url", new JsonPrimitive(human_readable_url.replace("$${SAMPLE_ID}",
                        element.getAsJsonObject().get(id_field).getAsString())));
                samples.add(object);
            }
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "get_external_samples_list",
                e.getMessage());
    } finally {
        /**
         * *******************************************************
         * STEP 3b CATCH ERROR. GO TO STEP 4
         * *******************************************************
         */
        if (ServerErrorManager.errorStatus()) {
            response.setStatus(400);
            response.getWriter().print(ServerErrorManager.getErrorResponse());
        } else {
            /**
             * *******************************************************
             * STEP 3A WRITE SUCCESS RESPONSE. GO TO STEP 4
             * *******************************************************
             */
            JsonObject obj = new JsonObject();
            obj.add("samples", samples);
            response.getWriter().print(obj.toString());
        }
    }
}

From source file:servlets.Samples_servlets.java

/**
 * *//ww  w .j  av a2s .  com
 * This function retrieves the details for a specific sample from a LIMS.
 *
 * @param request
 * @param response
 * @throws IOException
 */
private void get_external_samples_details(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    DAO dao_instance = null;
    JsonObject sample_details = new JsonObject();

    try {
        /**
         * *******************************************************
         * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF ERROR
         * --> throws exception if not valid session, GO TO STEP 5b ELSE -->
         * GO TO STEP 2
         * *******************************************************
         */
        Map<String, Cookie> cookies = this.getCookies(request);
        String loggedUser = cookies.get("loggedUser").getValue();
        String sessionToken = cookies.get("sessionToken").getValue();

        if (!checkAccessPermissions(loggedUser, sessionToken)) {
            throw new AccessControlException("Your session is invalid. User or session token not allowed.");
        }

        //Load the sample information
        String biocondition_id = request.getParameter("biocondition_id");
        dao_instance = DAOProvider.getDAOByName("Biocondition");
        boolean loadRecursive = true;
        Object[] params = { loadRecursive };
        BioCondition biocondition = (BioCondition) dao_instance.findByID(biocondition_id, params);

        //Read the JSON file
        File file = new File(DATA_LOCATION + File.separator + "extensions" + File.separator + "external_sources"
                + File.separator + biocondition.getExternalSampleType());
        JsonObject lims_data;
        if (file.isFile()) {
            lims_data = new JsonParser().parse(new BufferedReader(new FileReader(file))).getAsJsonObject();
        } else {
            throw new FileNotFoundException("JSON file for selected LIMS cannot be found. File name is "
                    + biocondition.getExternalSampleType());
        }

        String api_readable_url = lims_data.get("api_readable_url").getAsString();
        String human_readable_url = lims_data.get("human_readable_url").getAsString();
        String sample_details_field = lims_data.get("sample_details_field").getAsString();
        String apikey_param = "";
        if (lims_data.get("apikey_param") != null) {
            apikey_param = lims_data.get("apikey_param").getAsString();
        }

        //Request the list of samples for the selected LIMS
        String external_sample_url = biocondition.getExternalSampleURL();
        //Adapt URL
        if (!(external_sample_url.startsWith("http://") || external_sample_url.startsWith("https://"))) {
            external_sample_url = "http://" + external_sample_url;
        }
        if (external_sample_url.endsWith("/")) {
            external_sample_url = external_sample_url.substring(0, external_sample_url.length() - 1);
        }

        api_readable_url = api_readable_url.replace("$${APP_URL}", external_sample_url).replace("$${SAMPLE_ID}",
                biocondition.getExternalSampleID());
        human_readable_url = human_readable_url.replace("$${APP_URL}", external_sample_url);

        //Prepare request
        HttpClient client = new DefaultHttpClient();
        HttpGet _request = new HttpGet(api_readable_url);
        // Set LIMS credentials
        if (request.getParameter("credentials") != null) {
            _request.setHeader("Authorization", "Basic " + request.getParameter("credentials"));
        } else if (request.getParameter("apikey") != null) {
            URIBuilder uri = new URIBuilder(api_readable_url);
            uri.addParameter(apikey_param, request.getParameter("apikey"));
            _request = new HttpGet(uri.build());
        }

        //Send request
        HttpResponse _response = client.execute(_request);
        JsonElement json_response = new JsonParser().parse(EntityUtils.toString(_response.getEntity()));

        if (json_response.isJsonObject()) {
            JsonElement _sample_details = json_response.getAsJsonObject().get(sample_details_field);
            if (_sample_details.isJsonObject()) {
                sample_details = _sample_details.getAsJsonObject();
            } else if (_sample_details.isJsonArray()) {
                sample_details = _sample_details.getAsJsonArray().get(0).getAsJsonObject();
            }
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "get_external_samples_details",
                e.getMessage());
    } finally {
        /**
         * *******************************************************
         * STEP 3b CATCH ERROR. GO TO STEP 4
         * *******************************************************
         */
        if (ServerErrorManager.errorStatus()) {
            response.setStatus(400);
            response.getWriter().print(ServerErrorManager.getErrorResponse());
        } else {
            /**
             * *******************************************************
             * STEP 3A WRITE SUCCESS RESPONSE. GO TO STEP 4
             * *******************************************************
             */
            JsonObject obj = new JsonObject();
            obj.add("sample_details", sample_details);
            response.getWriter().print(obj.toString());
        }
    }
}

From source file:edu.harvard.hms.dbmi.scidb.SciDB.java

public String releaseSession(String sessionId) throws NotConnectedException {
    if (!this.connected) {
        throw new NotConnectedException();
    }/*  w  w w. j  av  a2s .c o  m*/

    try {
        URIBuilder uriBuilder = new URIBuilder(this.url + "/release_session");
        uriBuilder.addParameter("id", sessionId);
        URI uri = uriBuilder.build();
        System.out.println(uri.toASCIIString());
        HttpGet runQuery = new HttpGet(uri);
        HttpResponse response = client.execute(runQuery);
        return inputStreamToString(response.getEntity().getContent());
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:edu.harvard.hms.dbmi.scidb.SciDB.java

public String executeQuery(SciDBCommand operation, String save) throws NotConnectedException {
    if (!this.connected) {
        throw new NotConnectedException();
    }/*from   ww  w. jav  a 2s.co m*/

    try {
        URIBuilder uriBuilder = new URIBuilder(this.url + "/execute_query");
        uriBuilder.addParameter("id", this.sessionId);
        uriBuilder.addParameter("query", operation.toAFLQueryString());
        if (save != null) {
            uriBuilder.addParameter("save", save);
        }

        URI uri = uriBuilder.build();
        System.out.println(uri.toASCIIString());
        HttpGet runQuery = new HttpGet(uri);
        HttpResponse response = client.execute(runQuery);
        return inputStreamToString(response.getEntity().getContent());
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.imsglobal.lti.toolProvider.ToolProvider.java

/**
 * Perform the result of an action.//from   w  w w .  j a v  a 2  s.c  om
 *
 * This function may redirect the user to another URL rather than returning a value.
 *
 * @return string Output to be displayed (redirection, or display HTML or message)
 */
private void result() {
    if (!ok) {
        ok = onError();
    }
    if (!ok) {
        try {
            if (returnUrl != null) {
                URIBuilder errorUrlBuilder = new URIBuilder(returnUrl.toExternalForm());
                //add necessary query parameters to error url
                //first, figure out if we know the reason
                HashMap<String, String> params = new HashMap<String, String>();
                if (debugMode && StringUtils.isNotEmpty(reason)) {
                    params.put("lti_errormsg", "Debug error: " + reason);
                } else {
                    params.put("lti_errormsg", message);
                    if (StringUtils.isNotEmpty(reason)) {
                        params.put("lti_errorlog", "Debug error: " + reason);
                    }
                }
                for (String key : params.keySet()) {
                    errorUrlBuilder.addParameter(key, params.get(key));
                }
                URL errorUrl;

                errorUrl = errorUrlBuilder.build().toURL();

                if (consumer != null && request != null) {
                    String ltiMessageType = request.getParameter("lti_message_type");
                    if (ltiMessageType.equals("ContentItemSelectionRequest")) {
                        String version = request.getParameter("lti_version");
                        if (version == null) {
                            version = LTI_VERSION1;
                        }
                        Map<String, List<String>> toSend = new HashMap<String, List<String>>();
                        Map<String, String[]> formParams = request.getParameterMap();
                        for (String key : formParams.keySet()) {
                            for (String v : formParams.get(key)) {
                                LTIUtil.setParameter(toSend, key, v);
                            }
                        }
                        Map<String, List<String>> signedParams = consumer.signParameters(
                                errorUrl.toExternalForm(), "ContentItemSelection", version, "POST", toSend);
                        String page = sendForm(errorUrl, signedParams);
                        System.out.print(page);
                    } else {
                        System.err.println("Attempt to redirect to " + errorUrl);
                        response.sendRedirect(errorUrl.toExternalForm());
                    }
                } else {
                    try {
                        System.err.println("Attempt to redirect to " + errorUrl);
                        response.sendRedirect(errorUrl.toExternalForm());
                    } catch (IOException ioe) {
                        return;
                    }
                }
                return;
            } else {
                if (errorOutput != null) {
                    System.err.println(errorOutput);
                } else if (debugMode && StringUtils.isNotEmpty(reason)) {
                    System.err.println("Debug error: " + reason);
                } else {
                    System.err.println("Error: " + message);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (this.redirectUrl != null) {
        try {
            System.err.println("Attempt to redirect to " + redirectUrl);
            this.response.sendRedirect(this.redirectUrl.toExternalForm());
        } catch (IOException ioe) {
            return;
        }
        return;
    } else if (output != null) {
        System.out.println(output);
    } else {
        System.out.println("Successful handling of request finished.");
    }
}