📄 relayserver.java
字号:
/* * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. * * The Sun Project JXTA(TM) Software License * * 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 Sun Microsystems, Inc. for JXTA(TM) technology." * 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. * * JXTA is a registered trademark of Sun Microsystems, Inc. in the United * States and other countries. * * Please see the license information page at : * <http://www.jxta.org/project/www/license.html> for instructions on use of * the license in source files. * * ==================================================================== * * 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.HashMap;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.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 java.util.logging.Level;import net.jxta.logging.Logging;import java.util.logging.Logger;import net.jxta.impl.endpoint.EndpointUtils;/** * Relay server that maintains outgoing message queues, leases, etc. */public class RelayServer implements MessageSender, MessengerEventListener, Runnable { /** * Logger */ private final static transient Logger LOG = Logger.getLogger(RelayServer.class.getName()); private final static int MAX_CACHED_SERVERS = 20; /** * The EndpointService for the RelayService */ private 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 */ private final Map<String, RelayServerClient> relayedClients = new HashMap<String, RelayServerClient>(); 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 RelayServerCache relayServerCache; private Thread gcThread = null; private MessengerEventListener messengerEventListener = null; /** * constructor */ public RelayServer(PeerGroup group, String serviceName, RelayConfigAdv relayConfigAdv) { this.group = group; 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 (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("RelayServer Access Control granting all permissions"); } } if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { StringBuilder configInfo = new StringBuilder("Configuring Relay Server"); configInfo.append("\n\tGroup Params :"); configInfo.append("\n\t\tGroup : ").append(group); configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); configInfo.append("\n\tConfiguration :"); configInfo.append("\n\t\tService Name : ").append(serviceName); configInfo.append("\n\t\tMax Relay Clients : ").append(maxClients); configInfo.append("\n\t\tMax Lease Length : ").append(maxLeaseDuration).append("ms."); configInfo.append("\n\t\tBroadcast Interval : ").append(minBroadcastInterval).append("ms."); configInfo.append("\n\t\tStall Timeout : ").append(stallTimeout).append("ms."); LOG.config(configInfo.toString()); } } /** * Debug routine: returns the list of relayedClients with details. */ public List<String> getRelayedClients() { List<String> res = new ArrayList<String>(); for (Object o : Arrays.asList(relayedClients.values().toArray())) { String client = o.toString(); res.add(client); } return res; } public boolean startServer() { if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Starting " + publicAddress.toString()); } endpointService = group.getEndpointService(); discoveryService = group.getDiscoveryService(); if ((messengerEventListener = endpointService.addMessageTransport(this)) == null) { if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { LOG.severe("Transport registration refused"); } return false; } try { discoveryService.publish(createRdvAdvertisement(group.getPeerAdvertisement(), serviceName)); } catch (IOException e) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Could not publish Relay RdvAdvertisement", e); } } relayServerCache = new RelayServerCache(this); // start cache relay servers relayServerCache.startCache(); endpointService.addMessengerEventListener(this, EndpointService.HighPrecedence); if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Relay Server started"); } return true; } public void stopServer() { // stop cache relay servers relayServerCache.stopCache(); relayServerCache = null; // remove messenger events listener since we do not have any clients endpointService.removeMessengerEventListener(this, EndpointService.HighPrecedence); if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("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 = relayedClients.values().toArray(new RelayServerClient[0]); } int i = oldClients.length; while (i-- > 0) { oldClients[i].closeClient(); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -