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

📄 httpmessagereceiverservlet.java

📁 jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,程序编译需要Ant支持
💻 JAVA
字号:
/*
 *
 * $Id: HttpMessageReceiverServlet.java,v 1.15 2002/06/19 01:17:36 jice Exp $
 *
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 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 end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
 *    must not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``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 SUN MICROSYSTEMS 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.
 *
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 */

package net.jxta.impl.endpoint.servlethttp;

import net.jxta.endpoint.EndpointService;
import net.jxta.impl.endpoint.MessageImpl;
import net.jxta.endpoint.Message;
import net.jxta.document.MimeMediaType;
import net.jxta.impl.endpoint.MessageWireFormatFactory;
import javax.servlet.SingleThreadModel;

import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

import org.apache.log4j.Category;
import org.apache.log4j.Priority;

/**
 * This is a simple servlet that accepts POSTed Jxta messages over HTTP
 * and hands them up to EndpointService. It also supports a ping operation. When
 * the URI is /ping, it simply responds with a 200.
 */
public class HttpMessageReceiverServlet extends HttpServlet {

	/** standard log object **/
	private static final Category LOG =
	    Category.getInstance(HttpMessageReceiverServlet.class.getName());

	/** The endpoint that the servlet is receiving messages for **/
	private EndpointService endpoint = null;

	/** Clients cannot POST more than 10MB **/
	private static final int MAX_POST_CONTENT_LEN = 10 * 1024 * 1024;

        private static final MimeMediaType msgType = new MimeMediaType( "application/x-jxta-msg" );

	/**
	 * Stores the endpoint from the ServletContext in to the data member
	 * for easy access.
	 */
	public void init(ServletConfig config)
	throws ServletException {
		super.init(config);

		try {
			endpoint = (EndpointService) getServletContext().getAttribute("endpoint");
			if (endpoint == null) {
				throw new ServletException("Servlet Context did not contain " +
				                           "'endpoint'");
			}
		} catch( ClassCastException e ) {
			throw new ServletException( "'endpoint' attribute was not of the "+
			                            "proper type in the Servlet Context");
		}
	}


	/**
	 * Handle the ping by sending back a 200.
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {

		String uri = req.getRequestURI();

		if (uri.startsWith("/ping")) {
			if (LOG.isEnabledFor(Priority.DEBUG)){
				LOG.debug( "  responding with 200 to ping request");
			}
			res.setStatus(HttpServletResponse.SC_OK );
		}
	}

	/**
	 * Handle posted messages. We first validate the message, which is where
	 * we check the content-length of the message. If that passes
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {

		if (validateMessage(req, res)) {
			String uri = req.getRequestURI();
			if (LOG.isEnabledFor(Priority.DEBUG)){
				LOG.debug("POSTed message is valid; uri=" + uri);
			}
			if (uri.equals("/")) {
				processMessage(req, res);
			}
		}

		return;
	}

	/**
	 * Validate the HTTP message headers. Specifically, it ensures that the
	 * content-length is (a) non-zero; (b) non-negative; (c) below the max
	 * size. If there is a problem, validateMessage will send the response
	 * (forbidden) and return false. Otherwise, true is returned with the
	 * response untouched.
	 */
	private boolean validateMessage(HttpServletRequest req,
	                                HttpServletResponse res)
	throws ServletException, IOException {

		int contentLen = req.getContentLength();
		if (LOG.isEnabledFor(Priority.DEBUG)){
			LOG.debug("HTTP POST received from " + req.getRemoteAddr() +", Content-Length = " + contentLen);
		}

		// Handle the case where the declared content length is too long or
		// undeclared
		if (! (contentLen > 0 && contentLen <= MAX_POST_CONTENT_LEN) ) {

			if (LOG.isEnabledFor(Priority.INFO)){
				LOG.info("Rejected HTTP POST request; too long, not declared, or "
				         + "zero length; length=" + req.getContentLength() );
			}
			res.sendError(HttpServletResponse.SC_FORBIDDEN,
			              "Content-Length too long or not declared, or "
			              +"zero; max allowed is " + MAX_POST_CONTENT_LEN );
			return false;
		}

		return true;
	}


	/**
	 * Processes a normal incoming message. Read it, construct a message, hand
	 * the message to endpoint.demux(), and response with OK
	 **/
	private void processMessage(HttpServletRequest req,
	                            HttpServletResponse res)
	throws ServletException, IOException {

		if (LOG.isEnabledFor(Priority.DEBUG)){
			LOG.debug("processing posted message");
		}

		int contentLen = req.getContentLength();

		// read the stream
		InputStream in = req.getInputStream();

		// construct the message. Send BAD_REQUEST if the message construction
		// fails
		try {
			if (LOG.isEnabledFor(Priority.DEBUG)){
				LOG.debug("Constructing MessageImpl and calling EndpointService.demux()");
			}
			Message msg = endpoint.newMessage();
			MessageWireFormatFactory.newMessageWireFormat(msgType).readMessage(in, msg);

			try {
			    endpoint.demux(msg);
			} catch (IOException ex) {
			    if (LOG.isEnabledFor(Priority.ERROR)){
				LOG.error("Error sending message: " + ex);
				return;
			    }
			}
			// Make sure we are not hogging the cpu with input
			// thus preventing it from being processed.
			// It is better to slow the sending side a bit.
			Thread.yield();

		} catch(IOException e) {
			if (LOG.isEnabledFor(Priority.DEBUG)){
				LOG.debug("Malformed JXTA message, responding with BAD_REQUEST: ", e );
			}
			res.sendError(HttpServletResponse.SC_BAD_REQUEST,
			              "Message was not a valid JXTA message");
			return;
		}

		// Message okay; construct the OK response
		if (LOG.isEnabledFor(Priority.DEBUG)){
			LOG.debug( " Sending OK in response to HTTP POST" );
		}
		res.setStatus(HttpServletResponse.SC_OK);
		return;
	}
}

⌨️ 快捷键说明

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