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.seedstack.mqtt.internal.MqttPluginTest.java

/**
 * Test method for/*ww  w.j a v  a2 s .c o m*/
 * {@link org.seedstack.mqtt.internal.MqttPlugin#init(io.nuun.kernel.api.plugin.context.InitContext)}
 * .
 */
@Test(expected = SeedException.class)
public void testInitWithRejectHandlerAndNoClient(@Mocked final Configuration configuration) {
    final String clientName = "clientOK1";
    final String clientName2 = "clientNOK";
    final String[] clients = { clientName };
    final Collection<Class<?>> classes = new ArrayList<Class<?>>();
    classes.add(MyRejectHandler.class);
    final Collection<Class<?>> listenerClasses = new ArrayList<Class<?>>();
    final Collection<Class<?>> publisherClasses = new ArrayList<Class<?>>();
    MqttPlugin plugin = new MqttPlugin();
    new Expectations() {
        {
            application.getConfiguration();
            result = configuration;

            configuration.subset(anyString);
            result = configuration;

            configuration.getStringArray(CONNECTION_CLIENTS);
            result = clients;

            application.substituteWithConfiguration(clientName);
            result = clientName2;

            configuration.getString(BROKER_URI);
            result = "xx";

            specs.get(any);
            result = listenerClasses;
            result = publisherClasses;
            result = classes;

        }
    };

    new MockUp<MqttClient>() {
        @Mock
        public void $init(String serverURI, String clientId) throws MqttException {
        }

    };

    plugin.init(initContext);

    ConcurrentHashMap<String, MqttClientDefinition> defs = Deencapsulation.getField(plugin,
            "mqttClientDefinitions");
    Assertions.assertThat(defs).isNotEmpty();
    MqttClientDefinition clientDef = defs.get(clientName);
    Assertions.assertThat(clientDef.getPoolDefinition()).isNotNull();
    Assertions.assertThat(clientDef.getPoolDefinition().getRejectHandlerClass())
            .isEqualTo(MyRejectHandler.class);
}

From source file:org.seedstack.mqtt.internal.MqttPluginTest.java

/**
 * Test method for/*from  w w w .  j  a  v a  2 s  . c om*/
 * {@link org.seedstack.mqtt.internal.MqttPlugin#init(io.nuun.kernel.api.plugin.context.InitContext)}
 * .
 */
@Test(expected = SeedException.class)
public void testInitWithPublisherAndNoClient(@Mocked final Configuration configuration) {
    final String clientName = "clientOK1";
    final String clientName2 = "clientNOK";
    final String[] clients = { clientName };
    final Collection<Class<?>> listenerClasses = new ArrayList<Class<?>>();
    final Collection<Class<?>> rejectedHandlers = new ArrayList<Class<?>>();
    final Collection<Class<?>> classes = new ArrayList<Class<?>>();
    classes.add(PublishHandler.class);
    MqttPlugin plugin = new MqttPlugin();
    new Expectations() {
        {
            application.getConfiguration();
            result = configuration;

            configuration.subset(anyString);
            result = configuration;

            application.substituteWithConfiguration(clientName);
            result = clientName2;

            configuration.getStringArray(CONNECTION_CLIENTS);
            result = clients;

            configuration.getString(BROKER_URI);
            result = "xx";

            specs.get(any);
            result = listenerClasses;
            result = classes;
            result = rejectedHandlers;

        }
    };

    new MockUp<MqttClient>() {
        @Mock
        public void $init(String serverURI, String clientId) throws MqttException {
        }

    };

    plugin.init(initContext);

    ConcurrentHashMap<String, MqttClientDefinition> defs = Deencapsulation.getField(plugin,
            "mqttClientDefinitions");
    Assertions.assertThat(defs).isNotEmpty();
    MqttClientDefinition clientDef = defs.get("clientOK1");
    Assertions.assertThat(clientDef.getPublisherDefinition()).isNotNull();
    Assertions.assertThat(clientDef.getPublisherDefinition().getPublisherClass())
            .isEqualTo(PublishHandler.class);

}

From source file:edu.berkeley.compbio.phyloutils.HugenholtzTaxonomyService.java

@NotNull
public synchronized Integer findTaxidByName(String name) throws NoSuchNodeException {
    ConcurrentHashMap<String, Integer> nameToUniqueIdMap = (ConcurrentHashMap<String, Integer>) nameToUniqueIdMapStub
            .get();/*from w ww.j a  va2  s .c  o m*/

    Integer result = nameToUniqueIdMap.get(name);

    if (result == null) {
        BasicRootedPhylogeny<Integer> theIntegerTree = (BasicRootedPhylogeny<Integer>) theIntegerTreeStub.get();

        try {
            Integer id = new Integer(name);
            theIntegerTree.getNode(id); // throws exception if not present // intToNodeMap.containsKey(id))
            result = id;
        } catch (NumberFormatException e) {
            // ok, try the next thing
        } catch (NoSuchNodeException e) {
            // ok, try the next thing
        }

        if (result == null) {
            if (!name.contains(";")) {
                try {
                    BasicRootedPhylogeny<Integer> bTree = findSubtreeByNameRelaxed(name);
                    result = bTree.getShallowestLeaf();
                } catch (NoSuchNodeException e) {
                    result = NO_VALID_ID;
                }

                //result = getUniqueNodeForName(name);

                // REVIEW for our present purposes we always want the worst-case node; but in other contexts that may be the wrong thing to do

                //   result = getDeepestNodeForName(name);
            } else {
                result = getUniqueNodeForMultilevelName(name.split("[; ]+"));
            }
        }
        nameToUniqueIdMap.put(name, result);
    }

    if (result.equals(NO_VALID_ID)) {
        throw new NoSuchNodeException("Taxon not found: " + name);
    }

    return result;
}

From source file:com.thoughtworks.go.server.service.PipelineConfigServicePerformanceTest.java

private void run(Runnable runnable, int numberOfRequests, final ConcurrentHashMap<String, Boolean> results)
        throws InterruptedException {
    Boolean finalResult = true;/*www . j a  va2s. com*/
    LOGGER.info("Tests start now!");
    final ArrayList<Thread> threads = new ArrayList<>();
    for (int i = 0; i < numberOfRequests; i++) {
        Thread t = new Thread(runnable, "pipeline" + i);
        threads.add(t);
    }
    for (Thread t : threads) {
        Thread.sleep(1000 * (new Random().nextInt(3) + 1));
        t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                LOGGER.error("Exception " + e + " from thread " + t);
                results.put(t.getName(), false);
            }
        });
        t.start();
    }
    for (Thread t : threads) {
        int i = threads.indexOf(t);
        if (i == (numberOfRequests - 1)) {
            //                takeHeapDump(dumpDir, i);
        }
        t.join();
    }
    for (String threadId : results.keySet()) {
        finalResult = results.get(threadId) && finalResult;
    }
    assertThat(finalResult, is(true));
}

From source file:com.chen.emailsync.SyncManager.java

/**
 * Sent by services indicating that their thread is finished; action depends on the exitStatus
 * of the service./*  w  w  w.  ja  v a2 s  . co m*/
 *
 * @param svc the service that is finished
 */
static public void done(AbstractSyncService svc) {
    SyncManager ssm = INSTANCE;
    if (ssm == null)
        return;
    synchronized (sSyncLock) {
        long mailboxId = svc.mMailboxId;
        // If we're no longer the syncing thread for the mailbox, just return
        if (!ssm.isRunningInServiceThread(mailboxId)) {
            return;
        }
        ssm.releaseMailbox(mailboxId);
        ssm.setMailboxSyncStatus(mailboxId, EmailContent.SYNC_STATUS_NONE);

        ConcurrentHashMap<Long, SyncError> errorMap = ssm.mSyncErrorMap;
        SyncError syncError = errorMap.get(mailboxId);

        int exitStatus = svc.mExitStatus;
        Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId);
        if (m == null)
            return;

        if (exitStatus != AbstractSyncService.EXIT_LOGIN_FAILURE) {
            long accountId = m.mAccountKey;
            Account account = Account.restoreAccountWithId(ssm, accountId);
            if (account == null)
                return;
            if (ssm.releaseSyncHolds(ssm, AbstractSyncService.EXIT_LOGIN_FAILURE, account)) {
                new AccountServiceProxy(ssm).notifyLoginSucceeded(accountId);
            }
        }

        int lastResult = EmailContent.LAST_SYNC_RESULT_SUCCESS;
        // For error states, whether the error is fatal (won't automatically be retried)
        boolean errorIsFatal = true;
        try {
            switch (exitStatus) {
            case AbstractSyncService.EXIT_DONE:
                if (svc.hasPendingRequests()) {
                    // TODO Handle this case
                }
                errorMap.remove(mailboxId);
                // If we've had a successful sync, clear the shutdown count
                synchronized (SyncManager.class) {
                    sClientConnectionManagerShutdownCount = 0;
                }
                // Leave now; other statuses are errors
                return;
            // I/O errors get retried at increasing intervals
            case AbstractSyncService.EXIT_IO_ERROR:
                if (syncError != null) {
                    syncError.escalate();
                    log(m.mDisplayName + " held for " + (syncError.holdDelay / 1000) + "s");
                    return;
                } else {
                    log(m.mDisplayName + " added to syncErrorMap, hold for 15s");
                }
                lastResult = EmailContent.LAST_SYNC_RESULT_CONNECTION_ERROR;
                errorIsFatal = false;
                break;
            // These errors are not retried automatically
            case AbstractSyncService.EXIT_LOGIN_FAILURE:
                new AccountServiceProxy(ssm).notifyLoginFailed(m.mAccountKey, svc.mExitReason);
                lastResult = EmailContent.LAST_SYNC_RESULT_AUTH_ERROR;
                break;
            case AbstractSyncService.EXIT_SECURITY_FAILURE:
            case AbstractSyncService.EXIT_ACCESS_DENIED:
                lastResult = EmailContent.LAST_SYNC_RESULT_SECURITY_ERROR;
                break;
            case AbstractSyncService.EXIT_EXCEPTION:
                lastResult = EmailContent.LAST_SYNC_RESULT_INTERNAL_ERROR;
                break;
            }
            // Add this box to the error map
            errorMap.put(mailboxId, ssm.new SyncError(exitStatus, errorIsFatal));
        } finally {
            // Always set the last result
            ssm.setMailboxLastSyncResult(mailboxId, lastResult);
            kick("sync completed");
        }
    }
}

From source file:fastcall.FastCallSNP.java

private ConcurrentHashMap<String, List<List<String>>> getBamPileupResultMap(int currentChr, int binStart,
        int binEnd, HashMap<String, BufferedReader> bamPathPileupReaderMap,
        ConcurrentHashMap<BufferedReader, List<String>> readerRemainderMap) {
    ArrayList<String> empty = new ArrayList();
    ConcurrentHashMap<String, List<List<String>>> bamPileupMap = new ConcurrentHashMap(2048);
    List<String> bamList = Arrays.asList(bamPaths);
    bamList.parallelStream().forEach(bamFileS -> {
        ArrayList<List<String>> lineList = new ArrayList();
        BufferedReader br = bamPathPileupReaderMap.get(bamFileS);
        List<String> remainder = readerRemainderMap.get(br);
        boolean flag = false;
        if (remainder.size() == 0) {
            String temp = null;/*from  ww  w  .  j  a  va2  s  .c  om*/
            try {
                temp = br.readLine();
            } catch (Exception e) {
            }
            if (temp != null) {
                List<String> split = FStringUtils.fastSplit(temp, "\t");
                int currentPos = Integer.valueOf(split.get(1));
                if (currentPos > binEnd) {
                    readerRemainderMap.put(br, split);
                } else {
                    lineList.add(split);
                    flag = true;
                }
            }
        } else {
            int currentPos = Integer.valueOf(remainder.get(1));
            if (currentPos <= binEnd) {
                lineList.add(remainder);
                flag = true;
                readerRemainderMap.put(br, empty);
            }
        }
        if (flag == true) {
            try {
                String temp;
                while ((temp = br.readLine()) != null) {
                    List<String> split = FStringUtils.fastSplit(temp, "\t");
                    int currentPos = Integer.valueOf(split.get(1));
                    if (currentPos < binEnd) {
                        lineList.add(split);
                    } else if (currentPos == binEnd) {
                        lineList.add(split);
                        readerRemainderMap.put(br, empty);
                        break;
                    } else {
                        readerRemainderMap.put(br, split);
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        bamPileupMap.put(bamFileS, lineList);
    });
    return bamPileupMap;
}

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

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    try {/*  w  ww  .ja  v  a 2s.co m*/
        this.serviceList = serviceList;
        this.serverConfig = serverConfig;
        this.mbeanServer = mbeanServer;
        this.scanDirectory = serverConfig.getDeploydirectory();
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {

                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/executorservices-config.xml")));
                } catch (Exception e) {
                    log.error("Could not able to load config xml rules ./config/executorservices-config.xml",
                            e);
                    //e.printStackTrace();
                }

            }
        });
        serverdigester = serverdigesterLoader.newDigester();
    } catch (Exception e1) {
        log.error("Could not create digester executorservices-config.xml", e1);
        //e1.printStackTrace();
    }
    try {
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {

                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/messagingclass-rules.xml")));
                } catch (FileNotFoundException e) {
                    log.error("Could not able to load config xml rules ./config/messagingclass-rules.xml", e);
                    //e.printStackTrace();
                }

            }
        });
        messagedigester = serverdigesterLoader.newDigester();
        DigesterLoader messagingdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {
                // TODO Auto-generated method stub
                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/messagingconfig-rules.xml")));
                } catch (Exception e) {
                    log.error("Could not able to load xml config file ./config/messagingclass-rules.xml", e);
                    e.printStackTrace();
                }

            }
        });
        Digester messagingdigester = messagingdigesterLoader.newDigester();
        messagingElem = (MessagingElem) messagingdigester
                .parse(new InputSource(new FileInputStream("./config/messaging.xml")));
        synchronized (messagingElem) {
            ConcurrentHashMap randomQueue = messagingElem.randomQueue;
            Set<String> randomQueueSet = randomQueue.keySet();
            Iterator<String> ite = randomQueueSet.iterator();
            while (ite.hasNext()) {
                Queue queue = (Queue) randomQueue.get(ite.next());
                ConcurrentHashMap randomqueuemap = (ConcurrentHashMap) messagingClassMap.get("RandomQueue");
                if (randomqueuemap == null) {
                    randomqueuemap = new ConcurrentHashMap();
                    messagingClassMap.put("RandomQueue", randomqueuemap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) randomqueuemap
                        .get(queue.getQueuename());
                if (randomqueuelist == null)
                    randomqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
            }

            ConcurrentHashMap roundrobinQueue = messagingElem.roundrobinQueue;
            Set<String> roundrobinQueueSet = roundrobinQueue.keySet();
            ite = roundrobinQueueSet.iterator();
            while (ite.hasNext()) {
                Queue queue = (Queue) roundrobinQueue.get(ite.next());
                ConcurrentHashMap roundrobinqueuemap = (ConcurrentHashMap) messagingClassMap
                        .get("RoundRobinQueue");
                if (roundrobinqueuemap == null) {
                    roundrobinqueuemap = new ConcurrentHashMap();
                    messagingClassMap.put("RoundRobinQueue", roundrobinqueuemap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) roundrobinqueuemap
                        .get(queue.getQueuename());
                if (randomqueuelist == null)
                    roundrobinqueuemap.put(queue.getQueuename(), new CopyOnWriteArrayList());
            }

            ConcurrentHashMap topicMap = messagingElem.topicMap;
            Set<String> topicSet = topicMap.keySet();
            Iterator<String> iter = topicSet.iterator();
            while (iter.hasNext()) {
                Topic topic = (Topic) topicMap.get(iter.next());
                ConcurrentHashMap topicmap = (ConcurrentHashMap) messagingClassMap.get("Topic");
                if (topicmap == null) {
                    topicmap = new ConcurrentHashMap();
                    messagingClassMap.put("Topic", topicmap);
                }
                CopyOnWriteArrayList randomqueuelist = (CopyOnWriteArrayList) topicmap
                        .get(topic.getTopicname());
                if (randomqueuelist == null)
                    topicmap.put(topic.getTopicname(), new CopyOnWriteArrayList());
            }
            //log.info(messagingClassMap);
        }
    } catch (Exception e1) {
        log.error("", e1);
        //e1.printStackTrace();
    }

    try {
        DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

            protected void loadRules() {

                try {
                    loadXMLRules(new InputSource(new FileInputStream("./config/webxml-rules.xml")));
                } catch (FileNotFoundException e) {
                    log.error("could not able to load xml config rules ./config/webxml-rules.xml", e);
                    //e.printStackTrace();
                }

            }
        });
        webxmldigester = serverdigesterLoader.newDigester();
    } catch (Exception ex) {
        log.error("could not able to create web.xml digester", ex);
        // ex.printStackTrace();
    }
    log.info("initialized");
}

