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

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

Introduction

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

Prototype

public Request body(final HttpEntity entity) 

Source Link

Usage

From source file:io.coala.capability.online.FluentHCOnlineCapability.java

/**
 * @param request// w w w.java 2 s.  c  om
 * @param handler
 * @param sub
 * @param entity
 */
protected static void execute(final Request request, final MyResponseHandler handler,
        final Subscriber<? super ResourceStream> sub, final HttpEntity entity) {
    try {
        if (entity != null)
            request.body(entity);
        request.execute().handleResponse(handler);
    } catch (final Throwable e) {
        sub.onError(e);
    }
}

From source file:photosharing.api.oauth.OAuth20Handler.java

/**
 * renews an access token with the user's data
 * // w  ww  .  j  a  v a2s  .c o  m
 * @param oData
 *            the current OAuth 2.0 data.
 * @return {OAuth20Data} or null
 * @throws IOException
 */
public OAuth20Data renewAccessToken(OAuth20Data oData) throws IOException {
    logger.finest("renewAccessToken activated");

    Configuration config = Configuration.getInstance(null);
    String body = this.generateRenewAccessTokenRequestBody(oData.getAccessToken(), oData.getRefreshToken(),
            oData.getIssuedOn(), oData.getExpiresIn());

    // Builds the URL in a StringBuilder
    StringBuilder builder = new StringBuilder();
    builder.append(config.getValue(Configuration.BASEURL));
    builder.append(TOKENURL);

    Request post = Request.Post(builder.toString());
    post.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
    post.body(new StringEntity(body));

    /**
     * Block is executed if there is a trace
     */
    logger.info("URL Encoded body is " + body);
    logger.info("Token URL is " + builder.toString());

    /**
     * Executes with a wrapped executor
     */
    Executor exec = ExecutorUtil.getExecutor();
    Response apiResponse = exec.execute(post);
    HttpResponse hr = apiResponse.returnResponse();

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

    if (statusCode == 200) {
        InputStream in = hr.getEntity().getContent();
        String x = IOUtils.toString(in);
        oData = OAuth20Data.createInstance(x);
    } else {
        logger.warning("OAuth20Data status code " + statusCode);
    }

    return oData;
}

From source file:photosharing.api.oauth.OAuth20Handler.java

/**
 * gets an access token based on the code
 * /* w  ww.  j a  v a2s  .  com*/
 * @param code
 *            - the >254 character code representing temporary credentials
 * @return the OAuth 20 configuration for the user requesting
 * @throws IOException
 */
public OAuth20Data getAccessToken(String code) throws IOException {
    logger.info("getAccessToken activated");
    OAuth20Data oData = null;

    Configuration config = Configuration.getInstance(null);
    String body = this.generateAccessTokenRequestBody(config.getValue(Configuration.CLIENTID),
            config.getValue(Configuration.CLIENTSECRET), config.getValue(Configuration.CALLBACKURL), code);

    // Builds the URL in a StringBuilder
    StringBuilder builder = new StringBuilder();
    builder.append(config.getValue(Configuration.BASEURL));
    builder.append(TOKENURL);

    Request post = Request.Post(builder.toString());
    post.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
    post.body(new StringEntity(body));

    /**
     * Block is executed if there is a trace
     */
    logger.info("URL Encoded body is " + body);
    logger.info("Token URL is " + builder.toString());

    /**
     * Executes with a wrapped executor
     */
    Executor exec = ExecutorUtil.getExecutor();
    Response apiResponse = exec.execute(post);
    HttpResponse hr = apiResponse.returnResponse();

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

    if (statusCode == 200) {
        InputStream in = hr.getEntity().getContent();
        String x = IOUtils.toString(in);
        oData = OAuth20Data.createInstance(x);
    } else {
        logger.warning("OAuth20Data status code " + statusCode);
    }

    return oData;
}

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

/**
 * like a file/*from ww w  .j  a v  a 2  s  . c o  m*/
 * 
 * Example URL
 * http://localhost:9080/photoSharing/api/like?r=on&lid=f8ad2a54-
 * 4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727 maps
 * to
 * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed
 * 
 * 
 * @param bearer
 * @param pid
 * @param lid
 * @param nonce
 * @param response
 */
