Example usage for java.util.concurrent Executors newSingleThreadExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadExecutor.

Prototype

public static ExecutorService newSingleThreadExecutor() 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue.

Usage

From source file:org.simbrain.plot.projection.ProjectionGui.java

/**
 * Construct the Projection GUI.//from w  w  w. jav  a 2s .c om
 */
public ProjectionGui(final GenericFrame frame, final ProjectionComponent component) {
    super(frame, component);
    setPreferredSize(new Dimension(500, 400));
    actionManager = new PlotActionManager(this);
    setLayout(new BorderLayout());

    // Generate the graph
    chart = ChartFactory.createScatterPlot("High Dimensional Projection", "Projection X", "Projection Y",
            getWorkspaceComponent().getProjectionModel().getDataset(), PlotOrientation.VERTICAL, false, true,
            false);
    // chart.getXYPlot().getDomainAxis().setRange(-100, 100);
    // chart.getXYPlot().getRangeAxis().setRange(-100, 100);
    chart.getXYPlot().setBackgroundPaint(Color.white);
    chart.getXYPlot().setDomainGridlinePaint(Color.gray);
    chart.getXYPlot().setRangeGridlinePaint(Color.gray);
    chart.getXYPlot().getDomainAxis().setAutoRange(true);
    chart.getXYPlot().getRangeAxis().setAutoRange(true);
    panel = new ChartPanel(chart);

    // Custom render points as dots (not squares) and use custom tooltips
    // that show high-d point
    CustomRenderer renderer = new CustomRenderer();
    chart.getXYPlot().setRenderer(renderer);
    renderer.setSeriesLinesVisible(0, false);
    renderer.setSeriesShape(0, new Ellipse2D.Double(-5, -5, 5, 5));
    CustomToolTipGenerator generator = new CustomToolTipGenerator();
    renderer.setSeriesToolTipGenerator(0, generator);

    // Toolbar
    openBtn.setToolTipText("Open high-dimensional data");
    saveBtn.setToolTipText("Save data");
    projectionList.setMaximumSize(new java.awt.Dimension(200, 100));
    iterateBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getWorkspaceComponent().getProjector().iterate();
            update();
        }
    });
    clearBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getWorkspaceComponent().getWorkspace().stop();
            Executors.newSingleThreadExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    getWorkspaceComponent().clearData();
                }
            });
        }
    });
    playBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (getWorkspaceComponent().getProjectionModel().isRunning()) {
                playBtn.setIcon(ResourceManager.getImageIcon("Stop.png"));
                playBtn.setToolTipText("Stop iterating projection algorithm");
                getWorkspaceComponent().getProjectionModel().setRunning(false);
                Executors.newSingleThreadExecutor().execute(new ProjectionUpdater(getWorkspaceComponent()));
            } else {
                playBtn.setIcon(ResourceManager.getImageIcon("Play.png"));
                playBtn.setToolTipText("Start iterating projection algorithm");
                getWorkspaceComponent().getProjectionModel().setRunning(true);
            }
        }
    });
    prefsBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO (Still working out overall dialog structure).
        }
    });
    randomBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getWorkspaceComponent().getProjector().randomize(100);
        }
    });
    theToolBar.add(projectionList);
    playBtn.setToolTipText("Iterate projection algorithm");
    theToolBar.add(playBtn);
    iterateBtn.setToolTipText("Step projection algorithm");
    theToolBar.add(iterateBtn);
    clearBtn.setToolTipText("Clear current data");
    theToolBar.add(clearBtn);
    randomBtn.setToolTipText("Randomize datapoints");
    theToolBar.add(randomBtn);
    theToolBar.addSeparator();
    warningLabel.setPreferredSize(new Dimension(16, 16));
    warningLabel.setToolTipText("This method works best with more " + "datapoints already added");
    theToolBar.add(warningLabel);
    String stepSizeToolTip = "Scales the amount points are moved on each iteration";
    JLabel stepSizeLabel = new JLabel("Step Size");
    stepSizeLabel.setToolTipText(stepSizeToolTip);
    sammonStepSizePanel.add(stepSizeLabel);
    try {
        sammonStepSize = new JTextField("" + SimbrainPreferences.getDouble("projectorSammonEpsilon"));
    } catch (PropertyNotFoundException e1) {
        e1.printStackTrace();
    }
    sammonStepSize.setColumns(3);
    sammonStepSize.setToolTipText(stepSizeToolTip);
    sammonStepSizePanel.add(sammonStepSize);
    theToolBar.add(sammonStepSizePanel);
    adjustDimension1.setToolTipText("Dimension 1");
    adjustDimension2.setToolTipText("Dimension 2");
    theToolBar.add(adjustDimension1);
    theToolBar.add(adjustDimension2);

    // Help button
    JButton helpButton = new JButton();
    helpButton.setAction(helpAction);

    // Add/Remove dimension buttons
    JButton addButton = new JButton("Add Dimension");
    addButton.setActionCommand("Add");
    addButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getWorkspaceComponent().getProjectionModel().addSource();
        }
    });
    JButton deleteButton = new JButton("Remove Dimension");
    deleteButton.setActionCommand("Delete");
    deleteButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            getWorkspaceComponent().getProjectionModel().removeSource();
        }
    });

    // Button Panel
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(helpButton);
    buttonPanel.add(addButton);
    buttonPanel.add(deleteButton);

    // Setup Menu Bar
    createAttachMenuBar();

    // Status Bar
    statusBar.add(pointsLabel);
    statusBar.add(dimsLabel);
    errorBar.add(errorLabel);

    // Bottom panel
    bottomPanel.add("North", buttonPanel);
    JPanel southPanel = new JPanel();
    southPanel.add(errorBar);
    southPanel.add(statusBar);
    bottomPanel.add("South", southPanel);

    // Put all panels together
    add("North", theToolBar);
    add("Center", panel);
    add("South", bottomPanel);

    // Other initialization
    initializeComboBoxes();
    addListeners();
    updateToolBar();
    update();

}

