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:de.mendelson.comm.as2.client.AS2Gui.java

/**
 * Displays details for the selected msg row
 *///  w  w w. j  ava2s. c  o  m
private void showSelectedRowDetails() {
    if (this.runtimeConnection == null) {
        return;
    }
    final String uniqueId = this.getClass().getName() + ".showSelectedRowDetails." + System.currentTimeMillis();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {

            try {
                AS2Gui.this.jButtonMessageDetails.setEnabled(false);
                AS2Gui.this.as2StatusBar.startProgressIndeterminate(AS2Gui.this.rb.getResourceString("details"),
                        uniqueId);
                int selectedRow = AS2Gui.this.jTableMessageOverview.getSelectedRow();
                if (selectedRow >= 0) {
                    AS2Message message = ((TableModelMessageOverview) AS2Gui.this.jTableMessageOverview
                            .getModel()).getRow(selectedRow);
                    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
                    //download the full payload from the server
                    MessageAccessDB messageAccess = new MessageAccessDB(AS2Gui.this.configConnection,
                            AS2Gui.this.runtimeConnection);
                    List<AS2Payload> payloads = messageAccess.getPayload(info.getMessageId());
                    message.setPayloads(payloads);
                    DialogMessageDetails dialog = new DialogMessageDetails(AS2Gui.this,
                            AS2Gui.this.configConnection, AS2Gui.this.runtimeConnection,
                            AS2Gui.this.getBaseClient(), info, message.getPayloads());
                    AS2Gui.this.as2StatusBar.stopProgressIfExists(uniqueId);
                    dialog.setVisible(true);
                }
            } catch (Exception e) {
                //nop
            } finally {
                AS2Gui.this.as2StatusBar.stopProgressIfExists(uniqueId);
                AS2Gui.this.setButtonState();
            }
        }
    };
    Executors.newSingleThreadExecutor().submit(runnable);
}

From source file:com.uwsoft.editor.proxy.ProjectManager.java

public void importParticlesIntoProject(final Array<FileHandle> fileHandles, ProgressHandler progressHandler) {
    if (fileHandles == null) {
        return;/*w ww  . ja v  a2s. c  om*/
    }
    final String targetPath = currentProjectPath + "/assets/orig/particles";
    handler = progressHandler;
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(() -> {
        Array<FileHandle> imgs = new Array<>();
        for (FileHandle fileHandle : fileHandles) {
            if (!fileHandle.isDirectory() && fileHandle.exists()) {
                try {
                    //copy images
                    boolean allImagesFound = addParticleEffectImages(fileHandle, imgs);
                    if (allImagesFound) {
                        // copy the fileHandle
                        String newName = fileHandle.name();
                        File target = new File(targetPath + "/" + newName);
                        FileUtils.copyFile(fileHandle.file(), target);
                    }
                } catch (Exception e) {
                    //e.printStackTrace();
                    //System.out.println("Error importing particles");
                    //showError("Error importing particles \n Particle Atals not found \n Please place particle atlas and particle effect fileHandle in the same directory ");
                }
            }
        }
        if (imgs.size > 0) {
            copyImageFilesForAllResolutionsIntoProject(imgs, false);
        }
        ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
        resolutionManager.rePackProjectImagesForAllResolutions();
    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        handler.progressComplete();
    });
    executor.shutdown();
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

/**
 * Runs given test in a new thread with specified timeout
 * (DEFAULT_TIMEOUT_IN_SECONDS) and stores the results in given testResult.
 * //from   w  w  w.  j ava  2  s .  com
 * @param r
 *            the test to be run
 * @return the time needed for executing the test
 */
protected long runWithTimeoutOld(MutationTestRunnable r) {
    // ArrayList<Thread> threadsPre = ThreadUtil.getThreads();
    ExecutorService service = Executors.newSingleThreadExecutor();
    Future<?> future = service.submit(r);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    service.shutdown();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        logger.debug("Start  test: ");
        boolean terminated = service.awaitTermination(timeout, TimeUnit.SECONDS);
        logger.debug("First timeout");
        long time1 = stopWatch.getTime();
        if (!terminated) {
            service.shutdownNow();
        }
        future.get(1, TimeUnit.SECONDS);
        logger.debug("Second timeout");
        long time2 = stopWatch.getTime();
        if (time2 - time1 > 1000) {
            logger.info("Process got some extra time: " + (time2 - time1) + "  " + time2);
        }
        future.cancel(true);

    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed("Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();

    if (!r.hasFinished()) {
        shutDown(r, stopWatch);
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java

public void importParticlesIntoProject(final Array<FileHandle> fileHandles, ProgressHandler progressHandler) {
    if (fileHandles == null) {
        return;//from  w w w  .  j ava  2  s. c  o  m
    }
    final String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName
            + "/assets/orig/particles";
    handler = progressHandler;
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(() -> {
        Array<FileHandle> imgs = new Array<>();
        for (FileHandle fileHandle : fileHandles) {
            if (!fileHandle.isDirectory() && fileHandle.exists()) {
                try {
                    //copy images
                    boolean allImagesFound = addParticleEffectImages(fileHandle, imgs);
                    if (allImagesFound) {
                        // copy the fileHandle
                        String newName = fileHandle.name();
                        File target = new File(targetPath + "/" + newName);
                        FileUtils.copyFile(fileHandle.file(), target);
                    }
                } catch (Exception e) {
                    //e.printStackTrace();
                    //System.out.println("Error importing particles");
                    //showError("Error importing particles \n Particle Atals not found \n Please place particle atlas and particle effect fileHandle in the same directory ");
                }
            }
        }
        if (imgs.size > 0) {
            copyImageFilesForAllResolutionsIntoProject(imgs, false);
        }
        ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
        resolutionManager.rePackProjectImagesForAllResolutions();
    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        handler.progressComplete();
    });
    executor.shutdown();
}

From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java

@Test
public void testProduceLogRecords() throws StageException, IOException, InterruptedException {

    CountDownLatch startLatch = new CountDownLatch(1);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(new ProducerRunnable(TOPIC10, SINGLE_PARTITION, producer, startLatch, DataType.LOG,
            null, -1, null));/*from  w  w  w. ja v a  2 s .co  m*/

    KafkaConfigBean conf = new KafkaConfigBean();
    conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI();
    conf.topic = TOPIC10;
    conf.consumerGroup = CONSUMER_GROUP;
    conf.zookeeperConnect = zkConnect;
    conf.maxBatchSize = 9;
    conf.maxWaitTime = 5000;
    conf.kafkaConsumerConfigs = null;
    conf.produceSingleRecordPerMessage = false;
    conf.dataFormat = DataFormat.LOG;
    conf.dataFormatConfig.charset = "UTF-8";
    conf.dataFormatConfig.removeCtrlChars = false;
    conf.dataFormatConfig.logMode = LogMode.LOG4J;
    conf.dataFormatConfig.logMaxObjectLen = 1024;
    conf.dataFormatConfig.retainOriginalLine = true;
    conf.dataFormatConfig.customLogFormat = null;
    conf.dataFormatConfig.regex = null;
    conf.dataFormatConfig.fieldPathsToGroupName = null;
    conf.dataFormatConfig.grokPatternDefinition = null;
    conf.dataFormatConfig.grokPattern = null;
    conf.dataFormatConfig.onParseError = OnParseError.INCLUDE_AS_STACK_TRACE;
    conf.dataFormatConfig.maxStackTraceLines = 10;
    conf.dataFormatConfig.enableLog4jCustomLogFormat = false;
    conf.dataFormatConfig.log4jCustomLogFormat = null;

    SourceRunner sourceRunner = new SourceRunner.Builder(StandaloneKafkaSource.class, createSource(conf))
            .addOutputLane("lane").build();

    sourceRunner.runInit();

    startLatch.countDown();
    List<Record> records = new ArrayList<>();
    StageRunner.Output output = getOutputAndRecords(sourceRunner, 9, "lane", records);

    shutDownExecutorService(executorService);

    String newOffset = output.getNewOffset();
    Assert.assertNull(newOffset);

    Assert.assertEquals(9, records.size());

    for (Record record : records) {
        Assert.assertEquals(sdcKafkaTestUtil.generateTestData(DataType.LOG, null),
                record.get().getValueAsMap().get("originalLine").getValueAsString());

        Assert.assertFalse(record.has("/truncated"));

        Assert.assertTrue(record.has("/" + Constants.TIMESTAMP));
        Assert.assertEquals("2015-03-20 15:53:31,161",
                record.get("/" + Constants.TIMESTAMP).getValueAsString());

        Assert.assertTrue(record.has("/" + Constants.SEVERITY));
        Assert.assertEquals("DEBUG", record.get("/" + Constants.SEVERITY).getValueAsString());

        Assert.assertTrue(record.has("/" + Constants.CATEGORY));
        Assert.assertEquals("PipelineConfigurationValidator",
                record.get("/" + Constants.CATEGORY).getValueAsString());

        Assert.assertTrue(record.has("/" + Constants.MESSAGE));
        Assert.assertEquals("Pipeline 'test:preview' validation. valid=true, canPreview=true, issuesCount=0",
                record.get("/" + Constants.MESSAGE).getValueAsString());
    }
    sourceRunner.runDestroy();
}

From source file:ca.ualberta.cmput301w13t11.FoodBook.model.ServerClient.java

/**
 * Upload the given Photo to the appropriate Recipe.
 * @param (Photo) photo The photo to be added to the server-side version of the Recipe.
 * @param (long) uri The uri of the Recipe to be updated.
 * @return NOT_FOUND if the Recipe cannot be found on the server,
 *          ERROR on any other error occurred while attempting to upload,
 *          SUCCESS on successful upload.
 *//*from   www  . java 2  s.c o  m*/
public ReturnCode uploadPhotoToRecipe(Photo photo, long uri) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<ReturnCode> future = executor.submit(new UploadPhotoTask(photo, uri));
    ReturnCode ret = ReturnCode.ERROR;
    try {
        ret = future.get(TIMEOUT_PERIOD + UPLOAD_PHOTO_GRACE_PERIOD, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
        logger.log(Level.SEVERE, "Upload photo operation timed out.");
        return ReturnCode.BUSY;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception during upload photo operation.");
        return ReturnCode.ERROR;
    }
    /* Got here so the operation finished. */
    executor.shutdownNow();
    return ret;
}

From source file:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java

/**
 * Tests that if exception with the FileBackedOutputStream being written to and concurrently read by the client occurs
 * during a product retrieval, then the product download to the client is stopped, but the caching of the
 * file continues.//from  w ww  .java2  s  . co m
 *
 * @throws Exception
 */
@Test
@Ignore
// Currently Ignored because cannot figure out how to get FileBackedOutputStream (FBOS) to throw exception
// during product download - this test successfully closes the FBOS, but the ReliableResourceCallable
// does not seem to detect this and continues to stream successfully to the client.
public void testStreamToClientExceptionDuringProductDownloadCachingEnabled() throws Exception {

    mis = new MockInputStream(productInputFilename);

    Metacard metacard = getMockMetacard(EXPECTED_METACARD_ID, EXPECTED_METACARD_SOURCE_ID);
    resourceResponse = getMockResourceResponse();

    downloadMgr = new ReliableResourceDownloadManager(resourceCache, eventPublisher, eventListener,
            downloadStatusInfo, Executors.newSingleThreadExecutor());

    // Use small chunk size so download takes long enough for client
    // to have time to simulate FileBackedOutputStream exception
    int chunkSize = 2;
    downloadMgr.setChunkSize(chunkSize);

    ResourceRetriever retriever = mock(ResourceRetriever.class);
    when(retriever.retrieveResource()).thenReturn(resourceResponse);

    ArgumentCaptor<ReliableResource> argument = ArgumentCaptor.forClass(ReliableResource.class);

    ResourceResponse newResourceResponse = downloadMgr.download(resourceRequest, metacard, retriever);
    assertThat(newResourceResponse, is(notNullValue()));
    productInputStream = newResourceResponse.getResource().getInputStream();
    assertThat(productInputStream, is(instanceOf(ReliableResourceInputStream.class)));

    // On second chunk read by client it will close the download manager's cache file output stream
    // to simulate a cache file exception that should be detected by the ReliableResourceCallable
    executor = Executors.newCachedThreadPool();
    ProductDownloadClient productDownloadClient = new ProductDownloadClient(productInputStream, chunkSize);
    productDownloadClient.setSimulateFbosException(chunkSize, downloadMgr);
    future = executor.submit(productDownloadClient);
    ByteArrayOutputStream clientBytesRead = future.get();

    // Verify client did not receive entire product download
    assertTrue(clientBytesRead.size() < expectedFileSize);

    // Captures the ReliableResource object that should have been put in the ResourceCache's map
    verify(resourceCache, timeout(3000)).put(argument.capture());

    verifyCaching(argument.getValue(), EXPECTED_CACHE_KEY);

    cleanup();
}

From source file:com.jayway.maven.plugins.android.AbstractEmulatorMojo.java

/**
 * Sends a user command to the running emulator via its telnet interface.
 *
 * @param port    The emulator's telnet port.
 * @param command The command to execute on the emulator's telnet interface.
 * @return Whether sending the command succeeded.
 *//*from w  w w .ja  va2s .  c o  m*/
private boolean sendEmulatorCommand(
        //final Launcher launcher,
        //final PrintStream logger,
        final int port, final String command) {
    Callable<Boolean> task = new Callable<Boolean>() {
        public Boolean call() throws IOException {
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    return false;
                }

                out.write(command);
                out.write("\r\n");
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // Do nothing
                }
            }

            return true;
        }

        private static final long serialVersionUID = 1L;
    };

    boolean result = false;
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> future = executor.submit(task);
        result = future.get();
    } catch (Exception e) {
        getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e));
    }

    return result;
}

From source file:com.uwsoft.editor.data.manager.DataManager.java

public void importExternalParticlesIntoProject(final ArrayList<File> files, ProgressHandler progressHandler) {
    final String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName
            + "/assets/orig/particles";
    handler = progressHandler;/*w  w  w  .  j  a  v  a  2  s  . c  om*/
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(new Runnable() {
        @Override
        public void run() {
            for (File file : files) {
                if (file.isFile() && file.exists()) {
                    try {
                        //copy images
                        ArrayList<File> imgs = getImageListFromAtlas(file);
                        copyImageFilesForAllResolutionsIntoProject(imgs, false);
                        // copy the file
                        String newName = file.getName();
                        File target = new File(targetPath + "/" + newName);
                        FileUtils.copyFile(file, target);
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("Error importing particles");
                        //showError("Error importing particles \n Particle Atals not found \n Please place particle atlas and particle effect file in the same directory ");
                    }
                }
            }
            resolutionManager.rePackProjectImagesForAllResolutions();
        }
    });
    executor.execute(new Runnable() {
        @Override
        public void run() {
            changePercentBy(100 - currentPercent);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.progressComplete();
        }
    });
    executor.shutdown();
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClientTests.java

public void testThatHttpClientFailsOnNonHttpResponse() throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    AtomicReference<Exception> hasExceptionHappened = new AtomicReference();
    try (ServerSocket serverSocket = new MockServerSocket(0, 50, InetAddress.getByName("localhost"))) {
        executor.execute(() -> {//from w ww .ja  v a  2  s .  co m
            try (Socket socket = serverSocket.accept()) {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                in.readLine();
                socket.getOutputStream().write("This is not a HTTP response".getBytes(StandardCharsets.UTF_8));
                socket.getOutputStream().flush();
            } catch (Exception e) {
                hasExceptionHappened.set(e);
                logger.error((Supplier<?>) () -> new ParameterizedMessage("Error in writing non HTTP response"),
                        e);
            }
        });
        HttpRequest request = HttpRequest.builder("localhost", serverSocket.getLocalPort()).path("/").build();
        expectThrows(ClientProtocolException.class, () -> httpClient.execute(request));
        assertThat("A server side exception occured, but shouldn't", hasExceptionHappened.get(),
                is(nullValue()));
    } finally {
        terminate(executor);
    }
}