Example usage for java.util.concurrent ConcurrentHashMap get

List of usage examples for java.util.concurrent ConcurrentHashMap get

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentHashMap get.

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.wso2.carbon.event.input.adaptor.mqtt.MQTTEventAdaptorType.java

private void createMQTTAdaptorListener(
        InputEventAdaptorMessageConfiguration inputEventAdaptorMessageConfiguration,
        InputEventAdaptorListener inputEventAdaptorListener,
        InputEventAdaptorConfiguration inputEventAdaptorConfiguration, AxisConfiguration axisConfiguration,
        String subscriptionId, int tenantId) {

    String topic = inputEventAdaptorMessageConfiguration.getInputMessageProperties()
            .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_TOPIC);
    Map<String, ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>>> tenantSpecificListenerMap = inputEventAdaptorListenerMap
            .get(tenantId);/*from ww  w . j a  v  a  2s .  c om*/
    if (tenantSpecificListenerMap == null) {
        tenantSpecificListenerMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>>>();
        inputEventAdaptorListenerMap.put(tenantId, tenantSpecificListenerMap);
    }

    ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>> adaptorSpecificListenerMap = tenantSpecificListenerMap
            .get(inputEventAdaptorConfiguration.getName());

    if (adaptorSpecificListenerMap == null) {
        adaptorSpecificListenerMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorListener>>();
        if (null != tenantSpecificListenerMap.put(inputEventAdaptorConfiguration.getName(),
                adaptorSpecificListenerMap)) {
            adaptorSpecificListenerMap = tenantSpecificListenerMap
                    .get(inputEventAdaptorConfiguration.getName());
        }
    }

    ConcurrentHashMap<String, MQTTAdaptorListener> topicSpecificListenMap = adaptorSpecificListenerMap
            .get(topic);
    if (topicSpecificListenMap == null) {
        topicSpecificListenMap = new ConcurrentHashMap<String, MQTTAdaptorListener>();
        if (null != adaptorSpecificListenerMap.putIfAbsent(topic, topicSpecificListenMap)) {
            topicSpecificListenMap = adaptorSpecificListenerMap.get(topic);
        }
    }

    MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration(
            inputEventAdaptorConfiguration.getInputProperties().get(MQTTEventAdaptorConstants.ADAPTOR_CONF_URL),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_USERNAME),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_PASSWORD),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_CLEAN_SESSION),
            inputEventAdaptorConfiguration.getInputProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_KEEP_ALIVE));
    MQTTAdaptorListener mqttAdaptorListener = new MQTTAdaptorListener(mqttBrokerConnectionConfiguration,
            inputEventAdaptorMessageConfiguration.getInputMessageProperties()
                    .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_TOPIC),
            inputEventAdaptorMessageConfiguration.getInputMessageProperties().get(
                    MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_CLIENTID),
            inputEventAdaptorListener, tenantId);
    topicSpecificListenMap.put(subscriptionId, mqttAdaptorListener);
    mqttAdaptorListener.createConnection();

}

From source file:org.wso2.andes.server.cassandra.OnflightMessageTracker.java

/**
 * Track that this message is buffered. Return true if eligible to buffer
 *
 * @param slot                 slot message being read in
 * @param andesMessageMetadata metadata to buffer
 * @return eligibility to buffer/*from  w w  w . j a v a2s.  com*/
 */
public boolean addMessageToBufferingTracker(Slot slot, AndesMessageMetadata andesMessageMetadata) {
    long messageID = andesMessageMetadata.getMessageID();
    boolean isOKToBuffer;
    if (log.isDebugEnabled()) {
        log.debug("Buffering message id = " + messageID + " slot = " + slot.toString());
    }
    ConcurrentHashMap<Long, MsgData> messagesOfSlot = messageBufferingTracker.get(slot);
    if (messagesOfSlot == null) {
        messagesOfSlot = new ConcurrentHashMap<Long, MsgData>();
        messageBufferingTracker.put(slot, messagesOfSlot);
    }
    MsgData trackingData = messagesOfSlot.get(messageID);
    if (trackingData == null) {
        trackingData = new MsgData(messageID, slot, slot.getDestinationOfMessagesInSlot(),
                System.currentTimeMillis(), andesMessageMetadata.getExpirationTime(), MessageStatus.BUFFERED,
                andesMessageMetadata.getArrivalTime());
        msgId2MsgData.put(messageID, trackingData);
        messagesOfSlot.put(messageID, trackingData);
        isOKToBuffer = true;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Buffering rejected message id = " + messageID);
        }
        isOKToBuffer = false;
    }
    return isOKToBuffer;
}

From source file:com.app.server.EJBDeployer.java

public void undeploy(URL url) {
    try {//from  ww w . j  a  va  2  s . c  o  m
        //System.out.println(jarEJBMap.get(url.toString()));
        Vector<Object> objs = staticObjsEjbMap.remove(url.toString());
        if (objs != null) {
            objs.clear();
        }
        Vector<EJBContext> ejbContexts = jarEJBMap.get(url.toString());
        if (ejbContexts != null && ejbContexts.size() > 0) {
            for (EJBContext ejbContext : ejbContexts) {
                if (ejbContext != null) {
                    HashMap<String, Class> bindings = ejbContext.getRemoteBindings();
                    Set<String> remoteBindings = bindings.keySet();
                    Iterator<String> remoteBinding = remoteBindings.iterator();
                    while (remoteBinding.hasNext()) {
                        String binding = (String) remoteBinding.next();
                        Object unbindstatefulObjs = ic.lookup("java:/" + binding);
                        if (unbindstatefulObjs instanceof StatefulBeanObject) {
                            Vector<Object> StatefulBeanObjects = StatefulBeanObject.statefulSessionBeanObjectMap
                                    .get(url.toString());
                            StatefulBeanObject.statefulSessionBeanObjectMap.remove(url.toString());
                            StatefulBeanObjects.clear();
                        }
                        ic.unbind("java:/" + binding);
                        System.out.println("unregistering the class" + bindings.get(binding));
                    }
                    jarEJBMap.remove(url.toString());
                }
            }
        }
        ConcurrentHashMap<String, MDBContext> mdbContexts = jarMDBMap.get(url.toString());
        MDBContext mdbContext;
        if (mdbContexts != null) {
            Iterator<String> mdbnames = mdbContexts.keySet().iterator();
            while (mdbnames.hasNext()) {
                String mdbname = mdbnames.next();
                mdbContext = mdbContexts.get(mdbname);
                if (mdbContext.getResourceAdapter() != null) {
                    mdbContext.getResourceAdapter().endpointDeactivation(mdbContext.getMessageEndPointFactory(),
                            mdbContext.getActivationSpec());
                    mdbContext.getResourceAdapter().stop();
                }
                if (mdbContext.getConsumer() != null) {
                    mdbContext.getConsumer().setMessageListener(null);
                    mdbContext.getConsumer().close();
                }
                if (mdbContext.getSession() != null)
                    mdbContext.getSession().close();
                if (mdbContext.getConnection() != null)
                    mdbContext.getConnection().close();
                mdbContexts.remove(mdbname);
            }
            jarMDBMap.remove(url.toString());
        }
        log.info(url.toString() + " UnDeployed");
    } catch (Exception ex) {
        log.error("Error in undeploying the package " + url, ex);
        //ex.printStackTrace();
    }
}

From source file:org.wso2.carbon.event.output.adaptor.mqtt.MQTTEventAdaptorType.java

/**
 * @param outputEventAdaptorMessageConfiguration
 *                 - topic name to publish messages
 * @param message  - is and Object[]{Event, EventDefinition}
 * @param outputEventAdaptorConfiguration
 *                 the {@link OutputEventAdaptorConfiguration} object that will be used to
 *                 get configuration information
 * @param tenantId tenant id of the calling thread.
 *//*from  www.ja  v  a 2s .  c  om*/
public void publish(OutputEventAdaptorMessageConfiguration outputEventAdaptorMessageConfiguration,
        Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {

    ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorPublisher>> clientIdSpecificEventSenderMap = publisherMap
            .get(outputEventAdaptorConfiguration.getName());
    if (null == clientIdSpecificEventSenderMap) {
        clientIdSpecificEventSenderMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, MQTTAdaptorPublisher>>();
        if (null != publisherMap.putIfAbsent(outputEventAdaptorConfiguration.getName(),
                clientIdSpecificEventSenderMap)) {
            clientIdSpecificEventSenderMap = publisherMap.get(outputEventAdaptorConfiguration.getName());
        }
    }

    String clientId = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
            .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_CLIENTID);
    ConcurrentHashMap<String, MQTTAdaptorPublisher> topicSpecificEventPublisherMap = clientIdSpecificEventSenderMap
            .get(clientId);
    if (null == topicSpecificEventPublisherMap) {
        topicSpecificEventPublisherMap = new ConcurrentHashMap<String, MQTTAdaptorPublisher>();
        if (null != clientIdSpecificEventSenderMap.putIfAbsent(clientId, topicSpecificEventPublisherMap)) {
            topicSpecificEventPublisherMap = clientIdSpecificEventSenderMap.get(clientId);
        }
    }

    String topic = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
            .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_TOPIC);
    MQTTAdaptorPublisher mqttAdaptorPublisher = topicSpecificEventPublisherMap.get(topic);
    if (mqttAdaptorPublisher == null) {
        MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration(
                outputEventAdaptorConfiguration.getOutputProperties()
                        .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_URL),
                outputEventAdaptorConfiguration.getOutputProperties()
                        .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_USERNAME),
                outputEventAdaptorConfiguration.getOutputProperties()
                        .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_PASSWORD),
                outputEventAdaptorConfiguration.getOutputProperties()
                        .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_CLEAN_SESSION),
                outputEventAdaptorConfiguration.getOutputProperties()
                        .get(MQTTEventAdaptorConstants.ADAPTOR_CONF_KEEP_ALIVE));
        mqttAdaptorPublisher = new MQTTAdaptorPublisher(mqttBrokerConnectionConfiguration,
                outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
                        .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_TOPIC),
                outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
                        .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_CLIENTID));
        topicSpecificEventPublisherMap.put(topic, mqttAdaptorPublisher);
    }
    String qos = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
            .get(MQTTEventAdaptorConstants.ADAPTOR_MESSAGE_QOS);

    try {
        if (qos == null) {
            mqttAdaptorPublisher.publish(message.toString());
        } else {
            mqttAdaptorPublisher.publish(Integer.parseInt(qos), message.toString());
        }
    } catch (OutputEventAdaptorEventProcessingException ex) {
        log.error(ex);
        topicSpecificEventPublisherMap.remove(topic);
        throw new OutputEventAdaptorEventProcessingException(ex);
    }
}

From source file:com.app.server.EARDeployer.java

/**
 * This method removes the executor services from the executor services
 * map.//w  w  w  .j  av  a  2 s . c  o  m
 * 
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deleteExecutorServicesEar(URL url) throws FileSystemException {
    try {
        File file = new File(url.toURI());
        String fileName = file.getName();
        synchronized (urlClassLoaderMap) {
            ConcurrentHashMap map = (ConcurrentHashMap) filesMap.get(fileName);
            if (map != null) {
                //log.info("ClassLoader Map=\n\n\n\n"+urlClassLoaderMap);
                Set keysinclassloadermap = map.keySet();
                log.info(keysinclassloadermap.size());
                Iterator classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    log.info("ClassLoader=" + classloader);
                    ClassLoader webClassLoader = (ClassLoader) this.urlClassLoaderMap.get(map.get(classloader));
                    this.urlClassLoaderMap.remove(map.get(classloader));
                    ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                    urlClassLoaderMap.remove(map.get(classloader));
                    try {
                        if (webClassLoader instanceof WebClassLoader)
                            ((WebClassLoader) webClassLoader).close();
                        else if (webClassLoader instanceof VFSClassLoader) {
                            FileObject[] fObj = ((VFSClassLoader) webClassLoader).getFileObjects();
                            for (FileObject obj : fObj) {
                                obj.close();
                            }
                        }
                    } catch (Throwable e) {
                        log.error("Error in closing the classLoader", e);
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    }
                    /*if (classloader.contains(deployDirectory +"/"+ fileName)) {
                       log.info("removing classloader" + deployDirectory
                      + classloader);
                          File warDir=new File(fileName);
                          if(warDir.exists()){                                    
                      warDeployer.deleteDir(warDir);
                          }
                          //log.info("Before Remove class loader\n\n\n\n"+this.urlClassLoaderMap);                           
                          //log.info("Remove class loader\n\n\n\n"+this.urlClassLoaderMap);
                    }*/
                }
                System.gc();
                classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    if (classloader.endsWith(".war")) {
                        mbeanServer.invoke(warObjectName, "removeServlets",
                                new Object[] { (String) map.get(classloader), classloader },
                                new String[] { String.class.getName(), String.class.getName() });
                        File warDir = new File((String) map.get(classloader));
                        if (warDir.exists()) {
                            deleteDir(warDir);
                        }
                    }
                }
                log.info(this.urlClassLoaderMap);
            }
            filesMap.remove(fileName);
        }
    } catch (Exception ex) {
        try {
            log.error("Error in removing the executor services configuration for the file name "
                    + url.toURI().toString(), ex);
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //ex.printStackTrace();
    }
}

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  ww.j ava  2s  . c  o  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);
                }
            }

            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:org.starnub.starnubserver.connections.player.session.PlayerSession.java

public String getSpecificPermission(String basePermission, String subPermission) {
    ConcurrentHashMap<String, ArrayList<String>> concurrentHashMap = PERMISSIONS.get(basePermission);
    if (concurrentHashMap == null) {
        return null;
    }//w w  w. j a  v  a  2s  .c o  m
    ArrayList<String> arrayList = concurrentHashMap.get(subPermission);
    if (arrayList == null || arrayList.size() == 0) {
        return null;
    }
    return arrayList.get(0);
}

From source file:org.rifidi.edge.configuration.ConfigurationServiceImpl.java

/**
 * Load the configuration. Not thread safe.
 * //  ww w.j  a  va 2  s  .com
 * @return
 */
private ConcurrentHashMap<String, Set<DefaultConfigurationImpl>> loadConfig() {
    ConcurrentHashMap<String, Set<DefaultConfigurationImpl>> ret = new ConcurrentHashMap<String, Set<DefaultConfigurationImpl>>();

    ConfigurationStore store;
    try {
        store = (ConfigurationStore) jaxbContext.createUnmarshaller().unmarshal(persistanceResource.getFile());
    } catch (IOException e) {
        logger.error("Error loading config/rifidi.xml, no configuration loaded");
        return ret;
    } catch (JAXBException e) {
        logger.error("Exception loading config/rifidi.xml or file not found, no configuration loaded");
        return ret;
    }
    if (store.getServices() != null) {
        for (ServiceStore service : store.getServices()) {
            if (ret.get(service.getFactoryID()) == null) {
                ret.put(service.getFactoryID(), new CopyOnWriteArraySet<DefaultConfigurationImpl>());
            }
            AttributeList attributes = new AttributeList();
            // get all properties
            for (String key : service.getAttributes().keySet()) {
                // factoryid is already processed
                if (Constants.FACTORYID.equals(key)) {
                    continue;
                }
                // type is already processed
                if (Constants.FACTORY_TYPE.equals(key)) {
                    continue;
                }
                attributes.add(new Attribute(key, service.getAttributes().get(key)));
            }
            if (!checkName(service.getServiceID())) {
                continue;
            }
            ret.get(service.getFactoryID()).add(createAndRegisterConfiguration(service.getServiceID(),
                    service.getFactoryID(), attributes, service.getSessionDTOs()));
            serviceNames.add(service.getServiceID());
        }
    }
    return ret;
}

From source file:fastcall.FastCallSNP.java