From source file:com.opengamma.engine.cache.BerkeleyDBValueIdentifierMapTest.java

@Test(timeOut = 30000)
public void interruptThread() throws Throwable {
    final ExecutorService threads = Executors.newSingleThreadExecutor();
    try {//from   w  w w. j a  v a 2 s .c o m
        final Thread main = Thread.currentThread();
        final Runnable interrupter = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    main.interrupt();
                } catch (InterruptedException e) {
                    throw new OpenGammaRuntimeException("Interrupted", e);
                }
            }
        };
        threads.submit(interrupter);
        int count = 0;
        do {
            try {
                getPerformanceTest();
            } catch (OpenGammaRuntimeException e) {
                assertEquals("Interrupted", e.getMessage());
                count++;
                if (count <= 5) {
                    threads.submit(interrupter);
                } else {
                    break;
                }
            }
        } while (true);
    } finally {
        threads.shutdown();
        Thread.interrupted();
        threads.awaitTermination(5, TimeUnit.SECONDS);
    }
}

From source file:hudson.plugins.downstream_ext.DownstreamTrigger.java

public static void executeForProject(AbstractProject<?, ?> project, Runnable run) {
    Executor executor = executors.get(project);
    if (executor == null) {
        executor = Executors.newSingleThreadExecutor();
        Executor old = executors.putIfAbsent(project, executor);
        if (old != null) {
            executor = old;//from   w w w .  j  ava2 s.c o m
        }
    }
    executor.execute(run);
}

From source file:com.echopf.members.ECHOMemberQuery.java

/**
 * Does Logout/*from   ww w .  j  a  v a  2s  .com*/
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the logging-out in a background thread. 
 *              (a synchronous communication)
 * @param callback invoked after the logging-out is completed
 * @param instanceId the reference ID of the instance to which the logged-out member belong
 * @throws ECHOException
 */
protected static void doLogout(final boolean sync, final ResultCallback callback, final String instanceId)
        throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Void> communicator = new Callable<Void>() {

        @Override
        public Void call() throws ECHOException {

            ECHOException exception = null;

            try {
                ECHOQuery.postRequest(instanceId + "/login", new JSONObject());
            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.done(fException);
                        }
                    });
                }

                return null;

            } else {

                if (exception == null)
                    return null;
                throw exception;
            }
        }
    };

    Future<Void> future = executor.submit(communicator);

    if (sync) {
        try {
            future.get();
            return;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }

    return;
}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerTest.java

@Test
@Ignore/*from  www.  j ava  2  s.c om*/
public final void testConcurrency() throws Exception {
    /*
     * To run this concurrency test, you must setup a "reader" channel through the
     * administrator, that routes messages to other channels that will be pruned. Then specify
     * the ids of those channels below.
     */
    final String readerChannelId = "f7158274-8692-4e53-9d17-db732c3346b8";
    ExecutorService executor = Executors.newSingleThreadExecutor();
    TestUtils.startMirthServer(15000);

    DataPruner pruner = new DataPruner();
    pruner.setBlockSize(1);
    pruner.setStrategy(Strategy.INCLUDE_LIST);
    pruner.setRetryCount(0);

    TestUtils.deleteAllMessages(readerChannelId);
    TestUtils.deleteAllMessages("0831345e-bbe0-4d62-8f2d-c65280bd479b");
    TestUtils.deleteAllMessages("b2e28f1b-d867-435a-a5f6-3b33d5261e66");

    // send messages into the test channel on a separate thread
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            EngineController engineController = ControllerFactory.getFactory().createEngineController();
            logger.info("Sending messages");

            for (int i = 0; i < 100000; i++) {
                logger.info("sending message #" + i);
                engineController.dispatchRawMessage(readerChannelId,
                        new RawMessage(TestUtils.TEST_HL7_MESSAGE));
            }

            logger.info("Finished sending messages");
            return null;
        }
    });

    logger.info("Executing pruner");

    // run the pruner while messages are processing
    while (!future.isDone()) {
        pruner.run();
        Thread.sleep(2000);
    }

    logger.info("Test completed");
}

From source file:com.networking.ApiTestActivity.java

public void checkForHeaderPost(View view) {

    ANRequest.PostRequestBuilder postRequestBuilder = AndroidNetworking
            .post(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER);

    postRequestBuilder.addHeaders("token", "1234");

    ANRequest anRequest = postRequestBuilder.setTag(this).setPriority(Priority.LOW)
            .setExecutor(Executors.newSingleThreadExecutor()).build();

    anRequest.setAnalyticsListener(new AnalyticsListener() {
        @Override/*  ww  w .jav  a2  s  .  c  om*/
        public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived,
                boolean isFromCache) {
            Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
            Log.d(TAG, " bytesSent : " + bytesSent);
            Log.d(TAG, " bytesReceived : " + bytesReceived);
            Log.d(TAG, " isFromCache : " + isFromCache);
        }
    });

    anRequest.getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG, "onResponse object : " + response.toString());
            Log.d(TAG,
                    "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
        }

        @Override
        public void onError(ANError error) {
            if (error.getErrorCode() != 0) {
                // received ANError from server
                // error.getErrorCode() - the ANError code from server
                // error.getErrorBody() - the ANError body from server
                // error.getErrorDetail() - just a ANError detail
                Log.d(TAG, "onError errorCode : " + error.getErrorCode());
                Log.d(TAG, "onError errorBody : " + error.getErrorBody());
                Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
            } else {
                // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
            }
        }
    });
}

From source file:com.isoftstone.crawl.template.crawlstate.CrawlState.java

/**
 * ?./*from  w w w. ja va2  s .c  om*/
 *
 * @param dispatchName
 */
