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.ActualizarUsuariosAction.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 ultima_actualizacion = String.valueOf(request.getSession().getAttribute("ultima_actualizacion"));
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        if (ultima_actualizacion.equals("null") || ultima_actualizacion.isEmpty()) {
            ultima_actualizacion = String.valueOf(System.currentTimeMillis());
        }/*from  w ww  .j a  v a  2  s  .  co m*/

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

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

        if (restResp.equals("null") || restResp.isEmpty()) {
            return mapping.getForwardByName("success");
        }
        //parse actualizacion data from response
        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<ActualizacionBean>>() {
        }.getType();
        List<ActualizacionBean> actualizaciones = gson.fromJson(restResp, listType);
        List<UsuarioBean> usuarios = actualizaciones.stream()
                .filter(a -> a.getNombre_tipo().equals("UsuarioSala")).map(m -> m.getUsuario())
                .collect(Collectors.toList());

        request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis()));

        if (!usuarios.isEmpty()) {
            request.setAttribute("usuarios", usuarios);
        }

        return mapping.getForwardByName("success");

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

From source file:org.cloudcrawler.domain.crawler.robotstxt.RobotsTxtService.java

/**
 * This method is used to evaluate if the provided uri is
 * allowed to be crawled against the robots.txt of the website.
 *
 * @param uri/*from w  w w  .jav a2 s.  c  o  m*/
 * @return
 * @throws Exception
 */
public boolean isAllowedUri(URI uri) throws Exception {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(uri.getScheme());
    uriBuilder.setHost(uri.getHost());
    uriBuilder.setUserInfo(uri.getUserInfo());
    uriBuilder.setPath("/robots.txt");

    URI robotsTxtUri = uriBuilder.build();
    BaseRobotRules rules = (BaseRobotRules) cache.get(robotsTxtUri.toString());

    if (rules == null) {
        HttpResponse response = httpService.get(robotsTxtUri);

        try {

            // HACK! DANGER! Some sites will redirect the request to the top-level domain
            // page, without returning a 404. So look for a response which has a redirect,
            // and the fetched content is not plain text, and assume it's one of these...
            // which is the same as not having a robotstxt.txt file.

            String contentType = response.getEntity().getContentType().getValue();
            boolean isPlainText = (contentType != null) && (contentType.startsWith("text/plain"));

            if (response.getStatusLine().getStatusCode() == 404 || !isPlainText) {
                rules = robotsTxtParser.failedFetch(HttpStatus.SC_GONE);
            } else {
                StringWriter writer = new StringWriter();

                IOUtils.copy(response.getEntity().getContent(), writer);

                rules = robotsTxtParser.parseContent(uri.toString(), writer.toString().getBytes(),
                        response.getEntity().getContentType().getValue(), httpService.getUserAgent());

            }
        } catch (Exception e) {
            EntityUtils.consume(response.getEntity());
            throw e;
        }

        EntityUtils.consume(response.getEntity());
        cache.set(robotsTxtUri.toString(), 60 * 60 * 24, rules);
    }

    return rules.isAllowed(uri.toString());
}

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();/*  ww  w  .  j a  v  a  2 s  . c  o  m*/

    // 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:org.metaeffekt.dcc.agent.DccAgentUriBuilder.java

protected URIBuilder createUriBuilder() {

    Assert.notNull(host, "No host configured");
    Assert.notNull(port, "No port configured");

    URIBuilder builder = new URIBuilder();
    builder.setScheme(DEFAULT_PROTOCOL).setHost(host).setPort(port);

    return builder;
}

From source file:com.uber.stream.kafka.mirrormaker.common.utils.HttpClientUtils.java

public static int postData(final HttpClient httpClient, final RequestConfig requestConfig, final String host,
        final int port, final String path, final String src, final String dst, final int routeId)
        throws IOException, URISyntaxException {
    URI uri = new URIBuilder().setScheme("http").setHost(host).setPort(port).setPath(path)
            .addParameter("src", src).addParameter("dst", dst).addParameter("routeid", String.valueOf(routeId))
            .build();//from  w  ww  .j  a  v  a2s.com

    HttpPost httpPost = new HttpPost(uri);
    httpPost.setConfig(requestConfig);

    return httpClient.execute(httpPost, HttpClientUtils.createResponseCodeExtractor());
}

From source file:tools.devnull.boteco.plugins.redhat.KBaseMessageProcessor.java

