📄 relayserver.java
字号:
/* * * $Id: RelayServer.java,v 1.58 2006/06/07 17:48:49 hamada 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.relay;import java.io.File;import java.io.IOException;import java.net.URI;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Enumeration;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.NoSuchElementException;import java.util.Random;import net.jxta.discovery.DiscoveryService;import net.jxta.document.Advertisement;import net.jxta.document.AdvertisementFactory;import net.jxta.document.MimeMediaType;import net.jxta.document.XMLDocument;import net.jxta.document.XMLElement;import net.jxta.endpoint.EndpointAddress;import net.jxta.endpoint.EndpointService;import net.jxta.endpoint.Message;import net.jxta.endpoint.MessageElement;import net.jxta.endpoint.MessageSender;import net.jxta.endpoint.Messenger;import net.jxta.endpoint.MessengerEvent;import net.jxta.endpoint.MessengerEventListener;import net.jxta.endpoint.TextDocumentMessageElement;import net.jxta.id.ID;import net.jxta.id.IDFactory;import net.jxta.impl.access.AccessList;import net.jxta.impl.protocol.RelayConfigAdv;import net.jxta.impl.util.TimeUtils;import net.jxta.peer.PeerID;import net.jxta.peergroup.PeerGroup;import net.jxta.peergroup.PeerGroupID;import net.jxta.pipe.InputPipe;import net.jxta.pipe.OutputPipe;import net.jxta.pipe.PipeMsgEvent;import net.jxta.pipe.PipeMsgListener;import net.jxta.pipe.PipeService;import net.jxta.protocol.PeerAdvertisement;import net.jxta.protocol.PipeAdvertisement;import net.jxta.protocol.RdvAdvertisement;import net.jxta.protocol.RouteAdvertisement;import org.apache.log4j.Level;import org.apache.log4j.Logger;/** * Relay server that maintains outgoing message queues, leases, etc. */public class RelayServer implements MessageSender, MessengerEventListener, Runnable { /** * log4j Logger **/ private static final Logger LOG = Logger.getLogger(RelayServer.class.getName()); private static final int MAX_CACHED_SERVERS = 20; /** * The EndpointService for the RelayService **/ private final EndpointService endpointService; /** * The DiscoveryService for the RelayService **/ private DiscoveryService discoveryService; /** * The public address is of the form relay://peerId **/ private final EndpointAddress publicAddress; /** * Map of the current clients * * <ul> * <li>Keys are {@link java.lang.String} of the uniqueValue portion of their ID.</li> * <li>Values are {@link net.jxta.impl.endpoint.relay.RelayServerClient}.</li> * </ul> **/ private final HashMap relayedClients = new HashMap(); protected final PeerGroup group; protected final String serviceName; private final int maxClients; private final long maxLeaseDuration; private final long stallTimeout; private final int clientQueueSize; private final long minBroadcastInterval; protected final String peerId; protected final AccessList acl; protected File aclFile; protected long refreshTime =0; protected long aclFileLastModified = 0; private static final long ACL_REFRESH_PERIOD = 30 * TimeUtils.AMINUTE; protected final RelayServerCache relayServerCache; private Thread gcThread = null; private MessengerEventListener messengerEventListener = null; /** * constructor **/ public RelayServer(PeerGroup group, String serviceName, RelayConfigAdv relayConfigAdv) { this.group = group; endpointService = group.getEndpointService(); peerId = group.getPeerID().getUniqueValue().toString(); publicAddress = new EndpointAddress(RelayTransport.protocolName, peerId, null, null); this.serviceName = serviceName; this.maxClients = (-1 != relayConfigAdv.getMaxClients()) ? relayConfigAdv.getMaxClients() : RelayTransport.DEFAULT_MAX_CLIENTS; this.clientQueueSize = (-1 != relayConfigAdv.getClientMessageQueueSize()) ? relayConfigAdv.getClientMessageQueueSize() : RelayTransport.DEFAULT_CLIENT_QUEUE_SIZE; this.maxLeaseDuration = (-1 != relayConfigAdv.getServerLeaseDuration()) ? relayConfigAdv.getServerLeaseDuration() : RelayTransport.DEFAULT_LEASE; this.minBroadcastInterval = (-1 != relayConfigAdv.getAnnounceInterval()) ? relayConfigAdv.getAnnounceInterval() : RelayTransport.DEFAULT_BROADCAST_INTERVAL; this.stallTimeout = (-1 != relayConfigAdv.getStallTimeout()) ? relayConfigAdv.getStallTimeout() : RelayTransport.DEFAULT_STALL_TIMEOUT; aclFile = new File( new File(group.getStoreHome()), "relayACL.xml"); aclFileLastModified = aclFile.lastModified(); this.acl = new AccessList(); try { acl.init(aclFile); this.refreshTime = System.currentTimeMillis() + ACL_REFRESH_PERIOD; } catch (IOException io) { acl.setGrantAll(true); this.refreshTime = Long.MAX_VALUE; if (LOG.isEnabledFor(Level.INFO)) { LOG.info("RelayServer Access Control granting all permissions");; } } relayServerCache = new RelayServerCache(this); if (LOG.isEnabledFor(Level.INFO)) { StringBuffer configInfo = new StringBuffer("Configuring Relay Server"); configInfo.append("\n\tGroup Params :"); configInfo.append("\n\t\tGroup : " + group.getPeerGroupName()); configInfo.append("\n\t\tGroup ID : " + group.getPeerGroupID()); configInfo.append("\n\t\tPeer ID : " + group.getPeerID()); configInfo.append("\n\tConfiguration :"); configInfo.append("\n\t\tService Name : " + serviceName); configInfo.append("\n\t\tMax Relay Clients : " + maxClients); configInfo.append("\n\t\tMax Lease Length : " + maxLeaseDuration + "ms."); configInfo.append("\n\t\tBroadcast Interval : " + minBroadcastInterval + "ms."); configInfo.append("\n\t\tStall Timeout : " + stallTimeout + "ms."); LOG.info(configInfo); } } /** * Debug routine: returns the list of relayedClients with details. */ public List getRelayedClients() { List res = new ArrayList(); Iterator entries = Arrays.asList(relayedClients.values().toArray()).iterator(); while (entries.hasNext()) { String client = entries.next().toString(); res.add(client); } return res; } public boolean startServer() { if (LOG.isEnabledFor(Level.INFO)) { LOG.info("Starting " + publicAddress.toString()); } discoveryService = group.getDiscoveryService(); if ((messengerEventListener = endpointService.addMessageTransport(this)) == null) { if (LOG.isEnabledFor(Level.ERROR)) { LOG.error("Transport registration refused"); } return false; } try { discoveryService.publish(createRdvAdvertisement(group.getPeerAdvertisement(), serviceName)); } catch (IOException e) { if (LOG.isEnabledFor(Level.WARN)) { LOG.warn("Could not publish Relay RdvAdvertisement", e); } } // start cache relay servers relayServerCache.startCache(); endpointService.addMessengerEventListener(this, EndpointService.HighPrecedence); if (LOG.isEnabledFor(Level.INFO)) { LOG.info("Relay Server started"); } return true; } public void stopServer() { if (LOG.isEnabledFor(Level.INFO)) { LOG.info("Stopping " + publicAddress); } // stop cache relay servers relayServerCache.stopCache(); // remove messenger events listener since we do not have any clients endpointService.removeMessengerEventListener(this, EndpointService.HighPrecedence); if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug("Messenger Event Listener removed " + serviceName); } // Close all clients. // Get a list of the clients but leave them in the map; // they remove themselves by calling removeClient(this). // That's why we do not iterate through the real map to close them. RelayServerClient[] oldClients; synchronized (relayedClients) { oldClients = (RelayServerClient[]) relayedClients.values().toArray(new RelayServerClient[0]); } int i = oldClients.length; while (i-- > 0) { oldClients[i].closeClient(); } } /* * Methods inherited from MessageSender */ /**
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -