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

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

Introduction

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

Prototype

public URIBuilder setScheme(final String scheme) 

Source Link

Document

Sets URI scheme.

Usage

From source file:net.packet.Request.java

/**
 * Returns the composed endpoint URI.//from  w  ww . j a v a 2s  .co  m
 * 
 * @return {@link URI}
 * @throws URISyntaxException when URI is incorrect
 */
public URI buildUri() throws URISyntaxException {
    URIBuilder ub = new URIBuilder();
    ub.setScheme(Constants.URI_SCHEME);
    ub.setHost(Constants.HOSTNAME);

    String path = (null == pathParams) ? endpoint.getPath() : String.format(endpoint.getPath(), pathParams);
    ub.setPath(path);

    if (null != queryParams) {
        for (Map.Entry<String, String> entry : queryParams.entrySet()) {
            ub.setParameter(entry.getKey(), entry.getValue());
        }
    }

    return ub.build();
}

From source file:com.net.plus.common.http.transport.AbstractHttpClientTransport.java

public URI getSendUrl() {
    try {// ww  w .j a  v a  2 s .  co m
        if (StringUtils.hasText(url)) {
            return new URIBuilder(url).build();
        }
        URIBuilder builder = new URIBuilder();
        if (StringUtils.hasText(protocol)) {
            builder.setScheme(protocol);
        }
        if (StringUtils.hasText(host)) {
            builder.setHost(host);
        }
        if (port != -1) {
            builder.setPort(port);
        }
        if (StringUtils.hasText(target)) {
            builder.setPath(target);
        }
        if (StringUtils.hasText(queryString)) {
            builder.setQuery(queryString);
        }
        return builder.build();
    } catch (Exception e) {
        return null;
    }
}

From source file:com.att.voice.AttDigitalLife.java

public String getAttribute(Map<String, String> authMap, String deviceGUID, String attribute) {
    try {/*www.  ja v  a 2s.  c o  m*/
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices/" + deviceGUID + "/" + attribute);

        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Authtoken", authMap.get("Authtoken"));
        httpget.setHeader("Requesttoken", authMap.get("Requesttoken"));
        httpget.setHeader("Appkey", authMap.get("Appkey"));

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);

        String json = responseBody.trim();
        JSONObject content = new JSONObject(json);
        return content.getJSONObject("content").getString("value");
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
}

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

@Override
public MediaResource handle(String relPath, HttpServletRequest hreq) {
    String method = hreq.getMethod();
    String uri = relPath;//from  w w w. jav a2s  . c o m
    HttpUriRequest meth = null;

    try {
        URIBuilder builder = new URIBuilder();
        builder.setScheme(proto).setHost(host).setPort(port.intValue());
        if (uri == null) {
            uri = (startUri == null) ? "" : startUri;
        }
        if (uri.length() > 0 && uri.charAt(0) != '/') {
            uri = "/" + uri;
        }
        if (StringHelper.containsNonWhitespace(uri)) {
            builder.setPath(uri);
        }

        if (method.equals("GET")) {
            String queryString = hreq.getQueryString();
            if (StringHelper.containsNonWhitespace(queryString)) {
                builder.setCustomQuery(queryString);
            }
            meth = new HttpGet(builder.build());
        } else if (method.equals("POST")) {
            Map<String, String[]> params = hreq.getParameterMap();
            HttpPost pmeth = new HttpPost(builder.build());
            List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
            for (String key : params.keySet()) {
                String vals[] = params.get(key);
                for (String val : vals) {
                    pairs.add(new BasicNameValuePair(key, val));
                }
            }

            HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
            pmeth.setEntity(entity);
            meth = pmeth;
        }

        // 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
        if ("enabled".equals(
                CoreSpringFactory.getImpl(BaseSecurityModule.class).getUserInfosTunnelCourseBuildingBlock())) {
            User u = ident.getUser();
            meth.addHeader("X-OLAT-USERNAME", ident.getName());
            meth.addHeader("X-OLAT-LASTNAME", u.getProperty(UserConstants.LASTNAME, null));
            meth.addHeader("X-OLAT-FIRSTNAME", u.getProperty(UserConstants.FIRSTNAME, null));
            meth.addHeader("X-OLAT-EMAIL", u.getProperty(UserConstants.EMAIL, null));
            meth.addHeader("X-OLAT-USERIP", ipAddress);
        }

        HttpResponse response = httpClient.execute(meth);
        if (response == null) {
            // error
            return new NotFoundMediaResource(relPath);
        }

        // get or post successfully
        Header responseHeader = response.getFirstHeader("Content-Type");
        if (responseHeader == null) {
            // error
            EntityUtils.consumeQuietly(response.getEntity());
            return new NotFoundMediaResource(relPath);
        }
        return new HttpRequestMediaResource(response);
    } catch (ClientProtocolException e) {
        log.error("", e);
        return null;
    } catch (URISyntaxException e) {
        log.error("", e);
        return null;
    } catch (IOException e) {
        log.error("Error loading URI: " + (meth == null ? "???" : meth.getURI()), e);
        return null;
    }
}