private void fetch(IncomeMessage message, String number) {
    try {/*from   www .ja  v  a2  s  .co m*/
        URI uri = new URIBuilder().setScheme("https").setHost("api.access.redhat.com").setPath("/rs/search")
                .addParameter("enableElevation", "true").addParameter("fq", "language:(en)")
                .addParameter("q", number).build();

        KBaseSearchResult result = restClient.get(uri).withHeader("Accept", "application/vnd.redhat.solr+json")
                .to(KBaseSearchResult.class).result();

        KBaseSearchResult.Doc document = result.results().stream().filter(rightSolution(number)).findFirst()
                .orElse(null);

        if (document != null) {
            message.sendBack("[t]%s[/t] [l]%s|%s[/l] ([v]%s[/v] links)", document.getDocumentKind(),
                    document.getTitle(), document.getViewUri(), document.getCaseCount());
        }
    } catch (Exception e) {
        logger.error("Error while fetching kbase article", e);
    }
}

From source file:org.openhim.mediator.engine.connectors.HTTPConnector.java

private URI buildURI(MediatorHTTPRequest req) throws URISyntaxException {
    URIBuilder builder = new URIBuilder().setScheme(req.getScheme()).setHost(req.getHost())
            .setPort(req.getPort()).setPath(req.getPath());
    if (req.getParams() != null) {
        Iterator<String> iter = req.getParams().keySet().iterator();
        while (iter.hasNext()) {
            String param = iter.next();
            builder.addParameter(param, req.getParams().get(param));
        }//from   w w w  .ja  v a2 s.c  o m
    }
    return builder.build();
}

From source file:eu.seaclouds.platform.dashboard.http.HttpPostRequestBuilder.java

public String build() throws IOException, URISyntaxException {
    if (!params.isEmpty() && entity == null) {
        if (!isMultipart) {
            this.entity = new UrlEncodedFormEntity(params);
        } else {/*from   w w w  . jav a2s  .c o m*/
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            for (NameValuePair pair : params) {
                entityBuilder.addTextBody(pair.getName(), pair.getValue());
            }

            this.entity = entityBuilder.build();
        }
    }

    URI uri = new URIBuilder().setHost(host).setPath(path).setScheme(scheme).build();

    this.requestBase = new HttpPost(uri);

    for (NameValuePair header : super.headers) {
        requestBase.addHeader(header.getName(), header.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        if (this.entity != null) {
            this.requestBase.setEntity(this.entity);
        }
        return httpClient.execute(requestBase, responseHandler, context);
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.ConsulServiceProfileFactoryBuilder.java

public ProfileFactory build(SpinnakerService.Type type, ServiceSettings settings) {
    return new ProfileFactory() {
        @Override// ww  w  .  j av  a  2  s. c o m
        protected ArtifactService getArtifactService() {
            return artifactService;
        }

        @Override
        protected void setProfile(Profile profile, DeploymentConfiguration deploymentConfiguration,
                SpinnakerRuntimeSettings endpoints) {
            ConsulCheck check = new ConsulCheck().setId("default-hal-check").setInterval("30s");

            if (settings.getHealthEndpoint() != null) {
                check.setHttp(new URIBuilder().setScheme(settings.getScheme()).setHost("localhost")
                        .setPort(settings.getPort()).setPath(settings.getHealthEndpoint()).toString());
            } else {
                check.setTcp("localhost:" + settings.getPort());
            }

            ConsulService consulService = new ConsulService().setName(type.getCanonicalName())
                    .setPort(settings.getPort()).setChecks(Collections.singletonList(check));

            try {
                profile.appendContents(objectMapper.writeValueAsString(consulService));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        protected Profile getBaseProfile(String name, String version, String outputFile) {
            return new Profile(name, version, outputFile, "");
        }

        @Override
        public SpinnakerArtifact getArtifact() {
            return SpinnakerArtifact.CONSUL;
        }

        @Override
        protected String commentPrefix() {
            return "// ";
        }

        @Override
        protected boolean showEditWarning() {
            return false;
        }
    };
}

From source file:org.metaservice.demo.securityalert.NotificationBackend.java

public void send(String api, String s, String cve) {
    LOGGER.info("Sending {} {}", s, cve);
    URIBuilder uriBuilder = new URIBuilder();

    uriBuilder.setScheme("http").setHost("www.notifymyandroid.com").setPort(80).setPath("/publicapi/notify");

    try {//from www  .  j  a  va2s. co  m
        String result = Request.Post(uriBuilder.build())
                .bodyForm(Form.form().add("apikey", api).add("event", s).add("application", "metaservice.org")
                        .add("priority", "2").add("description", s).add("url", cve).build())
                .connectTimeout(1000).socketTimeout(30000)
                // .setHeader("Accept", mimeType)
                .execute().returnContent().asString();
        LOGGER.info(result);
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }
}