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:us.nineworlds.plex.rest.PlexappFactory.java

/**
 * Given a resource's URL, read and return the serialized MediaContainer
 * @param resourceURL//from w  w w  .j ava 2 s  .c o  m
 * @param get Is this a get request or post
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws Exception
 */
private MediaContainer serializeResource(String resourceURL, boolean get)
        throws MalformedURLException, IOException, Exception {
    System.out.println(resourceURL);
    Request request = generateRequest(resourceURL, get);
    if (!config.getPlexAuthenticationToken().isEmpty()) {
        //If we have an auth token, make sure to use it
        request = request.addHeader("X-Plex-Token", config.getPlexAuthenticationToken());
        System.out.println("Token: " + config.getPlexAuthenticationToken());
    }

    MediaContainer mediaContainer;
    mediaContainer = serializer.read(MediaContainer.class, request.execute().returnContent().asStream(), false);

    return mediaContainer;
}

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

/**
 * Returns the latest api version supported by the catalog
 *
 * @throws JackanException on error/*from  www  . j  a  v a 2s.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:eu.trentorise.opendata.jackan.ckan.CkanClient.java

/**
 * Method for http GET//  www .  ja  va 2  s . co  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 JackanException on error
 */
<T extends CkanResponse> T getHttp(Class<T> responseType, String path, Object... params) {
    checkNotNull(responseType);
    checkNotNull(path);

    String fullUrl = calcFullUrl(path, params);

    try {
        logger.log(Level.FINE, "getting {0}", fullUrl);
        Request request = Request.Get(fullUrl);
        if (proxy != null) {
            request.viaProxy(proxy);
        }
        String json = request.execute().returnContent().asString();
        T dr = getObjectMapper().readValue(json, responseType);
        if (!dr.success) {
            // monkey patching error type
            throw new JackanException("Reading from catalog " + catalogURL + " was not successful. Reason: "
                    + CkanError.read(getObjectMapper().readTree(json).get("error").asText()));
        }
        return dr;
    } catch (Exception ex) {
        throw new JackanException("Error while performing GET. Request url was: " + fullUrl, ex);
    }
}

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

protected String retrieveServerResponse(String text) {
    Request req = Request.Post(getTagMeServiceUrl().toString());

    req.addHeader("Content-Type", "application/x-www-form-urlencoded");
    req.bodyForm(/*from   ww  w  .  java2  s. c  om*/
            Form.form().add("text", text).add("gcube-token", getApiKey()).add("lang", getLanguageCode())
                    .add("tweet", getIsTweet().toString()).add("include_abstract", "false")
                    .add("include_categories", "false").add("include_all_spots", "false")
                    .add("long_text", getLongText().toString()).add("epsilon", getEpsilon().toString()).build(),
            Consts.UTF_8);
    logger.debug("Request is " + req);
    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("TagMe server response " + ret);
    return ret;
}

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

/**
 * Returns the given api number/*from   www.  j a v a 2 s  .c o m*/
 *
 * @throws JackanException
 *             on error
 */
private synchronized int getApiVersion(int number) {
    String fullUrl = catalogUrl + "/api/" + number;
    LOG.log(Level.FINE, "getting {0}", fullUrl);
    try {
        Request request = Request.Get(fullUrl);
        configureRequest(request);
        String json = request.execute().returnContent().asString();

        return getObjectMapper().readValue(json, ApiVersionResponse.class).version;
    } catch (Exception ex) {
        throw new CkanException("Error while fetching api version!", this, 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  w  w. ja va  2 s.  c om*/
 *
 * @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:org.talend.librariesmanager.nexus.ArtifacoryRepositoryHandler.java

@Override
public List<MavenArtifact> search(String groupIdToSearch, String artifactId, String versionToSearch,
        boolean fromRelease, boolean fromSnapshot) throws Exception {
    String serverUrl = serverBean.getServer();
    if (!serverUrl.endsWith("/")) {
        serverUrl = serverUrl + "/";
    }//w  ww  . j  ava 2 s . co m
    String searchUrl = serverUrl + SEARCH_SERVICE;

    String repositoryId = "";
    if (fromRelease) {
        repositoryId = serverBean.getRepositoryId();
    }
    if (fromSnapshot) {
        if ("".equals(repositoryId)) {
            repositoryId = serverBean.getSnapshotRepId();
        } else {
            repositoryId = repositoryId + "," + serverBean.getSnapshotRepId();
        }
    }
    String query = "";//$NON-NLS-1$
    if (!"".equals(repositoryId)) {
        query = "repos=" + repositoryId;//$NON-NLS-1$
    }
    if (groupIdToSearch != null) {
        if (!"".equals(query)) {
            query = query + "&";
        }
        query = query + "g=" + groupIdToSearch;//$NON-NLS-1$
    }
    if (artifactId != null) {
        if (!"".equals(query)) {
            query = query + "&";
        }
        query = query + "a=" + artifactId;//$NON-NLS-1$
    }

    if (versionToSearch != null) {
        if (!"".equals(query)) {
            query = query + "&";
        }
        query = query + "v=" + versionToSearch;//$NON-NLS-1$
    }
    searchUrl = searchUrl + query;
    Request request = Request.Get(searchUrl);
    String userPass = serverBean.getUserName() + ":" + serverBean.getPassword();
    String basicAuth = "Basic " + new String(new Base64().encode(userPass.getBytes()));
    Header authority = new BasicHeader("Authorization", basicAuth);
    request.addHeader(authority);
    List<MavenArtifact> resultList = new ArrayList<MavenArtifact>();

    HttpResponse response = request.execute().returnResponse();
    String content = EntityUtils.toString(response.getEntity());
    if (content.isEmpty()) {
        return resultList;
    }
    JSONObject responseObject = new JSONObject().fromObject(content);
    String resultStr = responseObject.getString("results");
    JSONArray resultArray = null;
    try {
        resultArray = new JSONArray().fromObject(resultStr);
    } catch (Exception e) {
        throw new Exception(resultStr);
    }
    if (resultArray != null) {
        String resultUrl = serverUrl + SEARCH_RESULT_PREFIX;
        for (int i = 0; i < resultArray.size(); i++) {
            JSONObject jsonObject = resultArray.getJSONObject(i);
            String uri = jsonObject.getString("uri");
            uri = uri.substring(resultUrl.length(), uri.length());
            String[] split = uri.split("/");
            if (split.length > 4) {
                String fileName = split[split.length - 1];
                if (!fileName.endsWith("pom")) {
                    String type = null;
                    int dotIndex = fileName.lastIndexOf('.');
                    if (dotIndex > 0) {
                        type = fileName.substring(dotIndex + 1);

                    }
                    if (type != null) {
                        MavenArtifact artifact = new MavenArtifact();
                        String v = split[split.length - 2];
                        String a = split[split.length - 3];
                        String g = "";
                        for (int j = 1; j < split.length - 3; j++) {
                            if ("".equals(g)) {
                                g = split[j];
                            } else {
                                g = g + "." + split[j];
                            }
                        }
                        artifact.setGroupId(g);
                        artifact.setArtifactId(a);
                        artifact.setVersion(v);
                        artifact.setType(type);
                        resultList.add(artifact);
                    }
                }

            }

        }
    }

    return resultList;
}