From source file:com.att.voice.AttDigitalLife.java

public Map<String, String> authtokens() {
    Map<String, String> authMap = new HashMap<>();
    String json = "";
    try {/*from  w  w w . j av a  2s .c  o  m*/
        URIBuilder builder = new URIBuilder();
        builder.setScheme(HTTP_PROTOCOL).setHost(DIGITAL_LIFE_PATH).setPath("/penguin/api/authtokens")
                .setParameter(USER_ID_PARAMETER, username).setParameter(PASSWORD_PARAMETER, password)
                .setParameter(DOMAIN_PARAMETER, "DL").setParameter(APP_KEY_PARAMETER, APP_KEY);

        URI uri = builder.build();
        HttpPost httpPost = new HttpPost(uri);
        HttpResponse httpResponse = httpclient.execute(httpPost);

        httpResponse.getEntity();
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            json = EntityUtils.toString(entity);
        }

        JSONObject jsonObject = new JSONObject(json);
        JSONObject content = jsonObject.getJSONObject("content");
        authMap.put("id", content.getJSONArray("gateways").getJSONObject(0).getString("id"));
        authMap.put("Authtoken", content.getString("authToken"));
        authMap.put("Requesttoken", content.getString("requestToken"));

        authMap.put("Appkey", APP_KEY);

        if (content.has("contact") && content.getJSONObject("contact").has("firstName")
                && content.getJSONObject("contact").has("lastName")) {
            authMap.put("name", content.getJSONObject("contact").getString("firstName") + " "
                    + content.getJSONObject("contact").getString("lastName"));
        }

        return authMap;
    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(AttDigitalLife.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.att.voice.AttDigitalLife.java

public String getDeviceGUID(String device, Map<String, String> authMap) {
    try {/*  w  w w . j  a  va2  s  .  c om*/
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices");

        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Authtoken", authMap.get("Authtoken"));
        httpget.setHeader("Requesttoken", authMap.get("Requesttoken"));
        httpget.setHeader("Appkey", authMap.get("Appkey"));

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);

        String json = responseBody.trim();
        JSONObject jsonObject = new JSONObject(json);

        JSONArray array = jsonObject.getJSONArray("content");

        for (int i = 0; i <= array.length(); i++) {
            JSONObject d = array.getJSONObject(i);
            String type = d.getString("deviceType");
            if (type.equalsIgnoreCase(device)) {
                return d.getString("deviceGuid");
            }
        }
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
    return null;
}

From source file:org.metaservice.frontend.rest.SparqlEndpointResource.java

@Deprecated
private @NotNull InputStream querySparql(@NotNull String mimeType, @NotNull String query)
        throws URISyntaxException, IOException {
    System.err.println(query);/* ww w  . j a v  a  2 s.c o  m*/
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http").setHost("graph.metaservice.org").setPort(8080).setPath("/bigdata/sparql");

    return Request.Post(uriBuilder.build()).bodyForm(Form.form().add("query", query).build())
            .connectTimeout(1000).socketTimeout(60000).setHeader("Accept", mimeType).execute().returnContent()
            .asStream();
}

From source file:org.n52.sos.service.it.SosITBase.java

/**
 * Get URI for the relative sos path and query using test host, port, and
 * basepath/*from w ww . j a  v a2  s  .  co  m*/
 * 
 * @param path
 *            The relative test endpoint
 * @param query
 *            Query parameters to add to the request
 * @return Constructed URI
 * @throws URISyntaxException
 */
protected URI getURI(String path, String query) throws URISyntaxException {
    URIBuilder b = new URIBuilder();
    b.setScheme("http");
    b.setHost(host);
    b.setPort(port);
    b.setPath(getPath(path));
    b.setQuery(query);
    b.setFragment(null);

    return b.build();
}

From source file:teletype.model.vk.Auth.java

public void authorize() throws VKAuthException, IOException {

    // Phase 1. Send authorization request.
    // Opening OAuth Authorization Dialog
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("https").setHost("oauth.vk.com").setPath("/authorize").setParameter("client_id", appID)
            .setParameter("scope", "messages,friends,status")
            .setParameter("redirect_uri", "https://oauth.vk.com/blank.html").setParameter("display", "wap")
            .setParameter("v", "5.28").setParameter("response_type", "token");

    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    URI uri = getUri(uriBuilder);
    HttpPost request = new HttpPost(uri);
    HttpResponse response = httpClient.execute(request);
    request.abort();/*w ww .j a  va  2s  . com*/

    // Get ip_h and to_h parameters for next request 
    StringBuilder contentText = getContentText(response);

    String ip_h = parseResponse(contentText, "ip_h", 18);
    //System.out.println("ip_h : " + ip_h);

    String to_h = parseResponse(contentText, "=\"to\"", 212);
    //System.out.println("to_h : " + to_h);

    uriBuilder = new URIBuilder();
    uriBuilder.setScheme("https").setHost("login.vk.com").setPath("/").setParameter("act", "login")
            .setParameter("soft", "1").setParameter("q", "1").setParameter("ip_h", ip_h)
            .setParameter("from_host", "oauth.vk.com").setParameter("to", to_h).setParameter("expire", "0")
            .setParameter("email", login).setParameter("pass", password);

    request = new HttpPost(getUri(uriBuilder));
    response = httpClient.execute(request);
    request.abort();

    //System.out.println("Incorrect login url: " + uriBuilder.toString());

    // Phase 2. Providing Access Permissions
    // TODO: if got access request then call externall web browser. possible do it ourselves.

    // Phase 3. Open url with webengine and receiving "access_token".
    // It does not work with httpClient
    LoginControllerHelper.callHiddenWebBrowser(uriBuilder.toString());

    //if (true) return;

    /*
    printHeader(response);
            
    // Phase 2. Got redirect to authorization page.
    // Filling the form and sending it.
    //String HeaderLocation = response.getFirstHeader("location").getValue();
    request = new HttpPost(HeaderLocation);
    response = httpClient.execute(request);
    //System.out.println("==================>");
    request.abort();
    //String url = response.getFirstHeader("location").getValue();
            
    // Phase 3. Got permissions request.
    // Open web browser and sending link there.
    //System.out.println("URL is: " + url);
    // Calling externall web browser.
    ControllerHelper.callHiddenWebBrowser(url);
    //ControllerHelper.callWebBrowser(url);
            
    /*
     * It works by calling external web-browser.
     * All redirects ok and gives the token.
     * But doesn't work using HttpClient.
     * Server redirects me to error page.
     *
            
    request = new HttpPost(url);
    response = httpClient.execute(request);
    System.out.println("Sending last ==================>\n");
            
    HeaderLocation = response.getFirstHeader("location").getValue();
            
    //String access_token = HeaderLocation.split("#")[1].split("&")[0].split("=")[1];
    System.out.println("Header is: " + HeaderLocation);
    */
}

From source file:com.streamreduce.core.service.SearchServiceImpl.java

@Override
public JSONObject makeRequest(String path, JSONObject payload, Map<String, String> urlParameters,
        String method) {/*  w  ww.j  av a  2s . c o  m*/
    URIBuilder urlBuilder = new URIBuilder();
    urlBuilder.setScheme("http").setHost(elasticSearchHost).setPort(elasticSearchPort).setPath(path);
    if (urlParameters != null) {
        for (String paramName : urlParameters.keySet()) {
            String value = urlParameters.get(paramName);
            if (StringUtils.isNotBlank(value)) {
                urlBuilder.setParameter(paramName, value);
            }
        }
    }

    String url;
    try {
        url = urlBuilder.build().toString();
        String response = HTTPUtils.openUrl(url, method, payload.toString(), MediaType.APPLICATION_JSON, null,
                null, null, null);
        return JSONObject.fromObject(response);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}