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

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

Introduction

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

Prototype

public static Request Get(final String uri) 

Source Link

Usage

From source file:photosharing.api.conx.FileDefinition.java

/**
 * manages the thumbnail access/*from w ww .  j  a v  a 2s.  co m*/
 * 
 * @param bearer
 * @param request
 * @param response
 */
public void getThumbnail(String bearer, HttpServletRequest request, HttpServletResponse response) {
    String pid = request.getParameter("pid");
    String lid = request.getParameter("lid");

    if (pid == null || lid == null || pid.isEmpty() || lid.isEmpty()) {
        logger.warning("bad parameters");
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
    } else {

        String apiUrl = getThumbnailApiUrl(pid, lid);

        Request get = Request.Get(apiUrl);
        get.addHeader("Authorization", "Bearer " + bearer);

        try {

            Executor exec = ExecutorUtil.getExecutor();
            Response apiResponse = exec.execute(get);

            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            // Session is no longer valid or access token is expired
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Default to SC_OK (200)
            else if (code == HttpStatus.SC_OK) {
                response.setContentType(hr.getFirstHeader("Content-Type").getValue());
                response.setHeader("content-length", hr.getFirstHeader("content-length").getValue());
                response.setStatus(HttpStatus.SC_OK);

                // Streams
                InputStream in = hr.getEntity().getContent();
                IOUtils.copy(in, response.getOutputStream());
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(response.getOutputStream());

            }

        } catch (IOException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("Issue with read file " + e.toString());
        }

    }

}

From source file:org.mule.module.http.functional.listener.HttpListenerResponseBuilderTestCase.java

private void statusLineResponseBuilderTest(String url, int expectedStatus, String expectedReasonPhrase)
        throws IOException {
    final Response response = Request.Get(url).connectTimeout(1000).execute();
    final HttpResponse httpResponse = response.returnResponse();
    assertThat(httpResponse.getAllHeaders().length, is(2));
    assertThat(httpResponse.getFirstHeader(HttpHeaders.Names.CONTENT_LENGTH).getValue(), is("0"));
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(expectedStatus));
    assertThat(httpResponse.getStatusLine().getReasonPhrase(), is(expectedReasonPhrase));
}

From source file:com.softinstigate.restheart.integrationtest.SecurityIT.java

@Test
public void testGetAsAdmin() throws Exception {
    // *** GET root
    Response resp = adminExecutor.execute(Request.Get(rootUri));
    check("check get root as admin", resp, HttpStatus.SC_OK);

    // *** GET db
    resp = adminExecutor.execute(Request.Get(dbUri));
    check("check get db as admin", resp, HttpStatus.SC_OK);

    // *** GET coll1
    resp = adminExecutor.execute(Request.Get(collection1Uri));
    check("check get coll1 as admin", resp, HttpStatus.SC_OK);

    // *** GET doc1
    resp = adminExecutor.execute(Request.Get(document1Uri));
    check("check get doc1 as admin", resp, HttpStatus.SC_OK);

    // *** GET coll2
    resp = adminExecutor.execute(Request.Get(collection2Uri));
    check("check get coll2 as admin", resp, HttpStatus.SC_OK);

    // *** GET doc2
    resp = adminExecutor.execute(Request.Get(document2Uri));
    check("check get doc2 as admin", resp, HttpStatus.SC_OK);
}

From source file:com.streamsets.stage.destination.waveanalytics.WaveAnalyticsTarget.java

private String getDataflowJson(String dataflowId) throws IOException {
    // Add the dataset to the dataflow
    return Request.Get(String.format(restEndpoint + dataflowJson, dataflowId))
            .addHeader("Authorization", "OAuth " + connection.getConfig().getSessionId()).execute()
            .returnContent().asString();
}

From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 *
 * @param msgContext//  ww w.  j  av  a 2s  .c  o m
 *            the messsage context
 *
 * @throws AxisFault
 */
