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

📄 httprelayclientmessagereceiver.java

📁 jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,程序编译需要Ant支持
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 *
 * $Id: HttpRelayClientMessageReceiver.java,v 1.18 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 java.io.*;
import java.util.*;
import java.net.URL;
import java.net.HttpURLConnection;

import net.jxta.peergroup.PeerGroup;
import net.jxta.endpoint.EndpointService;
import net.jxta.endpoint.Message;
import net.jxta.document.MimeMediaType;
import net.jxta.protocol.*;
import net.jxta.impl.protocol.*;
import net.jxta.impl.relay.AbstractRelayClient;
import net.jxta.impl.relay.RelayLeaseException;
import net.jxta.impl.endpoint.MessageWireFormatFactory;
import net.jxta.impl.endpoint.MessageImpl;

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

/**
 * This component connects to a remote relay URL and receives messages from
 * it.
 */
public class HttpRelayClientMessageReceiver
extends AbstractRelayClient
implements MessageReceiver {
  
  private static final Category LOG = Category.getInstance(HttpRelayClientMessageReceiver.class.getName());
  
  /** Global timer used for lease renewal for all relay clients **/
  private static Timer pollTimer = null;
  
  /** Polling request mode where the client polls on intervals **/
  private static final int MODE_POLL = 0;
  
  /** Blocking request mode where the client connects and blocks **/
  private static final int MODE_BLOCK = 1;
  
  /** poll every 15 seconds XXX move this into config **/
  private static final int POLL_INTERVAL = 15 * 1000;
  
  /** the time that we will remain blocked before trying again **/
  private static final int BLOCK_TIMEOUT = 60 * 1000;
  
  /** the interval that the blocking receiver sleeps for when the relay
   * server responds with a non-200 response **/
  private static final int BLOCK_RETRY_INTERVAL = 15 * 1000;
  
  /** the amount of time we wait for a response to an obtainLease or
   * renewLease command **/
  private static final int COMMAND_TIMEOUT = 20 * 1000;
  
  
  /** the URL of the relay that this relay client will connect to **/
  URL url = null;
  
  /** The local endpoint that we're receiving messages for **/
  EndpointService endpoint = null;
  
  /** The peergroup that this receiver is servicing **/
  PeerGroup group = null;
  
  /** The request mode that the receiver is in **/
  private int requestMode = MODE_BLOCK;
  
  /** The blocking mode receiver object **/
  private BlockingMessageReceiver blockingReceiver = null;
  
  /** The blocking mode receiver thread **/
  private Thread receiverThread = null;
  
  /** The polling mode receiver task **/
  private PollingMessageReceiverTask pollingTask = null;
  
  /**
   * Constructs the receiver
   * @param httpServer the Http server.  Must be non-null.
   */
  public HttpRelayClientMessageReceiver(URL url) {
    
    if (url==null) {
      throw new IllegalArgumentException("HttpRelayClientMessageReceiver"
      +" cannot be configured with a"+
      " null url");
    }
    
    this.url = url;
  }
  
  /**
   * Stores the endpoint that this receiver is receiving messages for.
   */
  public void init(PeerGroup group,
  EndpointService endpoint,
  TransportAdvertisement transportAdv)
  throws IOException {
    
    this.endpoint = endpoint;
    this.group = group;
  }
  
  
  /**
   * Obtain the lease with the relay. I just send my peer id for now--no
   * authentication supported.
   */
  public boolean obtainLease() {
    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Trying to obtain lease to relay: " + url);
    
    String peerId = group.getPeerID().getUniqueValue().toString();
    
    QueryString query = new QueryString();
    query.add(HttpUtil.COMMAND_NAME, HttpUtil.COMMAND_VALUE_OBTAIN_LEASE);
    query.add(HttpUtil.PARAM_PEER_ID, peerId);
    
    boolean success = false;
    try {
      HttpURLConnection conn = postCommand(query.toString(),
      COMMAND_TIMEOUT);
      success = processLeaseResponse(conn);
      conn.disconnect();
      
    } catch(Exception e) {
      if (LOG.isEnabledFor(Priority.INFO)) LOG.info( "Exception during lease request: " + e );
    }
    
    return success;
  }
  
  
  /**
   * Try to renew the lease with the relay.
   */
  public boolean renewLease() {
    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug( "Trying to renew lease to relay: " + url);
    QueryString query = new QueryString();
    query.add(HttpUtil.COMMAND_NAME, HttpUtil.COMMAND_VALUE_RENEW_LEASE);
    query.add(HttpUtil.PARAM_LEASE_ID, getLeaseId());
    boolean success = false;
    try {
      HttpURLConnection conn = postCommand(query.toString(),
      COMMAND_TIMEOUT);
      success = processLeaseResponse(conn);
      conn.disconnect();
    } catch(Exception e) {
      if (LOG.isEnabledFor(Priority.INFO)) LOG.info( "Exception during lease renewal request: " + e );
    }
    
    return success;
  }
  
  
  /**
   * Shared method betwen obtainLease() and renewLease(). Takes the response
   * stream and reads the result. If everything is good from the relay
   * peer, the lease is recorded.
   */
  private boolean processLeaseResponse(HttpURLConnection conn)
  throws IOException {
    
    if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("processing lease response");
    
    boolean success = false;
    if (conn.getResponseCode()==HttpUtil.HTTP_SC_OK) {
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String queryString = in.readLine();
      // read the lease id and the lease length
      HashMap map = QueryString.parse(queryString);
      String peerId = (String) map.get(HttpUtil.PARAM_PEER_ID);
      String leaseId = (String) map.get(HttpUtil.PARAM_LEASE_ID);
      String mode = (String) map.get(HttpUtil.PARAM_MODE);
      Integer leaseLength = extractInteger(map, HttpUtil.PARAM_LEASE_LENGTH);
      if (peerId!=null && leaseId!=null && leaseLength!=null) {
        // the default mode is to block, but the server can tell us
        // that blocking is not permitted, at which time we'll use
        // polling mode
        if (mode!=null && mode.equals("poll")) {
          requestMode = MODE_POLL;
        } else {
          requestMode = MODE_BLOCK;
        }
        
        recordLease(peerId, leaseId, leaseLength.intValue());
        
        if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("Successfully renewed lease");
        success = true;
      } else {
        if (LOG.isEnabledFor(Priority.INFO)) LOG.info("Could not renew lease; relay server did not return "
        + "proper information");
      }
    } else {
	if (LOG.isEnabledFor(Priority.INFO)) LOG.info("Could not renew lease; Invalid HTTP response code "+ conn.getResponseCode() +
      " (" + conn.getResponseMessage() + ") from relay server: "+url);
    }
    
    return success;
  }
  
  /**
   * When a lease is obtained or renewed, we set up appropriate mode.
   * this can be called any number of times to update the situation.
   * It is called both after obtaining and after renewing a lease.
   */
  public void onLeaseObtained() {
    if (requestMode==MODE_BLOCK) {
      
      if (blockingReceiver == null) { // we weren't blocking so far
        
        if (pollingTask != null) { // stop the polling mode
          if (LOG.isEnabledFor(Priority.DEBUG)) LOG.debug("stopping polling task");
          pollingTask.cancel();
          pollingTask = null;

⌨️ 快捷键说明

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