List of usage examples for java.nio.channels SelectionKey interestOps
public abstract SelectionKey interestOps(int ops);
From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java
final void dispatchEvent(final Set<SelectionKey> selectedKeySet) { final Iterator<SelectionKey> it = selectedKeySet.iterator(); boolean skipOpRead = false; // ? while (it.hasNext()) { final SelectionKey key = it.next(); it.remove();/*from w w w.j av a 2 s .c o m*/ if (!key.isValid()) { if (key.attachment() != null) { this.controller.closeSelectionKey(key); } else { key.cancel(); } continue; } try { if (key.isAcceptable()) { this.controller.onAccept(key); continue; } if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove write interest key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); this.controller.onWrite(key); if (!this.controller.isHandleReadWriteConcurrently()) { skipOpRead = true; } } if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // read key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); // ??? if (!this.controller.getStatistics().isReceiveOverFlow()) { // Remove read interest this.controller.onRead(key);// ? continue; } else { key.interestOps(key.interestOps() // | SelectionKey.OP_READ); } } if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) { this.controller.onConnect(key); continue; } } catch (final RejectedExecutionException e) { // ??? if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.notifyException(e); if (this.selector.isOpen()) { continue; } else { break; } } catch (final CancelledKeyException e) { // ignore } catch (final Exception e) { if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.closeSelectionKey(key); this.controller.notifyException(e); log.error("Reactor dispatch events error", e); if (this.selector.isOpen()) { continue; } else { break; } } } }
From source file:com.taobao.gecko.core.nio.impl.Reactor.java
final void dispatchEvent(final Set<SelectionKey> selectedKeySet) { final Iterator<SelectionKey> it = selectedKeySet.iterator(); boolean skipOpRead = false; // while (it.hasNext()) { final SelectionKey key = it.next(); it.remove();//w w w . j a va2s . co m if (!key.isValid()) { if (key.attachment() != null) { this.controller.closeSelectionKey(key); } else { key.cancel(); } continue; } try { if (key.isAcceptable()) { this.controller.onAccept(key); continue; } if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove write interest key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); this.controller.onWrite(key); if (!this.controller.isHandleReadWriteConcurrently()) { skipOpRead = true; } } if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // read key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); // if (!this.controller.getStatistics().isReceiveOverFlow()) { // Remove read interest this.controller.onRead(key);// continue; } else { key.interestOps(key.interestOps() // | SelectionKey.OP_READ); } } if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) { this.controller.onConnect(key); continue; } } catch (final RejectedExecutionException e) { // if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.notifyException(e); if (this.selector.isOpen()) { continue; } else { break; } } catch (final CancelledKeyException e) { // ignore } catch (final Exception e) { if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.closeSelectionKey(key); this.controller.notifyException(e); log.error("Reactor dispatch events error", e); if (this.selector.isOpen()) { continue; } else { break; } } } }
From source file:com.app.services.ExecutorServiceThread.java
public void run() { // create a selector that will by used for multiplexing. The selector // registers the socketserverchannel as // well as all socketchannels that are created String CLIENTCHANNELNAME = "clientChannel"; String SERVERCHANNELNAME = "serverChannel"; String channelType = "channelType"; ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>(); ClassLoader classLoader = null; ByteArrayOutputStream bstr;/*from w w w .j ava2s . c om*/ ByteBuffer buffer = null; ByteBuffer lengthBuffer = ByteBuffer.allocate(4); int bytesRead; InputStream bais; ObjectInputStream ois; Object object; ExecutorServiceInfo executorServiceInfo = null; Random random = new Random(System.currentTimeMillis()); // register the serversocketchannel with the selector. The OP_ACCEPT // option marks // a selection key as ready when the channel accepts a new connection. // When the // socket server accepts a connection this key is added to the list of // selected keys of the selector. // when asked for the selected keys, this key is returned and hence we // know that a new connection has been accepted. try { Selector selector = Selector.open(); SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // SelectionKey socketServerSelectionKey1 = // channel.register(selector1, // SelectionKey.OP_ACCEPT); // set property in the key that identifies the channel Map<String, String> properties = new ConcurrentHashMap<String, String>(); properties.put(channelType, SERVERCHANNELNAME); socketServerSelectionKey.attach(properties); // wait for the selected keys SelectionKey key = null; Set<SelectionKey> selectedKeys; // logger.info("Instance Number"+instanceNumber); Iterator<SelectionKey> iterator = null; SocketChannel clientChannel = null; while (true) { try { // the select method is a blocking method which returns when // atleast // one of the registered // channel is selected. In this example, when the socket // accepts // a // new connection, this method // will return. Once a socketclient is added to the list of // registered channels, then this method // would also return when one of the clients has data to be // read // or // written. It is also possible to perform a nonblocking // select // using the selectNow() function. // We can also specify the maximum time for which a select // function // can be blocked using the select(long timeout) function. if (selector.select() >= 0) { selectedKeys = selector.selectedKeys(); iterator = selectedKeys.iterator(); } while (iterator.hasNext()) { try { key = iterator.next(); // the selection key could either by the // socketserver // informing // that a new connection has been made, or // a socket client that is ready for read/write // we use the properties object attached to the // channel // to // find // out the type of channel. if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) { // a new connection has been obtained. This // channel // is // therefore a socket server. ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); // accept the new connection on the server // socket. // Since // the // server socket channel is marked as non // blocking // this channel will return null if no client is // connected. SocketChannel clientSocketChannel = serverSocketChannel.accept(); if (clientSocketChannel != null) { // set the client connection to be non // blocking clientSocketChannel.configureBlocking(false); SelectionKey clientKey = clientSocketChannel.register(selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE); Map<String, String> clientproperties = new ConcurrentHashMap<String, String>(); clientproperties.put(channelType, CLIENTCHANNELNAME); clientKey.attach(clientproperties); clientKey.interestOps(SelectionKey.OP_READ); // clientSocketChannel.close(); // write something to the new created client /* * CharBuffer buffer = * CharBuffer.wrap("Hello client"); while * (buffer.hasRemaining()) { * clientSocketChannel.write * (Charset.defaultCharset() * .encode(buffer)); } * clientSocketChannel.close(); * buffer.clear(); */ } } else { // data is available for read // buffer for reading clientChannel = (SocketChannel) key.channel(); if (key.isReadable()) { // the channel is non blocking so keep it // open // till // the // count is >=0 clientChannel = (SocketChannel) key.channel(); if (resultMap.get(key) == null) { //log.info(key); bstr = new ByteArrayOutputStream(); object = null; clientChannel.read(lengthBuffer); int length = lengthBuffer.getInt(0); lengthBuffer.clear(); //log.info(length); buffer = ByteBuffer.allocate(length); if ((bytesRead = clientChannel.read(buffer)) > 0) { // buffer.flip(); // System.out // .println(bytesRead); bstr.write(buffer.array(), 0, bytesRead); buffer.clear(); } buffer.clear(); //log.info("Message1"+new String(bstr // .toByteArray())); bais = new ByteArrayInputStream(bstr.toByteArray()); ois = new ObjectInputStream(bais); // Offending // line. // Produces // the // StreamCorruptedException. //log.info("In read obect"); object = ois.readObject(); //log.info("Class Cast"); //log.info("Class Cast1"); ois.close(); byte[] params = bstr.toByteArray(); bstr.close(); //log.info("readObject"); //log.info("After readObject"); if (object instanceof CloseSocket) { resultMap.remove(key); clientChannel.close(); key.cancel(); } // clientChannel.close(); String serviceurl = (String) object; String[] serviceRegistry = serviceurl.split("/"); //log.info("classLoaderMap" // + urlClassLoaderMap); //log.info(deployDirectory // + "/" + serviceRegistry[0]); int servicenameIndex; //log.info(earServicesDirectory // + "/" + serviceRegistry[0] // + "/" + serviceRegistry[1]); if (serviceRegistry[0].endsWith(".ear")) { classLoader = (VFSClassLoader) urlClassLoaderMap.get(deployDirectory + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]); servicenameIndex = 2; } else if (serviceRegistry[0].endsWith(".jar")) { classLoader = (WebClassLoader) urlClassLoaderMap .get(deployDirectory + "/" + serviceRegistry[0]); servicenameIndex = 1; } else { classLoader = (WebClassLoader) urlClassLoaderMap .get(deployDirectory + "/" + serviceRegistry[0]); servicenameIndex = 1; } String serviceName = serviceRegistry[servicenameIndex]; // log.info("servicename:"+serviceName);; synchronized (executorServiceMap) { executorServiceInfo = (ExecutorServiceInfo) executorServiceMap .get(serviceName.trim()); } ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader(); classLoaderExecutorServiceInfo.setClassLoader(classLoader); classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo); resultMap.put(key, classLoaderExecutorServiceInfo); // key.interestOps(SelectionKey.OP_READ); // log.info("Key interested Ops"); // continue; } //Thread.sleep(100); /* * if (classLoader == null) throw new * Exception( * "Could able to obtain deployed class loader" * ); */ /* * log.info( * "current context classloader" + * classLoader); */ //log.info("In rad object"); bstr = new ByteArrayOutputStream(); lengthBuffer.clear(); int numberofDataRead = clientChannel.read(lengthBuffer); //log.info("numberofDataRead" // + numberofDataRead); int length = lengthBuffer.getInt(0); if (length <= 0) { iterator.remove(); continue; } lengthBuffer.clear(); //log.info(length); buffer = ByteBuffer.allocate(length); buffer.clear(); if ((bytesRead = clientChannel.read(buffer)) > 0) { // buffer.flip(); // System.out // .println(bytesRead); bstr.write(buffer.array(), 0, bytesRead); buffer.clear(); } if (bytesRead <= 0 || bytesRead < length) { //log.info("bytesRead<length"); iterator.remove(); continue; } //log.info(new String(bstr // .toByteArray())); bais = new ByteArrayInputStream(bstr.toByteArray()); ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap .get(key); ois = new ClassLoaderObjectInputStream( (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending // line. // Produces // the // StreamCorruptedException. object = ois.readObject(); ois.close(); bstr.close(); executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo(); //System.out // .println("inputStream Read Object"); //log.info("Object=" // + object.getClass()); // Thread.currentThread().setContextClassLoader(currentContextLoader); if (object instanceof ExecutorParams) { ExecutorParams exeParams = (ExecutorParams) object; Object returnValue = null; //log.info("test socket1"); String ataKey; ATAConfig ataConfig; ConcurrentHashMap ataServicesMap; Enumeration<NodeResourceInfo> noderesourceInfos = addressmap.elements(); NodeResourceInfo noderesourceinfo = null; String ip = ""; int port = 1000; long memavailable = 0; long memcurr = 0; if (noderesourceInfos.hasMoreElements()) { noderesourceinfo = noderesourceInfos.nextElement(); if (noderesourceinfo.getMax() != null) { ip = noderesourceinfo.getHost(); port = Integer.parseInt(noderesourceinfo.getPort()); memavailable = Long.parseLong(noderesourceinfo.getMax()) - Long.parseLong(noderesourceinfo.getUsed()); ; } } while (noderesourceInfos.hasMoreElements()) { noderesourceinfo = noderesourceInfos.nextElement(); if (noderesourceinfo.getMax() != null) { memcurr = Long.parseLong(noderesourceinfo.getMax()) - Long.parseLong(noderesourceinfo.getUsed()); if (memavailable <= memcurr) { ip = noderesourceinfo.getHost(); port = Integer.parseInt(noderesourceinfo.getPort()); memavailable = memcurr; } } } ATAExecutorServiceInfo servicesAvailable; Socket sock1 = new Socket(ip, port); OutputStream outputStr = sock1.getOutputStream(); ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr); NodeInfo nodeInfo = new NodeInfo(); nodeInfo.setClassNameWithPackage( executorServiceInfo.getExecutorServicesClass().getName()); nodeInfo.setMethodName(executorServiceInfo.getMethod().getName()); nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS()); NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam(); nodeInfoMethodParam.setMethodParams(exeParams.getParams()); nodeInfoMethodParam .setMethodParamTypes(executorServiceInfo.getMethodParams()); //log.info("Serializable socket="+sock); //nodeInfo.setSock(sock); //nodeInfo.setOstream(sock.getOutputStream()); objOutputStream.writeObject(nodeInfo); objOutputStream = new ObjectOutputStream(outputStr); objOutputStream.writeObject(nodeInfoMethodParam); ObjectInputStream objInputStream1 = new ObjectInputStream( sock1.getInputStream()); returnValue = objInputStream1.readObject(); objOutputStream.close(); objInputStream1.close(); sock1.close(); /*returnValue = executorServiceInfo .getMethod() .invoke(executorServiceInfo .getExecutorServicesClass() .newInstance(), exeParams.getParams());*/ // Thread.currentThread().setContextClassLoader(oldCL); // log.info("Written Value=" // + returnValue.toString()); resultMap.put(key, returnValue); } key.interestOps(SelectionKey.OP_WRITE); //log.info("Key interested Ops1"); } else if (key.isWritable()) { // the channel is non blocking so keep it // open // till the // count is >=0 //log.info("In write"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make // a // BAOS // stream ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the // stream Object result = resultMap.get(key); oos.writeObject(result); // write an object // to // the stream oos.flush(); oos.close(); byte[] objData = baos.toByteArray(); // get // the // byte // array baos.close(); buffer = ByteBuffer.wrap(objData); // wrap // around // the // data buffer.rewind(); // buffer.flip(); //prep for writing //log.info(new String(objData)); //while (buffer.hasRemaining()) clientChannel.write(buffer); // write resultMap.remove(key); buffer.clear(); key.cancel(); clientChannel.close(); //log.info("In write1"); numberOfServicesRequests++; //log.info("Key interested Ops2"); } } iterator.remove(); } catch (Exception ex) { log.error("Error in executing the executor services thread", ex); //ex.printStackTrace(); key.cancel(); clientChannel.close(); resultMap.remove(key); //ex.printStackTrace(); } } } catch (Exception ex) { log.error("Error in executing the executor services thread", ex); //ex.printStackTrace(); } } } catch (Exception ex) { log.error("Error in executing the executor services thread", ex); } }
From source file:com.web.services.ExecutorServiceThread.java
public void run() { // create a selector that will by used for multiplexing. The selector // registers the socketserverchannel as // well as all socketchannels that are created String CLIENTCHANNELNAME = "clientChannel"; String SERVERCHANNELNAME = "serverChannel"; String channelType = "channelType"; ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>(); ClassLoader classLoader = null; ByteArrayOutputStream bstr;//from ww w .ja v a2 s.c o m ByteBuffer buffer = null; ByteBuffer lengthBuffer = ByteBuffer.allocate(4); int bytesRead; InputStream bais; ObjectInputStream ois; Object object; ExecutorServiceInfo executorServiceInfo = null; Random random = new Random(System.currentTimeMillis()); // register the serversocketchannel with the selector. The OP_ACCEPT // option marks // a selection key as ready when the channel accepts a new connection. // When the // socket server accepts a connection this key is added to the list of // selected keys of the selector. // when asked for the selected keys, this key is returned and hence we // know that a new connection has been accepted. try { Selector selector = Selector.open(); SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // SelectionKey socketServerSelectionKey1 = // channel.register(selector1, // SelectionKey.OP_ACCEPT); // set property in the key that identifies the channel Map<String, String> properties = new ConcurrentHashMap<String, String>(); properties.put(channelType, SERVERCHANNELNAME); socketServerSelectionKey.attach(properties); // wait for the selected keys SelectionKey key = null; Set<SelectionKey> selectedKeys; // logger.info("Instance Number"+instanceNumber); Iterator<SelectionKey> iterator = null; SocketChannel clientChannel = null; while (true) { try { // the select method is a blocking method which returns when // atleast // one of the registered // channel is selected. In this example, when the socket // accepts // a // new connection, this method // will return. Once a socketclient is added to the list of // registered channels, then this method // would also return when one of the clients has data to be // read // or // written. It is also possible to perform a nonblocking // select // using the selectNow() function. // We can also specify the maximum time for which a select // function // can be blocked using the select(long timeout) function. if (selector.select() >= 0) { selectedKeys = selector.selectedKeys(); iterator = selectedKeys.iterator(); } while (iterator.hasNext()) { try { key = iterator.next(); // the selection key could either by the // socketserver // informing // that a new connection has been made, or // a socket client that is ready for read/write // we use the properties object attached to the // channel // to // find // out the type of channel. if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) { // a new connection has been obtained. This // channel // is // therefore a socket server. ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); // accept the new connection on the server // socket. // Since // the // server socket channel is marked as non // blocking // this channel will return null if no client is // connected. SocketChannel clientSocketChannel = serverSocketChannel.accept(); if (clientSocketChannel != null) { // set the client connection to be non // blocking clientSocketChannel.configureBlocking(false); SelectionKey clientKey = clientSocketChannel.register(selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE); Map<String, String> clientproperties = new ConcurrentHashMap<String, String>(); clientproperties.put(channelType, CLIENTCHANNELNAME); clientKey.attach(clientproperties); clientKey.interestOps(SelectionKey.OP_READ); // clientSocketChannel.close(); // write something to the new created client /* * CharBuffer buffer = * CharBuffer.wrap("Hello client"); while * (buffer.hasRemaining()) { * clientSocketChannel.write * (Charset.defaultCharset() * .encode(buffer)); } * clientSocketChannel.close(); * buffer.clear(); */ } } else { // data is available for read // buffer for reading clientChannel = (SocketChannel) key.channel(); if (key.isReadable()) { // the channel is non blocking so keep it // open // till // the // count is >=0 clientChannel = (SocketChannel) key.channel(); if (resultMap.get(key) == null) { //System.out.println(key); bstr = new ByteArrayOutputStream(); object = null; clientChannel.read(lengthBuffer); int length = lengthBuffer.getInt(0); lengthBuffer.clear(); //System.out.println(length); buffer = ByteBuffer.allocate(length); if ((bytesRead = clientChannel.read(buffer)) > 0) { // buffer.flip(); // System.out // .println(bytesRead); bstr.write(buffer.array(), 0, bytesRead); buffer.clear(); } buffer.clear(); //System.out.println("Message1"+new String(bstr // .toByteArray())); bais = new ByteArrayInputStream(bstr.toByteArray()); ois = new ObjectInputStream(bais); // Offending // line. // Produces // the // StreamCorruptedException. //System.out.println("In read obect"); object = ois.readObject(); //System.out.println("Class Cast"); //System.out.println("Class Cast1"); ois.close(); byte[] params = bstr.toByteArray(); bstr.close(); //System.out.println("readObject"); //System.out.println("After readObject"); if (object instanceof CloseSocket) { resultMap.remove(key); clientChannel.close(); key.cancel(); } // clientChannel.close(); String serviceurl = (String) object; String[] serviceRegistry = serviceurl.split("/"); //System.out.println("classLoaderMap" // + urlClassLoaderMap); //System.out.println(deployDirectory // + "/" + serviceRegistry[0]); int servicenameIndex; //System.out.println(earServicesDirectory // + "/" + serviceRegistry[0] // + "/" + serviceRegistry[1]); if (serviceRegistry[0].endsWith(".ear")) { classLoader = (VFSClassLoader) urlClassLoaderMap .get(earServicesDirectory + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]); servicenameIndex = 2; } else if (serviceRegistry[0].endsWith(".jar")) { classLoader = (WebClassLoader) urlClassLoaderMap .get(jarservicesDirectory + "/" + serviceRegistry[0]); servicenameIndex = 1; } else { classLoader = (WebClassLoader) urlClassLoaderMap .get(deployDirectory + "/" + serviceRegistry[0]); servicenameIndex = 1; } String serviceName = serviceRegistry[servicenameIndex]; // System.out.println("servicename:"+serviceName);; synchronized (executorServiceMap) { executorServiceInfo = (ExecutorServiceInfo) executorServiceMap .get(serviceName.trim()); } ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader(); classLoaderExecutorServiceInfo.setClassLoader(classLoader); classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo); resultMap.put(key, classLoaderExecutorServiceInfo); // key.interestOps(SelectionKey.OP_READ); // System.out.println("Key interested Ops"); // continue; } //Thread.sleep(100); /* * if (classLoader == null) throw new * Exception( * "Could able to obtain deployed class loader" * ); */ /* * System.out.println( * "current context classloader" + * classLoader); */ //System.out.println("In rad object"); bstr = new ByteArrayOutputStream(); lengthBuffer.clear(); int numberofDataRead = clientChannel.read(lengthBuffer); //System.out.println("numberofDataRead" // + numberofDataRead); int length = lengthBuffer.getInt(0); if (length <= 0) { iterator.remove(); continue; } lengthBuffer.clear(); //System.out.println(length); buffer = ByteBuffer.allocate(length); buffer.clear(); if ((bytesRead = clientChannel.read(buffer)) > 0) { // buffer.flip(); // System.out // .println(bytesRead); bstr.write(buffer.array(), 0, bytesRead); buffer.clear(); } if (bytesRead <= 0 || bytesRead < length) { //System.out.println("bytesRead<length"); iterator.remove(); continue; } //System.out.println(new String(bstr // .toByteArray())); bais = new ByteArrayInputStream(bstr.toByteArray()); ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap .get(key); ois = new ClassLoaderObjectInputStream( (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending // line. // Produces // the // StreamCorruptedException. object = ois.readObject(); ois.close(); bstr.close(); executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo(); //System.out // .println("inputStream Read Object"); //System.out.println("Object=" // + object.getClass()); // Thread.currentThread().setContextClassLoader(currentContextLoader); if (object instanceof ExecutorParams) { ExecutorParams exeParams = (ExecutorParams) object; Object returnValue = null; //System.out.println("test socket1"); String ataKey; ATAConfig ataConfig; ConcurrentHashMap ataServicesMap; ATAExecutorServiceInfo servicesAvailable; Socket sock1 = new Socket("0.0.0.0", Integer.parseInt(nodesport[random.nextInt(nodesport.length)])); OutputStream outputStr = sock1.getOutputStream(); ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr); NodeInfo nodeInfo = new NodeInfo(); nodeInfo.setClassNameWithPackage( executorServiceInfo.getExecutorServicesClass().getName()); nodeInfo.setMethodName(executorServiceInfo.getMethod().getName()); nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS()); NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam(); nodeInfoMethodParam.setMethodParams(exeParams.getParams()); nodeInfoMethodParam .setMethodParamTypes(executorServiceInfo.getMethodParams()); //System.out.println("Serializable socket="+sock); //nodeInfo.setSock(sock); //nodeInfo.setOstream(sock.getOutputStream()); objOutputStream.writeObject(nodeInfo); objOutputStream = new ObjectOutputStream(outputStr); objOutputStream.writeObject(nodeInfoMethodParam); ObjectInputStream objInputStream1 = new ObjectInputStream( sock1.getInputStream()); returnValue = objInputStream1.readObject(); objOutputStream.close(); objInputStream1.close(); sock1.close(); /*returnValue = executorServiceInfo .getMethod() .invoke(executorServiceInfo .getExecutorServicesClass() .newInstance(), exeParams.getParams());*/ // Thread.currentThread().setContextClassLoader(oldCL); // System.out.println("Written Value=" // + returnValue.toString()); resultMap.put(key, returnValue); } key.interestOps(SelectionKey.OP_WRITE); //System.out.println("Key interested Ops1"); } else if (key.isWritable()) { // the channel is non blocking so keep it // open // till the // count is >=0 //System.out.println("In write"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make // a // BAOS // stream ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the // stream Object result = resultMap.get(key); oos.writeObject(result); // write an object // to // the stream oos.flush(); oos.close(); byte[] objData = baos.toByteArray(); // get // the // byte // array baos.close(); buffer = ByteBuffer.wrap(objData); // wrap // around // the // data buffer.rewind(); // buffer.flip(); //prep for writing //System.out.println(new String(objData)); //while (buffer.hasRemaining()) clientChannel.write(buffer); // write resultMap.remove(key); buffer.clear(); key.cancel(); clientChannel.close(); //System.out.println("In write1"); numberOfServicesRequests++; //System.out.println("Key interested Ops2"); } } iterator.remove(); } catch (Exception ex) { ex.printStackTrace(); key.cancel(); clientChannel.close(); resultMap.remove(key); //ex.printStackTrace(); } } } catch (Exception ex) { //ex.printStackTrace(); } } } catch (Exception ex) { //ex.printStackTrace(); } }
From source file:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java
protected void read(SelectionKey selectionKey, Consumer<List<String>> callback, Consumer<Exception> exceptionHandler) { try {/* ww w . j a va2 s.c o m*/ if (!selectionKey.isValid() || !selectionKey.isReadable()) return; byteBuffer.clear(); int bytesRead = ((ReadableByteChannel) selectionKey.channel()).read(byteBuffer); if (bytesRead < 0) { LOG.warn( "End of stream reached. Deregistering interest in reads on the selection key invoking exception handler."); invokeExceptionHandler(selectionKey, exceptionHandler, new EOFException("End of stream")); return; } byteBuffer.flip(); if (byteBuffer.remaining() + messageBuffer.size() > maxMessageSize) { LOG.error("Max message size of " + maxMessageSize + " bytes exceeded. Deregistering interest in reads on the selection key invoking exception handler."); invokeExceptionHandler(selectionKey, exceptionHandler, new IllegalStateException("Max message size of " + maxMessageSize + " bytes exceeded")); return; } while (byteBuffer.hasRemaining()) messageBuffer.write(byteBuffer.get()); String messagesString = messageBuffer.toString(charset); messageBuffer.reset(); List<String> messages = new ArrayList<>(); for (String message : splitter.split(messagesString)) messages.add(message); messageBuffer.write(messages.remove(messages.size() - 1).getBytes(charset)); if (!messages.isEmpty()) { selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ); callback.accept(messages); } } catch (Exception e) { LOG.error("ReadDelimitedMessage task failed", e); invokeExceptionHandler(selectionKey, exceptionHandler, e); } }
From source file:jp.queuelinker.system.net.SelectorThread.java
@Override public void run() { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); // I believe the inner try-catches does not cause overhead. // http://stackoverflow.com/questions/141560/ long sendCount = 0; SocketChannel currentChannel; SelectionKey key = null; while (true) { try {// ww w . ja v a 2s . c o m selector.select(); // selector.selectNow(); } catch (ClosedSelectorException e) { logger.fatal("BUG: The selector is closed."); return; } catch (IOException e) { logger.fatal("An IOException occured while calling select()."); // Fatal Error. Notify the error to the users and leave the matter to them. for (ChannelState state : channels) { state.callBack.fatalError(); } return; } if (!requests.isEmpty()) { handleRequest(); continue; } if (stopRequested) { return; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); iter_loop: while (iter.hasNext()) { key = iter.next(); iter.remove(); // Required. Don't remove. if (key.isReadable()) { currentChannel = (SocketChannel) key.channel(); final ChannelState state = (ChannelState) key.attachment(); int valid; try { valid = currentChannel.read(buffer); } catch (IOException e) { logger.warn("An IOException happened while reading from a channel."); state.callBack.exceptionOccured(state.channelId, state.attachment); key.cancel(); continue; } if (valid == -1) { // Normal socket close? state.callBack.exceptionOccured(state.channelId, state.attachment); // cleanUpChannel(state.channelId); key.cancel(); continue; } buffer.rewind(); if (state.callBack.receive(state.channelId, buffer, valid, state.attachment) == false) { state.key.interestOps(state.key.interestOps() & ~SelectionKey.OP_READ); } buffer.clear(); } else if (key.isWritable()) { currentChannel = (SocketChannel) key.channel(); final ChannelState state = (ChannelState) key.attachment(); while (state.sendBuffer.readableSize() < WRITE_SIZE) { ByteBuffer newBuffer = state.callBack.send(state.channelId, state.attachment); if (newBuffer != null) { state.sendBuffer.write(newBuffer); if (++sendCount % 50000 == 0) { logger.info("Send Count: " + sendCount); } } else if (state.sendBuffer.readableSize() == 0) { key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); continue iter_loop; } else { break; } } final int available = state.sendBuffer.readableSize(); if (available >= WRITE_SIZE || ++state.noopCount >= HEURISTIC_WAIT) { int done; try { done = currentChannel.write(state.sendBuffer.getByteBuffer()); } catch (IOException e) { logger.warn("An IOException occured while writing to a channel."); state.callBack.exceptionOccured(state.channelId, state.attachment); key.cancel(); continue; } if (done < available) { state.sendBuffer.rollback(available - done); } state.sendBuffer.compact(); state.noopCount = 0; } } else if (key.isAcceptable()) { ServerSocketChannel channel = (ServerSocketChannel) key.channel(); ChannelState state = (ChannelState) key.attachment(); SocketChannel socketChannel; try { socketChannel = channel.accept(); socketChannel.configureBlocking(false); } catch (IOException e) { continue; // Do nothing. } state.callBack.newConnection(state.channelId, socketChannel, state.attachment); } } } }
From source file:net.ymate.platform.serv.nio.support.NioEventProcessor.java
protected void __doConnectEvent(SelectionKey key) throws IOException { INioSession _session = (INioSession) key.attachment(); if (_session != null) { SocketChannel _channel = (SocketChannel) key.interestOps(0).channel(); if (_channel.finishConnect()) { _session.finishConnect();// w w w .ja va2 s.co m } _session.selectionKey(key); _session.status(ISession.Status.CONNECTED); __eventGroup.listener().onSessionConnected(_session); } }
From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java
public void listen() throws Exception { doListen = true;//from www . j a va2 s . c om // allocate an unbound server socket channel ServerSocketChannel serverChannel = ServerSocketChannel.open(); // Get the associated ServerSocket to bind it with ServerSocket serverSocket = serverChannel.socket(); // create a new Selector for use below Selector selector = Selector.open(); // set the port the server channel will listen to serverSocket.bind(new InetSocketAddress(bind, port)); // set non-blocking mode for the listening socket serverChannel.configureBlocking(false); // register the ServerSocketChannel with the Selector serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (doListen) { // this may block for a long time, upon return the // selected set contains keys of the ready channels try { //System.out.println("Selecting with timeout="+timeout); int n = selector.select(timeout); //System.out.println("select returned="+n); if (n == 0) { continue; // nothing to do } // get an iterator over the set of selected keys Iterator it = selector.selectedKeys().iterator(); // look at each key in the selected set while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); // Is a new connection coming in? if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); registerChannel(selector, channel, SelectionKey.OP_READ, new ObjectReader(channel, selector, callback)); } // is there data to read on this channel? //System.out.println("key readable="+key.isReadable()); if (key.isReadable()) { readDataFromSocket(key); } else { //System.out.println("This shouldn't get called"); key.interestOps(key.interestOps() & (~key.OP_WRITE)); } // remove key from selected set, it's been handled it.remove(); } //System.out.println("Done with loop"); } catch (java.nio.channels.CancelledKeyException nx) { log.warn("Replication client disconnected, error when polling key. Ignoring client."); } catch (Exception x) { log.error("Unable to process request in ReplicationListener", x); } } //while serverChannel.close(); selector.close(); }
From source file:org.apache.catalina.cluster.tcp.TcpReplicationThread.java
/** * Called to initiate a unit of work by this worker thread * on the provided SelectionKey object. This method is * synchronized, as is the run() method, so only one key * can be serviced at a given time.// w w w. ja va 2 s . com * Before waking the worker thread, and before returning * to the main selection loop, this key's interest set is * updated to remove OP_READ. This will cause the selector * to ignore read-readiness for this channel while the * worker thread is servicing it. */ synchronized void serviceChannel(SelectionKey key, boolean synchronous) { this.key = key; this.synchronous = synchronous; key.interestOps(key.interestOps() & (~SelectionKey.OP_READ)); key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); this.notify(); // awaken the thread }
From source file:org.apache.catalina.cluster.tcp.TcpReplicationThread.java
/** * The actual code which drains the channel associated with * the given key. This method assumes the key has been * modified prior to invocation to turn off selection * interest in OP_READ. When this method completes it * re-enables OP_READ and calls wakeup() on the selector * so the selector will resume watching this channel. *//*from w ww .j ava2 s.co m*/ private void drainChannel(SelectionKey key) throws Exception { boolean packetReceived = false; SocketChannel channel = (SocketChannel) key.channel(); int count; buffer.clear(); // make buffer empty ObjectReader reader = (ObjectReader) key.attachment(); // loop while data available, channel is non-blocking while ((count = channel.read(buffer)) > 0) { buffer.flip(); // make buffer readable int pkgcnt = reader.append(buffer.array(), 0, count); buffer.clear(); // make buffer empty } //check to see if any data is available int pkgcnt = reader.execute(); while (pkgcnt > 0) { if (synchronous) { sendAck(key, channel); } //end if pkgcnt--; } if (count < 0) { // close channel on EOF, invalidates the key channel.close(); return; } // resume interest in OP_READ, OP_WRITE key.interestOps(key.interestOps() | SelectionKey.OP_READ); // cycle the selector so this key is active again key.selector().wakeup(); }