Coverage Report - com.sun.grizzly.UDPSelectorHandler
 
Classes in this File Line Coverage Branch Coverage Complexity
UDPSelectorHandler
70 %
66/94
60 %
18/30
0
UDPSelectorHandler$1
100 %
2/2
N/A
0
 
 1  
 /*
 2  
  * 
 3  
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 4  
  * 
 5  
  * Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
 6  
  * 
 7  
  * The contents of this file are subject to the terms of either the GNU
 8  
  * General Public License Version 2 only ("GPL") or the Common Development
 9  
  * and Distribution License("CDDL") (collectively, the "License").  You
 10  
  * may not use this file except in compliance with the License. You can obtain
 11  
  * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 12  
  * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 13  
  * language governing permissions and limitations under the License.
 14  
  * 
 15  
  * When distributing the software, include this License Header Notice in each
 16  
  * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 17  
  * Sun designates this particular file as subject to the "Classpath" exception
 18  
  * as provided by Sun in the GPL Version 2 section of the License file that
 19  
  * accompanied this code.  If applicable, add the following below the License
 20  
  * Header, with the fields enclosed by brackets [] replaced by your own
 21  
  * identifying information: "Portions Copyrighted [year]
 22  
  * [name of copyright owner]"
 23  
  * 
 24  
  * Contributor(s):
 25  
  * 
 26  
  * If you wish your version of this file to be governed by only the CDDL or
 27  
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
 28  
  * elects to include this software in this distribution under the [CDDL or GPL
 29  
  * Version 2] license."  If you don't indicate a single choice of license, a
 30  
  * recipient has the option to distribute your version of this file under
 31  
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
 32  
  * its licensees as provided above.  However, if you add GPL Version 2 code
 33  
  * and therefore, elected the GPL Version 2 license, then the option applies
 34  
  * only if the new code is made subject to such option by the copyright
 35  
  * holder.
 36  
  *
 37  
  */
 38  
 
 39  
 package com.sun.grizzly;
 40  
 
 41  
 import com.sun.grizzly.async.UDPAsyncQueueReader;
 42  
 import com.sun.grizzly.async.UDPAsyncQueueWriter;
 43  
 import com.sun.grizzly.util.CallbackHandlerSelectionKeyAttachment;
 44  
 import com.sun.grizzly.util.Copyable;
 45  
 import com.sun.grizzly.util.SelectionKeyOP;
 46  
 import com.sun.grizzly.util.State;
 47  
 import java.io.IOException;
 48  
 import java.net.BindException;
 49  
 import java.net.DatagramSocket;
 50  
 import java.net.InetSocketAddress;
 51  
 import java.net.SocketAddress;
 52  
 import java.net.SocketException;
 53  
 import java.nio.channels.DatagramChannel;
 54  
 import java.nio.channels.SelectableChannel;
 55  
 import java.nio.channels.SelectionKey;
 56  
 import java.nio.channels.Selector;
 57  
 import java.util.concurrent.Callable;
 58  
 import java.util.logging.Level;
 59  
 
 60  
 /**
 61  
  * A SelectorHandler handles all java.nio.channels.Selector operations. 
 62  
  * One or more instance of a Selector are handled by SelectorHandler. 
 63  
  * The logic for processing of SelectionKey interest (OP_ACCEPT,OP_READ, etc.)
 64  
  * is usually defined using an instance of SelectorHandler.
 65  
  *
 66  
  * This class represent a UDP implementation of a SelectorHandler. 
 67  
  * This class first bind a datagramSocketChannel to a UDP port and then start 
 68  
  * waiting for NIO events. 
 69  
  *
 70  
  * @author Jeanfrancois Arcand
 71  
  */
 72  
 public class UDPSelectorHandler extends TCPSelectorHandler {
 73  
  
 74  
     private final static String NOT_SUPPORTED = 
 75  
             "Not supported by this SelectorHandler";
 76  
    
 77  
     /**
 78  
      * The datagramSocket instance.
 79  
      */
 80  
     protected DatagramSocket datagramSocket;
 81  
     
 82  
     
 83  
     /**
 84  
      * The DatagramChannel.
 85  
      */
 86  
     protected DatagramChannel datagramChannel;    
 87  
  
 88  
  
 89  6
     public UDPSelectorHandler() {
 90  6
     }
 91  
     
 92  
     
 93  
     public UDPSelectorHandler(boolean isClient) {
 94  0
         super(isClient);
 95  0
     }
 96  
 
 97  
     
 98  
     @Override
 99  
     public void copyTo(Copyable copy) {
 100  0
         super.copyTo(copy);
 101  0
         UDPSelectorHandler copyHandler = (UDPSelectorHandler) copy;
 102  0
         copyHandler.datagramSocket = datagramSocket;
 103  0
         copyHandler.datagramChannel= datagramChannel;
 104  0
     }
 105  
 
 106  
     /**
 107  
      * Before invoking Selector.select(), make sure the ServerScoketChannel
 108  
      * has been created. If true, then register all SelectionKey to the Selector.
 109  
      */
 110  
     @Override
 111  
     public void preSelect(Context ctx) throws IOException {
 112  52396
         initOpRegistriesIfRequired();
 113  
 
 114  52396
         if (asyncQueueReader == null) {
 115  6
             asyncQueueReader = new UDPAsyncQueueReader(this);
 116  
         }
 117  
 
 118  52396
         if (asyncQueueWriter == null) {
 119  6
             asyncQueueWriter = new UDPAsyncQueueWriter(this);
 120  
         }
 121  
         
 122  52396
         if (selector == null){
 123  
             try{
 124  6
                 isShutDown.set(false);
 125  
 
 126  6
                 connectorInstanceHandler = new ConnectorInstanceHandler.
 127  
                         ConcurrentQueueDelegateCIH(
 128  
                         getConnectorInstanceHandlerDelegate());
 129  
                                
 130  6
                 datagramChannel = DatagramChannel.open();
 131  6
                 selector = Selector.open();
 132  6
                 if (!isClient){                  
 133  6
                     datagramSocket = datagramChannel.socket();
 134  6
                     datagramSocket.setReuseAddress(reuseAddress);
 135  6
                     if (inet == null)
 136  6
                         datagramSocket.bind(new InetSocketAddress(port));
 137  
                     else
 138  0
                         datagramSocket.bind(new InetSocketAddress(inet,port));
 139  
 
 140  6
                     datagramChannel.configureBlocking(false);
 141  6
                     datagramChannel.register( selector, SelectionKey.OP_READ );
 142  
                                             
 143  6
                     datagramSocket.setSoTimeout(serverTimeout); 
 144  
                 } 
 145  6
                 ctx.getController().notifyReady();
 146  0
             } catch (SocketException ex){
 147  0
                 throw new BindException(ex.getMessage() + ": " + port);
 148  6
             }
 149  
    
 150  
         } else {
 151  52390
             processPendingOperations(ctx);
 152  
         }
 153  52396
     }
 154  
 
 155  
     
 156  
     /**
 157  
      * Handle new OP_CONNECT ops.
 158  
      */
 159  
     @Override
 160  
     protected void onConnectOp(Context ctx, 
 161  
             SelectionKeyOP.ConnectSelectionKeyOP selectionKeyOp) throws IOException {
 162  31
         SocketAddress remoteAddress = selectionKeyOp.getRemoteAddress();
 163  31
         SocketAddress localAddress = selectionKeyOp.getLocalAddress();
 164  31
         CallbackHandler callbackHandler = selectionKeyOp.getCallbackHandler();
 165  
 
 166  31
         final DatagramChannel datagramChannel = DatagramChannel.open();
 167  31
         datagramChannel.socket().setReuseAddress(reuseAddress);
 168  31
         if (localAddress != null) {
 169  0
             datagramChannel.socket().bind(localAddress);
 170  
         }
 171  31
         datagramChannel.configureBlocking(false);
 172  31
         datagramChannel.connect(remoteAddress);
 173  31
         SelectionKey key = datagramChannel.register(selector, 
 174  
                 SelectionKey.OP_READ | SelectionKey.OP_WRITE);
 175  31
         key.attach(CallbackHandlerSelectionKeyAttachment.create(key, callbackHandler));
 176  31
         onConnectInterest(key, ctx);
 177  31
     }
 178  
   
 179  
     
 180  
     /**
 181  
      * Shuntdown this instance by closing its Selector and associated channels.
 182  
      */
 183  
     @Override
 184  
     public void shutdown(){
 185  
         // If shutdown was called for this SelectorHandler
 186  6
         if (isShutDown.getAndSet(true)) return;
 187  
 
 188  6
         stateHolder.setState(State.STOPPED);
 189  
         
 190  
         try {
 191  6
             if ( datagramSocket != null )
 192  6
                 datagramSocket.close();
 193  0
         } catch (Throwable ex){
 194  0
             Controller.logger().log(Level.SEVERE,
 195  
                     "closeSocketException",ex);
 196  6
         }
 197  
 
 198  
         try{
 199  6
             if ( datagramChannel != null)
 200  6
                 datagramChannel.close();
 201  0
         } catch (Throwable ex){
 202  0
             Controller.logger().log(Level.SEVERE,
 203  
                     "closeSocketException",ex);
 204  6
         }
 205  
 
 206  
         try{
 207  6
             if ( selector != null)
 208  6
                 selector.close();
 209  0
         } catch (Throwable ex){
 210  0
             Controller.logger().log(Level.SEVERE,
 211  
                     "closeSocketException",ex);
 212  6
         }
 213  
         
 214  6
         if (asyncQueueReader != null) {
 215  6
             asyncQueueReader.close();
 216  6
             asyncQueueReader = null;
 217  
         }
 218  
 
 219  6
         if (asyncQueueWriter != null) {
 220  6
             asyncQueueWriter.close();
 221  6
             asyncQueueWriter = null;
 222  
         }
 223  6
     }
 224  
     
 225  
     
 226  
     /**
 227  
      * Handle OP_ACCEPT. Not used for UPD.
 228  
      */
 229  
     @Override
 230  
     public boolean onAcceptInterest(SelectionKey key, Context ctx) throws IOException{
 231  0
         return false;
 232  
     }
 233  
     
 234  
     
 235  
     /**
 236  
      * {@inheritDoc}
 237  
      */
 238  
     @Override
 239  
     public Class<? extends SelectionKeyHandler> getPreferredSelectionKeyHandler() {
 240  8
         return BaseSelectionKeyHandler.class;
 241  
     }
 242  
 
 243  
     
 244  
     /**
 245  
      * A token describing the protocol supported by an implementation of this
 246  
      * interface
 247  
      */
 248  
     @Override
 249  
     public Controller.Protocol protocol(){
 250  84119
         return Controller.Protocol.UDP;
 251  
     }   
 252  
     
 253  
     @Override
 254  
     public int getPortLowLevel() {
 255  1
         if (datagramSocket != null) {
 256  1
             return datagramSocket.getLocalPort();
 257  
         }
 258  
         
 259  0
         return -1;
 260  
     }
 261  
     
 262  
     @Override
 263  
     public int getSsBackLog() {
 264  0
         throw new IllegalStateException(NOT_SUPPORTED);
 265  
     }
 266  
 
 267  
     
 268  
     @Override
 269  
     public void setSsBackLog(int ssBackLog) {
 270  0
         throw new IllegalStateException(NOT_SUPPORTED);
 271  
     }
 272  
     
 273  
     
 274  
     @Override
 275  
     public boolean isTcpNoDelay() {
 276  0
         throw new IllegalStateException(NOT_SUPPORTED);
 277  
     }
 278  
 
 279  
     
 280  
     @Override
 281  
     public void setTcpNoDelay(boolean tcpNoDelay) {
 282  0
         throw new IllegalStateException(NOT_SUPPORTED);
 283  
     }
 284  
     
 285  
     
 286  
     @Override
 287  
     public int getLinger() {
 288  0
        throw new IllegalStateException(NOT_SUPPORTED);
 289  
     }
 290  
 
 291  
     
 292  
     @Override
 293  
     public void setLinger(int linger) {
 294  0
         throw new IllegalStateException(NOT_SUPPORTED);
 295  
     }    
 296  
     
 297  
     
 298  
     @Override
 299  
     public int getSocketTimeout() {
 300  0
         throw new IllegalStateException(NOT_SUPPORTED);
 301  
     }
 302  
 
 303  
     
 304  
     @Override
 305  
     public void setSocketTimeout(int socketTimeout) {
 306  0
         throw new IllegalStateException(NOT_SUPPORTED);
 307  
     }    
 308  
 
 309  
     @Override
 310  
     public void closeChannel(SelectableChannel channel) {
 311  
         try{
 312  31
             channel.close();
 313  0
         } catch (IOException ex){
 314  
             ; // LOG ME
 315  31
         }
 316  
         
 317  31
         if (asyncQueueReader != null) {
 318  31
             asyncQueueReader.onClose(channel);
 319  
         }
 320  
 
 321  31
         if (asyncQueueWriter != null) {
 322  31
             asyncQueueWriter.onClose(channel);
 323  
         }
 324  31
     }
 325  
     
 326  
     //--------------- ConnectorInstanceHandler -----------------------------
 327  
     @Override
 328  
     protected Callable<ConnectorHandler> getConnectorInstanceHandlerDelegate() {
 329  6
         return new Callable<ConnectorHandler>() {
 330  
             public ConnectorHandler call() throws Exception {
 331  4
                 return new UDPConnectorHandler();
 332  
             }
 333  
         };
 334  
     }
 335  
 }