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

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

Introduction

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

Prototype

public Request addHeader(final Header header) 

Source Link

Usage

From source file:org.schedulesdirect.api.json.DefaultJsonRequest.java

private HttpResponse submitRaw(Object reqData) throws IOException {
    if (!valid)//from www . j  a  v a 2  s  .c o  m
        throw new IllegalStateException("Cannot submit a partially constructed request!");
    try {
        targetUrl = baseUrl.toString();
        audit.append(String.format(">>>target: %s%n>>>verb: %s%n", targetUrl, action));
        Executor exe = Executor.newInstance(new DecompressingHttpClient(new DefaultHttpClient()));
        Request req = initRequest();
        if (hash != null)
            req.addHeader(new BasicHeader("token", hash));
        if (reqData != null)
            req.bodyString(reqData.toString(), ContentType.APPLICATION_JSON);
        audit.append(String.format(">>>req_headers:%n%s",
                HttpUtils.prettyPrintHeaders(HttpUtils.scrapeHeaders(req), "\t")));
        if (action == Action.PUT || action == Action.POST)
            audit.append(String.format(">>>input: %s%n", reqData));
        HttpResponse resp = exe.execute(req).returnResponse();
        if (LOG.isDebugEnabled()) {
            Header h = resp.getFirstHeader("Schedulesdirect-Serverid");
            String val = h != null ? h.getValue() : "[Unknown]";
            LOG.debug(String.format("Request to '%s' handled by: %s", targetUrl, val));
        }
        StatusLine status = resp.getStatusLine();
        audit.append(String.format("<<<resp_status: %s%n", status));
        audit.append(String.format("<<<resp_headers:%n%s",
                HttpUtils.prettyPrintHeaders(resp.getAllHeaders(), "\t")));
        if (LOG.isDebugEnabled() && status.getStatusCode() >= 400)
            LOG.debug(String.format("%s returned error! [rc=%d]", req, status.getStatusCode()));
        return resp;
    } catch (IOException e) {
        audit.append(String.format("*** REQUEST FAILED! ***%n%s", e.getMessage()));
        throw e;
    }
}

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

private String fetchDataSetId() throws IOException {
    if (dataSetName == null || authorisationHeader == null) {
        return null;
    }/* w ww  .ja va2s.  c om*/

    String result = null;

    URI uri = null;
    URL localUrl = new URL(url);
    try {
        uri = new URI(localUrl.getProtocol(), null, localUrl.getHost(), localUrl.getPort(), "/api/datasets",
                "name=" + dataSetName, null);
    } catch (URISyntaxException e) {
        throw new ComponentException(e);
    }

    Request request = Request.Get(uri);
    request.addHeader(authorisationHeader);
    HttpResponse response = request.execute().returnResponse();
    String content = extractResponseInformationAndConsumeResponse(response);

    if (returnStatusCode(response) != HttpServletResponse.SC_OK) {
        throw new IOException(content);
    }

    if (content != null && !"".equals(content)) {
        Object object = JsonReader.jsonToJava(content);
        if (object != null && object instanceof Object[]) {
            Object[] array = (Object[]) object;
            if (array.length > 0) {
                @SuppressWarnings("rawtypes")
                JsonObject jo = (JsonObject) array[0];
                result = (String) jo.get("id");
            }
        }
    }

    return result;
}

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. j a va  2s  .c  om*/

    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:org.obm.sync.push.client.WBXMLOPClient.java

private Request buildRequest(String namespace, Document doc, String cmd, String policyKey, boolean multipart)
        throws WBXmlException, IOException {
    ByteArrayEntity requestEntity = getRequestEntity(namespace, doc);

    Request request = Request.Post(buildUrl(ai.getUrl(), ai.getLogin(), ai.getDevId(), ai.getDevType(), cmd))
            .addHeader(new BasicHeader("Content-Type", requestEntity.getContentType().getValue()))
            .addHeader(new BasicHeader("Authorization", ai.authValue()))
            .addHeader(new BasicHeader("User-Agent", ai.getUserAgent()))
            .addHeader(new BasicHeader("Ms-Asprotocolversion", protocolVersion.asSpecificationValue()))
            .addHeader(new BasicHeader("Accept", "*/*")).addHeader(new BasicHeader("Accept-Language", "fr-fr"))
            .addHeader(new BasicHeader("Connection", "keep-alive")).body(requestEntity);

    if (multipart) {
        request.addHeader(new BasicHeader("MS-ASAcceptMultiPart", "T"));
        request.addHeader(new BasicHeader("Accept-Encoding", "gzip"));
    }/*from  www.  ja  v a2 s  .  c o m*/

    if (policyKey != null) {
        request.addHeader(new BasicHeader("X-MS-PolicyKey", policyKey));
    }
    return request;
}

From source file:org.talend.components.jira.connection.Rest.java

/**
 * Executes Http Get request/*from   www .j  a v  a 2  s  .co m*/
 * 
 * @param resource REST API resource. E. g. issue/{issueId}
 * @param parameters http query parameters
 * @return response result
 * @throws IOException
 */
public String get(String resource, Map<String, Object> parameters) throws IOException {
    try {
        URIBuilder builder = new URIBuilder(hostPort + resource);
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue().toString());
        }
        URI uri = builder.build();
        Request get = Request.Get(uri);
        for (Header header : headers) {
            get.addHeader(header);
        }
        executor.clearCookies();
        return executor.execute(get).returnContent().asString();
    } catch (URISyntaxException e) {
        LOG.debug("Wrong URI. {}", e.getMessage());
        throw new IOException("Wrong URI", e);
    }
}

From source file:org.talend.components.jira.connection.Rest.java

/**
 * Executes Http Delete request//  w  w w  . j  a  v a 2 s.  c  om
 * 
 * @param resource REST API resource. E. g. issue/{issueId}
 * @param parameters http query parameters
 * @return http status code
 * @throws IOException
 */
public int delete(String resource, Map<String, Object> parameters) throws IOException {
    try {
        URIBuilder builder = new URIBuilder(hostPort + resource);
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue().toString());
        }
        URI uri = builder.build();
        Request delete = Request.Delete(uri);
        for (Header header : headers) {
            delete.addHeader(header);
        }
        executor.clearCookies();
        return executor.execute(delete).returnResponse().getStatusLine().getStatusCode();
    } catch (URISyntaxException e) {
        LOG.debug("Wrong URI. {}", e.getMessage());
        throw new IOException("Wrong URI", e);
    }
}

From source file:org.talend.components.jira.connection.Rest.java

/**
 * Executes Http Post request//from   w ww. j  a v a 2 s .c o  m
 * 
 * @param resource REST API resource. E. g. issue/{issueId}
 * @param body message body
 * @return response status code
 * @throws ClientProtocolException
 * @throws IOException
 */
public int post(String resource, String body) throws IOException {
    Request post = Request.Post(hostPort + resource).bodyString(body, contentType);
    for (Header header : headers) {
        post.addHeader(header);
    }
    executor.clearCookies();
    return executor.execute(post).returnResponse().getStatusLine().getStatusCode();
}

From source file:org.talend.components.jira.connection.Rest.java

/**
 * Executes Http Put request/*from w  ww . j a  v a  2s . com*/
 * 
 * @param resource REST API resource. E. g. issue/{issueId}
 * @param body message body
 * @return http status code
 * @throws ClientProtocolException
 * @throws IOException
 */
public int put(String resource, String body) throws IOException {
    Request put = Request.Put(hostPort + resource).bodyString(body, contentType);
    for (Header header : headers) {
        put.addHeader(header);
    }
    executor.clearCookies();
    return executor.execute(put).returnResponse().getStatusLine().getStatusCode();
}

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 + "/";
    }/* www  .  j  av a 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;
}