public String crawlFull(final String folderName, boolean isDeploy) {
    String rootFolder = Config.getValue(WebtoolConstants.FOLDER_NAME_ROOT);
    String shDir;
    String crawlDir = Config.getValue(WebtoolConstants.KEY_NUTCH_CRAWLDIR);
    String solrURL = Config.getValue(WebtoolConstants.KEY_NUTCH_SOLR_URL);
    String depth = "3";
    final String dispatchName = folderName + WebtoolConstants.DISPATCH_REIDIS_POSTFIX_NORMAL;
    final DispatchVo dispatchVo = RedisOperator.getDispatchResult(dispatchName,
            Constants.DISPATCH_REDIS_DBINDEX);
    boolean userProxy = dispatchVo.isUserProxy();

    if (isDeploy) {
        shDir = Config.getValue(WebtoolConstants.KEY_NUTCH_DEPLOY_NORMAL_SHDIR);
        if (userProxy) {
            shDir = Config.getValue(WebtoolConstants.KEY_NUTCH_DEPLOY_NORMAL_PROXY_SHDIR);
        }
    } else {
        shDir = Config.getValue(WebtoolConstants.KEY_NUTCH_LOCAL_NORMAL_SHDIR);
        if (userProxy) {
            shDir = Config.getValue(WebtoolConstants.KEY_NUTCH_LOCAL_NORMAL_PROXY_SHDIR);
        }
    }

    String folderNameSeed = dispatchName.substring(0, dispatchName.lastIndexOf("_"));
    String folderNameData = folderNameSeed.substring(0, folderNameSeed.lastIndexOf("_"));
    String seedFolder = rootFolder + File.separator + folderNameSeed;
    if (isDeploy) {
        seedFolder = Config.getValue(WebtoolConstants.KEY_HDFS_ROOT_PREFIX) + folderNameSeed;
    }

    List<Seed> seedList = dispatchVo.getSeed();
    final List<String> seedStrs = new ArrayList<String>();
    for (Iterator<Seed> it = seedList.iterator(); it.hasNext();) {
        Seed seed = it.next();
        if ("true".equals(seed.getIsEnabled())) {
            seedStrs.add(seed.getUrl());
        }
    }
    contentToTxt4CrawlerAgain(folderName, seedStrs, "true");

    dispatchVo.setStatus(WebtoolConstants.DISPATCH_STATIS_RUNNING);
    RedisOperator.setDispatchResult(dispatchVo, dispatchName, Constants.DISPATCH_REDIS_DBINDEX);

    String command = shDir + " " + seedFolder + " " + crawlDir + folderNameData + "_data" + " " + solrURL + " "
            + depth;
    LOG.info("??:" + command);
    CrawlToolResource.putSeedsFolder(folderNameSeed, "local");
    final RunManager runManager = getRunmanager(command);

    String resultMsg = "";
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<String> result = es.submit(new Callable<String>() {
        public String call() throws Exception {
            // the other thread
            //return  ShellUtils.execCmd(runManager);
            String tpResult = "";
            LOG.info("?:runManager.ip" + runManager.getHostIp());
            LOG.info("?:runManager.command" + runManager.getCommand());
            tpResult = ShellUtils.execCmd(runManager);
            LOG.info("??runManager.command" + runManager.getCommand());
            contentToTxt4CrawlerAgain(folderName, seedStrs, "false");
            dispatchVo.setStatus(WebtoolConstants.DISPATCH_STATIS_COMPLETE);
            RedisOperator.setDispatchResult(dispatchVo, dispatchName, Constants.DISPATCH_REDIS_DBINDEX);
            return tpResult;
        }
    });
    try {
        resultMsg = result.get();
    } catch (Exception e) {
        // failed
    }

    //        new Thread(new Runnable() {
    //
    //            @Override
    //            public void run() {
    //                LOG.info("?:runManager.ip" + runManager.getHostIp());
    //                LOG.info("?:runManager.command" + runManager.getCommand());
    //                ShellUtils.execCmd(runManager);
    //                LOG.info("??runManager.command" + runManager.getCommand());
    //                contentToTxt4CrawlerAgain(folderName, seedStrs, "false");
    //                dispatchVo.setStatus(WebtoolConstants.DISPATCH_STATIS_COMPLETE);
    //                RedisOperator.setDispatchResult(dispatchVo, dispatchName, Constants.DISPATCH_REDIS_DBINDEX);
    //            }
    //        }).start();

    return resultMsg;
}

From source file:tuit.java

