⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tunnelservlet.java

📁 一个java方面的消息订阅发送的源码
💻 JAVA
字号:
/**
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright
 *    statements and notices.  Redistributions must also contain a
 *    copy of this document.
 *
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. The name "Exolab" must not be used to endorse or promote
 *    products derived from this Software without prior written
 *    permission of Exoffice Technologies.  For written permission,
 *    please contact info@exolab.org.
 *
 * 4. Products derived from this Software may not be called "Exolab"
 *    nor may "Exolab" appear in their names without prior written
 *    permission of Exoffice Technologies. Exolab is a registered
 *    trademark of Exoffice Technologies.
 *
 * 5. Due credit should be given to the Exolab Project
 *    (http://www.exolab.org/).
 *
 * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright 2004 (C) Exoffice Technologies Inc. All Rights Reserved.
 *
 * $Id: TunnelServlet.java,v 1.1 2004/11/26 01:51:17 tanderson Exp $
 */
package org.exolab.jms.net.tunnel;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * HTTP Tunnel servlet
 *
 * @author <a href="mailto:tma@netspace.net.au">Tim Anderson</a>
 * @version $Revision: 1.1 $ $Date: 2004/11/26 01:51:17 $
 */
public class TunnelServlet extends HttpServlet {

    /**
     * The host that the server is running on
     */
    private String _host;

    /**
     * The port that the connector is listening on
     */
    private int _port;

    /**
     * The connection manager
     */
    private static final EndpointManager _manager = new EndpointManager();

    /**
     * Initialisation property name for the host that the server is running on.
     */
    private static final String SERVER_HOST = "host";

    /**
     * Initialisation property name for the port that the connector is
     * listening on.
     */
    private static final String SERVER_PORT = "port";


    /**
     * Initialise the servlet
     *
     * @throws ServletException if the servlet can't be initialised
     */
    public void init() throws ServletException {
        String host = getInitParameter(SERVER_HOST);
        String port = getInitParameter(SERVER_PORT);
        if (host == null) {
            throw new ServletException("Property not defined: " + SERVER_HOST);
        }
        if (port == null) {
            throw new ServletException("Property not defined: " + SERVER_PORT);
        }
        _host = host;
        try {
            _port = Integer.parseInt(port);
        } catch (NumberFormatException exception) {
            throw new ServletException("Invalid port: " + port);
        }
        log("OpenJMS tunnel accepting requests");
    }

    /**
     * Handle a GET request. This method always sets the response code to
     * <code>HttpServletResponse.SC_BAD_REQUEST</code>
     *
     * @param request  the client request
     * @param response the response to the request
     * @throws IOException for any I/O error
     */
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    /**
     * Handle a POST request.
     *
     * @param request  the client request
     * @param response the response to the request
     * @throws IOException for any I/O error
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {

        String action = request.getHeader("action");

        if (action == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                               "Invalid action");
        } else if (action.equals("open")) {
            open(request, response);
        } else {
            String id = request.getHeader("id");
            if (id == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                   "Invalid connection");
            } else if (action.equals("read")) {
                read(id, response);
            } else if (action.equals("write")) {
                write(id, request, response);
            } else if (action.equals("close")) {
                close(id, response);
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                   "Invalid action");
            }
        }
    }

    /**
     * Handle an open request. A connection is established to the server and the
     * identifier written to the client.
     *
     * @param request  the client request
     * @param response the response to the request
     * @throws IOException for any I/O error
     */
    private void open(HttpServletRequest request,
                      HttpServletResponse response) throws IOException {
//        if (_log.isDebugEnabled()) {
//            _log.debug("open");
//        }

        response.setContentType("text/plain");
        PrintWriter out = new PrintWriter(response.getWriter());

        try {
            String id = _manager.open(_host, _port);
            out.println("OPEN " + id);
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception exception) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                               exception.getMessage());
            log("open failed", exception);
        }
    }

    /**
     * Handles a read request. Data is read from the endpoint and written to the
     * client.
     *
     * @param id       the endpoint identifier
     * @param response the response to the client
     * @throws IOException for any I/O error
     */
    private void read(String id, HttpServletResponse response)
            throws IOException {
        Socket endpoint = _manager.getEndpoint(id);
        if (endpoint == null) {
            log("Connection not found, id=" + id);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                               "Connection not found");
        } else {
            byte[] data = new byte[1024];
            try {
                endpoint.setSoTimeout(1000);
                InputStream in = endpoint.getInputStream();
                int count = 0;
                try {
                    count = in.read(data);
                } catch (InterruptedIOException ignore) {
                }
                // log("read(id=" + id + "), [length=" + count + "]");
                if (count != -1) {
                    response.setContentLength(count);
                    response.setStatus(HttpServletResponse.SC_OK);
                    OutputStream out = response.getOutputStream();
                    out.write(data, 0, count);
                    out.flush();
                } else {
                    remove(id);
                    response.setStatus(
                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            } catch (IOException exception) {
                String message = exception.getMessage();
                log("read failed", exception);
                remove(id);
                response.sendError(
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        exception.getMessage());
            }
        }
    }

    /**
     * Handles a write request. Data from the client is written to the endpoint
     *
     * @param id       the endpoint identifier
     * @param request  the client request
     * @param response the response to the client
     * @throws IOException for any I/O error
     */
    private void write(String id, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
        Socket endpoint = _manager.getEndpoint(id);
        if (endpoint == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                               "Connection not found");
        } else {
            try {
                // log("write(id=" + id + "), [length="
                //    + request.getContentLength()
                //    + "]");
                InputStream in = request.getInputStream();
                OutputStream out = endpoint.getOutputStream();
                byte[] data = new byte[1024];
                int count = 0;
                while (count != -1) {
                    count = in.read(data);
                    if (count > 0) {
                        out.write(data, 0, count);
                    }
                }
                in.close();
                out.flush();
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (IOException exception) {
                String message = exception.getMessage();
                log("write failed", exception);
                remove(id);
                response.sendError(
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        exception.getMessage());
            }
        }
    }

    /**
     * Handle a close request.
     *
     * @param id       the endpoint identifier
     * @param response the response to the client
     * @throws IOException for any I/O error
     */
    private void close(String id, HttpServletResponse response)
            throws IOException {

        try {
            log("close(id=" + id + ")");
            _manager.close(id);
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException exception) {
            log("close failed", exception);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                               exception.getMessage());
        }
    }

    /**
     * Removes an endpoint
     *
     * @param id the endpoint identifier
     */
    private void remove(String id) {
        try {
            _manager.close(id);
        } catch (IOException ignore) {
        }
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -