1 4 package com.tc.management.remote.protocol.terracotta; 5 6 import java.io.IOException ; 7 import java.util.LinkedList ; 8 import java.util.Map ; 9 10 import javax.management.remote.generic.MessageConnection; 11 import javax.management.remote.message.Message; 12 13 import com.tc.net.protocol.tcm.MessageChannel; 14 import com.tc.net.protocol.tcm.TCMessageType; 15 16 public final class TunnelingMessageConnection implements MessageConnection { 17 18 private final LinkedList inbox; 19 private final MessageChannel channel; 20 private boolean connected; 21 private final boolean isJmxConnectionServer; 22 23 27 public TunnelingMessageConnection(final MessageChannel channel, boolean isJmxConnectionServer) { 28 this.isJmxConnectionServer = isJmxConnectionServer; 29 this.inbox = new LinkedList (); 30 this.channel = channel; 31 connected = false; 32 } 33 34 public synchronized void close() throws IOException { 35 checkConnected(); 36 connected = false; 37 synchronized (inbox) { 38 inbox.clear(); 39 inbox.notifyAll(); 40 } 41 } 42 43 public synchronized void connect(final Map environment) throws IOException { 44 if (connected) { throw new IOException ("Connection is already open"); } 45 if (!isJmxConnectionServer) { 46 JmxRemoteTunnelMessage connectMessage = (JmxRemoteTunnelMessage) channel 47 .createMessage(TCMessageType.JMXREMOTE_MESSAGE_CONNECTION_MESSAGE); 48 connectMessage.setInitConnection(); 49 connectMessage.send(); 50 } 51 connected = true; 52 } 53 54 public String getConnectionId() { 55 return channel.getRemoteAddress().getStringForm(); 56 } 57 58 public Message readMessage() throws IOException , ClassNotFoundException { 59 Message inboundMessage = null; 60 while (inboundMessage == null) { 61 checkConnected(); 62 synchronized (inbox) { 63 if (inbox.isEmpty()) { 64 try { 65 inbox.wait(); 66 } catch (InterruptedException ie) { 67 throw new IOException ("Interrupted while waiting for inbound message"); 68 } 69 } else { 70 inboundMessage = (Message) inbox.removeFirst(); 71 inbox.notifyAll(); 72 } 73 } 74 } 75 return inboundMessage; 76 } 77 78 public void writeMessage(final Message outboundMessage) throws IOException { 79 JmxRemoteTunnelMessage messageEnvelope = (JmxRemoteTunnelMessage) channel 80 .createMessage(TCMessageType.JMXREMOTE_MESSAGE_CONNECTION_MESSAGE); 81 messageEnvelope.setTunneledMessage(outboundMessage); 82 messageEnvelope.send(); 83 } 84 85 88 void incomingNetworkMessage(final Message inboundMessage) { 89 synchronized (this) { 90 if (!connected) return; 91 } 92 synchronized (inbox) { 93 inbox.addLast(inboundMessage); 94 inbox.notifyAll(); 95 } 96 } 97 98 private synchronized void checkConnected() throws IOException { 99 if (!connected) { throw new IOException ("Connection has been closed"); } 100 } 101 102 } 103 | Popular Tags |