com.lushapp.common.web.servlet.RemoteContentServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.lushapp.common.web.servlet.RemoteContentServlet.java

Source

/**
 *  Copyright (c) 2014 http://www.lushapp.wang
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.lushapp.common.web.servlet;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lushapp.common.utils.StringUtils;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ???Servlet.
 * <br>
 * Apache HttpClient???.
 * 
 * <br>?:
 * <br>1?contentUrl: url?(get???)
 * <br>2?client: 'apache'Apache HttpClient ?JDK HttpUrlConnection
 * 
 * <br>?(contentUrl?URL?):
 * remote-content?contentUrl=http%3A%2F%2Flocalhost%3A8080%2Fshowcase%2Fimages%2Flogo.jpg
 * 
 * @author honey.zhao@aliyun.com  
 * @date 2014-10-24 ?3:43:18
 * 
 */
public class RemoteContentServlet extends HttpServlet {

    private static final long serialVersionUID = -8483811141908827663L;

    private static final int CONNECTION_POOL_SIZE = 10;
    private static final int TIMEOUT_SECONDS = 20;

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

    private HttpClient httpClient = null;

    /**
     * HttpClient.
     */
    @Override
    public void init() throws ServletException {
        // Set connection pool
        PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
        cm.setMaxTotal(CONNECTION_POOL_SIZE);
        httpClient = new DefaultHttpClient(cm);

        // set timeout
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SECONDS * 1000);
    }

    /**
     * ?HttpClient.
     */
    @Override
    public void destroy() {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }

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

        // ??
        String client = request.getParameter("client");

        InputStream input = null;
        if ("apache".equals(client)) {
            // Apache HttpClient
            fetchContentByApacheHttpClient(response, contentUrl);
        } else {
            // JDK HttpUrlConnection
            fetchContentByJDKConnection(response, contentUrl);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * HttpClient?.
     */
    private void fetchContentByApacheHttpClient(HttpServletResponse response, String contentUrl)
            throws IOException {

        // ?
        HttpEntity entity = null;
        HttpGet httpGet = new HttpGet(contentUrl);
        try {
            HttpContext context = new BasicHttpContext();
            HttpResponse remoteResponse = httpClient.execute(httpGet, context);
            entity = remoteResponse.getEntity();
        } catch (Exception e) {
            logger.error("fetch remote content" + contentUrl + "  error", e);
            httpGet.abort();
            return;
        }

        // 404
        if (entity == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

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

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

    }

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