Example usage for org.apache.http.client.fluent Request execute

List of usage examples for org.apache.http.client.fluent Request execute

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request execute.

Prototype

public Response execute() throws ClientProtocolException, IOException 

Source Link

Usage

From source file:org.kurento.orion.OrionConnector.java

/**
 * Sends a request to Orion/*w  ww  . jav  a2  s  .c o m*/
 *
 * @param ctxElement
 *          The context element
 * @param path
 *          the path from the context broker that determines which "operation"will be executed
 * @param responseClazz
 *          The class expected for the response
 * @return The object representing the JSON answer from Orion
 * @throws OrionConnectorException
 *           if a communication exception happens, either when contacting the context broker at
 *           the given address, or obtaining the answer from it.
 */
private <E, T> T sendRequestToOrion(E ctxElement, String path, Class<T> responseClazz) {
    String jsonEntity = gson.toJson(ctxElement);
    log.debug("Send request to Orion: {}", jsonEntity);

    Request req = Request.Post(this.orionAddr.toString() + path)
            .addHeader("Accept", APPLICATION_JSON.getMimeType()).bodyString(jsonEntity, APPLICATION_JSON)
            .connectTimeout(5000).socketTimeout(5000);
    Response response;
    try {
        response = req.execute();
    } catch (IOException e) {
        throw new OrionConnectorException("Could not execute HTTP request", e);
    }

    HttpResponse httpResponse = checkResponse(response);

    T ctxResp = getOrionObjFromResponse(httpResponse, responseClazz);
    log.debug("Sent to Orion. Obtained response: {}", httpResponse);

    return ctxResp;
}

From source file:com.kurento.kmf.orion.OrionConnector.java

/**
 * Sends a request to Orion//from   ww w  .j  a  v  a 2s .  c  om
 * 
 * @param ctxElement
 *            The context element
 * @param path
 *            the path from the context broker that determines which
 *            "operation"will be executed
 * @param responseClazz
 *            The class expected for the response
 * @return The object representing the JSON answer from Orion
 * @throws OrionConnectorException
 *             if a communication exception happens, either when contacting
 *             the context broker at the given address, or obtaining the
 *             answer from it.
 */
private <E, T> T sendRequestToOrion(E ctxElement, String path, Class<T> responseClazz) {
    String jsonEntity = gson.toJson(ctxElement);
    log.debug("Send request to Orion: {}", jsonEntity);

    Request req = Request.Post(orionAddr.toString() + path).addHeader("Accept", APPLICATION_JSON.getMimeType())
            .bodyString(jsonEntity, APPLICATION_JSON).connectTimeout(5000).socketTimeout(5000);
    Response response;
    try {
        response = req.execute();
    } catch (IOException e) {
        throw new OrionConnectorException("Could not execute HTTP request", e);
    }

    HttpResponse httpResponse = checkResponse(response);

    T ctxResp = getOrionObjFromResponse(httpResponse, responseClazz);

    log.debug("Send to Orion response: {}", httpResponse);

    return ctxResp;
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

public List<Column> readSourceSchema() throws IOException {
    Request request = Request.Get(url + API_DATASETS + dataSetId + "/metadata");
    request.addHeader(authorisationHeader);

    DataPrepStreamMapper dataPrepStreamMapper = null;
    MetaData metaData;/*from  w w w. jav a 2  s  .c o  m*/

    try {
        HttpResponse response = request.execute().returnResponse();
        if (returnStatusCode(response) != HttpServletResponse.SC_OK) {
            String moreInformation = extractResponseInformationAndConsumeResponse(response);
            LOGGER.error(messages.getMessage("error.retrieveSchemaFailed", moreInformation));
            throw new IOException(messages.getMessage("error.retrieveSchemaFailed", moreInformation));
        }
        dataPrepStreamMapper = new DataPrepStreamMapper(response.getEntity().getContent());
        metaData = dataPrepStreamMapper.getMetaData();
    } finally {
        if (dataPrepStreamMapper != null) {
            dataPrepStreamMapper.close();
        }
    }

    return metaData.getColumns();
}

From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java

private Response put(HttpRequest request) throws IOException {
    Request apacheRequest = Request.Put(request.getUrl());
    if (request.getBody() != null) {
        ContentType ct = ContentType.create(request.getContentType().getMimeType(),
                request.getContentType().getCharset());
        apacheRequest.bodyString(request.getBody(), ct);
    } else if (request.getBodyForm() != null) {
        apacheRequest.bodyForm(buildFormBody(request.getBodyForm()));
    }//from  w  ww  .  ja  v  a2  s .c  o m
    prepareRequest(apacheRequest);
    return apacheRequest.execute();
}

From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java

private Response post(HttpRequest request) throws IOException {
    Request apacheRequest = Request.Post(request.getUrl());
    if (request.getBody() != null) {
        ContentType ct = ContentType.create(request.getContentType().getMimeType(),
                request.getContentType().getCharset());
        apacheRequest.bodyString(request.getBody(), ct);
    } else if (request.getBodyForm() != null) {
        apacheRequest.bodyForm(buildFormBody(request.getBodyForm()));
    }/*w  w w  . j  a  v  a 2s  .  co m*/
    prepareRequest(apacheRequest);
    return apacheRequest.execute();
}

From source file:com.helger.peppol.httpclient.AbstractGenericSMPClient.java

/**
 * The main execution routine. Overwrite this method to add additional
 * properties to the call.// w w  w. j  a va2 s  .c o  m
 *
 * @param aRequest
 *        The request to be executed. Never <code>null</code>.
 * @return The HTTP execution response. Never <code>null</code>.
 * @throws IOException
 *         On HTTP error
 * @see #setProxy(HttpHost)
 * @see #setConnectionTimeoutMS(int)
 * @see #setRequestTimeoutMS(int)
 */
@Nonnull
@OverrideOnDemand
protected Response executeRequest(@Nonnull final Request aRequest) throws IOException {
    if (m_aProxy != null)
        aRequest.viaProxy(m_aProxy);
    if (m_nConnectionTimeoutMS > 0)
        aRequest.connectTimeout(m_nConnectionTimeoutMS);
    if (m_nRequestTimeoutMS > 0)
        aRequest.socketTimeout(m_nRequestTimeoutMS);

    return aRequest.execute();
}

From source file:aiai.ai.station.actors.DownloadSnippetActor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;// w w  w  .  j a  va 2  s  .c  o m
    }
    if (!globals.isStationEnabled) {
        return;
    }

    DownloadSnippetTask task;
    while ((task = poll()) != null) {
        if (Boolean.TRUE.equals(preparedMap.get(task.getSnippetCode()))) {
            continue;
        }
        final String snippetCode = task.snippetCode;

        AssetFile assetFile = StationResourceUtils.prepareResourceFile(globals.stationResourcesDir,
                Enums.BinaryDataType.SNIPPET, task.snippetCode, task.filename);
        if (assetFile.isError) {
            log.warn("Resource can't be downloaded. Asset file initialization was failed, {}", assetFile);
            continue;
        }
        if (assetFile.isContent) {
            log.info("Snippet was already downloaded. Snippet file: {}", assetFile.file.getPath());
            preparedMap.put(snippetCode, true);
            continue;
        }

        Checksum checksum = null;
        if (globals.isAcceptOnlySignedSnippets) {
            try {
                Request request = Request.Get(snippetChecksumUrl + '/' + snippetCode).connectTimeout(5000)
                        .socketTimeout(5000);

                Response response;
                if (globals.isSecureRestUrl) {
                    response = executor.executor.execute(request);
                } else {
                    response = request.execute();
                }
                String checksumStr = response.returnContent().asString(StandardCharsets.UTF_8);

                checksum = Checksum.fromJson(checksumStr);
            } catch (HttpResponseException e) {
                logError(snippetCode, e);
                break;
            } catch (SocketTimeoutException e) {
                log.error("SocketTimeoutException", e);
                break;
            } catch (IOException e) {
                log.error("IOException", e);
                break;
            } catch (Throwable th) {
                log.error("Throwable", th);
                return;
            }
        }

        try {
            File snippetTempFile = new File(assetFile.file.getAbsolutePath() + ".tmp");
            //  @GetMapping("/rest-anon/payload/resource/{type}/{code}")
            Request request = Request.Get(targetUrl + '/' + snippetCode).connectTimeout(5000)
                    .socketTimeout(5000);

            Response response;
            if (globals.isSecureRestUrl) {
                response = executor.executor.execute(request);
            } else {
                response = request.execute();
            }
            response.saveContent(snippetTempFile);

            boolean isOk = true;
            if (globals.isAcceptOnlySignedSnippets) {
                CheckSumAndSignatureStatus status;
                try (FileInputStream fis = new FileInputStream(snippetTempFile)) {
                    status = checksumWithSignatureService.verifyChecksumAndSignature(checksum, snippetCode, fis,
                            true);
                }
                if (status.isSignatureOk == null) {
                    log.warn(
                            "globals.isAcceptOnlySignedSnippets is {} but snippet with code {} doesn't have signature",
                            globals.isAcceptOnlySignedSnippets, snippetCode);
                    continue;
                }
                if (Boolean.FALSE.equals(status.isSignatureOk)) {
                    log.warn(
                            "globals.isAcceptOnlySignedSnippets is {} but snippet with code {} has the broken signature",
                            globals.isAcceptOnlySignedSnippets, snippetCode);
                    continue;
                }
                isOk = (status.isOk && !Boolean.FALSE.equals(status.isSignatureOk));
            }
            if (isOk) {
                //noinspection ResultOfMethodCallIgnored
                snippetTempFile.renameTo(assetFile.file);
                preparedMap.put(snippetCode, true);
            } else {
                //noinspection ResultOfMethodCallIgnored
                snippetTempFile.delete();
            }
        } catch (HttpResponseException e) {
            logError(snippetCode, e);
        } catch (SocketTimeoutException e) {
            log.error("SocketTimeoutException", e.toString());
        } catch (IOException e) {
            log.error("IOException", e);
        }
    }
}

From source file:net.bluemix.newsaggregator.api.AuthenticationServlet.java

private String getAccessTokenFromCodeResponse(String id, String secret, String redirect, String code) {
    String output = null;/*from ww  w . ja  va  2  s. c  om*/
    try {
        configureSSL();

        org.apache.http.client.fluent.Request req = Request
                .Post("https://idaas.ng.bluemix.net/sps/oauth20sp/oauth20/token");
        String body = "client_secret=" + secret + "&grant_type=authorization_code" + "&redirect_uri=" + redirect
                + "&code=" + code + "&client_id=" + id;

        req.bodyString(body, ContentType.create("application/x-www-form-urlencoded"));

        org.apache.http.client.fluent.Response res = req.execute();

        output = res.returnContent().asString();

        output = output.substring(output.indexOf("access_token") + 15, output.indexOf("access_token") + 35);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return output;
}

From source file:br.gov.jfrj.siga.base.SigaHTTP.java

/**
 * @param URL//from www .  j av  a2 s.  co  m
 * @param request (se for modulo play, setar pra null)
 * @param cookieValue (necessario apenas nos modulos play)
 */
public String get(String URL, HttpServletRequest request, String cookieValue) {
    String html = "";

    if (URL.startsWith("/"))
        URL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URL;

    try {
        // Efetua o request para o Service Provider (mdulo)
        Request req = Request.Get(URL);
        //    req.addHeader(COOKIE, JSESSIONID_PREFIX+getCookie(request, cookieValue));
        // Atribui o html retornado e pega o header do Response
        // Se a aplicao j efetuou a autenticao entre o mdulo da URL o contedo ser trago nesse primeiro GET
        // Caso contrrio passar pelo processo de autenticao (if abaixo)
        html = req.execute().handleResponse(new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse)
                    throws ClientProtocolException, IOException {
                // O atributo que importa nesse header  o set-cookie que ser utilizado posteriormente
                headers = httpResponse.getAllHeaders();
                return IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
            }
        });

        // Verifica se retornou o form de autenticao do picketlink 
        if (html.contains(HTTP_POST_BINDING_REQUEST)) {
            // Atribui o cookie recuperado no response anterior
            String setCookie = null;
            try {
                setCookie = extractCookieFromHeader(getHeader(SET_COOKIE));
            } catch (ElementNotFoundException elnf) {
                log.warning("Nao encontrou o set-cookie");
                setCookie = getCookie(request, cookieValue);
            }

            // Atribui o valor do SAMLRequest contido no html retornado no GET efetuado.
            String SAMLRequestValue = getAttributeValueFromHtml(html, SAMLRequest);
            // Atribui a URL do IDP (sigaidp)
            String idpURL = getAttributeActionFromHtml(html);

            // Faz um novo POST para o IDP com o SAMLRequest como parametro e utilizando o sessionID do IDP
            html = Request.Post(idpURL).addHeader(COOKIE, JSESSIONID_PREFIX + getIdp(request))
                    .bodyForm(Form.form().add(SAMLRequest, SAMLRequestValue).build()).execute().returnContent()
                    .toString();

            // Extrai o valor do SAMLResponse
            // Caso o SAMLResponse no esteja disponvel aqui,  porque o JSESSIONID utilizado no foi o do IDP.
            String SAMLResponseValue = getAttributeValueFromHtml(html, SAMLResponse);

            // Faz um POST para o SP com o atributo SAMLResponse utilizando o sessionid do primeiro GET
            // O retorno  discartado pois o resultado  um 302.
            Request.Post(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie)
                    .bodyForm(Form.form().add(SAMLResponse, SAMLResponseValue).build()).execute()
                    .discardContent();

            // Agora que estamos autenticado efetua o GET para pgina desejada.
            html = Request.Get(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie).execute().returnContent()
                    .toString();
            if (html.contains(HTTP_POST_BINDING_REQUEST)) {
                log.info("Alguma coisa falhou na autenticao!: " + idpURL);
            }
        }
    } catch (Exception io) {
        io.printStackTrace();
    }

    return html;
}