@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
    System.out.println(licence);/*from www  .ja  v  a 2 s.c o  m*/
    //Declare variables
    File inputFile;
    File outputFile;
    File tmpDir;
    File blastnExecutable;
    File properties;
    File blastOutputFile = null;
    //
    TUITPropertiesLoader tuitPropertiesLoader;
    TUITProperties tuitProperties;
    //
    String[] parameters = null;
    //
    Connection connection = null;
    MySQL_Connector mySQL_connector;
    //
    Map<Ranks, TUITCutoffSet> cutoffMap;
    //
    BLASTIdentifier blastIdentifier = null;
    //
    RamDb ramDb = null;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)");
    options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)");
    options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)");
    options.addOption(tuit.V, "verbose", false, "Enable verbose output");
    options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output");
    options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases");
    options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases");
    options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy");

    Option option = new Option(tuit.REDUCE, "reduce", true,
            "Pack identical (100% similar sequences) records in the given sample file");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(tuit.COMBINE, "combine", true,
            "Combine a set of given reduction files into an HMP Tree-compatible taxonomy");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    options.addOption(tuit.NORMALIZE, "normalize", false,
            "If used in combination with -combine ensures that the values are normalized by the root value");

    HelpFormatter formatter = new HelpFormatter();

    try {

        //Get TUIT directory
        final File tuitDir = new File(
                new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
                        .getParent());
        final File ramDbFile = new File(tuitDir, tuit.RAM_DB);

        //Setup logger
        Log.getInstance().setLogName("tuit.log");

        //Read command line
        final CommandLine commandLine = parser.parse(options, args, true);

        //Check if the REDUCE option is on
        if (commandLine.hasOption(tuit.REDUCE)) {

            final String[] fileList = commandLine.getOptionValues(tuit.REDUCE);
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "...");
                final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor
                        .fromPath(path);
                ReductorFileOperator.save(nucleotideFastaSequenceReductor,
                        path.resolveSibling(path.getFileName().toString() + ".rdc"));
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Check if COMBINE is on
        if (commandLine.hasOption(tuit.COMBINE)) {
            final boolean normalize = commandLine.hasOption(tuit.NORMALIZE);
            final String[] fileList = commandLine.getOptionValues(tuit.COMBINE);
            //TODO: implement a test for format here

            final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>();
            final TreeFormatter treeFormatter = TreeFormatter
                    .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat());
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "...");
                treeFormatter.loadFromPath(path);
                final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput
                        .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf(".")));
                hmpTreesOutputs.add(output);
                treeFormatter.erase();
            }
            final Path destination;
            if (commandLine.hasOption(OUT)) {
                destination = Paths.get(commandLine.getOptionValue(tuit.OUT));
            } else {
                destination = Paths.get("merge.tcf");
            }
            CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination);
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        if (!commandLine.hasOption(tuit.P)) {
            throw new ParseException("No properties file option found, exiting.");
        } else {
            properties = new File(commandLine.getOptionValue(tuit.P));
        }

        //Load properties
        tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties);
        tuitProperties = tuitPropertiesLoader.getTuitProperties();

        //Create tmp directory and blastn executable
        tmpDir = new File(tuitProperties.getTMPDir().getPath());
        blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath());

        //Check for deploy
        if (commandLine.hasOption(tuit.DEPLOY)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir);
            } else {
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }
        //Check for update
        if (commandLine.hasOption(tuit.UPDATE)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir);
            } else {
                //No need to specify a different way to update the database other than just deploy in case of the RAM database
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Connect to the database
        if (commandLine.hasOption(tuit.USE_DB)) {
            mySQL_connector = MySQL_Connector.newDefaultInstance(
                    "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/",
                    tuitProperties.getDBConnection().getLogin().trim(),
                    tuitProperties.getDBConnection().getPassword().trim());
            mySQL_connector.connectToDatabase();
            connection = mySQL_connector.getConnection();
        } else {
            //Probe for ram database

            if (ramDbFile.exists() && ramDbFile.canRead()) {
                Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map...");
                try {
                    ramDb = RamDb.loadSelfFromFile(ramDbFile);
                } catch (IOException ie) {
                    if (ie instanceof java.io.InvalidClassException)
                        throw new IOException("The RAM-based taxonomic database needs to be updated.");
                }

            } else {
                Log.getInstance().log(Level.SEVERE,
                        "The RAM database either has not been deployed, or is not accessible."
                                + "Please use the --deploy option and check permissions on the TUIT directory. "
                                + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option.");
                return;
            }
        }

        if (commandLine.hasOption(tuit.B)) {
            blastOutputFile = new File(commandLine.getOptionValue(tuit.B));
            if (!blastOutputFile.exists() || !blastOutputFile.canRead()) {
                throw new Exception("BLAST output file either does not exist, or is not readable.");
            } else if (blastOutputFile.isDirectory()) {
                throw new Exception("BLAST output file points to a directory.");
            }
        }
        //Check vital parameters
        if (!commandLine.hasOption(tuit.IN)) {
            throw new ParseException("No input file option found, exiting.");
        } else {
            inputFile = new File(commandLine.getOptionValue(tuit.IN));
            Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log");
        }
        //Correct the output file option if needed
        if (!commandLine.hasOption(tuit.OUT)) {
            outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT);
        } else {
            outputFile = new File(commandLine.getOptionValue(tuit.OUT));
        }

        //Adjust the output level
        if (commandLine.hasOption(tuit.V)) {
            Log.getInstance().setLevel(Level.FINE);
            Log.getInstance().log(Level.INFO, "Using verbose output for the log");
        } else {
            Log.getInstance().setLevel(Level.INFO);
        }
        //Try all files
        if (inputFile != null) {
            if (!inputFile.exists() || !inputFile.canRead()) {
                throw new Exception("Input file either does not exist, or is not readable.");
            } else if (inputFile.isDirectory()) {
                throw new Exception("Input file points to a directory.");
            }
        }

        if (!properties.exists() || !properties.canRead()) {
            throw new Exception("Properties file either does not exist, or is not readable.");
        } else if (properties.isDirectory()) {
            throw new Exception("Properties file points to a directory.");
        }

        //Create blast parameters
        final StringBuilder stringBuilder = new StringBuilder();
        for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) {
            stringBuilder.append(database.getUse());
            stringBuilder.append(" ");//Gonna insert an extra space for the last database
        }
        String remote;
        String entrez_query;
        if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) {
            remote = "-remote";
            entrez_query = "-entrez_query";
            parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query,
                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue",
                    tuitProperties.getBLASTNParameters().getExpect().getValue() };
        } else {
            if (!commandLine.hasOption(tuit.B)) {
                if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .startsWith("NOT")
                        || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                                .startsWith("ALL")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist",
                            TUITFileOperatorHelper.restrictToEntrez(tmpDir,
                                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()
                                            .toUpperCase().replace("NOT", "OR"))
                                    .getAbsolutePath(),
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .equals("")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads",
                            tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(),
                            /*"-gilist", TUITFileOperatorHelper.restrictToEntrez(
                            tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!!
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                }
            }
        }
        //Prepare a cutoff Map
        if (tuitProperties.getSpecificationParameters() != null
                && tuitProperties.getSpecificationParameters().size() > 0) {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size());
            for (SpecificationParameters specificationParameters : tuitProperties
                    .getSpecificationParameters()) {
                cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()),
                        TUITCutoffSet.newDefaultInstance(
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getPIdentCutoff().getValue()),
                                Double.parseDouble(specificationParameters.getCutoffSet()
                                        .getQueryCoverageCutoff().getValue()),
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getAlpha().getValue())));
            }
        } else {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>();
        }
        final TUITFileOperatorHelper.OutputFormat format;
        if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) {
            format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK;
        } else {
            format = TUITFileOperatorHelper.OutputFormat.TUIT;
        }

        try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator
                .newInstance(format, cutoffMap);) {
            nucleotideFastaTUITFileOperator.setInputFile(inputFile);
            nucleotideFastaTUITFileOperator.setOutputFile(outputFile);
            final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep();
            final boolean cleanup;
            if (cleanupString.equals("no")) {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted.");
                cleanup = true;
            } else {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept.");
                cleanup = false;
            }
            //Create blast identifier
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            if (commandLine.hasOption(tuit.USE_DB)) {

                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection,
                            cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup, ramDb);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup, ramDb);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Future<?> runnableFuture = executorService.submit(blastIdentifier);
            runnableFuture.get();
            executorService.shutdown();
        }
    } catch (ParseException pe) {
        Log.getInstance().log(Level.SEVERE, (pe.getMessage()));
        formatter.printHelp("tuit", options);
    } catch (SAXException saxe) {
        Log.getInstance().log(Level.SEVERE, saxe.getMessage());
    } catch (FileNotFoundException fnfe) {
        Log.getInstance().log(Level.SEVERE, fnfe.getMessage());
    } catch (TUITPropertyBadFormatException tpbfe) {
        Log.getInstance().log(Level.SEVERE, tpbfe.getMessage());
    } catch (ClassCastException cce) {
        Log.getInstance().log(Level.SEVERE, cce.getMessage());
    } catch (JAXBException jaxbee) {
        Log.getInstance().log(Level.SEVERE,
                "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema.");
    } catch (ClassNotFoundException cnfe) {
        //Probably won't happen unless the library deleted from the .jar
        Log.getInstance().log(Level.SEVERE, cnfe.getMessage());
        //cnfe.printStackTrace();
    } catch (SQLException sqle) {
        Log.getInstance().log(Level.SEVERE,
                "A database communication error occurred with the following message:\n" + sqle.getMessage());
        //sqle.printStackTrace();
        if (sqle.getMessage().contains("Access denied for user")) {
            Log.getInstance().log(Level.SEVERE, "Please use standard database login: "
                    + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password);
        }
    } catch (Exception e) {
        Log.getInstance().log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqle) {
                Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle);
            }
        }
        Log.getInstance().log(Level.FINE, "Task done, exiting...");
    }
}

From source file:com.mirth.connect.plugins.datapruner.test.DataPrunerTest.java

@Test
@Ignore/*w ww  .j ava 2  s.co m*/
public final void testConcurrency() throws Exception {
    /*
     * To run this concurrency test, you must setup a "reader" channel through the
     * administrator, that routes messages to other channels that will be pruned. Then specify
     * the ids of those channels below.
     */
    final String readerChannelId = "f7158274-8692-4e53-9d17-db732c3346b8";
    ExecutorService executor = Executors.newSingleThreadExecutor();
    TestUtils.startMirthServer(15000);

    DataPruner pruner = new DataPruner();
    pruner.setPrunerBlockSize(1);
    pruner.setRetryCount(0);

    TestUtils.deleteAllMessages(readerChannelId);
    TestUtils.deleteAllMessages("0831345e-bbe0-4d62-8f2d-c65280bd479b");
    TestUtils.deleteAllMessages("b2e28f1b-d867-435a-a5f6-3b33d5261e66");

    // send messages into the test channel on a separate thread
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            EngineController engineController = ControllerFactory.getFactory().createEngineController();
            logger.info("Sending messages");

            for (int i = 0; i < 100000; i++) {
                logger.info("sending message #" + i);
                engineController.dispatchRawMessage(readerChannelId, new RawMessage(TestUtils.TEST_HL7_MESSAGE),
                        false, true);
            }

            logger.info("Finished sending messages");
            return null;
        }
    });

    logger.info("Executing pruner");

    // run the pruner while messages are processing
    while (!future.isDone()) {
        pruner.run();
        Thread.sleep(2000);
    }

    logger.info("Test completed");
}