private void callSNPByChromosomeTest(int currentChr, String vcfDirS, String referenceFileS, String chrSeq,
        int startPos, int endPos, int binSize) {
    int regionStart = startPos;
    int regionEnd = endPos;

    String outfileS = "chr" + FStringUtils.getNDigitNumber(3, currentChr) + ".VCF.txt";
    outfileS = new File(vcfDirS, outfileS).getAbsolutePath();
    int[][] binBound = this.creatBins(currentChr, binSize, regionStart, regionEnd);
    try {//from   ww w.  j  a v a 2s. com
        HashMap<String, BufferedReader> bamPathPileupReaderMap = this.getBamPathPileupReaderMap();
        ConcurrentHashMap<BufferedReader, List<String>> readerRemainderMap = this
                .getReaderRemainderMap(bamPathPileupReaderMap);
        BufferedWriter bw = IoUtils.getTextWriter(outfileS);
        bw.write(this.getAnnotation(referenceFileS));
        bw.write(this.getVCFHeader());
        bw.newLine();
        for (int i = 0; i < binBound.length; i++) {
            long startTimePoint = System.nanoTime();
            int binStart = binBound[i][0];
            int binEnd = binBound[i][1];
            ConcurrentHashMap<String, List<List<String>>> bamPileupResultMap = this.getBamPileupResultMap(
                    currentChr, binStart, binEnd, bamPathPileupReaderMap, readerRemainderMap);
            StringBuilder[][] baseSb = this.getPopulateBaseBuilder(binStart, binEnd);
            int[][] depth = this.getPopulatedDepthArray(binStart, binEnd);
            this.fillDepthAndBase(bamPileupResultMap, baseSb, depth, binStart);
            String[][] base = this.getBaseMatrix(baseSb);
            ArrayList<Integer> positionList = this.getPositionList(binStart, binEnd);
            ConcurrentHashMap<Integer, String> posVCFMap = new ConcurrentHashMap(
                    (int) ((binEnd - binStart + 1) * 1.5));
            this.calculateVCF(posVCFMap, positionList, currentChr, binStart, chrSeq, depth, base);
            for (int j = 0; j < positionList.size(); j++) {
                String vcfStr = posVCFMap.get(positionList.get(j));
                if (vcfStr == null)
                    continue;
                bw.write(vcfStr);
                bw.newLine();
            }
            StringBuilder sb = new StringBuilder();
            sb.append("Bin from ").append(binStart).append(" to ").append(binEnd).append(" is finished. Took ")
                    .append(Benchmark.getTimeSpanSeconds(startTimePoint)).append(" seconds. Memory used: ")
                    .append(Benchmark.getUsedMemoryGb()).append(" Gb");
            System.out.println(sb.toString());
        }
        bw.flush();
        bw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(
            "Chromosome " + String.valueOf(currentChr) + " is finished. File written to " + outfileS + "\n");
}

From source file:fastcall.FastCallSNP.java

private void callSNPByChromosome(int currentChr, String referenceFileS, String vcfDirS) {
    int chrIndex = Arrays.binarySearch(chroms, currentChr);
    String chrSeq = genomeFa.getSeq(chrIndex).toUpperCase();
    int regionStart = 1;
    int regionEnd = chrSeq.length();
    this.performPileup(currentChr, regionStart, regionEnd, referenceFileS);
    String outfileS = "chr" + FStringUtils.getNDigitNumber(3, currentChr) + ".VCF.txt";
    outfileS = new File(vcfDirS, outfileS).getAbsolutePath();
    int[][] binBound = this.creatBins(currentChr, binSize, regionStart, regionEnd);
    try {/*from   w  w  w  .j a  v a2  s .  com*/
        HashMap<String, BufferedReader> bamPathPileupReaderMap = this.getBamPathPileupReaderMap();
        ConcurrentHashMap<BufferedReader, List<String>> readerRemainderMap = this
                .getReaderRemainderMap(bamPathPileupReaderMap);
        BufferedWriter bw = IoUtils.getTextWriter(outfileS);
        bw.write(this.getAnnotation(referenceFileS));
        bw.write(this.getVCFHeader());
        bw.newLine();
        for (int i = 0; i < binBound.length; i++) {
            long startTimePoint = System.nanoTime();
            int binStart = binBound[i][0];
            int binEnd = binBound[i][1];
            ConcurrentHashMap<String, List<List<String>>> bamPileupResultMap = this.getBamPileupResultMap(
                    currentChr, binStart, binEnd, bamPathPileupReaderMap, readerRemainderMap);
            StringBuilder[][] baseSb = this.getPopulateBaseBuilder(binStart, binEnd);
            int[][] depth = this.getPopulatedDepthArray(binStart, binEnd);
            this.fillDepthAndBase(bamPileupResultMap, baseSb, depth, binStart);
            String[][] base = this.getBaseMatrix(baseSb);
            ArrayList<Integer> positionList = this.getPositionList(binStart, binEnd);
            ConcurrentHashMap<Integer, String> posVCFMap = new ConcurrentHashMap(
                    (int) ((binEnd - binStart + 1) * 1.5));
            this.calculateVCF(posVCFMap, positionList, currentChr, binStart, chrSeq, depth, base);
            for (int j = 0; j < positionList.size(); j++) {
                String vcfStr = posVCFMap.get(positionList.get(j));
                if (vcfStr == null)
                    continue;
                bw.write(vcfStr);
                bw.newLine();
            }
            StringBuilder sb = new StringBuilder();
            sb.append("Bin from ").append(binStart).append(" to ").append(binEnd).append(" is finished. Took ")
                    .append(Benchmark.getTimeSpanSeconds(startTimePoint)).append(" seconds. Memory used: ")
                    .append(Benchmark.getUsedMemoryGb()).append(" Gb");
            System.out.println(sb.toString());
        }
        bw.flush();
        bw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(
            "Chromosome " + String.valueOf(currentChr) + " is finished. File written to " + outfileS + "\n");
}