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

/**
 * gets the user library results/*w  w  w .  j  a  v  a2  s .  co m*/
 * 
 * @param request
 * @param response
 */
public void getUserLibraryResults(String bearer, HttpServletRequest request, HttpServletResponse response) {

    String userId = request.getParameter("userid");
    if (userId == null || userId.isEmpty()) {
        logger.warning("userId is null");
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    } else {
        // sets the content type - application/json
        response.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        String apiUrl = getUserLibraryApiUrl(userId);

        logger.info(apiUrl);

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

                logger.info(feed.toString());

                JSONArray files = new JSONArray();

                JSONArray entries = null;
                if (feed.has("entry")) {
                    //Check if the Entry is a JSONObject or JSONArray
                    Object o = feed.get("entry");
                    if (o.getClass().getName().contains("JSONObject")) {
                        entries = new JSONArray();
                        entries.put(o);
                    } else {
                        entries = (JSONArray) o;
                    }
                } else {
                    entries = new JSONArray();
                }

                int len = entries.length();
                for (int i = 0; i < len; i++) {

                    JSONObject entry = entries.getJSONObject(i);
                    logger.info(entry.toString());

                    JSONObject author = entry.getJSONObject("author");
                    String photographer = author.getString("name");
                    String uid = author.getString("userid");

                    String title = entry.getJSONObject("title").getString("content");

                    String lid = entry.getString("libraryId");

                    String pid = entry.getString("uuid");

                    String thumbnail = "./api/file?action=thumbnail&pid=" + pid + "&lid=" + lid;

                    files.add(createPhoto(lid, pid, title, uid, photographer, thumbnail));

                }

                // Flush the Object to the Stream with content type
                response.setHeader("Content-Type", "application/json");
                PrintWriter out = response.getWriter();
                out.println(files.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 userlibrary " + 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 userlibrary " + 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 userlibrary " + e.toString());
        }

    }

}

From source file:com.qwazr.search.index.IndexSingleClient.java

@Override
public LinkedHashMap<String, Object> getDocument(String schema_name, String index_name, String doc_id) {
    final UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/doc/", doc_id);
    Request request = Request.Get(uriBuilder.build());
    return commonServiceRequest(request, null, null, MapStringObjectTypeRef, 200);
}

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

/**
 * Returns status of the registry./* w w  w  .j a  va2s  .co  m*/
 *
 * @return Status
 * @throws IOException Thrown when unable to request status of the registry
 */
public RegistryStatus getRegistryStatus() throws IOException {
    if (registryURI == null) {
        throw new IllegalArgumentException("Parameter 'registryURI' must not be null!");
    }

    LOG.debug("Getting registry status");
    URI uri = CaraFileUtils.buildURI(registryURI, "registry", "status");
    HttpResponse response = executeRequest(Request.Get(uri)).returnResponse();

    Charset charset = ContentType.getOrDefault(response.getEntity()).getCharset();

    RegistryStatus status = JsonUtil.read(new InputStreamReader(response.getEntity().getContent(), charset),
            RegistryStatus.class);

    LOG.debug("Registry status responsed");

    return status;
}

From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java

/**
 * Returns the latest api version supported by the catalog
 *
 * @throws JackanException on error/*w w w . ja  va2 s.  c  o m*/
 */
private synchronized int getApiVersion(int number) {
    String fullUrl = catalogURL + "/api/" + number;
    logger.log(Level.FINE, "getting {0}", fullUrl);
    try {
        Request request = Request.Get(fullUrl);
        if (proxy != null) {
            request.viaProxy(proxy);
        }
        String json = request.execute().returnContent().asString();
        return getObjectMapper().readValue(json, ApiVersionResponse.class).version;
    } catch (Exception ex) {
        throw new JackanException("Error while fetching api version!", this, ex);
    }

}

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

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

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

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);/*w  w  w .j av  a2s . c om*/
    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 _size not null", json.get("_size"));

    assertEquals("check _size value to be 2", 2, json.get("_size").asInt());

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

    assertEquals("check _returned value to be 2", 2, json.get("_returned").asInt());

    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 _embedded.rh:doc[1].name value to be Mark", "Mark", 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 _embedded.rh:doc[1].name value to be Nick", "Nick", rhdoc1.get("name").asString());
}

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

private Set<PeerData> downloadPeerSet() throws IOException {
    if (registryURI == null) {
        throw new IllegalArgumentException("Parameter 'registryURI' must not be null!");
    }//from w w  w.  j  ava  2  s.  c  o  m

    LOG.debug("Download set of peers");
    URI uri = CaraFileUtils.buildURI(registryURI, "registry", "listPeers");
    HttpResponse response = executeRequest(Request.Get(uri)).returnResponse();

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        Charset charset = ContentType.getOrDefault(response.getEntity()).getCharset();

        Set<PeerData> peerSet = JsonUtil.read(new InputStreamReader(response.getEntity().getContent(), charset),
                PeerDataSet.class);

        LOG.debug("Registry response set of " + peerSet.size() + " peer(s)");

        return peerSet;
    }

    throw new IOException("HTTP responce code " + response.getStatusLine().getStatusCode() + " "
            + response.getStatusLine().getReasonPhrase());
}

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

