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

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

Introduction

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

Prototype

public URIBuilder() 

Source Link

Document

Constructs an empty instance.

Usage

From source file:ar.edu.ubp.das.src.chat.actions.ActualizarMensajesAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String ultimo_mensaje = String.valueOf(request.getSession().getAttribute("ultimo_mensaje"));
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        if (ultimo_mensaje.equals("null") || ultimo_mensaje.isEmpty()) {
            ultimo_mensaje = "-1";
        }/*w w w  .ja va 2  s  .  c  om*/

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/mensajes/sala/" + sala.getId());
        builder.setParameter("ultimo_mensaje", ultimo_mensaje);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //parse message data from response
        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<MensajeBean>>() {
        }.getType();
        List<MensajeBean> mensajes = gson.fromJson(restResp, listType);

        if (!mensajes.isEmpty()) {
            MensajeBean ultimo = mensajes.get(mensajes.size() - 1);
            request.getSession().removeAttribute("ultimo_mensaje");
            request.getSession().setAttribute("ultimo_mensaje", ultimo.getId_mensaje());
        }

        if (!ultimo_mensaje.equals("-1")) {
            request.setAttribute("mensajes", mensajes);
        }

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        String id_sala = (String) request.getSession().getAttribute("id_sala");
        request.setAttribute("message",
                "Error al intentar actualizar mensajes de Sala " + id_sala + ": " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java

public static OAuthApplicationInfo createOAuthApplication(RegistrationProfile registrationProfile, String host)
        throws DynamicClientRegistrationException {
    if (log.isDebugEnabled()) {
        log.debug("Invoking DCR service to create OAuth application for web app : "
                + registrationProfile.getClientName());
    }/*from  w  ww. ja  v a 2  s. c  o  m*/
    DefaultHttpClient httpClient = getHTTPSClient();
    String clientName = registrationProfile.getClientName();
    try {
        URI uri = new URIBuilder().setScheme(
                DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host)
                .setPath(
                        DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT)
                .build();
        Gson gson = new Gson();
        StringEntity entity = new StringEntity(gson.toJson(registrationProfile),
                DynamicClientWebAppRegistrationConstants.ContentTypes.CONTENT_TYPE_APPLICATION_JSON,
                DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8);
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();
        HttpEntity responseData = response.getEntity();
        String responseString = EntityUtils.toString(responseData,
                DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8);
        if (status != 201) {
            String msg = "Backend server error occurred while invoking DCR endpoint for "
                    + "registering service-provider upon web-app : '" + clientName
                    + "'; Server returned response '" + responseString + "' with HTTP status code '" + status
                    + "'";
            throw new DynamicClientRegistrationException(msg);
        }
        return getOAuthApplicationInfo(gson.fromJson(responseString, JsonElement.class));
    } catch (URISyntaxException e) {
        throw new DynamicClientRegistrationException(
                "Exception occurred while constructing the URI for invoking "
                        + "DCR endpoint for registering service-provider for web-app : " + clientName,
                e);
    } catch (UnsupportedEncodingException e) {
        throw new DynamicClientRegistrationException(
                "Exception occurred while constructing the payload for invoking "
                        + "DCR endpoint for registering service-provider for web-app : " + clientName,
                e);
    } catch (IOException e) {
        throw new DynamicClientRegistrationException("Connection error occurred while invoking DCR endpoint for"
                + " registering service-provider for web-app : " + clientName, e);
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:com.m3958.vertxio.assetfeed.integration.java.FileUploadTest.java

@Test
public void testPostRename() throws ClientProtocolException, IOException, URISyntaxException {

    File f = new File("README.md");

    InputStream is = Files.asByteSource(f).openBufferedStream();

    Assert.assertTrue(f.exists());//  w ww  .  j a  va 2s.  c o m

    String c = Request.Post(new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).build())
            .body(MultipartEntityBuilder.create()
                    .addBinaryBody("afile", is, ContentType.MULTIPART_FORM_DATA, f.getName())
                    .addTextBody("fn", "abcfn.md").build())
            .execute().returnContent().asString();

    String url = c.trim();
    Assert.assertTrue(url.endsWith("abcfn.md"));

    testComplete();
}

From source file:org.mushrappa.jparse.JParse.java

public JParse(String applicationID, String restAPIKey) {
    this.applicationID = applicationID;
    this.restAPIKey = restAPIKey;

    builder = new URIBuilder();
    builder.setScheme("https").setHost("api.parse.com");
}

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

public Map<String, String> authtokens() {
    Map<String, String> authMap = new HashMap<>();
    String json = "";
    try {//from ww w.  j  a  v a  2  s  .c  om
        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:org.dbrane.cloud.util.httpclient.HttpClientHelper.java

public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params) {
    try {// w  w w. ja v a 2s  .  c  o  m
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet);
    } catch (Exception e) {
        logger.debug(ErrorType.Httpclient.toString(), e);
        throw new BaseException(ErrorType.Httpclient, e);
    }
}

From source file:org.wso2.carbon.dynamic.client.web.proxy.RegistrationProxy.java

@POST
@Consumes(MediaType.APPLICATION_JSON)/*w ww.ja va  2  s  .  c  o  m*/
@Produces(MediaType.APPLICATION_JSON)
public Response register(RegistrationProfile registrationProfile) {
    DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient();
    String host = DCRProxyUtils.getKeyManagerHost();
    Response response;
    try {
        URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL)
                .setHost(host).setPath(Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT)
                .build();
        Gson gson = new Gson();
        StringEntity entity = new StringEntity(gson.toJson(registrationProfile), MediaType.APPLICATION_JSON,
                Constants.CharSets.CHARSET_UTF_8);
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(entity);
        CloseableHttpResponse serverResponse = httpClient.execute(httpPost);
        HttpEntity responseData = serverResponse.getEntity();
        int status = serverResponse.getStatusLine().getStatusCode();
        String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8);
        response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build();
    } catch (URISyntaxException e) {
        String msg = "Server error occurred while registering client '" + registrationProfile.getClientName()
                + "'";
        log.error(msg, e);
        response = Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
    } catch (UnsupportedEncodingException e) {
        String msg = "Request data encoding error occurred while registering client '"
                + registrationProfile.getClientName() + "'";
        log.error(msg, e);
        response = Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).entity(msg).build();
    } catch (IOException e) {
        String msg = "Service invoke error occurred while registering client.";
        log.error(msg, e);
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    } finally {
        httpClient.close();
    }
    return response;
}

