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:org.apache.james.jmap.methods.integration.cucumber.DownloadStepdefs.java

@When("^\"([^\"]*)\" downloads \"([^\"]*)\" with an expired token$")
public void getDownloadWithExpiredToken(String username, String attachmentId) throws Exception {
    String blobId = blobIdByAttachmentId.get(attachmentId);
    response = Request.Get(mainStepdefs.baseUri().setPath("/download/" + blobId)
            .addParameter("access_token", EXPIRED_ATTACHMENT_TOKEN).build()).execute().returnResponse();
}

From source file:com.twosigma.beaker.NamespaceClient.java

public String getVersion() throws IOException {
    return Request.Get(utilUrl + "/version").addHeader("Authorization", auth).execute().returnContent()
            .asString();//  www.  j  a  v a  2 s  .  com
}

From source file:com.helger.peppol.bdxrclient.BDXRClientReadOnly.java

/**
 * Gets a signed service metadata object given by its service group id and its
 * document type. This is a specification compliant method.
 *
 * @param aServiceGroupID/*from  ww w  . j  a va  2  s  . c o m*/
 *        The service group id of the service metadata to get. May not be
 *        <code>null</code>.
 * @param aDocumentTypeID
 *        The document type of the service metadata to get. May not be
 *        <code>null</code>.
 * @return A signed service metadata object. Never <code>null</code>.
 * @throws SMPClientException
 *         in case something goes wrong
 * @throws SMPClientUnauthorizedException
 *         A HTTP Forbidden was received, should not happen.
 * @throws SMPClientNotFoundException
 *         The service group id or document type did not exist.
 * @throws SMPClientBadRequestException
 *         The request was not well formed.
 * @see #getServiceRegistrationOrNull(IParticipantIdentifier,
 *      IDocumentTypeIdentifier)
 */
@Nonnull
public SignedServiceMetadataType getServiceRegistration(@Nonnull final IParticipantIdentifier aServiceGroupID,
        @Nonnull final IDocumentTypeIdentifier aDocumentTypeID) throws SMPClientException {
    ValueEnforcer.notNull(aServiceGroupID, "ServiceGroupID");
    ValueEnforcer.notNull(aDocumentTypeID, "DocumentTypeID");

    try {
        final String sURI = m_sSMPHost + IdentifierHelper.getIdentifierURIPercentEncoded(aServiceGroupID)
                + "/services/" + IdentifierHelper.getIdentifierURIPercentEncoded(aDocumentTypeID);
        Request aRequest = Request.Get(sURI);
        SignedServiceMetadataType aMetadata = executeRequest(aRequest).handleResponse(
                SMPHttpResponseHandlerSigned.create(new BDXRMarshallerSignedServiceMetadataType()));

        // If the Redirect element is present, then follow 1 redirect.
        if (aMetadata.getServiceMetadata() != null && aMetadata.getServiceMetadata().getRedirect() != null) {
            final RedirectType aRedirect = aMetadata.getServiceMetadata().getRedirect();

            // Follow the redirect
            s_aLogger.info("Following a redirect from '" + sURI + "' to '" + aRedirect.getHref() + "'");
            aRequest = Request.Get(aRedirect.getHref());
            aMetadata = executeRequest(aRequest).handleResponse(
                    SMPHttpResponseHandlerSigned.create(new BDXRMarshallerSignedServiceMetadataType()));

            // Check that the certificateUID is correct.
            boolean bCertificateSubjectFound = false;
            outer: for (final Object aObj : aMetadata.getSignature().getKeyInfo().getContent()) {
                final Object aInfoValue = ((JAXBElement<?>) aObj).getValue();
                if (aInfoValue instanceof X509DataType) {
                    final X509DataType aX509Data = (X509DataType) aInfoValue;
                    for (final Object aX509Obj : aX509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
                        final JAXBElement<?> aX509element = (JAXBElement<?>) aX509Obj;
                        // Find the first subject (of type string)
                        if (aX509element.getValue() instanceof String) {
                            final String sSubject = (String) aX509element.getValue();
                            if (!aRedirect.getCertificateUID().equals(sSubject)) {
                                throw new SMPClientException(
                                        "The certificate UID of the redirect did not match the certificate subject. Subject is '"
                                                + sSubject + "'. Required certificate UID is '"
                                                + aRedirect.getCertificateUID() + "'");
                            }
                            bCertificateSubjectFound = true;
                            break outer;
                        }
                    }
                }
            }

            if (!bCertificateSubjectFound)
                throw new SMPClientException("The X509 certificate did not contain a certificate subject.");
        }
        return aMetadata;
    } catch (final Exception ex) {
        throw getConvertedException(ex);
    }
}

