List of usage examples for java.util.concurrent Executors newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java
@Test public void testProduceJsonRecordsArrayObjects() throws StageException, IOException, InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(new ProducerRunnable(TOPIC5, SINGLE_PARTITION, producer, startLatch, DataType.JSON, StreamingJsonParser.Mode.ARRAY_OBJECTS, -1, null)); KafkaConfigBean conf = new KafkaConfigBean(); conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI(); conf.topic = TOPIC5;/*ww w. j av a2 s . com*/ conf.consumerGroup = CONSUMER_GROUP; conf.zookeeperConnect = zkConnect; conf.maxBatchSize = 9; conf.maxWaitTime = 5000; conf.kafkaConsumerConfigs = null; conf.produceSingleRecordPerMessage = true; conf.dataFormat = DataFormat.JSON; conf.dataFormatConfig.charset = "UTF-8"; conf.dataFormatConfig.removeCtrlChars = false; conf.dataFormatConfig.jsonContent = JsonMode.ARRAY_OBJECTS; conf.dataFormatConfig.jsonMaxObjectLen = 4096; 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()); sourceRunner.runDestroy(); }
From source file:com.example.android.cardreader.MainActivity.java
public static void checkin(User u) { usr = u;/*from w w w . j a v a 2 s.c o m*/ new MultiThread(new Runnable() { @Override public void run() { SyncHttpClient client = new SyncHttpClient(); RequestParams params = new RequestParams(); params.put("nfctag", usr.rfid); params.put("event_id", "1"); params.setUseJsonStreamer(true); System.out.println("rfid = " + usr.rfid); client.post(Globals.start + "/event/checkin", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String result = new String(responseBody); System.out.println("Posted res: " + result); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { System.out.println("Posted failed: " + error.toString()); } }); } }).executeOnExecutor(Executors.newSingleThreadExecutor()); }
From source file:de.mendelson.comm.as2.client.AS2Gui.java
/** * Creates new form NewJFrame/* w w w . j a v a 2s .c om*/ */ public AS2Gui(Splash splash, String host) { this.host = host; //Set System default look and feel try { //support the command line option -Dswing.defaultlaf=... if (System.getProperty("swing.defaultlaf") == null) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } } catch (Exception e) { this.logger.warning(this.getClass().getName() + ":" + e.getMessage()); } //load resource bundle try { this.rb = (MecResourceBundle) ResourceBundle.getBundle(ResourceBundleAS2Gui.class.getName()); } catch (MissingResourceException e) { throw new RuntimeException("Oops..resource bundle " + e.getClassName() + " not found."); } initComponents(); this.jButtonNewVersion.setVisible(false); this.jPanelRefreshWarning.setVisible(false); //set preference values to the GUI this.setBounds(this.clientPreferences.getInt(PreferencesAS2.FRAME_X), this.clientPreferences.getInt(PreferencesAS2.FRAME_Y), this.clientPreferences.getInt(PreferencesAS2.FRAME_WIDTH), this.clientPreferences.getInt(PreferencesAS2.FRAME_HEIGHT)); //ensure to display all messages this.getLogger().setLevel(Level.ALL); LogConsolePanel consolePanel = new LogConsolePanel(this.getLogger()); //define the colors for the log levels consolePanel.setColor(Level.SEVERE, LogConsolePanel.COLOR_BROWN); consolePanel.setColor(Level.WARNING, LogConsolePanel.COLOR_BLUE); consolePanel.setColor(Level.INFO, LogConsolePanel.COLOR_BLACK); consolePanel.setColor(Level.CONFIG, LogConsolePanel.COLOR_DARK_GREEN); consolePanel.setColor(Level.FINE, LogConsolePanel.COLOR_DARK_GREEN); consolePanel.setColor(Level.FINER, LogConsolePanel.COLOR_DARK_GREEN); consolePanel.setColor(Level.FINEST, LogConsolePanel.COLOR_DARK_GREEN); this.jPanelServerLog.add(consolePanel); this.setTitle(AS2ServerVersion.getProductName() + " " + AS2ServerVersion.getVersion()); //initialize the help system if available this.initializeJavaHelp(); this.jTableMessageOverview.getSelectionModel().addListSelectionListener(this); this.jTableMessageOverview.getTableHeader().setReorderingAllowed(false); //icon columns TableColumn column = this.jTableMessageOverview.getColumnModel().getColumn(0); column.setMaxWidth(20); column.setResizable(false); column = this.jTableMessageOverview.getColumnModel().getColumn(1); column.setMaxWidth(20); column.setResizable(false); this.jTableMessageOverview.setDefaultRenderer(Date.class, new TableCellRendererDate(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT))); //add row sorter RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(this.jTableMessageOverview.getModel()); jTableMessageOverview.setRowSorter(sorter); sorter.addRowSorterListener(this); this.jPanelFilterOverview.setVisible(this.showFilterPanel); this.jMenuItemHelpForum.setEnabled(Desktop.isDesktopSupported()); //destroy splash, possible login screen for the client should come up if (splash != null) { splash.destroy(); } this.setButtonState(); this.jTableMessageOverview.addMouseListener(this); //popup menu issues this.jPopupMenu.setInvoker(this.jScrollPaneMessageOverview); this.jPopupMenu.addPopupMenuListener(this); super.addMessageProcessor(this); //perform the connection to the server //warning! this works for localhost only so far int clientServerCommPort = this.clientPreferences.getInt(PreferencesAS2.CLIENTSERVER_COMM_PORT); if (splash != null) { splash.destroy(); } this.browserLinkedPanel.cyleText(new String[] { "For additional EDI software to convert and process your data please contact <a href='http://www.mendelson-e-c.com'>mendelson-e-commerce GmbH</a>", "To buy a commercial license please visit the <a href='http://shop.mendelson-e-c.com/'>mendelson online shop</a>", "Most trading partners demand a trusted certificate - Order yours at the <a href='http://ca.mendelson-e-c.com'>mendelson CA</a> now!", "Looking for additional secure data transmission software? Try the <a href='http://oftp2.mendelson-e-c.com'>mendelson OFTP2</a> solution!", "You want to send EDIFACT data from your SAP system? Ask <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20SAP%20integration%20solutions'>mendelson-e-commerce GmbH</a> for a solution.", "You need a secure FTP solution? <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20SFTP%20solution'>Ask us</a> for the mendelson SFTP software.", "Convert flat files, EDIFACT, SAP IDos, VDA, inhouse formats? <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20converter%20solution'>Ask us</a> for the mendelson EDI converter.", "For commercial support of this software please buy a license at <a href='http://as2.mendelson-e-c.com'>the mendelson AS2</a> website.", "Have a look at the <a href='http://www.mendelson-e-c.com/products_mbi.php'>mendelson business integration</a> for a powerful EDI solution.", "The <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20RosettaNet%20solution'>mendelson RosettaNet solution</a> supports RNIF 1.1 and RNIF 2.0.", "The <a href='http://www.mendelson-e-c.com/products_ide.php'>mendelson converter IDE</a> is the graphical mapper for the mendelson converter.", "To process any XML data and convert it to EDIFACT, VDA, flat files, IDocs and inhouse formats use <a href='http://www.mendelson-e-c.com/products_converter.php'>the mendelson converter</a>.", "To transmit your EDI data via HTTP/S please <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20HTTPS%20solution'>ask us</a> for the mendelson HTTPS solution.", "If you have questions regarding this product please refer to the <a href='http://community.mendelson-e-c.com/'>mendelson community</a>.", }); this.connect(new InetSocketAddress(host, clientServerCommPort), 5000); Runnable dailyNewsThread = new Runnable() { @Override public void run() { while (true) { long lastUpdateCheck = Long.valueOf(clientPreferences.get(PreferencesAS2.LAST_UPDATE_CHECK)); //check only once a day even if the system is started n times a day if (lastUpdateCheck < (System.currentTimeMillis() - TimeUnit.HOURS.toMillis(23))) { clientPreferences.put(PreferencesAS2.LAST_UPDATE_CHECK, String.valueOf(System.currentTimeMillis())); jButtonNewVersion.setVisible(false); String version = (AS2ServerVersion.getVersion() + " " + AS2ServerVersion.getBuild()) .replace(' ', '+'); Header[] header = htmlPanel.setURL( "http://www.mendelson.de/en/mecas2/client_welcome.php?version=" + version, AS2ServerVersion.getProductName() + " " + AS2ServerVersion.getVersion(), new File("start/client_welcome.html")); if (header != null) { String downloadURL = null; String actualBuild = null; for (Header singleHeader : header) { if (singleHeader.getName().equals("x-actual-build")) { actualBuild = singleHeader.getValue().trim(); } if (singleHeader.getName().equals("x-download-url")) { downloadURL = singleHeader.getValue().trim(); } } if (downloadURL != null && actualBuild != null) { try { int thisBuild = AS2ServerVersion.getBuildNo(); int availableBuild = Integer.valueOf(actualBuild); if (thisBuild < availableBuild) { jButtonNewVersion.setVisible(true); } downloadURLNewVersion = downloadURL; } catch (Exception e) { //nop } } } } else { htmlPanel.setPage(new File("start/client_welcome.html")); } try { //check once a day for new update Thread.sleep(TimeUnit.DAYS.toMillis(1)); } catch (InterruptedException e) { //nop } } } }; Executors.newSingleThreadExecutor().submit(dailyNewsThread); this.as2StatusBar.setConnectedHost(this.host); }
From source file:c3.ops.priam.resources.BackupServlet.java
/** * Convert SSTable2Json and search for given key *//*from ww w . ja va2 s.co m*/ public void checkSSTablesForKey(String rowkey, String keyspace, String cf, String fileExtension, String jsonFilePath) throws Exception { try { logger.info("Starting SSTable2Json conversion ..."); //Setting timeout to 10 Mins long TIMEOUT_PERIOD = 10l; String unixCmd = formulateCommandToRun(rowkey, keyspace, cf, fileExtension, jsonFilePath); String[] cmd = { "/bin/sh", "-c", unixCmd.toString() }; final Process p = Runtime.getRuntime().exec(cmd); Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { int returnCode = p.waitFor(); return returnCode; } }; ExecutorService exeService = Executors.newSingleThreadExecutor(); try { Future<Integer> future = exeService.submit(callable); int returnVal = future.get(TIMEOUT_PERIOD, TimeUnit.MINUTES); if (returnVal == 0) logger.info("Finished SSTable2Json conversion and search."); else logger.error("Error occurred during SSTable2Json conversion and search."); } catch (TimeoutException e) { logger.error(ExceptionUtils.getStackTrace(e)); throw e; } finally { p.destroy(); exeService.shutdown(); } } catch (IOException e) { logger.error(ExceptionUtils.getStackTrace(e)); } }
From source file:com.uwsoft.editor.proxy.ProjectManager.java
public void importSpriteAnimationsIntoProject(final Array<FileHandle> fileHandles, ProgressHandler progressHandler) { if (fileHandles == null) { return;/*from ww w .j a v a 2 s. c om*/ } handler = progressHandler; ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { String newAnimName = null; String rawFileName = fileHandles.get(0).name(); String fileExtension = FilenameUtils.getExtension(rawFileName); if (fileExtension.equals("png")) { Settings settings = new Settings(); settings.square = true; settings.flattenPaths = true; TexturePacker texturePacker = new TexturePacker(settings); FileHandle pngsDir = new FileHandle(fileHandles.get(0).parent().path()); for (FileHandle entry : pngsDir.list(Overlap2DUtils.PNG_FILTER)) { texturePacker.addImage(entry.file()); } String fileNameWithoutExt = FilenameUtils.removeExtension(rawFileName); String fileNameWithoutFrame = fileNameWithoutExt.replaceAll("\\d*$", ""); String targetPath = currentProjectPath + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutFrame; File targetDir = new File(targetPath); if (targetDir.exists()) { try { FileUtils.deleteDirectory(targetDir); } catch (IOException e) { e.printStackTrace(); } } texturePacker.pack(targetDir, fileNameWithoutFrame); newAnimName = fileNameWithoutFrame; } else { for (FileHandle fileHandle : fileHandles) { try { Array<File> imgs = getAtlasPages(fileHandle); String fileNameWithoutExt = FilenameUtils.removeExtension(fileHandle.name()); String targetPath = currentProjectPath + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutExt; File targetDir = new File(targetPath); if (targetDir.exists()) { FileUtils.deleteDirectory(targetDir); } for (File img : imgs) { FileUtils.copyFileToDirectory(img, targetDir); } FileUtils.copyFileToDirectory(fileHandle.file(), targetDir); newAnimName = fileNameWithoutExt; } catch (IOException e) { e.printStackTrace(); } } } if (newAnimName != null) { ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME); resolutionManager.resizeSpriteAnimationForAllResolutions(newAnimName, currentProjectInfoVO); } }); executor.execute(() -> { changePercentBy(100 - currentPercent); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } handler.progressComplete(); }); executor.shutdown(); }
From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java
public void importSpriteAnimationsIntoProject(final Array<FileHandle> fileHandles, ProgressHandler progressHandler) { if (fileHandles == null) { return;// w w w. j a v a 2 s .c o m } handler = progressHandler; ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { String newAnimName = null; String rawFileName = fileHandles.get(0).name(); String fileExtension = FilenameUtils.getExtension(rawFileName); if (fileExtension.equals("png")) { Settings settings = new Settings(); settings.square = true; settings.flattenPaths = true; TexturePacker texturePacker = new TexturePacker(settings); FileHandle pngsDir = new FileHandle(fileHandles.get(0).parent().path()); for (FileHandle entry : pngsDir.list(Overlap2DUtils.PNG_FILTER)) { texturePacker.addImage(entry.file()); } String fileNameWithoutExt = FilenameUtils.removeExtension(rawFileName); String fileNameWithoutFrame = fileNameWithoutExt.replaceAll("\\d*$", ""); String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutFrame; File targetDir = new File(targetPath); if (targetDir.exists()) { try { FileUtils.deleteDirectory(targetDir); } catch (IOException e) { e.printStackTrace(); } } texturePacker.pack(targetDir, fileNameWithoutFrame); newAnimName = fileNameWithoutFrame; } else { for (FileHandle fileHandle : fileHandles) { try { Array<File> imgs = getAtlasPages(fileHandle); String fileNameWithoutExt = FilenameUtils.removeExtension(fileHandle.name()); String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName + "/assets/orig/sprite-animations" + File.separator + fileNameWithoutExt; File targetDir = new File(targetPath); if (targetDir.exists()) { FileUtils.deleteDirectory(targetDir); } for (File img : imgs) { FileUtils.copyFileToDirectory(img, targetDir); } FileUtils.copyFileToDirectory(fileHandle.file(), targetDir); newAnimName = fileNameWithoutExt; } catch (IOException e) { e.printStackTrace(); } } } if (newAnimName != null) { ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME); resolutionManager.resizeSpriteAnimationForAllResolutions(newAnimName, currentProjectInfoVO); } }); executor.execute(() -> { changePercentBy(100 - currentPercent); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } handler.progressComplete(); }); executor.shutdown(); }
From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.WorkerTest.java
@Test public final void testInitializationFailureWithRetries() { String stageName = "testInitializationWorker"; IRecordProcessorFactory recordProcessorFactory = new TestStreamletFactory(null, null); int count = 0; when(proxy.getShardList()).thenThrow(new RuntimeException(Integer.toString(count++))); int maxRecords = 2; long idleTimeInMilliseconds = 1L; StreamConfig streamConfig = new StreamConfig(proxy, maxRecords, idleTimeInMilliseconds, callProcessRecordsForEmptyRecordList, skipCheckpointValidationValue, INITIAL_POSITION_LATEST); when(leaseCoordinator.getLeaseManager()).thenReturn(leaseManager); ExecutorService execService = Executors.newSingleThreadExecutor(); long shardPollInterval = 0L; Worker worker = new Worker(stageName, recordProcessorFactory, streamConfig, INITIAL_POSITION_TRIM_HORIZON, shardPollInterval, shardSyncIntervalMillis, cleanupLeasesUponShardCompletion, leaseCoordinator, leaseCoordinator, execService, nullMetricsFactory, taskBackoffTimeMillis, failoverTimeMillis, KinesisClientLibConfiguration.DEFAULT_SKIP_SHARD_SYNC_AT_STARTUP_IF_LEASES_EXIST, shardPrioritization);/*from w w w . j av a 2 s .c om*/ worker.run(); Assert.assertTrue(count > 0); }
From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java
@Test public void testProduceXmlRecordsNoRecordElement() throws StageException, IOException, InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(/*from w w w .j a v a 2 s . c om*/ new ProducerRunnable(TOPIC6, SINGLE_PARTITION, producer, startLatch, DataType.XML, null, -1, null)); KafkaConfigBean conf = new KafkaConfigBean(); conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI(); conf.topic = TOPIC6; conf.consumerGroup = CONSUMER_GROUP; conf.zookeeperConnect = zkConnect; conf.maxBatchSize = 9; conf.maxWaitTime = 5000; conf.kafkaConsumerConfigs = null; conf.produceSingleRecordPerMessage = false; conf.dataFormat = DataFormat.XML; conf.dataFormatConfig.charset = "UTF-8"; conf.dataFormatConfig.removeCtrlChars = false; conf.dataFormatConfig.xmlRecordElement = ""; conf.dataFormatConfig.xmlMaxObjectLen = 4096; 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()); sourceRunner.runDestroy(); }
From source file:com.netflix.priam.resources.BackupServlet.java
/** * Convert SSTable2Json and search for given key *//* www .jav a 2 s. com*/ public void checkSSTablesForKey(String rowkey, String keyspace, String cf, String fileExtension, String jsonFilePath) throws Exception { try { logger.info("Starting SSTable2Json conversion ..."); //Setting timeout to 10 Mins long TIMEOUT_PERIOD = 10l; String unixCmd = formulateCommandToRun(rowkey, keyspace, cf, fileExtension, jsonFilePath); String[] cmd = { "/bin/sh", "-c", unixCmd.toString() }; final Process p = Runtime.getRuntime().exec(cmd); Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { int returnCode = p.waitFor(); return returnCode; } }; ExecutorService exeService = Executors.newSingleThreadExecutor(); try { Future<Integer> future = exeService.submit(callable); int returnVal = future.get(TIMEOUT_PERIOD, TimeUnit.MINUTES); if (returnVal == 0) logger.info("Finished SSTable2Json conversion and search."); else logger.error("Error occurred during SSTable2Json conversion and search."); } catch (TimeoutException e) { logger.error(ExceptionUtils.getFullStackTrace(e)); throw e; } finally { p.destroy(); exeService.shutdown(); } } catch (IOException e) { logger.error(ExceptionUtils.getFullStackTrace(e)); } }
From source file:org.opennms.web.controller.ksc.AscoTlcCustomViewController.java
/** * <p>afterPropertiesSet</p> * * @throws java.lang.Exception if any./*from w w w.j a v a 2 s .c om*/ */ public void afterPropertiesSet() throws Exception { Assert.state(m_kscReportFactory != null, "property kscReportFactory must be set"); Assert.state(m_kscReportService != null, "property kscReportService must be set"); Assert.state(m_resourceService != null, "property resourceService must be set"); Assert.state(m_defaultGraphsPerLine != 0, "property defaultGraphsPerLine must be set"); m_executor = Executors.newSingleThreadExecutor(); }