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 String name, final String value) 

Source Link

Usage

From source file:com.qwazr.crawler.web.driver.BrowserDriver.java

void httpClientDownload(String url, String userAgent, File file) throws NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, IOException, URISyntaxException {
    URI uri = new URI(url);
    final CloseableHttpClient httpClient = HttpUtils.createHttpClient_AcceptsUntrustedCerts();
    try {/*w  w w . j  av  a2s .  c o  m*/
        final Executor executor = Executor.newInstance(httpClient);
        Request request = Request.Get(uri.toString()).addHeader("Connection", "close").connectTimeout(60000)
                .socketTimeout(60000);
        if (userAgent != null)
            request = request.addHeader("User-Agent", userAgent);
        if (currentProxy != null) {
            if (currentProxy.http_proxy != null && !currentProxy.http_proxy.isEmpty())
                request = request.viaProxy(currentProxy.http_proxy);
            if ("https".equals(uri.getScheme()) && currentProxy.ssl_proxy != null
                    && !currentProxy.ssl_proxy.isEmpty())
                request = request.viaProxy(currentProxy.ssl_proxy);
        }
        executor.execute(request).saveContent(file);
    } finally {
        IOUtils.close(httpClient);
    }
}

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

/**
 * deletes a comment with the given comments api url uses the HTTP method
 * delete//from   w ww.  java2  s . c  o m
 * 
 * Method: DELETE URL:
 * http://localhost:9080/photoSharing/api/comments?uid=20514318
 * &pid=bf33a9b5-
 * 3042-46f0-a96e-b8742fced7a4&cid=4ec9c9c2-6e21-4815-bd42-91d502d2d427
 * 
 * @param bearer
 *            token
 * @param cid
 *            comment id
 * @param pid
 *            document id
 * @param uid
 *            user id
 * @param response
 * @param nonce
 */