/**
 * Returns a service group. A service group references to the service
 * metadata. This is a specification compliant method.
 *
 * @param aServiceGroupID//from www . j a v  a2  s  .c o  m
 *        The service group id corresponding to the service group which one
 *        wants to get.
 * @return The service group. 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 #getServiceGroupOrNull(IParticipantIdentifier)
 */
@Nonnull
public ServiceGroupType getServiceGroup(@Nonnull final IParticipantIdentifier aServiceGroupID)
        throws SMPClientException {
    ValueEnforcer.notNull(aServiceGroupID, "ServiceGroupID");

    try {
        final Request aRequest = Request
                .Get(m_sSMPHost + IdentifierHelper.getIdentifierURIPercentEncoded(aServiceGroupID));
        return executeRequest(aRequest)
                .handleResponse(SMPHttpResponseHandlerUnsigned.create(new SMPMarshallerServiceGroupType()));
    } catch (final Exception ex) {
        throw getConvertedException(ex);
    }
}

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Performs HTTP GET on server. If {@link CkanResponse#isSuccess()} is false
 * throws {@link CkanException}./* w  ww.  j  a  va2s.c  o m*/
 *
 * @param <T>
 * @param responseType
 *            a descendant of CkanResponse
 * @param path
 *            something like /api/3/package_show
 * @param params
 *            list of key, value parameters. They must be not be url
 *            encoded. i.e. "id","laghi-monitorati-trento"
 * @throws CkanException
 *             on error
 */
private <T extends CkanResponse> T getHttp(Class<T> responseType, String path, Object... params) {

    checkNotNull(responseType);
    checkNotNull(path);

    String fullUrl = calcFullUrl(path, params);

    T ckanResponse;
    String returnedText;

    try {
        LOG.log(Level.FINE, "getting {0}", fullUrl);
        Request request = Request.Get(fullUrl);

        configureRequest(request);

        Response response = request.execute();

        InputStream stream = response.returnResponse().getEntity().getContent();

        try (InputStreamReader reader = new InputStreamReader(stream, Charsets.UTF_8)) {
            returnedText = CharStreams.toString(reader);
        }
    } catch (Exception ex) {
        throw new CkanException("Error while performing GET. Request url was: " + fullUrl, this, ex);
    }
    try {
        ckanResponse = getObjectMapper().readValue(returnedText, responseType);
    } catch (Exception ex) {
        throw new CkanException(
                "Couldn't interpret json returned by the server! Returned text was: " + returnedText, this, ex);
    }

    if (!ckanResponse.isSuccess()) {
        throwCkanException("Error while performing GET. Request url was: " + fullUrl, ckanResponse);
    }
    return ckanResponse;
}

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

/**
 * gets the user's organization's public files results
 * /* w  w  w.  j  av  a2  s.c om*/
 * @param request
 * @param response
 */
public void getOrgPublicFeed(String bearer, HttpServletRequest request, HttpServletResponse response) {

    String apiUrl = getPublicFilesApiUrl();
    logger.info(apiUrl);

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

    try {
        // sets the content type - application/json
        response.setContentType(ContentType.APPLICATION_JSON.getMimeType());

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

            logger.info(feed.toString());

            JSONArray files = new JSONArray();

            JSONArray entries = null;
            if (feed.has("entry")) {
                //Check if the Entry is a JSONObject or JSONArray
                Object o = feed.get("entry");
                if (o.getClass().getName().contains("JSONObject")) {
                    entries = new JSONArray();
                    entries.put(o);
                } else {
                    entries = (JSONArray) o;
                }
            } else {
                entries = new JSONArray();
            }

            int len = entries.length();
            for (int i = 0; i < len; i++) {

                JSONObject entry = entries.getJSONObject(i);
                logger.info(entry.toString());

                JSONObject author = entry.getJSONObject("author");
                String photographer = author.getString("name");
                String uid = author.getString("userid");

                String title = entry.getJSONObject("title").getString("content");

                String lid = entry.getString("libraryId");

                String pid = entry.getString("uuid");

                String thumbnail = "./api/file?action=file&pid=" + pid + "&lid=" + lid;

                String share = "0";
                String like = "0";
                JSONArray rank = entry.getJSONArray("rank");

                @SuppressWarnings("rawtypes")
                Iterator r = rank.iterator();
                while (r.hasNext()) {
                    JSONObject temp = (JSONObject) r.next();
                    String scheme = temp.getString("scheme");
                    if (scheme.contains("share")) {
                        share = temp.getString("content");
                    } else if (scheme.contains("recommendations")) {
                        like = temp.getString("content");
                    }
                }

                JSONObject e = createPhoto(lid, pid, title, uid, photographer, thumbnail);
                e.put("likes", like);
                e.put("shares", share);
                files.add(e);

            }

            // Flush the Object to the Stream with content type
            response.setHeader("Content-Type", "application/json");
            PrintWriter out = response.getWriter();
            out.println(files.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 user's org feed " + 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 user's org feed " + 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 user's org feed " + e.toString());
    }

}

From source file:com.helger.peppol.smpclient.SMPClientReadOnly.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   www . j av  a  2  s.  c om*/
 *        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 SMPMarshallerSignedServiceMetadataType()));

        // 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 SMPMarshallerSignedServiceMetadataType()));

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