From source file:org.mobicents.servlet.restcomm.http.client.HttpRequestDescriptor.java

private URI base(final URI uri) {
    try {/*from  w  w  w .  ja v  a2s  . co m*/
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setScheme(uri.getScheme());
        uriBuilder.setHost(uri.getHost());
        uriBuilder.setPort(uri.getPort());
        uriBuilder.setPath(uri.getPath());

        if (uri.getUserInfo() != null) {
            uriBuilder.setUserInfo(uri.getUserInfo());
        }
        return uriBuilder.build();
    } catch (final URISyntaxException ignored) {
        // This should never happen since we are using a valid URI to construct ours.
        return null;
    }
}

From source file:com.ibm.connectors.splunklog.SplunkConnectionData.java

private void populateURI(Properties props) throws ConnectorException {
    this.setHost(props.getProperty("host", ""));
    if (this.getHost().equalsIgnoreCase("")) {
        throw new ConnectorException("No host name configured for Splunk target.");
    }/*from   w ww .ja v a  2  s.c  om*/
    ;
    this.setPort(props.getProperty("port", "8089"));
    this.setScheme(props.getProperty("usehttps", "false").equalsIgnoreCase("true") ? "https" : "http");
    String resource = props.getProperty("resource");
    this.setUser(props.getProperty("user"));
    this.setPass(props.getProperty("pass"));
    this.setIgnoreSplunkErrors(props.getProperty("ignoreSplunkErrors", "").equalsIgnoreCase("true"));

    this.myUriBuilder = new URIBuilder();
    this.myUriBuilder.setHost(host);
    this.myUriBuilder.setPort(Integer.parseInt(port));
    this.myUriBuilder.setScheme(scheme);
    this.myUriBuilder.setPath(resource);
    this.myUriBuilder.addParameter("source", props.getProperty("event_source_component", "noSource"));
    if (!props.getProperty("index", "").isEmpty()) {
        this.myUriBuilder.addParameter("index", props.getProperty("index"));
    }
    this.myUriBuilder.addParameter("sourcetype", props.getProperty("sourcetype", "not specified"));
    this.myUriBuilder.addParameter("host", props.getProperty("event_source_host", getLocalhost()));

}

From source file:org.apache.trafficcontrol.client.trafficops.TOSession.java

protected URIBuilder newUriBuilder(final String path) {
    final String _path = String.format(URL_FORMAT_STR, this.apiBasePath(), this.apiVersion(), path);

    return new URIBuilder().setScheme(this.ssl() ? "https" : "http").setHost(this.host()).setPort(this.port())
            .setPath(_path);//from www . j a  v  a  2s  . com
}