public void like(String bearer, String pid, String lid, String nonce, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed";

    try {

        String recommendation = generateRecommendationContent();
        logger.info("like -> " + apiUrl + " " + recommendation);

        // Generate the apiUrl for like
        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(recommendation.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();
        logger.info("code " + code);

        // 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_NO_CONTENT (204)
        else {
            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("IOException " + e.toString());
        e.printStackTrace();
    }
}

From source file:me.vertretungsplan.parser.LoginHandler.java

private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse)
        throws JSONException, IOException, CredentialInvalidException {
    if (auth == null)
        return null;
    if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) {
        throw new IllegalArgumentException("Wrong authentication type");
    }//  w w w . j av a 2s  .  c o  m

    String login;
    String password;
    if (auth instanceof UserPasswordCredential) {
        login = ((UserPasswordCredential) auth).getUsername();
        password = ((UserPasswordCredential) auth).getPassword();
    } else {
        login = null;
        password = ((PasswordCredential) auth).getPassword();
    }

    JSONObject data = scheduleData.getData();
    JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG);
    String type = loginConfig.optString(PARAM_TYPE, "post");
    switch (type) {
    case "post":
        List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null;
        if (cookieList != null && !needsResponse) {
            for (Cookie cookie : cookieList)
                cookieStore.addCookie(cookie);

            String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
            String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
            if (checkUrl != null && checkText != null) {
                String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                if (!response.contains(checkText)) {
                    return null;
                }
            } else {
                return null;
            }
        }
        executor.clearCookies();
        Document preDoc = null;
        if (loginConfig.has(PARAM_PRE_URL)) {
            String preUrl = loginConfig.getString(PARAM_PRE_URL);
            String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString();
            preDoc = Jsoup.parse(preHtml);
        }

        String postUrl = loginConfig.getString(PARAM_URL);
        JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA);
        List<NameValuePair> nvps = new ArrayList<>();

        String typo3Challenge = null;

        if (loginData.has("_hiddeninputs") && preDoc != null) {
            for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) {
                nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
                if (hidden.attr("name").equals("challenge")) {
                    typo3Challenge = hidden.attr("value");
                }
            }
        }

        for (String name : JSONObject.getNames(loginData)) {
            String value = loginData.getString(name);

            if (name.equals("_hiddeninputs"))
                continue;

            switch (value) {
            case "_login":
                value = login;
                break;
            case "_password":
                value = password;
                break;
            case "_password_md5":
                value = DigestUtils.md5Hex(password);
                break;
            case "_password_md5_typo3":
                value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge);
                break;
            }

            nvps.add(new BasicNameValuePair(name, value));
        }
        Request request = Request.Post(postUrl);
        if (loginConfig.optBoolean("form-data", false)) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (NameValuePair nvp : nvps) {
                builder.addTextBody(nvp.getName(), nvp.getValue());
            }
            request.body(builder.build());
        } else {
            request.bodyForm(nvps, Charset.forName("UTF-8"));
        }
        String html = executor.execute(request).returnContent().asString();
        if (cookieProvider != null)
            cookieProvider.saveCookies(auth, cookieStore.getCookies());

        String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
        String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
        if (checkUrl != null && checkText != null) {
            String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
            if (response.contains(checkText))
                throw new CredentialInvalidException();
        } else if (checkText != null) {
            if (html.contains(checkText))
                throw new CredentialInvalidException();
        }
        return html;
    case "basic":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "ntlm":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password, null, null);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "fixed":
        String loginFixed = loginConfig.optString(PARAM_LOGIN, null);
        String passwordFixed = loginConfig.getString(PARAM_PASSWORD);
        if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) {
            throw new CredentialInvalidException();
        }
        break;
    }
    return null;
}

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

/**
 * unlike a file/*from   w ww. ja v a 2s  . c  o  m*/
 * 
 * Example URL
 * http://localhost:9080/photoSharing/api/like?r=off&lid=f8ad2a54
 * -4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727
 * maps to
 * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed
         
 * 
 * @param bearer
 * @param lid
 * @param uid
 * @param nonce
 * @param response
 */
