List of usage examples for java.util.concurrent Executors newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
From source file:io.syndesis.project.converter.DefaultProjectGenerator.java
private InputStream createTarInputStream(GenerateProjectRequest request) throws IOException { PipedInputStream is = new PipedInputStream(); ExecutorService executor = Executors.newSingleThreadExecutor(); PipedOutputStream os = new PipedOutputStream(is); executor.submit(generateAddProjectTarEntries(request, os)); return is;/*w ww . java2 s .com*/ }
From source file:com.oneops.sensor.ws.SensorWsController.java
@RequestMapping(method = RequestMethod.GET, value = "/monitors/restore") @ResponseBody/*from w w w . j ava 2 s . co m*/ public String restoreMonitors( @RequestParam(value = "writeMode", required = false, defaultValue = "false") boolean writeMode, @RequestParam(value = "manifestId", required = false) Long manifestId) { Executors.newSingleThreadExecutor().execute(() -> restorer.restore(writeMode, manifestId)); return "Restore process started. WriteMode:" + writeMode + ". Monitor log files"; }
From source file:co.kuali.coeus.sys.impl.persistence.SchemaSpyFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final UserSession session = getGlobalVariableService().getUserSession() != null ? getGlobalVariableService().getUserSession() : (UserSession) ((HttpServletRequest) request).getSession() .getAttribute(KRADConstants.USER_SESSION_KEY); if (session == null || !getPermissionService().isAuthorizedByTemplate(session.getPrincipalId(), KRADConstants.KRAD_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_VIEW, Collections.singletonMap(KimConstants.AttributeConstants.VIEW_ID, KIM_SCHEMA_SPY_VIEW_ID), Collections.<String, String>emptyMap())) { HttpUtils.disableCache((HttpServletResponse) response); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN); return;/*from ww w . j av a 2 s .c om*/ } if (!getConfigurationService().getPropertyValueAsBoolean(SCHEMA_SPY_CONFIG_PARAM)) { HttpUtils.disableCache((HttpServletResponse) response); response.getWriter().write("SchemaSpy has been disabled."); return; } synchronized (initialized) { if (REFRESH_TRUE.equals(request.getParameter(REFRESH_PARAM)) && initialized.get()) { Executors.newSingleThreadExecutor().execute(refreshSchemaSpy); } if (!initialized.get()) { HttpUtils.disableCache((HttpServletResponse) response); response.getWriter().write("Please wait. SchemaSpy is still processing."); return; } } chain.doFilter(request, response); }
From source file:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java
@Test public void testSimple() throws Exception { Timing timing = new Timing(); DistributedQueue<String> queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try {//from w ww . ja va 2s. co m client.start(); final List<String> messages = new CopyOnWriteArrayList<String>(); final CountDownLatch latch = new CountDownLatch(2); final Semaphore semaphore = new Semaphore(0); QueueConsumer<String> consumer = new QueueConsumer<String>() { @Override public void consumeMessage(String message) throws Exception { messages.add(message); semaphore.acquire(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; queue = QueueBuilder.builder(client, consumer, serializer, "/queue") .executor(Executors.newSingleThreadExecutor()).maxItems(1).buildQueue(); queue.start(); QueuePutListener<String> listener = new QueuePutListener<String>() { @Override public void putCompleted(String item) { latch.countDown(); } @Override public void putMultiCompleted(MultiItem<String> items) { } }; queue.getPutListenerContainer().addListener(listener); Assert.assertTrue(queue.put("1", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should end up in consumer Assert.assertTrue(queue.put("2", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should sit blocking in DistributedQueue Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertFalse(queue.put("3", timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS)); semaphore.release(100); Assert.assertTrue(queue.put("3", timing.milliseconds(), TimeUnit.MILLISECONDS)); Assert.assertTrue(queue.put("4", timing.milliseconds(), TimeUnit.MILLISECONDS)); Assert.assertTrue(queue.put("5", timing.milliseconds(), TimeUnit.MILLISECONDS)); for (int i = 0; i < 5; ++i) { if (messages.size() == 3) { break; } timing.sleepABit(); } timing.sleepABit(); Assert.assertEquals(messages, Arrays.asList("1", "2", "3", "4", "5")); } finally { IOUtils.closeQuietly(queue); IOUtils.closeQuietly(client); } }
From source file:com.mobiperf.MeasurementScheduler.java
@Override public void onCreate() { Logger.d("Service onCreate called"); PhoneUtils.setGlobalContext(this.getApplicationContext()); phoneUtils = PhoneUtils.getPhoneUtils(); phoneUtils.registerSignalStrengthListener(); this.checkin = new Checkin(this); this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC; this.checkinRetryCnt = 0; this.checkinTask = new CheckinTask(); this.pauseRequested = true; this.stopRequested = false; this.measurementExecutor = Executors.newSingleThreadExecutor(); this.taskQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE, new TaskComparator()); this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult>>(); // expect it to be the same size as the queue this.currentSchedule = new Hashtable<String, MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE); this.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this); restoreState();//from w ww. j a v a 2 s . com // Register activity specific BroadcastReceiver here IntentFilter filter = new IntentFilter(); filter.addAction(UpdateIntent.PREFERENCE_ACTION); filter.addAction(UpdateIntent.MSG_ACTION); filter.addAction(UpdateIntent.CHECKIN_ACTION); filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION); filter.addAction(UpdateIntent.MEASUREMENT_ACTION); filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION); broadcastReceiver = new BroadcastReceiver() { // Handles various broadcast intents. // If traffic is paused by RRCTrafficControl (because a RRC test is // running), we do not perform the checkin, since sending interfering // traffic makes the RRC inference task abort and restart the current // test as the traffic may have altered the phone's RRC state. @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(UpdateIntent.PREFERENCE_ACTION)) { updateFromPreference(); } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION) || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION) && !RRCTrafficControl.checkIfPaused()) { Logger.d("Checkin intent received"); handleCheckin(false); } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION) && !RRCTrafficControl.checkIfPaused()) { Logger.d("MeasurementIntent intent received"); handleMeasurement(); } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) { Logger.d("MeasurementIntent update intent received"); if (intent.getIntExtra(UpdateIntent.PROGRESS_PAYLOAD, Config.INVALID_PROGRESS) == Config.MEASUREMENT_END_PROGRESS) { if (intent.getStringExtra(UpdateIntent.ERROR_STRING_PAYLOAD) != null) { failedMeasurementCnt++; } else { // Process result completedMeasurementCnt++; } if (intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD) != null) { Logger.d("Measurement result intent received"); saveResultToFile(intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD)); } updateResultsConsole(intent); } } else if (intent.getAction().equals(UpdateIntent.MSG_ACTION)) { String msg = intent.getExtras().getString(UpdateIntent.STRING_PAYLOAD); Date now = Calendar.getInstance().getTime(); insertStringToConsole(systemConsole, now + "\n\n" + msg); } } }; this.registerReceiver(broadcastReceiver, filter); // TODO(mdw): Make this a user-selectable option addIconToStatusBar(); }
From source file:org.ulyssis.ipp.reader.Reader.java
private void initSpeedway() { ExecutorService executor = Executors.newSingleThreadExecutor(); try {/* w ww . j a v a 2 s. c o m*/ while (!speedwayInitialized && !Thread.currentThread().isInterrupted()) { // We're doing this in another thread because LLRPReader doesn't // interrupt properly. Callable<Boolean> runCallable = () -> llrpReader .run(Config.getCurrentConfig().getSpeedwayURI(options.getId())); Future<Boolean> initFuture = executor.submit(runCallable); try { speedwayInitialized = initFuture.get(); } catch (ExecutionException e) { LOG.error("Starting the Speedway caused an exception.", e); speedwayInitialized = false; } if (!speedwayInitialized) { LOG.error("Couldn't start the Speedway! Retrying in {} ms.", Config.getCurrentConfig().getRetryInterval()); statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.STARTUP_FAILURE, "Failed to start the Speedway!")); Thread.sleep(Config.getCurrentConfig().getRetryInterval()); } } } catch (InterruptedException e) { // Shutting down } }
From source file:ai.grakn.engine.loader.client.LoaderClient.java
/** * Re-sets the executor and indicates the system is no longer checking the status of the transactions *//*from w w w .j a v a 2 s . c o m*/ private void stopCheckingStatus() { executor.shutdownNow(); executor = Executors.newSingleThreadExecutor(); future = null; }
From source file:com.example.android.cardreader.MainActivity.java
public static void register(User u) { usr = u;//www .j a v a2 s . c o m usr.checkinTime = new Date(); new MultiThread(new Runnable() { @Override public void run() { SyncHttpClient client = new SyncHttpClient(); RequestParams params = new RequestParams(); params.put("andrewid", usr.andrewID); System.out.println("Posting " + usr.andrewID + " " + usr.rfid); params.setUseJsonStreamer(true); client.post(Globals.start + "/user/getid", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { new MultiThread(new Runnable() { @Override public void run() { SyncHttpClient client = new SyncHttpClient(); RequestParams params = new RequestParams(); params.put("event_id", 1); params.put("nfctag", usr.rfid); params.setUseJsonStreamer(true); client.post(Globals.start + "/event/register", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String result = new String(responseBody); System.out.println("Posted res: " + result); 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()); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { System.out.println("Posted failed: " + error.toString()); } }); } }).executeOnExecutor(Executors.newSingleThreadExecutor()); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { new MultiThread(new Runnable() { @Override public void run() { SyncHttpClient client = new SyncHttpClient(); RequestParams params = new RequestParams(); params.put("password", "asbjdbajhscbjabshd"); params.put("andrewid", usr.andrewID); params.put("nfctag", usr.rfid); System.out.println("Posted " + usr.andrewID + " " + usr.rfid); params.setUseJsonStreamer(true); client.post(Globals.start + "/user/signup", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String result = new String(responseBody); System.out.println("Posted res1: " + result); new MultiThread(new Runnable() { @Override public void run() { SyncHttpClient client = new SyncHttpClient(); RequestParams params = new RequestParams(); params.put("event_id", 1); params.put("nfctag", usr.rfid); params.setUseJsonStreamer(true); client.post(Globals.start + "/event/register", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String result = new String(responseBody); System.out.println("Posted res: " + result); 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()); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { System.out.println( "Posted failed: " + error.toString()); } }); } }).executeOnExecutor(Executors.newSingleThreadExecutor()); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { System.out.println("Posted failed1: " + error.toString()); System.out.println("Posted code = " + statusCode); System.out.println("Posted 1 headers = " + headers[0] + " " + headers[1] + " " + headers[2]); } }); } }).executeOnExecutor(Executors.newSingleThreadExecutor()); } }); } }).executeOnExecutor(Executors.newSingleThreadExecutor()); }
From source file:com.dumontierlab.pdb2rdf.Pdb2Rdf.java
private static void printRdf(final CommandLine cmd, final Map<String, Double> stats) { final File outDir = getOutputDirectory(cmd); final RDFWriter writer = getWriter(cmd); final ProgressMonitor monitor = getProgressMonitor(); Pdb2RdfInputIterator i = processInput(cmd); final int inputSize = i.size(); final AtomicInteger progressCount = new AtomicInteger(); ExecutorService pool = null;/*w w w. j a v a2s . co m*/ if (outDir != null) { pool = getThreadPool(cmd); } else { // if output is going to the STDOUT then we need to do process in // sequential mode. pool = Executors.newSingleThreadExecutor(); } final Object lock = new Object(); while (i.hasNext()) { final InputSource input = i.next(); pool.execute(new Runnable() { @Override public void run() { OutputStream out = System.out; PdbXmlParser parser = new PdbXmlParser(); PdbRdfModel model = null; try { if (cmd.hasOption("detailLevel")) { try { DetailLevel detailLevel = Enum.valueOf(DetailLevel.class, cmd.getOptionValue("detailLevel")); model = parser.parse(input, new PdbRdfModel(), detailLevel); } catch (IllegalArgumentException e) { LOG.fatal("Invalid argument value for detailLevel option", e); System.exit(1); } } else { model = parser.parse(input, new PdbRdfModel()); } // add the input file information model.addInputFileInformation(); // add the outputFile information(); model.addRDFFileInformation(); if (outDir != null) { File directory = new File(outDir, model.getPdbId().substring(1, 3)); synchronized (lock) { if (!directory.exists()) { directory.mkdir(); } } File file = new File(directory, model.getPdbId() + ".rdf.gz"); out = new GZIPOutputStream(new FileOutputStream(file)); } if (cmd.hasOption("format")) { if (cmd.getOptionValue("format").equalsIgnoreCase("NQUADs")) { Dataset ds = TDBFactory.createDataset(); ds.addNamedModel(model.getDatasetResource().toString(), model); StringWriter sw = new StringWriter(); RDFDataMgr.write(sw, ds, Lang.NQUADS); out.write(sw.toString().getBytes(Charset.forName("UTF-8"))); ds.close(); } } writer.write(model, out, null); if (stats != null) { updateStats(stats, model); } if (monitor != null) { monitor.setProgress(progressCount.incrementAndGet(), inputSize); } } catch (Exception e) { String id = null; if (model != null) { id = model.getPdbId(); } LOG.error("Unable to parse input for PDB: " + id, e); } finally { try { out.close(); } catch (IOException e) { LOG.error("Unable to close output stream", e); } } } }); } pool.shutdown(); while (!pool.isTerminated()) { try { pool.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { break; } } }
From source file:me.taylorkelly.mywarp.bukkit.MyWarpPlugin.java
@Override public void onEnable() { // create the data-folder getDataFolder().mkdirs();/*from w ww . j ava2 s. com*/ profileService = new SquirrelIdProfileService(new File(getDataFolder(), "profiles.db")); groupResolverManager = new GroupResolverManager(); adapter = new BukkitAdapter(this); // setup the configurations settings = new BukkitSettings(new File(getDataFolder(), "config.yml"), YamlConfiguration.loadConfiguration(getTextResource("config.yml")), adapter); // setup the DataService ConnectionConfiguration config = settings.getStorageConfiguration(); //TODO fail for SQLite driver 3.7.x... SingleConnectionDataSource dataSource; try { dataSource = DataSourceFactory.createSingleConnectionDataSource(config); } catch (SQLException e) { log.error("Failed to connect to the database. MyWarp will be disabled.", e); Bukkit.getPluginManager().disablePlugin(this); return; } ListeningExecutorService executorService = MoreExecutors .listeningDecorator(Executors.newSingleThreadExecutor()); dataService = new SingleConnectionDataService(dataSource, config, executorService); // setup the Game game = new BukkitGame(new BukkitExecutor(this), adapter); // try to setup the core try { myWarp = new MyWarp(this); } catch (InitializationException e) { log.error( "A critical failure has been encountered and MyWarp is unable to continue. MyWarp will be disabled.", e); Bukkit.getPluginManager().disablePlugin(this); return; } // command registration ResourceProvider resourceProvider = new IntakeResourceProvider(control); ExceptionConverter exceptionConverter = new ExceptionConverter(); PlayerBinding playerBinding = new PlayerBinding(game); WarpBinding warpBinding = new WarpBinding(myWarp.getWarpManager()); ParametricBuilder builder = new ParametricBuilder(resourceProvider); builder.setAuthorizer(new ActorAuthorizer()); builder.setExternalResourceProvider(new CommandResourceProvider(control)); builder.addBinding(new ActorBindung()); builder.addBinding(new ConnectionConfigurationBinding()); builder.addBinding(new FileBinding(getDataFolder())); builder.addBinding(playerBinding); builder.addBinding(new ProfileBinding(profileService)); builder.addBinding(warpBinding); builder.addExceptionConverter(exceptionConverter); builder.addInvokeListener(new EconomyInvokeHandler(myWarp.getEconomyManager())); UsageCommands usageCommands = new UsageCommands(myWarp); //XXX this should be covered by unit tests CommandCallable fallback = Iterables.getOnlyElement(builder.build(usageCommands).values()); // @formatter:off dispatcher = new CommandGraph(resourceProvider).builder(builder).commands().registerMethods(usageCommands) .group(new FallbackDispatcher(resourceProvider, fallback), "warp", "myWarp", "mw") .describeAs("warp-to.description") .registerMethods( new InformativeCommands(myWarp.getLimitManager(), settings, myWarp.getWarpManager())) .registerMethods(new ManagementCommands(myWarp, this, new WelcomeEditorFactory(this, adapter))) .registerMethods(new SocialCommands(game, myWarp.getLimitManager(), profileService, new WarpAcceptancePromptFactory(this, adapter))) .registerMethods(new UtilityCommands(myWarp, this)).group("import", "migrate") .describeAs("import.description").registerMethods(new ImportCommands(myWarp)).graph() .getDispatcher(); // @formatter:on setupPlugin(); }