com.ppcxy.cyfm.showcase.demos.web.RemoteContentServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.ppcxy.cyfm.showcase.demos.web.RemoteContentServlet.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.ppcxy.cyfm.showcase.demos.web;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Apache HttpClient JDK????Servlet.
 * <p>
 * ???Apache HttpClient Fluent API
 * <p>
 * ?(contentUrl?URL?):
 * remote-content?contentUrl=http%3A%2F%2Flocalhost%3A8080%2Fshowcase%2Fimages%2Flogo.png
 *
 * @author calvin
 */
public class RemoteContentServlet extends HttpServlet {

    private static final long serialVersionUID = -8483811141908827663L;

    private static final int TIMEOUT_SECONDS = 20;

    private static final int POOL_SIZE = 20;

    private static Logger logger = LoggerFactory.getLogger(RemoteContentServlet.class);

    private static CloseableHttpClient httpClient;

    @Override
    public void init(ServletConfig config) throws ServletException {
        initApacheHttpClient();
    }

    @Override
    public void destroy() {
        destroyApacheHttpClient();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // ?URL
        String contentUrl = request.getParameter("contentUrl");
        if (StringUtils.isBlank(contentUrl)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentUrl parameter is required.");
        }

        // ?HttpClientJDK ??URL
        String client = request.getParameter("client");
        if ("apache".equals(client)) {
            fetchContentByApacheHttpClient(response, contentUrl);
        } else {
            fetchContentByJDKConnection(response, contentUrl);
        }
    }

    private void fetchContentByApacheHttpClient(HttpServletResponse response, String contentUrl)
            throws IOException {
        // ?
        HttpGet httpGet = new HttpGet(contentUrl);
        CloseableHttpResponse remoteResponse = httpClient.execute(httpGet);
        try {
            // 
            int statusCode = remoteResponse.getStatusLine().getStatusCode();
            if (statusCode >= 400) {
                response.sendError(statusCode, "fetch image error from " + contentUrl);
                return;
            }

            HttpEntity entity = remoteResponse.getEntity();

            // Header
            response.setContentType(entity.getContentType().getValue());
            if (entity.getContentLength() > 0) {
                response.setContentLength((int) entity.getContentLength());
            }
            // 
            InputStream input = entity.getContent();
            OutputStream output = response.getOutputStream();
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            remoteResponse.close();
        }
    }

    private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

        HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
        // Socket
        connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
        try {
            connection.connect();

            // ?
            InputStream input;
            try {
                input = connection.getInputStream();
            } catch (FileNotFoundException e) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
                return;
            }

            // Header
            response.setContentType(connection.getContentType());
            if (connection.getContentLength() > 0) {
                response.setContentLength(connection.getContentLength());
            }

            // 
            OutputStream output = response.getOutputStream();
            try {
                // byte?InputStreamOutputStream, ?4k.
                IOUtils.copy(input, output);
                output.flush();
            } finally {
                // ??InputStream.
                IOUtils.closeQuietly(input);
            }
        } finally {
            connection.disconnect();
        }
    }

    // ?connection poolclient
    private void initApacheHttpClient() {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT_SECONDS * 1000)
                .setConnectTimeout(TIMEOUT_SECONDS * 1000).build();

        httpClient = HttpClientBuilder.create().setMaxConnTotal(POOL_SIZE).setMaxConnPerRoute(POOL_SIZE)
                .setDefaultRequestConfig(requestConfig).build();
    }

    private void destroyApacheHttpClient() {
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("httpclient close fail", e);
        }
    }

    /**
     * FluentAPI
     */
    @SuppressWarnings("unused")
    public void fluentAPIDemo(String contentUrl) throws IOException {
        try {
            // demo1: ? , (200 total/100 per route), returnContent()??inputstream
            String resultString = Request.Get(contentUrl).execute().returnContent().asString();

            // demo2: ?, 
            byte[] resultBytes = Request.Get(contentUrl).connectTimeout(TIMEOUT_SECONDS * 1000)
                    .socketTimeout(TIMEOUT_SECONDS * 1000).execute().returnContent().asBytes();

            // demo3: ??httpClient
            Executor executor = Executor.newInstance(httpClient);
            String resultString2 = executor.execute(Request.Get(contentUrl)).returnContent().asString();
        } catch (HttpResponseException e) {
            logger.error("Status code:" + e.getStatusCode(), e);
        }
    }
}