From source file:com.evon.injectTemplate.InjectTemplateFilter.java

private void loadContentTemplate(TemplateBean template, String domain, Integer port, boolean https,
        HttpServletRequest httpRequest) throws Exception {
    HTMLInfoBean htmlInfo = templates.get("/" + template.path);

    String sport = (port == null) ? "" : ":" + String.valueOf(port);

    String url = htmlInfo.getProtocol() + "://" + domain + sport + "/" + template.path;

    Request request = Request.Get(url);

    Enumeration<String> headerNames = httpRequest.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();

        Enumeration<String> headerValues = httpRequest.getHeaders(name);
        while (headerValues.hasMoreElements()) {
            String value = headerValues.nextElement();
            request = request.addHeader(name, value);
        }//from   ww w. j  a va 2 s  . c o m
    }

    String content = request.execute().returnContent().asString();

    Pattern pattern = Pattern.compile("<INJECT[ ]{1,}selector=[\"'](.*?)[\"']/>",
            Pattern.CASE_INSENSITIVE + Pattern.DOTALL);

    Matcher matcher = pattern.matcher(content);

    List<String> selectors = new ArrayList<String>();

    while (matcher.find()) {
        String tagInject = matcher.group(0);
        String selector = matcher.group(1);
        selectors.add(selector);
        content = content.replace(tagInject, "<INJECT selector='" + selector + "'/>");
    }

    String key = null;

    if (template.cache.equals("SESSION")) {
        String cookiesNames = getCookieHashs(httpRequest);
        key = template.path + cookiesNames;
    } else {
        key = template.path;
    }

    HtmlContentBean contentBean = new HtmlContentBean();
    contentBean.setContent(content);
    contentBean.setLastAccess(System.currentTimeMillis());
    htmlContents.remove(key);
    htmlContents.put(key, contentBean);
    htmlInfo.setSelectors(selectors);
}