List of usage examples for java.util.concurrent FutureTask get
public V get() throws InterruptedException, ExecutionException
From source file:io.teak.sdk.DeviceConfiguration.java
private void registerForGCM(@NonNull final AppConfiguration appConfiguration) { try {/*from ww w . j a va 2 s . c om*/ if (appConfiguration.pushSenderId != null) { final DeviceConfiguration _this = this; final FutureTask<String> gcmRegistration = new FutureTask<>( new RetriableTask<>(100, 7000L, new Callable<String>() { @Override public String call() throws Exception { GoogleCloudMessaging gcm = _this.gcm.get(); if (Teak.isDebug) { Log.d(LOG_TAG, "Registering for GCM with sender id: " + appConfiguration.pushSenderId); } return gcm.register(appConfiguration.pushSenderId); } })); new Thread(gcmRegistration).start(); new Thread(new Runnable() { public void run() { try { String registration = gcmRegistration.get(); if (registration == null) { Log.e(LOG_TAG, "Got null token during GCM registration."); return; } if (_this.preferences != null) { SharedPreferences.Editor editor = _this.preferences.edit(); editor.putInt(PREFERENCE_APP_VERSION, appConfiguration.appVersion); editor.putString(PREFERENCE_GCM_ID, registration); editor.apply(); } // Inform event listeners GCM is here if (!registration.equals(gcmId)) { _this.gcmId = registration; synchronized (eventListenersMutex) { for (EventListener e : eventListeners) { e.onGCMIdChanged(_this); } } } displayGCMDebugMessage(); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } } }).start(); } } catch (Exception ignored) { } }
From source file:org.apache.jackrabbit.oak.segment.CompactionAndCleanupIT.java
@Test public void testCancelCompaction() throws Throwable { final FileStore fileStore = fileStoreBuilder(getFileStoreFolder()) .withGCOptions(defaultGCOptions().setRetainedGenerations(2)).withMaxFileSize(1).build(); SegmentNodeStore nodeStore = SegmentNodeStoreBuilders.builder(fileStore).build(); NodeBuilder builder = nodeStore.getRoot().builder(); addNodes(builder, 10);//from w w w . j av a 2s . c o m nodeStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY); fileStore.flush(); FutureTask<Boolean> async = runAsync(new Callable<Boolean>() { @Override public Boolean call() throws IOException { boolean cancelled = false; for (int k = 0; !cancelled && k < 1000; k++) { cancelled = !fileStore.compact(); } return cancelled; } }); // Give the compaction thread a head start sleepUninterruptibly(1, SECONDS); fileStore.close(); try { assertTrue(async.get()); } catch (ExecutionException e) { if (!(e.getCause() instanceof IllegalStateException)) { // Throw cause unless this is an ISE thrown by the // store being already closed, which is kinda expected throw e.getCause(); } } }
From source file:com.hortonworks.registries.storage.filestorage.DbFileStorageTest.java
@Test(expected = StorageException.class) public void testConcurrentUpload() throws Throwable { try {/*from www .j a v a 2 s .c o m*/ transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE); String input = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_NAME), "UTF-8"); String updated = input + " new text"; dbFileStorage.upload(IOUtils.toInputStream(input, "UTF-8"), FILE_NAME); InputStream slowStream = new InputStream() { byte[] bytes = updated.getBytes("UTF-8"); int i = 0; @Override public int read() throws IOException { try { Thread.sleep(10); } catch (InterruptedException ex) { } return (i < bytes.length) ? (bytes[i++] & 0xff) : -1; } }; FutureTask<String> ft1 = new FutureTask<>(() -> { try { transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE); String name = dbFileStorage.upload(slowStream, FILE_NAME); transactionManager.commitTransaction(); return name; } catch (Exception e) { transactionManager.rollbackTransaction(); throw e; } }); FutureTask<String> ft2 = new FutureTask<>(() -> { try { transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE); String name = dbFileStorage.upload(IOUtils.toInputStream(updated, "UTF-8"), FILE_NAME); transactionManager.commitTransaction(); return name; } catch (Exception e) { transactionManager.rollbackTransaction(); throw e; } }); Thread t1 = new Thread(ft1); Thread t2 = new Thread(ft2); t1.start(); t2.start(); t1.join(); t2.join(); try { ft1.get(); } catch (ExecutionException ex) { throw ex.getCause(); } transactionManager.commitTransaction(); } catch (Exception e) { transactionManager.rollbackTransaction(); throw e; } }
From source file:plugin.chartboost.hasCachedInterstitial.java
/** * This method is called when the Lua function is called. * <p>/* w w w . ja v a 2 s . com*/ * Warning! This method is not called on the main UI thread. * @param luaState Reference to the Lua state. * Needed to retrieve the Lua function's parameters and to return values back to Lua. * @return Returns the number of values to be returned by the Lua function. */ @Override public int invoke(LuaState luaState) { try { // The named location final String namedLocation = luaState.checkString(1); // Corona Activity CoronaActivity coronaActivity = null; if (CoronaEnvironment.getCoronaActivity() != null) { coronaActivity = CoronaEnvironment.getCoronaActivity(); } // The lua state final LuaState L = luaState; // See if the more apps page is cached FutureTask<Boolean> isCachedResult = new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() throws Exception { // Is more apps cached? boolean result = false; // If the chartboost instance is valid - could be invalid by calling this method before init invokes if (chartboostHelper.chartboostInstance != null) { // Check the result if (namedLocation != null) { result = chartboostHelper.chartboostInstance.hasCachedInterstitial(namedLocation); } else { result = chartboostHelper.chartboostInstance .hasCachedInterstitial("DefaultInterstitial"); } } // Push the result L.pushBoolean(result); // Return the result return result; } }); // Run the activity on the uiThread if (coronaActivity != null) { coronaActivity.runOnUiThread(isCachedResult); // Get the value of isCached boolean returnValue = isCachedResult.get(); } } catch (Exception ex) { // An exception will occur if given an invalid argument or no argument. Print the error. ex.printStackTrace(); } return 1; }
From source file:i5.las2peer.services.videoAdapter.AdapterClass.java
@GET @Path("playlist") public HttpResponse getPlaylist(@QueryParam(name = "sub", defaultValue = "*") String subId, //@QueryParam(name="username" , defaultValue = "*") String username, @QueryParam(name = "search", defaultValue = "*") String searchString, @QueryParam(name = "lat", defaultValue = "*") String lat, @QueryParam(name = "lng", defaultValue = "*") String lng, @QueryParam(name = "duration", defaultValue = "true") boolean duration, @QueryParam(name = "language", defaultValue = "true") boolean language, @QueryParam(name = "location", defaultValue = "true") boolean location, @QueryParam(name = "relevance", defaultValue = "true") boolean relevance, @QueryParam(name = "weightOrder", defaultValue = "true") boolean weightOrder, @QueryParam(name = "sequence", defaultValue = "LRDOW") String sequence, @QueryParam(name = "mobile", defaultValue = "false") boolean mobile, @QueryParam(name = "Authorization", defaultValue = "") String token) { String username = null;/*from w w w. ja v a2 s .c om*/ System.out.println("TOKEN: " + token); if (token != null) { token = token.replace("Bearer ", ""); username = OIDC.verifyAccessToken(token, userinfo); } System.out.println("Adapter Service Checkpoint:0 -- request received" + " - User: " + username + " - Search Query: " + searchString); //Query parameters validation if (!isInteger(lat)) lat = "*"; if (!isInteger(lng)) lng = "*"; if (username.isEmpty() || username.equals("undefined") || username.equals("error")) { HttpResponse r = new HttpResponse("User is not signed in!"); r.setStatus(401); return r; } if (searchString.isEmpty() || searchString.equals("undefined")) { HttpResponse r = new HttpResponse("Please enter a valid search query!"); r.setStatus(400); return r; } /*StopWords sw=new StopWords(); searchString = sw.remove(searchString);*/ System.out.println("Stemmed search query: " + searchString); dbm = new DatabaseManager(); dbm.init(driverName, databaseServer, port, database, this.username, password, hostName); FutureTask<String> future = new FutureTask<>(new Adapt(searchString, username, lat, lng, dbm, duration, location, language, mobile, relevance, weightOrder, sequence, token)); future.run(); String annotations = "No Annotation"; try { annotations = future.get(); //System.out.println("Result="+result); } catch (InterruptedException | ExecutionException e) { System.out.println("EXCEPTION!!!"); e.printStackTrace(); } //String annotations = getAndAdapt(searchString, username, id++); HttpResponse r = new HttpResponse(annotations); r.setStatus(200); return r; }
From source file:io.teak.sdk.DeviceConfiguration.java
private void fetchAdvertisingInfo(@NonNull final Context context) { final DeviceConfiguration _this = this; final FutureTask<AdvertisingIdClient.Info> adInfoFuture = new FutureTask<>( new RetriableTask<>(100, 7000L, new Callable<AdvertisingIdClient.Info>() { @Override//from www . j a v a2 s.c o m public AdvertisingIdClient.Info call() throws Exception { int googlePlayStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context); if (googlePlayStatus == ConnectionResult.SUCCESS) { return AdvertisingIdClient.getAdvertisingIdInfo(context); } throw new Exception("Retrying GooglePlayServicesUtil.isGooglePlayServicesAvailable()"); } })); new Thread(adInfoFuture).start(); // TODO: This needs to be re-checked in case it's something like SERVICE_UPDATING or SERVICE_VERSION_UPDATE_REQUIRED int googlePlayStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context); if (googlePlayStatus == ConnectionResult.SUCCESS) { new Thread(new Runnable() { @Override public void run() { try { AdvertisingIdClient.Info adInfo = adInfoFuture.get(); // Inform listeners Ad Info has changed if (adInfo != _this.advertsingInfo) { _this.advertsingInfo = adInfo; synchronized (eventListenersMutex) { for (EventListener e : eventListeners) { e.onAdvertisingInfoChanged(_this); } } } } catch (Exception e) { if (Teak.isDebug) { Log.e(LOG_TAG, "Couldn't get Google Play Advertising Information."); } } } }).start(); } }
From source file:com.esri.squadleader.view.SquadLeaderActivity.java
private OnSingleTapListener createDefaultOnSingleTapListener() { return new OnSingleTapListener() { private static final long serialVersionUID = 3247725674465463146L; @Override//from w ww. j av a 2s . c om public void onSingleTap(float x, float y) { Callout callout = mapController.getCallout(); //Identify a chem light if (null != mil2525cController && null != (poppedUpChemLight = mil2525cController .identifyOneGraphic("chemlights", x, y, 5))) { View calloutView = getLayoutInflater().inflate(R.layout.chem_light_callout, null); callout.setStyle(R.xml.chem_light_callout_style); callout.refresh(); callout.animatedShow((Point) poppedUpChemLight.getGeometry(), calloutView); } else { callout.animatedHide(); // Identify a feature from a layer findViewById(R.id.button_saveAttributes).setVisibility(View.GONE); findViewById(R.id.button_cancelEditAttributes).setVisibility(View.GONE); findViewById(R.id.button_editAttributes).setVisibility(View.VISIBLE); final FutureTask<List<Popup>> identifyFuture = mapController.identifyFeatureLayers(x, y); Executors.newSingleThreadExecutor().submit(identifyFuture); try { final List<Popup> popups = identifyFuture.get(); if (0 < popups.size()) { loadPopupContainer(popups, BottomSheetBehavior.STATE_COLLAPSED); } else { bottomSheetBehavior_featurePopups.setState(BottomSheetBehavior.STATE_HIDDEN); findViewById(R.id.button_saveAttributes).setVisibility(View.GONE); findViewById(R.id.button_cancelEditAttributes).setVisibility(View.GONE); findViewById(R.id.button_editAttributes).setVisibility(View.VISIBLE); } } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "Exception while identifying feature layers", e); } } } }; }
From source file:com.brainflow.application.toplevel.Brainflow.java
public void launch() throws Throwable { try {/*from ww w.jav a 2 s . c o m*/ String osname = System.getProperty("os.name"); if (osname.toUpperCase().contains("WINDOWS")) { UIManager.setLookAndFeel(new WindowsLookAndFeel()); //UIManager.setLookAndFeel(new com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel()); //LookAndFeelFactory.NimbusInitializer init = new LookAndFeelFactory.NimbusInitializer(); //init.initialize(UIManager.getDefaults()); //UIManager.getDefaults(). LookAndFeelFactory.installJideExtension(); //LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE); } else if (osname.toUpperCase().contains("LINUX")) { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE); } else { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); LookAndFeelFactory.installJideExtension(); } } catch (UnsupportedLookAndFeelException e) { log.severe("could not load look and feel"); } //final SplashScreen splash = SplashScreen.getSplashScreen(); //JFrame.setDefaultLookAndFeelDecorated(true); long startTime = System.currentTimeMillis(); brainFrame = new BrainFrame(); statusBar = new StatusBar(); reportTime(startTime, "created brainframe"); brainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); log.info("initializing DisplayManager ..."); DisplayManager.getInstance().createCanvas(); log.info("initializing resources ..."); FutureTask<Boolean> initResources = new FutureTask<Boolean>(new Callable<Boolean>() { public Boolean call() throws Exception { return initializeResources(); } }); threadService.execute(initResources); log.info("loading commands ..."); FutureTask<Boolean> loadCommandsTask = new FutureTask<Boolean>(new Callable<Boolean>() { public Boolean call() throws Exception { return loadCommands(); } }); threadService.execute(loadCommandsTask); log.info("initializing IO ..."); FutureTask<Boolean> initIOTask = new FutureTask<Boolean>(new Callable<Boolean>() { public Boolean call() throws Exception { return initImageIO(); } }); threadService.execute(initIOTask); log.info("initializing status bar ..."); initializeStatusBar(); reportTime(startTime, "initialized status bar"); log.info("initializing work space ..."); initializeWorkspace(); reportTime(startTime, "initialized work space"); loadCommandsTask.get(); reportTime(startTime, "loaded commands"); log.info("binding container ..."); bindContainer(); reportTime(startTime, "bound container"); log.info("initializing tool bar ..."); initializeToolBar(); reportTime(startTime, "initialized tool bar"); log.info("initializing menu ..."); initializeMenu(); reportTime(startTime, "initialized menu"); initIOTask.get(); reportTime(startTime, "initialized IO"); initResources.get(); reportTime(startTime, "initialized resources"); initExceptionHandler(); }
From source file:com.loopj.android.http.sample.AsyncBackgroundThreadSample.java
@Override public ResponseHandlerInterface getResponseHandler() { FutureTask<ResponseHandlerInterface> future = new FutureTask<>(new Callable<ResponseHandlerInterface>() { @Override//from w w w . j av a 2s. co m public ResponseHandlerInterface call() throws Exception { Log.d(LOG_TAG, "Creating AsyncHttpResponseHandler on background thread"); return new AsyncHttpResponseHandler(Looper.getMainLooper()) { @Override public void onStart() { clearOutputs(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { Log.d(LOG_TAG, String.format("onSuccess executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper())); debugHeaders(LOG_TAG, headers); debugStatusCode(LOG_TAG, statusCode); debugResponse(LOG_TAG, new String(response)); } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { Log.d(LOG_TAG, String.format("onFailure executing on main thread : %B", Looper.myLooper() == Looper.getMainLooper())); debugHeaders(LOG_TAG, headers); debugStatusCode(LOG_TAG, statusCode); debugThrowable(LOG_TAG, e); if (errorResponse != null) { debugResponse(LOG_TAG, new String(errorResponse)); } } @Override public void onRetry(int retryNo) { Toast.makeText(AsyncBackgroundThreadSample.this, String.format("Request is retried, retry no. %d", retryNo), Toast.LENGTH_SHORT) .show(); } }; } }); executor.execute(future); ResponseHandlerInterface responseHandler = null; try { responseHandler = future.get(); Log.d(LOG_TAG, "Background thread for AsyncHttpResponseHandler has finished"); } catch (Exception e) { e.printStackTrace(); } return responseHandler; }
From source file:info.pancancer.arch3.test.TestWorker.java
@Test public void testWorker_endlessFromConfig() throws Exception { HierarchicalINIConfiguration configObj = new HierarchicalINIConfiguration(); configObj.addProperty("rabbit.rabbitMQQueueName", "seqware"); configObj.addProperty("rabbit.rabbitMQHost", "localhost"); configObj.addProperty("rabbit.rabbitMQUser", "guest"); configObj.addProperty("rabbit.rabbitMQPass", "guest"); configObj.addProperty("worker.heartbeatRate", "2.5"); configObj.addProperty("worker.max-runs", "1"); configObj.addProperty("worker.preworkerSleep", "1"); configObj.addProperty("worker.postworkerSleep", "1"); configObj.addProperty("worker.endless", "true"); configObj.addProperty("worker.hostUserName", System.getProperty("user.name")); byte[] body = setupMessage(); Delivery testDelivery = new Delivery(mockEnvelope, mockProperties, body); setupMockQueue(testDelivery);//w w w .j a v a 2s . com Mockito.when(Utilities.parseConfig(anyString())).thenReturn(configObj); //Because the code that does cleanup in calls resultHandler.waitFor(); we need to actually execute something, even if it does nothing. Mockito.doNothing().when(mockExecutor).execute(any(CommandLine.class), any(DefaultExecuteResultHandler.class)); // This is to mock the cleanup command - we don't really want to execute the command for deleting contents of /datastore, at least not when unit testing on a workstation! PowerMockito.whenNew(DefaultExecutor.class).withNoArguments().thenReturn(mockExecutor); Mockito.when(mockExecHandler.hasResult()).thenReturn(true); PowerMockito.whenNew(DefaultExecuteResultHandler.class).withNoArguments().thenReturn(mockExecHandler); final FutureTask<String> tester = new FutureTask<>(new Callable<String>() { @Override public String call() { LOG.info("tester thread started"); try { Worker.main(new String[] { "--config", "src/test/resources/workerConfig.ini", "--uuid", "vm123456", "--pidFile", "/var/run/arch3_worker.pid" }); } catch (CancellationException | InterruptedException e) { LOG.error("Exception caught: " + e.getMessage()); return e.getMessage(); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception"); return null; } finally { Mockito.verify(mockAppender, Mockito.atLeastOnce()).doAppend(argCaptor.capture()); String s = appendEventsIntoString(argCaptor.getAllValues()); return s; } } }); final Thread killer = new Thread(new Runnable() { @Override public void run() { LOG.info("killer thread started"); try { // The endless worker will not end on its own (because it's endless) so we need to wait a little bit (0.5 seconds) and // then kill it as if it were killed by the command-line script (kill_worker_daemon.sh). Thread.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); LOG.error(e.getMessage()); } tester.cancel(true); } }); ExecutorService es = Executors.newFixedThreadPool(2); es.execute(tester); es.execute(killer); try { tester.get(); } catch (CancellationException e) { Mockito.verify(mockAppender, Mockito.atLeastOnce()).doAppend(argCaptor.capture()); List<LoggingEvent> tmpList = new LinkedList<LoggingEvent>(argCaptor.getAllValues()); String output = this.appendEventsIntoString(tmpList); assertTrue("--endless flag was detected and set", output.contains("The \"--endless\" flag was set, this worker will run endlessly!")); int numJobsPulled = StringUtils.countMatches(output, " WORKER IS PREPARING TO PULL JOB FROM QUEUE "); LOG.info("Number of jobs attempted: " + numJobsPulled); assertTrue("number of jobs attempted > 1", numJobsPulled > 1); } catch (Exception e) { e.printStackTrace(); fail(); } }