From source file:com.helger.peppol.smpclient.SMPClientReadOnly.java

/**
 * Returns a complete service group. A complete service group contains both
 * the service group and the service metadata. This is a non-specification
 * compliant method./*from   w  w w .j a  va 2s . c o  m*/
 *
 * @param sCompleteURL
 *        The complete URL for the full service group to query.
 * @return The complete service group containing service group and service
 *         metadata. Never <code>null</code>.
 * @throws SMPClientException
 *         in case something goes wrong
 * @throws SMPClientUnauthorizedException
 *         A HTTP Forbidden was received, should not happen.
 * @throws SMPClientNotFoundException
 *         The service group id did not exist.
 * @throws SMPClientBadRequestException
 *         The request was not well formed.
 * @see #getCompleteServiceGroup(IParticipantIdentifier)
 * @see #getCompleteServiceGroupOrNull(IParticipantIdentifier)
 */
@Nonnull
public CompleteServiceGroupType getCompleteServiceGroup(@Nonnull final String sCompleteURL)
        throws SMPClientException {
    ValueEnforcer.notEmpty(sCompleteURL, "CompleteURL");

    try {
        final Request aRequest = Request.Get(sCompleteURL);
        return executeRequest(aRequest).handleResponse(
                SMPHttpResponseHandlerUnsigned.create(new SMPMarshallerCompleteServiceGroupType()));
    } catch (final Exception ex) {
        throw getConvertedException(ex);
    }
}

From source file:hudson.plugins.jira.JiraRestService.java

private Request buildGetRequest(URI uri) {
    return Request.Get(uri).connectTimeout(timeoutInMiliseconds()).socketTimeout(timeoutInMiliseconds())
            .addHeader("Authorization", authHeader).addHeader("Content-Type", "application/json");
}

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

@Test
public void testGetCollectionSort() throws Exception {
    LOG.info("@@@ testGetCollectionSort URI: " + docsCollectionUriSort);

    Response resp = adminExecutor.execute(Request.Get(docsCollectionUriSort));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);/*from  w  w  w  . j a v a 2s  . c  o  m*/
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
        json = JsonObject.readFrom(content);
    } catch (Throwable t) {
        fail("@@@ Failed parsing received json");
    }

    assertNotNull("check json not null", json);

    assertNotNull("check not null _embedded", json.get("_embedded"));

    assertTrue("check _embedded to be a json object", (json.get("_embedded") instanceof JsonObject));

    JsonObject embedded = (JsonObject) json.get("_embedded");

    assertNotNull("check not null _embedded.rh:doc", embedded.get("rh:doc"));

    assertTrue("check _embedded.rh:doc to be a json array", (embedded.get("rh:doc") instanceof JsonArray));

    JsonArray rhdoc = (JsonArray) embedded.get("rh:doc");

    assertNotNull("check not null _embedded.rh:doc[0]", rhdoc.get(0));

    assertTrue("check _embedded.rh:coll[0] to be a json object", (rhdoc.get(0) instanceof JsonObject));

    JsonObject rhdoc0 = (JsonObject) rhdoc.get(0);

    assertNotNull("check not null _embedded.rh:doc[0]._id", rhdoc0.get("_id"));
    assertNotNull("check not null _embedded.rh:doc[0].name", rhdoc0.get("name"));
    assertEquals("check not null _embedded.rh:doc[1].name", "Morrissey", rhdoc0.get("name").asString());

    JsonObject rhdoc1 = (JsonObject) rhdoc.get(1);

    assertNotNull("check not null _embedded.rh:doc[1]._id", rhdoc1.get("_id"));
    assertNotNull("check not null _embedded.rh:doc[1].name", rhdoc1.get("name"));
    assertEquals("check not null _embedded.rh:doc[1].name", "Ian", rhdoc1.get("name").asString());
}