public void unlike(String bearer, String pid, String lid, String nonce, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed";

    try {

        String recommendation = generateRecommendationContent();
        logger.info("like -> " + apiUrl + " " + recommendation);

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

        ByteArrayEntity entity = new ByteArrayEntity(recommendation.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();

        // 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_NO_CONTENT (204)
        else {
            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("IOException " + e.toString());
    }
}

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

/**
 * updates a given comment/*from   ww w  .ja  v  a 2 s .  com*/
 * 
 * @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:photosharing.api.conx.CommentsDefinition.java

/**
 * creates a new comment with a given library id and document id
 * /*from w  w w .  j  a  v a 2  s  .c om*/
 * @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.UploadFileDefinition.java

/**
 * uploads a file to the IBM Connections Cloud using the Files Service
 * /*from   w w  w  . j a  v a  2s  .c  o m*/
 * @param bearer token
 * @param nonce 
 * @param request
 * @param response
 */
public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) {

    // Extracts from the Request Parameters
    String visibility = request.getParameter("visibility");
    String title = request.getParameter("title");
    String share = request.getParameter("share");
    String tagsUnsplit = request.getParameter("q");

    // Check for the Required Parameters
    if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);

    } else {

        /*
         * Builds the URL Parameters 
         */
        StringBuilder builder = new StringBuilder();
        builder.append("visibility=" + visibility + "&");
        builder.append("title=" + title + "&");

        // The Share parameters for the URL
        if (share != null && !share.isEmpty()) {
            builder.append("shared=true&");
            builder.append("shareWith=" + share + "&");
        }

        if (visibility.compareTo("private") == 0 && share == null) {
            builder.append("shared=false&");
        }

        // Splits the TagString into Indvidual Tags
        // - Technically this API is limited to 3 tags at most. 
        String[] tags = tagsUnsplit.split(",");
        for (String tag : tags) {
            logger.info("Tag-> " + tag);
            builder.append("tag=" + tag + "&");
        }

        // Build the apiURL
        String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString();

        //API Url
        logger.info(apiUrl);

        // Add the Headers
        String length = request.getHeader("X-Content-Length");
        String contentType = request.getHeader("Content-Type");
        String fileext = contentType.split("/")[1].split(";")[0];
        String slug = title + "." + fileext;

        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Slug", slug);
        post.addHeader("Content-Type", contentType);

        logger.info("Authorization: Bearer " + bearer);
        logger.info("X-Update-Nonce: " + nonce);
        logger.info("Slug: " + slug);
        logger.info("Content-Type: " + contentType);

        try {
            //
            InputStream in = request.getInputStream();
            Base64InputStream bis = new Base64InputStream(in);

            long len = Long.parseLong(length);
            InputStreamEntity entity = new InputStreamEntity(bis, len);

            post.body(entity);

            post.removeHeaders("Cookie");

            Executor exec = ExecutorUtil.getExecutor();

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

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

            logger.info("code is " + code);

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

            // Duplicate Item
            else if (code == HttpStatus.SC_CONFLICT) {
                response.setStatus(HttpStatus.SC_CONFLICT);
            }

            // Checks if Created
            else if (code == HttpStatus.SC_CREATED) {
                response.setStatus(HttpStatus.SC_OK);
                /**
                 * Do Extra Processing Here to process the body
                 */
                InputStream inRes = hr.getEntity().getContent();

                // Converts XML to JSON String
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes);
                JSONObject obj = new JSONObject(jsonString);

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.append(obj.toString());
                writer.close();

            } else {
                // Catch All
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                InputStream inRes = hr.getEntity().getContent();
                String out = IOUtils.toString(inRes);
                logger.info("Content: " + out);
                logger.info("Content Type of Response: " + response.getContentType());

                Collection<String> coll = response.getHeaderNames();
                Iterator<String> iter = coll.iterator();

                while (iter.hasNext()) {
                    String header = iter.next();
                    logger.info(header + " " + response.getHeader(header));
                }

            }

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

            logger.severe("JSONException " + e.toString());
        }
    }
}

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

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

    try {//  ww w.ja  v  a2s  . co  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.");
        }
    }

}