public void invoke(final MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    Request req = null;
    Response response = null;
    try {
        if (exec == null) {
            targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
            String userID = msgContext.getUsername();
            String passwd = msgContext.getPassword();
            // if UserID is not part of the context, but is in the URL, use
            // the one in the URL.
            if ((userID == null) && (targetURL.getUserInfo() != null)) {
                String info = targetURL.getUserInfo();
                int sep = info.indexOf(':');

                if ((sep >= 0) && (sep + 1 < info.length())) {
                    userID = info.substring(0, sep);
                    passwd = info.substring(sep + 1);
                } else
                    userID = info;
            }
            Credentials cred = new UsernamePasswordCredentials(userID, passwd);
            if (userID != null) {
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userID.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userID.substring(0, domainIndex);
                    if (userID.length() > domainIndex + 1) {
                        String user = userID.substring(domainIndex + 1);
                        cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
                    }
                }
            }
            HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() {

                public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                        final HttpContext context) throws ProtocolException {
                    URI uri = getLocationURI(request, response, context);
                    String method = request.getRequestLine().getMethod();
                    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME))
                        return new HttpHead(uri);
                    else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                        HttpPost httpPost = new HttpPost(uri);
                        httpPost.addHeader(request.getFirstHeader("Authorization"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        httpPost.addHeader(request.getFirstHeader("Content-Type"));
                        httpPost.addHeader(request.getFirstHeader("User-Agent"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        if (request instanceof HttpEntityEnclosingRequest)
                            httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
                        return httpPost;
                    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
                        return new HttpGet(uri);
                    } else {
                        throw new IllegalStateException(
                                "Redirect called on un-redirectable http method: " + method);
                    }
                }
            }).build();

            exec = Executor.newInstance(httpClient);
            HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol());
            exec.auth(host, cred);
            exec.authPreemptive(host);
            HttpUtils.setupProxy(exec, targetURL.toURI());
        }
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI());
        if (posting) {
            req = Request.Post(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            Message reqMessage = msgContext.getRequestMessage();

            addContextInfo(req, msgContext, targetURL);
            Iterator<?> it = reqMessage.getAttachments();
            if (it.hasNext()) {
                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    reqMessage.writeTo(bos);
                    req.body(new ByteArrayEntity(bos.toByteArray()));
                } finally {
                    FileUtils.closeStream(bos);
                }
            } else
                req.body(new StringEntity(reqMessage.getSOAPPartAsString()));

        } else {
            req = Request.Get(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            addContextInfo(req, msgContext, targetURL);
        }

        response = exec.execute(req);
        response.handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity en = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    int returnCode = statusLine.getStatusCode();
                    String contentType = en.getContentType().getValue();

                    in = new BufferedHttpEntity(en).getContent();
                    // String str = IOUtils.toString(in);
                    if (returnCode > 199 && returnCode < 300) {
                        // SOAP return is OK - so fall through
                    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
                        // For now, if we're SOAP 1.2, fall
                        // through, since the range of
                        // valid result codes is much greater
                    } else if (contentType != null && !contentType.equals("text/html")
                            && ((returnCode > 499) && (returnCode < 600))) {
                        // SOAP Fault should be in here - so
                        // fall through
                    } else {
                        String statusMessage = statusLine.getReasonPhrase();
                        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null,
                                null);
                        fault.setFaultDetailString(
                                Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in)));
                        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
                                Integer.toString(returnCode));
                        throw fault;
                    }
                    Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP))
                            in = new GZIPInputStream(in);
                        else {
                            AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '"
                                    + contentEncoding.getValue() + "' found", null, null);
                            throw fault;
                        }

                    }

                    // Transfer HTTP headers of HTTP message
                    // to MIME headers of SOAP
                    // message
                    MimeHeaders mh = new MimeHeaders();
                    for (Header h : response.getAllHeaders())
                        mh.addHeader(h.getName(), h.getValue());
                    Message outMsg = new Message(in, false, mh);

                    outMsg.setMessageType(Message.RESPONSE);
                    msgContext.setResponseMessage(outMsg);
                    if (log.isDebugEnabled()) {
                        log.debug("\n" + Messages.getMessage("xmlRecd00"));
                        log.debug("-----------------------------------------------");
                        log.debug(outMsg.getSOAPPartAsString());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return "";
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        log.debug(e);
        throw AxisFault.makeFault(e);
    }
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
}