public void deleteComment(String bearer, String cid, String pid, String uid, HttpServletResponse response,
        String nonce) {
    String apiUrl = getApiUrl() + "/userlibrary/" + uid + "/document/" + pid + "/comment/" + cid + "/entry";

    Request delete = Request.Delete(apiUrl);
    delete.addHeader("Authorization", "Bearer " + bearer);
    delete.addHeader("X-Update-Nonce", nonce);

    try {
        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(delete);

        HttpResponse hr = apiResponse.returnResponse();

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

        // Checks the Status Code
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else {
            // Default to SC_NO_CONTENT(204)
            response.setStatus(HttpStatus.SC_NO_CONTENT);
        }

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

}

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

/**
 * get nonce as described with nonce <a href="http://ibm.co/1fG83gY">Get a
 * Cryptographic Key</a>// ww  w. j  a va  2s. co m
 * 
 * @param bearer
 *            the access token
 * @return {String} the nonce
 */
private String getNonce(String bearer, HttpServletResponse response) {
    String nonce = "";

    // Build the Request
    Request get = Request.Get(getNonceUrl());
    get.addHeader("Authorization", "Bearer " + bearer);

    try {
        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(get);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes and if 200, convert to String
         */
        int code = hr.getStatusLine().getStatusCode();

        // Checks the Status Code
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else if (code == HttpStatus.SC_OK) {
            // Default to 200
            InputStream in = hr.getEntity().getContent();
            nonce = IOUtils.toString(in);
        } else {
            // SC_BAD_GATEWAY (503)
            response.setStatus(HttpStatus.SC_BAD_GATEWAY);
        }

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

    return nonce;
}

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

/**
 * updates a given comment/*from w  w w .  j  a va2  s  .  co m*/
 * 
 * @param bearer
 *            the accessToken
 * @param cid
 *            the comment id
 * @param pid
 *            the file id
 * @param uid
 *            the library id
 * @param body
 *            the text body
 * @param nonce
 *            the nonce value
 * @param response
 *            the response that is going to get the response
 */
public void updateComment(String bearer, String cid, String pid, String uid, String body, String nonce,
        HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/userlibrary/" + uid + "/document/" + pid + "/comment/" + cid + "/entry";
    try {
        JSONObject obj = new JSONObject(body);

        String comment = generateComment(obj.getString("comment"));

        // Generate the
        Request put = Request.Put(apiUrl);
        put.addHeader("Authorization", "Bearer " + bearer);
        put.addHeader("X-Update-Nonce", nonce);
        put.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(comment.getBytes("UTF-8"));
        put.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(put);
        HttpResponse hr = apiResponse.returnResponse();

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

        // Checks the status code for the response
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else {
            // Default to 200
            response.setStatus(HttpStatus.SC_OK);
        }

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

}

From source file:de.elomagic.maven.http.HTTPMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    try {/*  w w  w . ja  v a 2s  .c  o  m*/
        Executor executor;

        if (httpsInsecure) {
            getLog().info("Accepting unsecure HTTPS connections.");
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustAllStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

                final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslsf).build();

                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                        sfr);
                connectionManager.setDefaultMaxPerRoute(100);
                connectionManager.setMaxTotal(200);
                connectionManager.setValidateAfterInactivity(1000);

                HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                        .build();

                executor = Executor.newInstance(httpClient);
            } catch (Exception ex) {
                throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex);
            }
        } else {
            executor = Executor.newInstance();
        }

        Settings settings = session.getSettings();
        if (StringUtils.isNotBlank(serverId)) {
            Server server = settings.getServer(serverId);
            if (server == null) {
                throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml");
            }
            getLog().debug("ServerId: " + serverId);
            executor.auth(server.getUsername(), server.getPassword());
        }

        Request request = createRequestMethod();

        request.setHeader("Accept", accept);

        if (httpHeaders != null) {
            for (Entry<String, String> entry : httpHeaders.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (formParams != null) {
            Form form = Form.form();
            for (Entry<String, String> entry : formParams.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        if (fromFile != null) {
            if (!fromFile.exists()) {
                throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist.");
            }

            if (StringUtils.isBlank(contentType)) {
                contentType = Files.probeContentType(fromFile.toPath());
            }

            getLog().debug("From file: " + fromFile);
            getLog().debug("Upload file size: "
                    + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue()));
            getLog().debug("Content type: " + contentType);

            if (StringUtils.isBlank(contentType)) {
                request.body(new FileEntity(fromFile));
            } else {
                request.body(new FileEntity(fromFile, ContentType.create(contentType)));
            }
        }

        getLog().info(method + " " + url);

        Response response = executor.execute(request);
        handleResponse(response);
    } catch (Exception ex) {
        getLog().error(ex);
        if (failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            getLog().info("Fail on error is disabled. Continue execution.");
        }
    }

}

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

/**
 * creates a new comment with a given library id and document id
 * /*from   w  ww.  j  a v  a 2s.  c o  m*/
 * @param bearer
 *            the accesstoken used to make the request
 * @param pid
 *            the document id
 * @param uid
 *            the library id
 * @param body
 *            the body of the comment
 * @param nonce
 *            the nonce code
 * @param response
 *            the http response that the results are sent to
 */
public void createComment(String bearer, String pid, String uid, String body, String nonce,
        HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + uid + "/document/" + pid + "/feed";

    logger.info(apiUrl);

    try {
        JSONObject obj = new JSONObject(body);

        String comment = generateComment(obj.getString("comment"));

        // Generate the
        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(comment.getBytes("UTF-8"));
        post.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(post);
        HttpResponse hr = apiResponse.returnResponse();

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

        // Process the Status Codes
        if (code == HttpStatus.SC_FORBIDDEN) {
            // Session is no longer valid or access token is expired
            response.setStatus(HttpStatus.SC_FORBIDDEN);
        } else if (code == HttpStatus.SC_UNAUTHORIZED) {
            // User is not authorized
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        } else if (code == HttpStatus.SC_CREATED) {
            // Default to 201
            response.setStatus(HttpStatus.SC_OK);

            InputStream in = hr.getEntity().getContent();

            String jsonString = org.apache.wink.json4j.utils.XML.toJson(in);

            JSONObject base = new JSONObject(jsonString);
            JSONObject entry = base.getJSONObject("entry");
            JSONObject author = entry.getJSONObject("author");

            String name = author.getString("name");
            String userid = author.getString("userid");
            String date = entry.getString("modified");
            String content = entry.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);

            // Flush the Object to the Stream with content type
            response.setHeader("Content-Type", "application/json");

            PrintWriter out = response.getWriter();
            out.write(commentJSON.toString());
            out.flush();
            out.close();

        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("Issue with create comment " + e.toString());
    } catch (JSONException e) {
        response.setHeader("X-Application-Error ", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("Issue with create comment " + 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 create comment " + e.toString());
    }
}

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

/**
 * reads the comments from the comments feed
 * /* w  ww.j ava2s . 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:com.evon.injectTemplate.InjectTemplateFilter.java

private void loadContentTemplate(TemplateBean template, String domain, Integer port, boolean https,
        HttpServletRequest httpRequest) throws Exception {
    HTMLInfoBean htmlInfo = templates.get("/" + template.path);

    String sport = (port == null) ? "" : ":" + String.valueOf(port);

    String url = htmlInfo.getProtocol() + "://" + domain + sport + "/" + template.path;

    Request request = Request.Get(url);

    Enumeration<String> headerNames = httpRequest.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();

        Enumeration<String> headerValues = httpRequest.getHeaders(name);
        while (headerValues.hasMoreElements()) {
            String value = headerValues.nextElement();
            request = request.addHeader(name, value);
        }//from w w  w .j a v  a2  s .  c o  m
    }

    String content = request.execute().returnContent().asString();

    Pattern pattern = Pattern.compile("<INJECT[ ]{1,}selector=[\"'](.*?)[\"']/>",
            Pattern.CASE_INSENSITIVE + Pattern.DOTALL);

    Matcher matcher = pattern.matcher(content);

    List<String> selectors = new ArrayList<String>();

    while (matcher.find()) {
        String tagInject = matcher.group(0);
        String selector = matcher.group(1);
        selectors.add(selector);
        content = content.replace(tagInject, "<INJECT selector='" + selector + "'/>");
    }

    String key = null;

    if (template.cache.equals("SESSION")) {
        String cookiesNames = getCookieHashs(httpRequest);
        key = template.path + cookiesNames;
    } else {
        key = template.path;
    }

    HtmlContentBean contentBean = new HtmlContentBean();
    contentBean.setContent(content);
    contentBean.setLastAccess(System.currentTimeMillis());
    htmlContents.remove(key);
    htmlContents.put(key, contentBean);
    htmlInfo.setSelectors(selectors);
}

From source file:org.jspare.jsdbc.JsdbcTransportImpl.java

@Override
public String execute(DataSource datasource, Credential credential, Optional<Domain> domain, String operation,
        int method, String data) throws JsdbcException {

    if (datasource == null) {

        throw new JsdbcException("DataSource not loaded");
    }/*from w  w  w.j  a  v  a 2 s  .c  om*/

    try {

        Request request = null;
        org.apache.http.client.fluent.Response response = null;

        String uriAddress = getUrlConnection(datasource, operation,
                Optional.of(domain.orElse(Domain.of(StringUtils.EMPTY)).domain()));
        if (method == RETRIEVE) {
            request = Request.Get(new URIBuilder(uriAddress).build().toString());
        } else if (method == SEND) {
            request = Request.Post(new URIBuilder(uriAddress).build().toString()).bodyString(data,
                    ContentType.APPLICATION_JSON);
        } else {
            throw new JsdbcException("Method called is not mapped");
        }
        request.addHeader(AGENT_KEY, AGENT);

        response = buildAuthentication(request, datasource, credential).execute();

        HttpResponse httpResponse = response.returnResponse();

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {

            if (statusCode == HttpStatus.SC_BAD_REQUEST) {

                throw new JsdbcException("Authorization error, validate your credentials.");
            }
            if (statusCode == HttpStatus.SC_FORBIDDEN) {

                throw new JsdbcException("Forbidden access, validate your user roles.");
            }

            String content = IOUtils.toString(httpResponse.getEntity().getContent());

            ErrorResult result = my(Serializer.class).fromJSON(content, ErrorResult.class);
            throw new CommandFailException(result);
        }

        return IOUtils.toString(httpResponse.getEntity().getContent());

    } catch (Exception e) {

        log.error(e.getMessage(), e);
        throw new JsdbcException("JSDB Server Error");
    }
}

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

/**
 * manages the thumbnail access// w  w  w  . ja va2  s. c om
 * 
 * @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());
        }

    }

}