List of usage examples for java.util.concurrent ConcurrentHashMap remove
public V remove(Object key)
From source file:org.wso2.carbon.event.output.adaptor.cassandra.CassandraEventAdaptorType.java
/** * @param outputEventMessageConfiguration * - topic name to publish messages * @param message - is and Object[]{Event, EventDefinition} * @param outputEventAdaptorConfiguration * * @param tenantId/*from w w w. ja v a 2 s .com*/ */ public void publish(OutputEventAdaptorMessageConfiguration outputEventMessageConfiguration, Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) { ConcurrentHashMap<OutputEventAdaptorConfiguration, EventAdaptorInfo> cassandraClusterCache = null; if (message instanceof Map) { try { cassandraClusterCache = tenantedCassandraClusterCache.get(tenantId); if (null == cassandraClusterCache) { cassandraClusterCache = new ConcurrentHashMap<OutputEventAdaptorConfiguration, EventAdaptorInfo>(); if (null != tenantedCassandraClusterCache.putIfAbsent(tenantId, cassandraClusterCache)) { cassandraClusterCache = tenantedCassandraClusterCache.get(tenantId); } } EventAdaptorInfo eventAdaptorInfo = cassandraClusterCache.get(outputEventAdaptorConfiguration); if (null == eventAdaptorInfo) { Map<String, String> properties = outputEventAdaptorConfiguration.getOutputProperties(); Map<String, String> credentials = new HashMap<String, String>(); credentials.put("username", properties.get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_USER_NAME)); credentials.put("password", properties.get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_PASSWORD)); // cleaning existing cached copies. Cluster cluster = HFactory.getCluster( properties.get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_CLUSTER_NAME)); if (cluster != null) { HFactory.shutdownCluster(cluster); } cluster = HFactory.createCluster( properties.get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_CLUSTER_NAME), new CassandraHostConfigurator( properties.get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_HOSTNAME) + ":" + properties .get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_PORT)), credentials); if (cluster.getKnownPoolHosts(true).size() < 1) { // not properly connected. log.error("Cannot connect to the Cassandra cluster: " + cluster.getName() + ". Please check the configuration."); HFactory.shutdownCluster(cluster); return; } String indexAllColumnsString = properties .get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_INDEX_ALL_COLUMNS); boolean indexAllColumns = false; if (indexAllColumnsString != null && indexAllColumnsString.equals("true")) { indexAllColumns = true; } eventAdaptorInfo = new EventAdaptorInfo(cluster, indexAllColumns); if (null != cassandraClusterCache.putIfAbsent(outputEventAdaptorConfiguration, eventAdaptorInfo)) { eventAdaptorInfo = cassandraClusterCache.get(outputEventAdaptorConfiguration); } else { log.info("Initiated Cassandra Writer " + outputEventAdaptorConfiguration.getName()); } } String keySpaceName = outputEventMessageConfiguration.getOutputMessageProperties() .get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_KEY_SPACE_NAME); String columnFamilyName = outputEventMessageConfiguration.getOutputMessageProperties() .get(CassandraEventAdaptorConstants.ADAPTOR_CASSANDRA_COLUMN_FAMILY_NAME); MessageInfo messageInfo = eventAdaptorInfo.getMessageInfoMap().get(outputEventMessageConfiguration); if (null == messageInfo) { Keyspace keyspace = HFactory.createKeyspace(keySpaceName, eventAdaptorInfo.getCluster()); messageInfo = new MessageInfo(keyspace); if (null != eventAdaptorInfo.getMessageInfoMap().putIfAbsent(outputEventMessageConfiguration, messageInfo)) { messageInfo = eventAdaptorInfo.getMessageInfoMap().get(outputEventMessageConfiguration); } } if (eventAdaptorInfo.getCluster().describeKeyspace(keySpaceName) == null) { BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(); columnFamilyDefinition.setKeyspaceName(keySpaceName); columnFamilyDefinition.setName(columnFamilyName); columnFamilyDefinition.setComparatorType(ComparatorType.UTF8TYPE); columnFamilyDefinition.setDefaultValidationClass(ComparatorType.UTF8TYPE.getClassName()); columnFamilyDefinition.setKeyValidationClass(ComparatorType.UTF8TYPE.getClassName()); ColumnFamilyDefinition cfDef = new ThriftCfDef(columnFamilyDefinition); KeyspaceDefinition keyspaceDefinition = HFactory.createKeyspaceDefinition(keySpaceName, "org.apache.cassandra.locator.SimpleStrategy", 1, Arrays.asList(cfDef)); eventAdaptorInfo.getCluster().addKeyspace(keyspaceDefinition); KeyspaceDefinition fromCluster = eventAdaptorInfo.getCluster().describeKeyspace(keySpaceName); messageInfo.setColumnFamilyDefinition( new BasicColumnFamilyDefinition(fromCluster.getCfDefs().get(0))); } else { KeyspaceDefinition fromCluster = eventAdaptorInfo.getCluster().describeKeyspace(keySpaceName); for (ColumnFamilyDefinition columnFamilyDefinition : fromCluster.getCfDefs()) { if (columnFamilyDefinition.getName().equals(columnFamilyName)) { messageInfo.setColumnFamilyDefinition( new BasicColumnFamilyDefinition(columnFamilyDefinition)); break; } } } Mutator<String> mutator = HFactory.createMutator(messageInfo.getKeyspace(), sser); String uuid = UUID.randomUUID().toString(); for (Map.Entry<String, Object> entry : ((Map<String, Object>) message).entrySet()) { if (eventAdaptorInfo.isIndexAllColumns() && !messageInfo.getColumnNames().contains(entry.getKey())) { BasicColumnFamilyDefinition columnFamilyDefinition = messageInfo .getColumnFamilyDefinition(); BasicColumnDefinition columnDefinition = new BasicColumnDefinition(); columnDefinition.setName(StringSerializer.get().toByteBuffer(entry.getKey())); columnDefinition.setIndexType(ColumnIndexType.KEYS); columnDefinition.setIndexName( keySpaceName + "_" + columnFamilyName + "_" + entry.getKey() + "_Index"); columnDefinition.setValidationClass(ComparatorType.UTF8TYPE.getClassName()); columnFamilyDefinition.addColumnDefinition(columnDefinition); eventAdaptorInfo.getCluster().updateColumnFamily(new ThriftCfDef(columnFamilyDefinition)); messageInfo.getColumnNames().add(entry.getKey()); } mutator.insert(uuid, columnFamilyName, HFactory.createStringColumn(entry.getKey(), entry.getValue().toString())); } mutator.execute(); } catch (Throwable t) { if (cassandraClusterCache != null) { cassandraClusterCache.remove(outputEventAdaptorConfiguration); } log.error("Cannot connect to Cassandra: " + t.getMessage(), t); } } }
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 av a 2 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) { //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 w ww .ja va2 s . com*/ 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:org.wso2.carbon.event.output.adaptor.cassandraext.CassandraExtendedEventAdaptorType.java
/** * @param outputEventMessageConfiguration * - topic name to publish messages * @param message - is and Object[]{Event, EventDefinition} * @param outputEventAdaptorConfiguration * * @param tenantId/* w ww. j av a 2 s.co m*/ */ public void publish(OutputEventAdaptorMessageConfiguration outputEventMessageConfiguration, Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) { ConcurrentHashMap<OutputEventAdaptorConfiguration, EventAdaptorInfo> cassandraClusterCache = null; if (message instanceof Map) { try { cassandraClusterCache = tenantedCassandraClusterCache.get(tenantId); if (null == cassandraClusterCache) { cassandraClusterCache = new ConcurrentHashMap<OutputEventAdaptorConfiguration, EventAdaptorInfo>(); if (null != tenantedCassandraClusterCache.putIfAbsent(tenantId, cassandraClusterCache)) { cassandraClusterCache = tenantedCassandraClusterCache.get(tenantId); } } String keySpaceName = outputEventMessageConfiguration.getOutputMessageProperties() .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_KEY_SPACE_NAME); String columnFamilyName = outputEventMessageConfiguration.getOutputMessageProperties() .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_COLUMN_FAMILY_NAME); EventAdaptorInfo eventAdaptorInfo = cassandraClusterCache.get(outputEventAdaptorConfiguration); if (null == eventAdaptorInfo) { Map<String, String> properties = outputEventAdaptorConfiguration.getOutputProperties(); String username = properties .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_USER_NAME); String password = properties .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_PASSWORD); String cassandraHost = properties .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_HOSTNAME); String cassandraPort = properties .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_PORT); String clusterName = properties .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_CLUSTER_NAME); Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost); if (cassandraPort != null && cassandraPort.length() > 0) { clusterBuilder.withPort(Integer.parseInt(cassandraPort)); } clusterBuilder.withClusterName(clusterName); if (username != null && username.length() > 0) { clusterBuilder.withCredentials(username, password); } Cluster cluster = clusterBuilder.build(); String indexAllColumnsString = properties .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_INDEX_ALL_COLUMNS); boolean indexAllColumns = false; if (indexAllColumnsString != null && indexAllColumnsString.equals("true")) { indexAllColumns = true; } eventAdaptorInfo = new EventAdaptorInfo(cluster, indexAllColumns); if (null != cassandraClusterCache.putIfAbsent(outputEventAdaptorConfiguration, eventAdaptorInfo)) { eventAdaptorInfo = cassandraClusterCache.get(outputEventAdaptorConfiguration); } else { log.info("Initiated Cassandra Writer " + outputEventAdaptorConfiguration.getName()); } } MessageInfo messageInfo = eventAdaptorInfo.getMessageInfoMap().get(outputEventMessageConfiguration); String executionMode = outputEventMessageConfiguration.getOutputMessageProperties() .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_EXECUTION_MODE); String updateColKeys = outputEventMessageConfiguration.getOutputMessageProperties() .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_INDEX_KEYS); if (null == messageInfo) { messageInfo = new MessageInfo(); // this is eternal and thread-safe. Session session = eventAdaptorInfo.getCluster().connect(keySpaceName); messageInfo.setSession(session); messageInfo.setInsertOrUpdate(executionMode.equalsIgnoreCase(resourceBundle.getString( CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_EXECUTION_MODE_UPDATE))); if (messageInfo.isInsertOrUpdate()) { ArrayList<String> keyList = new ArrayList<String>(); String[] keys = updateColKeys == null ? new String[0] : updateColKeys.trim().split(","); for (String key : keys) { keyList.add(key.trim()); } messageInfo.setKeyColumns(keyList); } messageInfo.setPrimaryKey(outputEventMessageConfiguration.getOutputMessageProperties() .get(CassandraExtendedEventAdaptorConstants.ADAPTOR_CASSANDRA_PRIMARY_KEY)); if (null != eventAdaptorInfo.getMessageInfoMap().putIfAbsent(outputEventMessageConfiguration, messageInfo)) { messageInfo = eventAdaptorInfo.getMessageInfoMap().get(outputEventMessageConfiguration); } } // customized code Session session = messageInfo.getSession(); Map<String, Object> attributeMap = (Map<String, Object>) message; // optional String primaryKey = messageInfo.getPrimaryKey(); if (primaryKey != null && primaryKey.trim().length() == 0) { // not configured properly. primaryKey = null; } // optional ArrayList<String> indexCols = messageInfo.getKeyColumns(); // create table and indexes if not exist. if (!messageInfo.isCfInitialized()) { try { session.execute("select * from " + columnFamilyName + " limit 1"); messageInfo.setCfInitialized(true); } catch (Exception ex) { // assuming table doesn't exist. StringBuilder creationQuery = new StringBuilder("create table " + columnFamilyName + " ("); if (primaryKey == null || primaryKey.length() == 0) { creationQuery.append("uuid_key text primary key, "); } for (String col : attributeMap.keySet()) { creationQuery.append(col).append(" ").append("text"); if (col.equals(primaryKey)) { creationQuery.append(" primary key"); } creationQuery.append(","); } String query = creationQuery.substring(0, creationQuery.length() - 1) + ")"; session.execute(query); // creating indexes if (indexCols != null) { for (String index : indexCols) { if (!index.equals(primaryKey)) { String indexQuery = "create index ind_" + columnFamilyName + "_" + index + " on " + columnFamilyName + " (" + index + ")"; session.execute(indexQuery); } } } messageInfo.setCfInitialized(true); } } // end of table creation // inserting and updating. if (messageInfo.isInsertOrUpdate()) { // checking whether the key cols values exist StringBuilder queryBuilder = new StringBuilder("update "); queryBuilder.append(columnFamilyName); queryBuilder.append(" set "); boolean addComma = false; for (Map.Entry<String, Object> entry : attributeMap.entrySet()) { if (!entry.getKey().equals(primaryKey)) { if (addComma) { queryBuilder.append(","); } queryBuilder.append(entry.getKey()); queryBuilder.append(" = '"); queryBuilder.append(entry.getValue()); queryBuilder.append("'"); addComma = true; } } queryBuilder.append(" where "); queryBuilder.append(primaryKey); queryBuilder.append(" = '"); queryBuilder.append(attributeMap.get(primaryKey)); queryBuilder.append("'"); session.execute(queryBuilder.toString()); } else { // inserting with uuid to allow duplicates // if user enters a primary key here, it will be similar to the update clause. StringBuilder queryBuilder = new StringBuilder("insert into "); queryBuilder.append(columnFamilyName); queryBuilder.append(" ("); boolean addComma = false; if (primaryKey == null) { queryBuilder.append("uuid_key, "); } for (Map.Entry<String, Object> entry : attributeMap.entrySet()) { if (addComma) { queryBuilder.append(", "); } queryBuilder.append(entry.getKey()); addComma = true; } queryBuilder.append(") values ("); if (primaryKey == null) { queryBuilder.append("'").append(UUID.randomUUID()).append("'"); queryBuilder.append(","); } addComma = false; for (Map.Entry<String, Object> entry : attributeMap.entrySet()) { if (addComma) { queryBuilder.append(","); } queryBuilder.append("'").append(entry.getValue()).append("'"); addComma = true; } queryBuilder.append(")"); session.execute(queryBuilder.toString()); } // end of customized code } catch (Throwable t) { if (cassandraClusterCache != null) { cassandraClusterCache.remove(outputEventAdaptorConfiguration); } log.error("Cannot connect to Cassandra: " + t.getMessage(), t); } } }