From source file:com.adobe.acs.commons.it.build.ScrMetadataIT.java

private DescriptorList getDescriptorsFromLatestRelease() throws Exception {
    JsonObject packageDetails = (JsonObject) Request
            .Get("https://api.bintray.com/packages/acs/releases/acs-aem-commons").execute()
            .handleResponse(responseHandler);
    String latestVersion = packageDetails.get("latest_version").getAsString();

    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    File cachedFile = new File(tempDir, String.format("acs-aem-commons-bundle-%s.jar", latestVersion));
    if (cachedFile.exists()) {
        System.out.printf("Using cached file %s\n", cachedFile);
    } else {//from w w  w .  java  2  s.  c  o m
        String url = String.format(
                "https://dl.bintray.com/acs/releases/com/adobe/acs/acs-aem-commons-bundle/%s/acs-aem-commons-bundle-%s.jar",
                latestVersion, latestVersion);

        System.out.printf("Fetching %s\n", url);

        InputStream content = Request.Get(url).execute().returnContent().asStream();

        IOUtils.copy(content, new FileOutputStream(cachedFile));
    }
    return parseJar(new FileInputStream(cachedFile), false);
}

From source file:com.twosigma.beaker.kdb.KdbShell.java

/**
 * Query the beaker server to get an available port.
 *///  w  w  w .ja v  a2  s  .c o  m
protected int getPortFromCore() throws IOException {
    String password = System.getenv("beaker_core_password");
    String auth = Base64.encodeBase64String(("beaker:" + password).getBytes("ASCII"));
    String response = Request.Get("http://127.0.0.1:" + corePort + "/rest/plugin-services/getAvailablePort")
            .addHeader("Authorization", "Basic " + auth).execute().returnContent().asString();
    return Integer.parseInt(response);
}

From source file:org.mule.module.http.functional.listener.HttpListenerHttpMessagePropertiesTestCase.java

@Test
public void getFullUriAndPath() throws Exception {
    final String url = String.format("http://localhost:%s%s", listenPort.getNumber(), CONTEXT_PATH);
    Request.Get(url).connectTimeout(RECEIVE_TIMEOUT).execute();
    final MuleMessage message = muleContext.getClient().request("vm://out", RECEIVE_TIMEOUT);
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_REQUEST_URI),
            is(CONTEXT_PATH));//from  w  ww  .java  2 s  .co m
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_REQUEST_PATH_PROPERTY),
            is(CONTEXT_PATH));
    assertThat(message.<String>getInboundProperty(HttpConstants.RequestProperties.HTTP_RELATIVE_PATH),
            is(CONTEXT_PATH));
}

From source file:gate.tagger.tagme.TaggerWatWS.java

protected String retrieveServerResponse(String text) {
    URI uri;/*from  w  w  w .j a  va  2  s  . c o m*/
    try {
        uri = new URIBuilder(getTagMeServiceUrl().toURI()).setParameter("text", text)
                .setParameter("gcube-token", getApiKey()).setParameter("lang", getLanguageCode()).build();
    } catch (URISyntaxException ex) {
        throw new GateRuntimeException("Could not create URI for the request", ex);
    }

    //System.err.println("DEBUG: WAT URL="+uri);
    Request req = Request.Get(uri);

    Response res = null;
    try {
        res = req.execute();
    } catch (Exception ex) {
        throw new GateRuntimeException("Problem executing HTTP request: " + req, ex);
    }
    Content cont = null;
    try {
        cont = res.returnContent();
    } catch (Exception ex) {
        throw new GateRuntimeException("Problem getting HTTP response content: " + res, ex);
    }
    String ret = cont.asString();
    logger.debug("WAT server response " + ret);
    return ret;
}