From source file:org.cerberus.engine.entity.threadpool.ExecutionWorkerThread.java

/**
 * Request execution of the inner {@link TestCaseExecutionInQueue} to the {@link RunTestCase} servlet
 *
 * @return the execution answer from the {@link RunTestCase} servlet
 * @throws RunProcessException if an error occurred during request execution
 * @see #run()//  w  ww . j a  va 2s.co m
 */
private String runExecution() {
    try {
        return Request.Get(toExecuteUrl).connectTimeout(toExecuteTimeout).socketTimeout(toExecuteTimeout)
                .execute().returnContent().asString();
    } catch (Exception e) {
        final StringBuilder errorMessage = new StringBuilder(
                "An unexpected error occurred during test case execution: ");
        if (e instanceof HttpResponseException) {
            errorMessage.append(
                    String.format("%d (%s)", ((HttpResponseException) e).getStatusCode(), e.getMessage()));
        } else {
            errorMessage.append(e.getMessage());
            errorMessage.append(". Check server logs");
        }
        throw new RunProcessException(errorMessage.toString(), e);
    }
}

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

/**
 * reads the comments from the comments feed
 * //from  w  ww  .  j a  v a  2 s .co  m
 * Example URL
 * http://localhost:9080/photoSharing/api/comments?uid=20514318&pid
 * =bf33a9b5-3042-46f0-a96e-b8742fced7a4
 * 
 * @param bearer
 * @param pid
 * @param uid
 * @param response
 */
public void readComments(String bearer, String pid, String uid, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + uid + "/document/" + pid
            + "/feed?category=comment&sortBy=created&sortOrder=desc";

    logger.info("Executing Request to: " + apiUrl + " " + bearer);

    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.setStatus(HttpStatus.SC_OK);

            InputStream in = hr.getEntity().getContent();
            String jsonString = org.apache.wink.json4j.utils.XML.toJson(in);

            // Logging out the JSON Object
            logger.info(jsonString);

            JSONObject feed = new JSONObject(jsonString).getJSONObject("feed");

            JSONArray comments = new JSONArray();

            JSONArray entries = null;
            try {

                entries = feed.getJSONArray("entry");

            } catch (JSONException e) {
                entries = new JSONArray();
                if (feed.has("entry")) {
                    JSONObject entry = feed.getJSONObject("entry");
                    entries.put(entry);
                }
            }
            int len = entries.length();
            for (int i = 0; i < len; i++) {
                JSONObject entry = entries.getJSONObject(i);
                JSONObject author = entry.getJSONObject("author");

                String name = author.getString("name");
                String userid = author.getString("userid");

                String date = entry.getString("modified");
                String content = entry.getJSONObject("content").getString("content");
                String cid = entry.getString("uuid");

                // Build the JSON object
                JSONObject commentJSON = new JSONObject();
                commentJSON.put("uid", userid);
                commentJSON.put("author", name);
                commentJSON.put("date", date);
                commentJSON.put("content", content);
                commentJSON.put("cid", cid);

                comments.add(commentJSON);

            }

            // Flush the Object to the Stream with content type
            response.setHeader("Content-Type", "application/json");
            PrintWriter out = response.getWriter();
            out.println(comments.toString());
            out.flush();

        }

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

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Don't call this method!/*  w  w  w  .  jav a2 s . com*/
 * <p/>
 * This method will be called usually by the server and this class.
 *
 * @param sp
 * @param md
 * @param out
 * @throws IOException
 */
public void downloadShunk(final PeerChunk sp, final MetaData md, final OutputStream out) throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("Parameter 'out' must not be null!");
    }

    URI uri = CaraFileUtils.buildURI(sp.getPeerURI(), "peer", "leechChunk", sp.getChunkId());

    HttpResponse response = executeRequest(
            Request.Get(uri).addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_OCTET_STREAM.toString()))
                    .returnResponse();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    response.getEntity().writeTo(baos);

    String sha1 = DigestUtils.sha1Hex(baos.toByteArray());
    if (!sha1.equalsIgnoreCase(sp.getChunkId())) {
        throw new IOException("SHA1 validation failed. Expected " + sp.getChunkId() + " but was " + sha1);
    }

    out.write(baos.toByteArray());
}