List of usage examples for java.nio.channels Selector open
public static Selector open() throws IOException
From source file:org.openhab.binding.keba.handler.KeContactHandler.java
@Override public void initialize() { if (getConfig().get(IP_ADDRESS) != null && !getConfig().get(IP_ADDRESS).equals("")) { broadcastListener.registerHandler(this); try {/* w w w . j a va 2 s.c o m*/ selector = Selector.open(); } catch (IOException e) { logger.error("An exception occurred while registering the selector: '{}'", e.getMessage()); } establishConnection(); if (listeningJob == null || listeningJob.isCancelled()) { try { listeningJob = scheduler.scheduleWithFixedDelay(listeningRunnable, 0, LISTENING_INTERVAL, TimeUnit.MILLISECONDS); } catch (Exception e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "An exception occurred while scheduling the listening job"); } } if (pollingJob == null || pollingJob.isCancelled()) { try { pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 0, ((BigDecimal) getConfig().get(POLLING_REFRESH_INTERVAL)).intValue(), TimeUnit.SECONDS); } catch (Exception e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "An exception occurred while scheduling the polling job"); } } } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "IP address or port number not set"); } }
From source file:com.packetsender.android.PacketListenerService.java
@Override protected void onHandleIntent(Intent intent) { dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0), getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0)); listenportTCP = dataStore.getTCPPort(); listenportUDP = dataStore.getUDPPort(); Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP)); Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); startNotification();/*w ww . ja v a 2 s .co m*/ CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); ByteBuffer response = null; try { response = encoder.encode(CharBuffer.wrap("response")); } catch (CharacterCodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { SocketAddress localportTCP = new InetSocketAddress(listenportTCP); SocketAddress localportUDP = new InetSocketAddress(listenportUDP); tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localportTCP); udpserver = DatagramChannel.open(); udpserver.socket().bind(localportUDP); tcpserver.configureBlocking(false); udpserver.configureBlocking(false); Selector selector = Selector.open(); tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); ByteBuffer receiveBuffer = ByteBuffer.allocate(1024); receiveBuffer.clear(); shutdownListener = new Runnable() { public void run() { if (false) { try { tcpserver.close(); } catch (IOException e) { } try { udpserver.close(); } catch (IOException e) { } stopSelf(); } else { mHandler.postDelayed(shutdownListener, 2000); } } }; sendListener = new Runnable() { public void run() { //Packet fetchedPacket = mDbHelper.needSendPacket(); Packet[] fetchedPackets = dataStore.fetchAllServicePackets(); if (fetchedPackets.length > 0) { dataStore.clearServicePackets(); Log.d("service", DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets")); for (int i = 0; i < fetchedPackets.length; i++) { Packet fetchedPacket = fetchedPackets[i]; Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString())); } new SendPacketsTask().execute(fetchedPackets); } mHandler.postDelayed(sendListener, 2000); } }; //start shutdown listener mHandler.postDelayed(shutdownListener, 2000); //start send listener mHandler.postDelayed(sendListener, 5000); while (true) { try { // Handle per-connection problems below // Wait for a client to connect Log.d("service", DataStorage.FILE_LINE("waiting for connection")); selector.select(); Log.d("service", DataStorage.FILE_LINE("client connection")); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); Channel c = (Channel) key.channel(); if (key.isAcceptable() && c == tcpserver) { SocketChannel client = tcpserver.accept(); if (client != null) { Socket tcpSocket = client.socket(); packetCounter++; DataInputStream in = new DataInputStream(tcpSocket.getInputStream()); byte[] buffer = new byte[1024]; int received = in.read(buffer); byte[] bufferConvert = new byte[received]; System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = tcpSocket.getPort(); storepacket.port = tcpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP); Log.i("service", DataStorage.FILE_LINE("Got TCP")); //dataStore.SavePacket(storepacket); /* Intent tcpIntent = new Intent(); tcpIntent.setAction(ResponseReceiver.ACTION_RESP); tcpIntent.addCategory(Intent.CATEGORY_DEFAULT); tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name); sendBroadcast(tcpIntent); */ storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = "You"; storepacket.toIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.fromPort = tcpSocket.getLocalPort(); storepacket.port = tcpSocket.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); client.write(response); // send response } client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { DatagramSocket udpSocket; DatagramPacket udpPacket; byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer udpPacket = new DatagramPacket(buffer, buffer.length); udpSocket = udpserver.socket(); receiveBuffer.clear(); InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer); if (clientAddress != null) { String fromAddress = clientAddress.getAddress().getHostAddress(); packetCounter++; int received = receiveBuffer.position(); byte[] bufferConvert = new byte[received]; System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = clientAddress.getAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = clientAddress.getPort(); storepacket.port = udpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP); //dataStore.SavePacket(storepacket); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = "You"; storepacket.toIP = clientAddress.getAddress().getHostAddress(); storepacket.fromPort = udpSocket.getLocalPort(); storepacket.port = clientAddress.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); //dataStore.SavePacket(storepacket); udpserver.send(response, clientAddress); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); } } } } } catch (java.io.IOException e) { Log.i("service", DataStorage.FILE_LINE("IOException ")); } catch (Exception e) { Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e))); } } } catch (BindException e) { //mDbHelper.putServiceError("Error binding to port"); dataStore.putToast("Port already in use."); Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e))); } catch (Exception e) { //mDbHelper.putServiceError("Fatal Error starting service"); Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e))); } stopNotification(); }
From source file:org.limewire.mojito.io.MessageDispatcherImpl.java
@Override public void bind(SocketAddress address) throws IOException { synchronized (lock) { if (isBound()) { throw new IOException("DatagramChannel is already bound"); }//from www . j ava 2 s. c om channel = DatagramChannel.open(); channel.configureBlocking(false); selector = Selector.open(); channel.register(selector, SelectionKey.OP_READ); DatagramSocket socket = channel.socket(); socket.setReuseAddress(false); socket.setReceiveBufferSize(RECEIVE_BUFFER_SIZE); socket.setSendBufferSize(SEND_BUFFER_SIZE); socket.bind(address); } }
From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java
public void listen() throws Exception { doListen = true;/* w w w . j av a 2 s.co m*/ // 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:net.jenet.Host.java
/** * Creates a new <code>Host</code> object. If the incoming/outgoing * bandwidths are not bounded, the host will drop unreliable packets in * order to keep them below the fixed limits. This parameter also influences * the number and size of the reliable packets that may be handled at once. * /*from w w w . jav a2 s .co m*/ * @param address * The to bind this host to (<emph>ie</emph> the address at * which other peers may connect to this one) or * <code>0</code> to get a system-assigned address. * @param maxConnections * The maximum number of peers/connections that this host will be * able to connect to. * @param incomingBandwith * The maximum incoming bandwidth in bytes/second (0 = * unbounded). * @param outgoingBandwith * The maximum outgoing bandwidth in bytes/second (0 = * unbounded). * @throws IOException * if it can not bind the port. * @throws ConfigurationException * if the file enet.properties is not in the path */ public Host(InetSocketAddress address, int maxConnections, int incomingBandwith, int outgoingBandwith) throws IOException, ConfigurationException { super(); communicationChannel = DatagramChannel.open(); communicationChannel.configureBlocking(false); communicationChannel.socket().bind(address); communicationSelector = Selector.open(); communicationChannel.register(communicationSelector, SelectionKey.OP_READ); LOG.debug("Host bound to address: " + address); this.address = (InetSocketAddress) communicationChannel.socket().getLocalSocketAddress(); initHost(maxConnections, incomingBandwith, outgoingBandwith); }
From source file:xbird.server.services.RemotePagingService.java
private void acceptConnections(final ServerSocketChannel channel) throws IOException { // set to non blocking mode channel.configureBlocking(false);//from w ww . ja va 2 s. c o m // Bind the server socket to the local host and port InetAddress host = InetAddress.getLocalHost(); InetSocketAddress sockAddr = new InetSocketAddress(host, PORT); ServerSocket socket = channel.socket(); //socket.setReuseAddress(true); socket.bind(sockAddr); // Register accepts on the server socket with the selector. This // step tells the selector that the socket wants to be put on the // ready list when accept operations occur. Selector selector = Selector.open(); ByteBuffer cmdBuffer = ByteBuffer.allocateDirect(MAX_COMMAND_BUFLEN); IOHandler ioHandler = new IOHandler(cmdBuffer); AcceptHandler acceptHandler = new AcceptHandler(ioHandler); channel.register(selector, SelectionKey.OP_ACCEPT, acceptHandler); int n; while ((n = selector.select()) > 0) { // Someone is ready for I/O, get the ready keys Set<SelectionKey> selectedKeys = selector.selectedKeys(); final Iterator<SelectionKey> keyItor = selectedKeys.iterator(); while (keyItor.hasNext()) { SelectionKey key = keyItor.next(); keyItor.remove(); // The key indexes into the selector so you // can retrieve the socket that's ready for I/O Handler handler = (Handler) key.attachment(); try { handler.handle(key); } catch (CancelledKeyException cke) { ; } catch (IOException ioe) { LOG.fatal(ioe); NIOUtils.cancelKey(key); } catch (Throwable e) { LOG.fatal(e); NIOUtils.cancelKey(key); } } } }
From source file:middleware.NewServerSocket.java
NewServerSocket(SharedData s) { sharedData = s;// www . jav a 2s. c om try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(s.getMiddlePortNum())); serverSocketChannel.configureBlocking(false); } catch (IOException e) { System.out.println("Error: cannot bind to port " + s.getMiddlePortNum()); e.printStackTrace(); } try { adminServerSocketChannel = ServerSocketChannel.open(); adminServerSocketChannel.socket().bind(new InetSocketAddress(s.getAdminPortNum())); adminServerSocketChannel.configureBlocking(false); } catch (IOException e) { System.out.println("Error: cannot bind to port " + s.getAdminPortNum()); e.printStackTrace(); } try { selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); adminServerSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { e.printStackTrace(); } keyIterator = null; dir = new File(sharedData.getFilePathName() + File.separator + "Transactions"); if (!dir.exists()) { dir.mkdirs(); } else { for (File f : dir.listFiles()) { if (!f.delete()) { // TODO } } } numWorkers = sharedData.getNumWorkers(); workers = new NewWorker[numWorkers]; for (int i = 0; i < numWorkers; ++i) { Selector tmpS = null; try { tmpS = Selector.open(); } catch (IOException e) { e.printStackTrace(); } workers[i] = new NewWorker(sharedData, tmpS); workers[i].start(); } data = new byte[sharedData.getMaxSize()]; buffer = ByteBuffer.wrap(data); endingMonitoring = false; sendingFiles = false; monitoring = false; dstatDeployed = false; failDeployDstat = false; configSetenv = false; mysql_user = null; mysql_pass = null; mysql_host = null; mysql_port = null; sharedData.allTransactionData = new ArrayList<TransactionData>(); sharedData.allTransactions = new ConcurrentSkipListMap<Integer, byte[]>(); // sharedData.allStatementsInfo = new ConcurrentLinkedQueue<byte[]>(); sharedData.allQueries = new ConcurrentSkipListMap<Long, QueryData>(); userInfo = Encrypt.getUsrMap(sharedData.getUserInfoFilePath()); fileBuffer = new byte[1024]; curUser = null; userList = new ArrayList<MiddleSocketChannel>(); dstat = null; ntpdate = null; stopRemoteDstat = null; incrementalLogQueue = new ArrayBlockingQueue<IncrementalLog>(64 * 1024); }
From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java
@Override public void initialize() { // register ourselves as a Transceiver Status Listener registerTransceiverStatusListener(this); try {/*from ww w . jav a 2s. c om*/ selector = Selector.open(); } catch (IOException e) { logger.debug("An exception occurred while registering the selector: '{}'", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, e.getMessage()); } if (selector != null) { if (getConfig().get(IP_ADDRESS) != null && getConfig().get(PORT_NUMBER) != null) { if (pollingThread == null) { pollingThread = new Thread(pollingRunnable, "ESH-IRtrans-Polling " + getThing().getUID()); pollingThread.start(); } } else { logger.debug("Cannot connect to IRtrans Ethernet device. IP address or port number not set."); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "IP address or port number not set."); } if (getConfig().get(IS_LISTENER) != null) { configureListener((String) getConfig().get(LISTENER_PORT)); } } }
From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java
@Override public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException { stopped = false;//from www. j av a 2 s . co m executor = Executors.newFixedThreadPool(maxConnections); final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); if (maxBufferSize > 0) { serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize); final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF); if (actualReceiveBufSize < maxBufferSize) { logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer"); } } serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port)); selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); }
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;//w w w. j ava 2s .co 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(); } }