From source file:fastcall.FastCallSNP.java

private void fillDepthAndBase(ConcurrentHashMap<String, List<List<String>>> bamPileupResultMap,
        StringBuilder[][] baseSb, int[][] depth, int startPos) {
    Set<Map.Entry<String, String[]>> entries = this.taxaBamPathMap.entrySet();
    entries.parallelStream().forEach(e -> {
        String taxa = e.getKey();
        int taxaIndex = Arrays.binarySearch(this.taxaNames, taxa);
        String[] bams = e.getValue();

        int count = 0;
        String b = null;//from   w w  w .  j  a va2  s.co  m
        try {
            for (int i = 0; i < bams.length; i++) {
                List<List<String>> lines = bamPileupResultMap.get(bams[i]);
                count = lines.size();
                b = bams[i];
                for (int j = 0; j < lines.size(); j++) {
                    List<String> split = lines.get(j);
                    if (split.get(2).startsWith("N") || split.get(2).startsWith("n"))
                        continue;
                    int siteIndex = Integer.valueOf(split.get(1)) - startPos;
                    depth[siteIndex][taxaIndex] += Integer.valueOf(split.get(3));
                    baseSb[siteIndex][taxaIndex].append(split.get(4));
                }
            }
        } catch (Exception ee) {
            System.out.println(b);
            System.out.println(count);
            ee.printStackTrace();
            System.exit(1);
        }
    });
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void locationMap() throws Exception {
    ConcurrentHashMap<String, String> locationMap = new ConcurrentHashMap<String, String>();
    CrailUtils.parseMap(CrailConstants.LOCATION_MAP, locationMap);

    System.out.println("Parsing locationMap " + CrailConstants.LOCATION_MAP);
    for (String key : locationMap.keySet()) {
        System.out.println("key " + key + ", value " + locationMap.get(key));
    }//from w  ww.ja  v a2 s . c  om
}

From source file:org.wso2.carbon.event.processor.core.internal.CarbonEventProcessorService.java

/**
 * Starts an execution plan runtime for the given (valid) execution plan.
 *
 * @param executionPlan Execution plan. It is assumed that the execution plan is a valid one when reaching this function.
 * @param isEditable    whether the execution plan is editable.
 * @throws ExecutionPlanConfigurationException
 *///from   w ww .  j a  v  a 2 s  . com
public void addExecutionPlan(String executionPlan, boolean isEditable)
        throws ExecutionPlanConfigurationException {

    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    SiddhiManager siddhiManager = EventProcessorValueHolder.getSiddhiManager();
    EventProcessorHelper.loadDataSourceConfiguration(siddhiManager);
    ExecutionPlanRuntime executionPlanRuntime = null;
    org.wso2.siddhi.query.api.ExecutionPlan parsedExecutionPlan = SiddhiCompiler.parse(executionPlan);

    ExecutionPlanConfiguration executionPlanConfiguration = new ExecutionPlanConfiguration();
    executionPlanConfiguration.setExecutionPlan(executionPlan);

    String executionPlanName = AnnotationHelper
            .getAnnotationElement(EventProcessorConstants.ANNOTATION_NAME_NAME, null,
                    parsedExecutionPlan.getAnnotations())
            .getValue(); //Element is not null since the plan is a valid one.
    executionPlanConfiguration.setName(executionPlanName);

    Element executionPlanDescriptionElement = AnnotationHelper.getAnnotationElement(
            EventProcessorConstants.ANNOTATION_NAME_DESCRIPTION, null, parsedExecutionPlan.getAnnotations());
    if (executionPlanDescriptionElement != null) {
        String executionPlanDescription = executionPlanDescriptionElement.getValue();
        executionPlanConfiguration.setDescription(executionPlanDescription);
    } else {
        executionPlanConfiguration.setDescription("");
    }

    Element isTracingEnabledElement = AnnotationHelper.getAnnotationElement(
            EventProcessorConstants.ANNOTATION_NAME_TRACE, null, parsedExecutionPlan.getAnnotations());
    if (isTracingEnabledElement != null) {
        String isTracingEnabled = isTracingEnabledElement.getValue();
        executionPlanConfiguration.setTracingEnabled(Boolean.valueOf(isTracingEnabled));
    } else {
        executionPlanConfiguration.setTracingEnabled(false);
    }

    Element isStatsEnabledElement = AnnotationHelper.getAnnotationElement(
            EventProcessorConstants.ANNOTATION_NAME_STATISTICS, null, parsedExecutionPlan.getAnnotations());
    if (isStatsEnabledElement != null) {
        String isStatsEnabled = isStatsEnabledElement.getValue();
        executionPlanConfiguration.setStatisticsEnabled(Boolean.valueOf(isStatsEnabled));
    } else {
        executionPlanConfiguration.setStatisticsEnabled(false);
    }
    executionPlanConfiguration.setEditable(isEditable);

    ConcurrentHashMap<String, ExecutionPlan> tenantExecutionPlans = tenantSpecificExecutionPlans.get(tenantId);
    if (tenantExecutionPlans == null) {
        tenantExecutionPlans = new ConcurrentHashMap<String, ExecutionPlan>();
        tenantSpecificExecutionPlans.put(tenantId, tenantExecutionPlans);
    } else if (tenantExecutionPlans.get(executionPlanName) != null) {
        // if an execution plan with the same name already exists, we are not going to override it with this plan.
        throw new ExecutionPlanConfigurationException(
                "Execution plan with the same name already exists. Please remove it and retry.");
    }

    //building Import/Export Map
    Map<String, String> importsMap = new HashMap<String, String>(); //<SiddhiStreamName, StreamID>
    Map<String, String> exportsMap = new HashMap<String, String>(); //<SiddhiStreamName, StreamID>
    for (Map.Entry<String, org.wso2.siddhi.query.api.definition.StreamDefinition> entry : parsedExecutionPlan
            .getStreamDefinitionMap().entrySet()) {

        String siddhiStreamName = entry.getKey();
        Element importElement = AnnotationHelper.getAnnotationElement(EventProcessorConstants.ANNOTATION_IMPORT,
                null, entry.getValue().getAnnotations());
        Element exportElement = AnnotationHelper.getAnnotationElement(EventProcessorConstants.ANNOTATION_EXPORT,
                null, entry.getValue().getAnnotations());

        if (importElement != null) {
            String streamId = importElement.getValue();
            importsMap.put(siddhiStreamName, streamId);
            String[] streamIdComponents = streamId.split(EventProcessorConstants.STREAM_SEPARATOR);
            String streamName = streamIdComponents[0];
            String streamVersion = streamIdComponents[1];
            executionPlanConfiguration
                    .addImportedStream(new StreamConfiguration(streamName, streamVersion, siddhiStreamName));
        }
        if (exportElement != null) {
            String streamId = exportElement.getValue();
            exportsMap.put(siddhiStreamName, streamId);
            String[] streamIdComponents = streamId.split(EventProcessorConstants.STREAM_SEPARATOR);
            String streamName = streamIdComponents[0];
            String streamVersion = streamIdComponents[1];
            executionPlanConfiguration
                    .addExportedStream(new StreamConfiguration(streamName, streamVersion, siddhiStreamName));
        }
    }

    Map<String, InputHandler> inputHandlerMap = new ConcurrentHashMap<String, InputHandler>(importsMap.size());

    List<String> importDefinitions;
    List<String> exportDefinitions;

    importDefinitions = new ArrayList<String>(executionPlanConfiguration.getImportedStreams().size());
    for (StreamConfiguration importedStreamConfiguration : executionPlanConfiguration.getImportedStreams()) {
        StreamDefinition streamDefinition;
        try {
            streamDefinition = EventProcessorValueHolder.getEventStreamService()
                    .getStreamDefinition(importedStreamConfiguration.getStreamId());
            importDefinitions.add(EventProcessorUtil.getDefinitionString(streamDefinition,
                    importedStreamConfiguration.getSiddhiStreamName()));
        } catch (EventStreamConfigurationException e) {
            //ignored as this will not happen
        }
    }
    exportDefinitions = new ArrayList<String>(executionPlanConfiguration.getExportedStreams().size());
    for (StreamConfiguration exportedStreamConfiguration : executionPlanConfiguration.getExportedStreams()) {
        StreamDefinition streamDefinition;
        try {
            streamDefinition = EventProcessorValueHolder.getEventStreamService()
                    .getStreamDefinition(exportedStreamConfiguration.getStreamId());
            exportDefinitions.add(EventProcessorUtil.getDefinitionString(streamDefinition,
                    exportedStreamConfiguration.getSiddhiStreamName()));
        } catch (EventStreamConfigurationException e) {
            //ignored as this will not happen
        }
    }

    /**
     * Section to handle query deployment
     */
    DistributedConfiguration stormDeploymentConfiguration = EventProcessorValueHolder
            .getStormDeploymentConfiguration();

    try {
        executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan);
        executionPlanRuntime.handleExceptionWith(new ExceptionHandler<Object>() {
            @Override
            public void handleEventException(Throwable throwable, long l, Object o) {
                log.error(throwable.getMessage(), throwable);
                if (log.isDebugEnabled()) {
                    log.debug("Event dropped by distruptor due to exception : " + o);
                }
            }

            @Override
            public void handleOnStartException(Throwable throwable) {
                log.error("Exception when starting the distruptor process ", throwable);
            }

            @Override
            public void handleOnShutdownException(Throwable throwable) {
                log.error("Exception when stopping the distruptor process ", throwable);
            }
        });
    } catch (Exception e) {
        throw new ExecutionPlanConfigurationException("Invalid query specified, " + e.getMessage(), e);
    }

    if (managementInfo.getMode() == Mode.Distributed) {
        if (stormDeploymentConfiguration != null && stormDeploymentConfiguration.isManagerNode()
                && EventProcessorValueHolder.getStormManagerServer().isStormCoordinator()) {
            try {
                EventProcessorValueHolder.getStormTopologyManager().submitTopology(executionPlanConfiguration,
                        importDefinitions, exportDefinitions, tenantId,
                        stormDeploymentConfiguration.getTopologySubmitRetryInterval());
            } catch (StormDeploymentException e) {
                throw new ExecutionPlanConfigurationException(
                        "Invalid distributed query specified, " + e.getMessage(), e);
            }
        }
    }

    for (Map.Entry<String, String> entry : importsMap.entrySet()) {
        inputHandlerMap.put(entry.getValue(), executionPlanRuntime.getInputHandler(entry.getKey()));
    }

    //Assumption: executionPlan is valid
    ExecutionPlan processorExecutionPlan = new ExecutionPlan(executionPlanName, executionPlanRuntime,
            executionPlanConfiguration);
    tenantExecutionPlans.put(executionPlanName, processorExecutionPlan);

    boolean isDistributedEnabledAndIsWorker = (managementInfo.getMode() == Mode.Distributed
            && stormDeploymentConfiguration != null && stormDeploymentConfiguration.isWorkerNode());

    StormStatusMonitor stormStatusMonitor = null;
    if (isDistributedEnabledAndIsWorker) {
        StormStatusMapListener mapListener = null;
        try {
            stormStatusMonitor = new StormStatusMonitor(tenantId, executionPlanName, importsMap.size());
            mapListener = new StormStatusMapListener(executionPlanName, tenantId, stormStatusMonitor);
        } catch (DeploymentStatusMonitorException e) {
            log.error("Failed to initialize map listener. Reason: " + e.getMessage(), e);
        }
        processorExecutionPlan.setStormStatusMonitor(stormStatusMonitor);
        processorExecutionPlan.setStormStatusMapListener(mapListener);
    }

    /**
     * Section to configure outputs
     */
    SiddhiStormOutputEventListener stormOutputListener = null;
    if (managementInfo.getMode() == Mode.Distributed
            && managementInfo.getDistributedConfiguration().isWorkerNode()) {
        stormOutputListener = new SiddhiStormOutputEventListener(executionPlanConfiguration, tenantId,
                stormDeploymentConfiguration, stormStatusMonitor);
        processorExecutionPlan.addStormOutputListener(stormOutputListener);
    }

    for (Map.Entry<String, String> entry : exportsMap.entrySet()) {

        SiddhiOutputStreamListener streamCallback;
        try {
            streamCallback = new SiddhiOutputStreamListener(entry.getKey(), entry.getValue(),
                    executionPlanConfiguration, tenantId);
        } catch (EventStreamConfigurationException e) {
            throw new ExecutionPlanConfigurationException(e.getMessage(), e);
        }

        try {
            EventProcessorValueHolder.getEventStreamService().subscribe(streamCallback);
        } catch (EventStreamConfigurationException e) {
            //ignored as this will never happen
        }

        if (managementInfo.getMode() == Mode.Distributed && stormDeploymentConfiguration != null
                && stormDeploymentConfiguration.isWorkerNode()) {
            try {
                StreamDefinition databridgeDefinition = EventProcessorValueHolder.getEventStreamService()
                        .getStreamDefinition(entry.getValue());
                org.wso2.siddhi.query.api.definition.StreamDefinition siddhiStreamDefinition = EventProcessorUtil
                        .convertToSiddhiStreamDefinition(databridgeDefinition, entry.getKey());
                stormOutputListener.registerOutputStreamListener(siddhiStreamDefinition, streamCallback);
            } catch (EventStreamConfigurationException e) {
                throw new ExecutionPlanConfigurationException(e.getMessage(), e);
            }
        } else {
            executionPlanRuntime.addCallback(entry.getKey(), streamCallback);
        }

        processorExecutionPlan.addProducer(streamCallback);
    }

    /**
     * Section to configure inputs
     */

    List<AbstractSiddhiInputEventDispatcher> inputEventDispatchers = new ArrayList<>();
    for (Map.Entry<String, String> entry : importsMap.entrySet()) {
        InputHandler inputHandler = inputHandlerMap.get(entry.getValue());

        AbstractSiddhiInputEventDispatcher eventDispatcher;
        if (isDistributedEnabledAndIsWorker) {
            StreamDefinition streamDefinition = null;
            try {
                streamDefinition = EventProcessorValueHolder.getEventStreamService()
                        .getStreamDefinition(entry.getValue());
            } catch (EventStreamConfigurationException e) {
                // Ignore as this would never happen
            }
            eventDispatcher = new SiddhiStormInputEventDispatcher(streamDefinition, entry.getKey(),
                    executionPlanConfiguration, tenantId, stormDeploymentConfiguration, stormStatusMonitor);
        } else {
            eventDispatcher = new SiddhiInputEventDispatcher(entry.getValue(), inputHandler,
                    executionPlanConfiguration, tenantId);
        }
        inputEventDispatchers.add(eventDispatcher);

    }

    if (executionPlanRuntime != null) {
        executionPlanRuntime.start();
    }

    for (AbstractSiddhiInputEventDispatcher eventDispatcher : inputEventDispatchers) {
        try {
            EventProcessorValueHolder.getEventStreamService().subscribe(eventDispatcher);
            processorExecutionPlan.addConsumer(eventDispatcher);
        } catch (EventStreamConfigurationException e) {
            //ignored as this will never happen
        }
    }

    if (EventProcessorValueHolder.getPersistenceConfiguration() != null && managementInfo.getMode() == Mode.HA
            && managementInfo.getHaConfiguration().isActive()) {
        executionPlanRuntime.restoreLastRevision();
    }

}