From source file:com.playhaven.android.view.HTMLView.java

/**
 * This switches on the host portion of a request prefixed with
 * DISPATCH_PREFIX in order to handle events from the content templates.
 *
 * @TODO this would be a good candidate for factoring out to a cleaner custom WebViewClient
 *
 * @param dispatchUrl//  w  w  w.  ja  v a  2  s. c  o  m
 */
private void handleDispatch(String dispatchUrl) {
    Uri callbackUri = Uri.parse(dispatchUrl);
    String callbackId = callbackUri.getQueryParameter("callback");
    String callbackString = callbackUri.getHost();
    String dispatchContext = callbackUri.getQueryParameter("context");
    PlayHaven.d("Handling dispatch: %s of type %s", dispatchUrl, callbackString);

    switch (Dispatches.valueOf(callbackString)) {
    /**
     * closeButton hides the native emergency close button, and passes
     * notice of whether it was hidden back to the content template
     */
    case closeButton:
        String hidden = "true";
        try {
            hidden = new JSONObject(dispatchContext).getString("hidden");
        } catch (JSONException jse) {
            // Default to NOT hiding the emergency close button
            hidden = "false";
        }

        if ("true".equals(hidden)) {
            ((PlayHavenView) getParent()).setExitVisible(false);
        }

        // Tell the content template that we've hidden the emergency close button.
        this.loadUrl(String.format(CALLBACK_TEMPLATE, callbackId, "{'hidden':'" + hidden + "'}", null));
        break;
    /**
     * dismiss triggers the contentDismissed listener
     */
    case dismiss:
        PlayHavenView.DismissType dismiss = PlayHavenView.DismissType.NoThanks;
        if (mRewards != null)
            dismiss = PlayHavenView.DismissType.Reward;

        if (mDataFields != null)
            dismiss = PlayHavenView.DismissType.OptIn;

        if (mPurchases != null)
            dismiss = PlayHavenView.DismissType.Purchase;

        mPlacement.getListener().contentDismissed(mPlacement, dismiss, generateResponseBundle());

        // Unregister the web view client so that any future dispatches will be ignored.
        HTMLView.this.setWebViewClient(null);

        break;
    /**
     * launch retrieves a URL from the server to be parsed using
     * Intent.ACTION_VIEW
     */
    case launch:
        mPlacement.getListener().contentDismissed(mPlacement, PlayHavenView.DismissType.Launch, null);

        /*
         * We can't get this from the original model because we don't
         * know which one they picked (if this was a more_games template).
         */
        String url;
        try {
            url = new JSONObject(dispatchContext).getString("url");
        } catch (JSONException jse) {
            PlayHaven.e("Could not parse launch URL.");
            return;
        }

        UrlRequest urlRequest = new UrlRequest(url);
        ExecutorService pool = Executors.newSingleThreadExecutor();
        final Future<String> uriFuture = pool.submit(urlRequest);
        final String initialUrl = url;

        new Thread(new Runnable() {
            @Override
            public void run() {
                // Wait for our final link.
                String url = null;
                try {
                    url = uriFuture.get();
                } catch (Exception e) {
                    PlayHaven.v("Could not retrieve launch URL from server. Using initial url.");

                    // If the redirect failed, proceed with the original url.
                    url = initialUrl;
                }

                // Launch whatever it is. It might be a Play, web, or other link
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    HTMLView.this.getContext().startActivity(intent);
                } catch (Exception e) {
                    PlayHaven.e("Unable to launch URI from template.");
                    e.printStackTrace();
                }
            }
        }).start();
        break;
    /**
     * loadContext passes the full "context" JSON blob to the
     * content template
     */
    case loadContext:
        this.loadUrl(DISPATCH_PROTOCOL_TEMPLATE);
        net.minidev.json.JSONObject context = JsonUtil.getPath(mPlacement.getModel(), "$.response.context");

        /**
         * @playhaven.apihack KitKat+ changed how the webview is loaded
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.evaluateJavascript(String.format(CALLBACK_TEMPLATE, callbackId, context, null), null);
        } else {
            this.loadUrl(String.format(CALLBACK_TEMPLATE, callbackId, context, null));
        }
        break;
    /**
     * purchase stores the purchase object (which is generated by the
     * content template) as mPurchases, for use with dismiss dispatch
     */
    case purchase:
        collectAttachments(dispatchContext);
        break;
    /**
     * reward stores the reward object (which is generated by the
     * content template) as mRewards, for use with dismiss dispatch
     */
    case reward:
        net.minidev.json.JSONObject rewardParam = JsonUtil.getPath(mPlacement.getModel(),
                "$.response.context.content.open_dispatch.parameters");
        if (rewardParam == null || rewardParam.size() == 0) {
            // data_collection template sends a reward dispatch when it submits form data ...
            // @TODO: have templates return more than key/value pairs (eg class, pattern)
            this.loadUrl(COLLECT_FORM_DATA);
        }

        collectAttachments(dispatchContext);
        break;
    /**
     * subcontent takes a JSON blob generated by the content template
     * and uses that to get data for a new impression, currently a
     * more_games widget that follows a featured ad
     */
    case subcontent:
        SubcontentRequest subcontentRequest = new SubcontentRequest(dispatchContext);
        subcontentRequest.send(getContext());
        break;
    /**  @TODO Find out why this dispatch was abandoned in 1.12 */
    case track:
        PlayHaven.d("track callback not implemented.");
        break;
    /**
     * This is one injected to let the Android SDK harvest data from the
     * opt-in data collection form.
     */
    case dcData:
        try {
            mDataFields = DataCollectionField.fromUrl(callbackUri);
        } catch (PlayHavenException e) {
            e.printStackTrace();
        }
        break;
    default:
        break;
    }
}