List of usage examples for java.util.concurrent Callable call
V call() throws Exception;
From source file:com.alibaba.wasp.client.WaspAdmin.java
/** * Helper function called by other execute functions. */// w ww .j a v a2 s .c om private <V> V executeCallable(Callable<V> function) throws IOException { try { return function.call(); } catch (RemoteException re) { throw re.unwrapRemoteException(); } catch (IOException e) { throw e; } catch (ServiceException se) { throw ProtobufUtil.getRemoteException(se); } catch (Exception e) { // This should not happen... throw new IOException("Unexpected exception when calling master", e); } }
From source file:org.apache.distributedlog.BKLogSegmentWriter.java
void scheduleFlushWithDelayIfNeeded(final Callable<?> callable, final AtomicReferenceFieldUpdater<BKLogSegmentWriter, ScheduledFuture> scheduledFutureRefUpdater) { final long delayMs = Math.max(0, minDelayBetweenImmediateFlushMs - lastTransmit.elapsed(TimeUnit.MILLISECONDS)); final ScheduledFuture scheduledFuture = scheduledFutureRefUpdater.get(this); if ((null == scheduledFuture) || scheduledFuture.isDone()) { scheduledFutureRefUpdater.set(this, scheduler.schedule(new Runnable() { @Override/*from w w w. ja v a 2 s . com*/ public void run() { synchronized (this) { scheduledFutureRefUpdater.set(BKLogSegmentWriter.this, null); try { callable.call(); // Flush was successful or wasn't needed, the exception should be unset. scheduledFlushExceptionUpdater.set(BKLogSegmentWriter.this, null); } catch (Exception exc) { scheduledFlushExceptionUpdater.set(BKLogSegmentWriter.this, exc); LOG.error("Delayed flush failed", exc); } } } }, delayMs, TimeUnit.MILLISECONDS)); } }
From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java
/** * Initializes the cache. Only the cache specific to the sesison's locale * will be populated.//from w w w . j a va2 s.c o m */ protected void initCache(IPentahoSession session) { final List<Catalog> cache = getCache(session); final boolean needUpdate; final Lock readLock = cacheLock.readLock(); try { readLock.lock(); // Check if the cache is empty. if (cache.size() == 0) { needUpdate = true; } else { needUpdate = false; } } finally { readLock.unlock(); } if (needUpdate) { final Lock writeLock = cacheLock.writeLock(); try { writeLock.lock(); // First clear the cache cache.clear(); final Callable<Void> call = new Callable<Void>() { public Void call() throws Exception { // Now build the cache. Use the system session in the holder. for (String name : getHelper().getHostedCatalogs()) { try { addCatalogToCache(PentahoSessionHolder.getSession(), name); } catch (Throwable t) { LOG.error("Failed to initialize the cache for OLAP connection " + name, t); } } for (String name : getHelper().getOlap4jServers()) { try { addCatalogToCache(PentahoSessionHolder.getSession(), name); } catch (Throwable t) { LOG.error("Failed to initialize the cache for OLAP connection " + name, t); } } return null; } }; if (isSecurityEnabled()) { SecurityHelper.getInstance().runAsSystem(call); } else { call.call(); } // Sort it all. Collections.sort(cache, new Comparator<IOlapService.Catalog>() { public int compare(Catalog o1, Catalog o2) { return o1.name.compareTo(o2.name); } }); } catch (Throwable t) { LOG.error("Failed to initialize the connection cache", t); throw new IOlapServiceException(t); } finally { writeLock.unlock(); } } }
From source file:org.pentaho.platform.engine.core.system.PentahoSystem.java
/** * Runs code as system with full privileges. * <p/>//from w w w . ja v a 2s . c o m * <p> * Unfortunate copy and paste from SecurityHelper due to dependencies. * </p> */ private static <T> T runAsSystem(final Callable<T> callable) throws Exception { final String name = StringUtils .defaultIfEmpty(PentahoSystem.get(String.class, "singleTenantAdminUserName", null), "admin"); IPentahoSession origSession = PentahoSessionHolder.getSession(); SecurityContext originalContext = SecurityContextHolder.getContext(); try { // create pentaho session StandaloneSession session = new StandaloneSession(name); session.setAuthenticated(name); // create authentication GrantedAuthority[] roles; ISystemSettings settings = PentahoSystem.getSystemSettings(); String roleName = (settings != null) ? settings.getSystemSetting("acl-voter/admin-role", "Admin") : "Admin"; roles = new GrantedAuthority[1]; roles[0] = new GrantedAuthorityImpl(roleName); User user = new User(name, "", true, true, true, true, roles); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, "", roles); //$NON-NLS-1$ // set holders PentahoSessionHolder.setSession(session); // Clearing the SecurityContext to force the subsequent call to getContext() to generate a new SecurityContext. // This prevents us from modifying the Authentication on a SecurityContext isntance which may be shared between // threads. SecurityContextHolder.clearContext(); SecurityContextHolder.getContext().setAuthentication(auth); return callable.call(); } finally { IPentahoSession sessionToDestroy = PentahoSessionHolder.getSession(); if (sessionToDestroy != null && sessionToDestroy != origSession) { try { sessionToDestroy.destroy(); } catch (Exception e) { e.printStackTrace(); } } PentahoSessionHolder.setSession(origSession); SecurityContextHolder.setContext(originalContext); } }
From source file:com.teradata.benchto.service.BenchmarkControllerTest.java
private void doTestBenchmarkSuccessfulExecution(boolean reportRunFinishBeforeBenchmarkFinish, boolean sendEndTimeWithExecutionFinish) throws Exception { String environmentName = "environmentName"; String benchmarkName = "benchmarkName" + reportRunFinishBeforeBenchmarkFinish; String uniqueName = benchmarkName + "_k1=v1"; String benchmarkSequenceId = "benchmarkSequenceId"; String executionSequenceId = "executionSequenceId"; ZonedDateTime testStart = currentDateTime(); // create environment mvc.perform(post("/v1/environment/{environmentName}", environmentName).contentType(APPLICATION_JSON) .content("{\"attribute1\": \"value1\", \"attribute2\": \"value2\"}")).andExpect(status().isOk()); // get environment mvc.perform(get("/v1/environment/{environmentName}", environmentName)).andExpect(status().isOk()) .andExpect(jsonPath("$.name", is(environmentName))) .andExpect(jsonPath("$.attributes.attribute1", is("value1"))) .andExpect(jsonPath("$.attributes.attribute2", is("value2"))); // start benchmark mvc.perform(//w ww.j av a 2 s . c o m post("/v1/benchmark/{benchmarkName}/{benchmarkSequenceId}/start", uniqueName, benchmarkSequenceId) .contentType(APPLICATION_JSON) .content("{\"name\": \"" + benchmarkName + "\",\"environmentName\": \"" + environmentName + "\", \"variables\":{\"k1\":\"v1\"}}")) .andExpect(status().isOk()).andExpect(content().string(uniqueName)); // get benchmark - no measurements, no executions mvc.perform(get("/v1/benchmark/{uniqueName}/{benchmarkSequenceId}", uniqueName, benchmarkSequenceId)) .andExpect(status().isOk()).andExpect(jsonPath("$.name", is(benchmarkName))) .andExpect(jsonPath("$.uniqueName", is(uniqueName))).andExpect(jsonPath("$.status", is("STARTED"))) .andExpect(jsonPath("$.sequenceId", is(benchmarkSequenceId))) .andExpect(jsonPath("$.environment.name", is(environmentName))) .andExpect(jsonPath("$.variables.k1", is("v1"))).andExpect(jsonPath("$.measurements", hasSize(0))) .andExpect(jsonPath("$.executions", hasSize(0))); // start execution mvc.perform(post("/v1/benchmark/{uniqueName}/{benchmarkSequenceId}/execution/{executionSequenceId}/start", uniqueName, benchmarkSequenceId, executionSequenceId).contentType(APPLICATION_JSON) .content("{\"attributes\": {}}")) .andExpect(status().isOk()); // get benchmark - no measurements, single execution without measurements mvc.perform(get("/v1/benchmark/{uniqueName}/{benchmarkSequenceId}", uniqueName, benchmarkSequenceId)) .andExpect(status().isOk()).andExpect(jsonPath("$.name", is(benchmarkName))) .andExpect(jsonPath("$.uniqueName", is(uniqueName))).andExpect(jsonPath("$.status", is("STARTED"))) .andExpect(jsonPath("$.sequenceId", is(benchmarkSequenceId))) .andExpect(jsonPath("$.environment.name", is(environmentName))) .andExpect(jsonPath("$.measurements", hasSize(0))).andExpect(jsonPath("$.executions", hasSize(1))) .andExpect(jsonPath("$.variables.k1", is("v1"))) .andExpect(jsonPath("$.executions[0].status", is("STARTED"))) .andExpect(jsonPath("$.executions[0].sequenceId", is(executionSequenceId))); Instant executionFinish = currentDateTime().toInstant(); Callable<?> reportExecutionFinish = () -> { // finish execution - post execution measurements mvc.perform(post( "/v1/benchmark/{uniqueName}/{benchmarkSequenceId}/execution/{executionSequenceId}/finish", uniqueName, benchmarkSequenceId, executionSequenceId).contentType(APPLICATION_JSON).content( "{\"measurements\":[{\"name\": \"duration\", \"value\": 12.34, \"unit\": \"MILLISECONDS\"},{\"name\": \"bytes\", \"value\": 56789.0, \"unit\": \"BYTES\"}]," + "\"attributes\":{\"attribute1\": \"value1\"}, \"status\": \"FAILED\"" + (sendEndTimeWithExecutionFinish ? (", \"endTime\": " + toJsonRepresentation(executionFinish)) : "") + "}")) .andExpect(status().isOk()); return null; }; Callable<?> reportBenchmarkFinish = () -> { // finish benchmark - post benchmark measurements mvc.perform(post("/v1/benchmark/{uniqueName}/{benchmarkSequenceId}/finish", uniqueName, benchmarkSequenceId).contentType(APPLICATION_JSON).content( "{\"measurements\":[{\"name\": \"meanDuration\", \"value\": 12.34, \"unit\": \"MILLISECONDS\"},{\"name\": \"sumBytes\", \"value\": 56789.0, \"unit\": \"BYTES\"}]," + "\"attributes\":{\"attribute1\": \"value1\"}, \"status\": \"ENDED\"}")) .andExpect(status().isOk()); return null; }; ZonedDateTime testEnd; if (reportRunFinishBeforeBenchmarkFinish) { reportExecutionFinish.call(); reportBenchmarkFinish.call(); testEnd = currentDateTime(); } else { reportBenchmarkFinish.call(); testEnd = currentDateTime(); Thread.sleep(2); // make sure current time changes (assuming we're not on Windows) reportExecutionFinish.call(); } mvc.perform(get("/v1/benchmark/{uniqueName}?environment={environment}", uniqueName, environmentName)) .andExpect(status().isOk()).andExpect(jsonPath("$.[0].name", is(benchmarkName))) .andExpect(jsonPath("$.[0].uniqueName", is(uniqueName))) .andExpect(jsonPath("$.[0].sequenceId", is(benchmarkSequenceId))) .andExpect(jsonPath("$.[0].status", is("ENDED"))) .andExpect(jsonPath("$.[0].variables.k1", is("v1"))) .andExpect(jsonPath("$.[0].environment.name", is(environmentName))) .andExpect(jsonPath("$.[0].attributes.attribute1", is("value1"))) .andExpect(jsonPath("$.[0].measurements", hasSize(2))) .andExpect(jsonPath("$.[0].measurements[*].name", containsInAnyOrder("meanDuration", "sumBytes"))) .andExpect(jsonPath("$.[0].measurements[*].value", containsInAnyOrder(12.34, 56789.0))) .andExpect(jsonPath("$.[0].measurements[*].unit", containsInAnyOrder("MILLISECONDS", "BYTES"))) .andExpect(jsonPath("$.[0].executions", hasSize(1))) .andExpect(jsonPath("$.[0].executions[0].sequenceId", is(executionSequenceId))) .andExpect(jsonPath("$.[0].executions[0].status", is("FAILED"))) .andExpect(jsonPath("$.[0].executions[0].attributes.attribute1", is("value1"))) .andExpect(jsonPath("$.[0].executions[0].measurements[*].name", containsInAnyOrder("duration", "bytes"))) .andExpect( jsonPath("$.[0].executions[0].measurements[*].value", containsInAnyOrder(12.34, 56789.0))) .andExpect(jsonPath("$.[0].executions[0].measurements[*].unit", containsInAnyOrder("MILLISECONDS", "BYTES"))); // assert database state withinTransaction(() -> { Environment environment = environmentRepo.findByName(environmentName); assertThat(environment).isNotNull(); assertThat(environment.getName()).isEqualTo(environmentName); assertThat(environment.getAttributes().get("attribute1")).isEqualTo("value1"); assertThat(environment.getAttributes().get("attribute2")).isEqualTo("value2"); BenchmarkRun benchmarkRun = benchmarkRunRepo.findByUniqueNameAndSequenceId(uniqueName, benchmarkSequenceId); assertThat(benchmarkRun).isNotNull(); assertThat(benchmarkRun.getId()).isGreaterThan(0); assertThat(benchmarkRun.getName()).isEqualTo(benchmarkName); assertThat(benchmarkRun.getVariables()).containsEntry("k1", "v1"); assertThat(benchmarkRun.getUniqueName()).isEqualTo(uniqueName); assertThat(benchmarkRun.getSequenceId()).isEqualTo(benchmarkSequenceId); assertThat(benchmarkRun.getStatus()).isEqualTo(ENDED); assertThat(benchmarkRun.getMeasurements()).hasSize(2).extracting("unit").contains(BYTES, MILLISECONDS); assertThat(benchmarkRun.getStarted()).isAfter(testStart).isBefore(testEnd); assertThat(benchmarkRun.getEnded()).isAfter(testStart).isBefore(testEnd); assertThat(benchmarkRun.getExecutions()).hasSize(1); BenchmarkRunExecution execution = benchmarkRun.getExecutions().iterator().next(); assertThat(execution.getId()).isGreaterThan(0); assertThat(execution.getSequenceId()).isEqualTo(executionSequenceId); assertThat(execution.getStatus()).isEqualTo(FAILED); assertThat(execution.getMeasurements()).hasSize(2).extracting("name").contains("duration", "bytes"); assertThat(execution.getStarted()).isAfter(testStart).isBefore(testEnd); assertThat(execution.getEnded()).isAfter(testStart).isBefore(testEnd); }); }
From source file:com.parse.ParseQuery.java
/** * Wraps a callable with checking that only one of these is running. */// w ww .j a va 2 s.c o m private <TResult> Task<TResult> doWithRunningCheck(Callable<Task<TResult>> runnable) { checkIfRunning(true); Task<TResult> task; try { task = runnable.call(); } catch (Exception e) { task = Task.forError(e); } return task.continueWithTask(new Continuation<TResult, Task<TResult>>() { @Override public Task<TResult> then(Task<TResult> task) throws Exception { synchronized (lock) { isRunning = false; if (cts != null) { cts.trySetResult(null); } cts = null; } return task; } }); }
From source file:com.linkedin.pinot.integration.tests.HybridClusterScanComparisonIntegrationTest.java
protected void runTestLoop(Callable<Object> testMethod, boolean useMultipleThreads) throws Exception { // Clean up the Kafka topic // TODO jfim: Re-enable this once PINOT-2598 is fixed // purgeKafkaTopicAndResetRealtimeTable(); List<Pair<File, File>> enabledRealtimeSegments = new ArrayList<>(); // Sort the realtime segments based on their segment name so they get added from earliest to latest TreeMap<File, File> sortedRealtimeSegments = new TreeMap<File, File>(new Comparator<File>() { @Override/*from w ww .jav a 2 s . c om*/ public int compare(File o1, File o2) { return _realtimeAvroToSegmentMap.get(o1).getName() .compareTo(_realtimeAvroToSegmentMap.get(o2).getName()); } }); sortedRealtimeSegments.putAll(_realtimeAvroToSegmentMap); for (File avroFile : sortedRealtimeSegments.keySet()) { enabledRealtimeSegments.add(Pair.of(avroFile, sortedRealtimeSegments.get(avroFile))); if (useMultipleThreads) { _queryExecutor = new ThreadPoolExecutor(4, 4, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50), new ThreadPoolExecutor.CallerRunsPolicy()); } // Push avro for the new segment LOGGER.info("Pushing Avro file {} into Kafka", avroFile); pushAvroIntoKafka(Collections.singletonList(avroFile), KafkaStarterUtils.DEFAULT_KAFKA_BROKER, KAFKA_TOPIC); // Configure the scan based comparator to use the distinct union of the offline and realtime segments configureScanBasedComparator(enabledRealtimeSegments); QueryResponse queryResponse = _scanBasedQueryProcessor.processQuery("select count(*) from mytable"); int expectedRecordCount = queryResponse.getNumDocsScanned(); waitForRecordCountToStabilizeToExpectedCount(expectedRecordCount, System.currentTimeMillis() + getStabilizationTimeMs()); // Run the actual tests LOGGER.info("Running queries"); testMethod.call(); if (useMultipleThreads) { if (_nQueriesRead == -1) { _queryExecutor.shutdown(); _queryExecutor.awaitTermination(5, TimeUnit.MINUTES); } else { int totalQueries = _failedQueries.get() + _successfulQueries.get(); while (totalQueries < _nQueriesRead) { LOGGER.info("Completed " + totalQueries + " out of " + _nQueriesRead + " - waiting"); Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS); totalQueries = _failedQueries.get() + _successfulQueries.get(); } if (totalQueries > _nQueriesRead) { throw new RuntimeException("Executed " + totalQueries + " more than " + _nQueriesRead); } _queryExecutor.shutdown(); } } int totalQueries = _failedQueries.get() + _successfulQueries.get(); doDisplayStatus(totalQueries); // Release resources _scanBasedQueryProcessor.close(); _compareStatusFileWriter.write("Status after push of " + avroFile + ":" + System.currentTimeMillis() + ":Executed " + _nQueriesRead + " queries, " + _failedQueries + " failures," + _emptyResults.get() + " empty results\n"); } }
From source file:com.appdynamics.analytics.processor.event.ElasticSearchEventService.java
private void handleBulkRequest(String accountName, String eventType, byte[] payloads, int payloadOffset, int payloadLength, Callable<BulkRequestBuilder> requestBuilderCallable) /* */ throws Exception /* */ {//from w w w . ja v a 2 s .co m /* */ BulkResponse resp; /* */ try /* */ { /* 1621 */ BulkRequestBuilder requestBuilder = (BulkRequestBuilder) requestBuilderCallable.call(); /* 1622 */ resp = (BulkResponse) requestBuilder.get(); /* */ } catch (Exception e) { /* 1624 */ log.error( "Event Service Publish Error: account [{}], eventType [{}], payload [{}], exception [{}]", new Object[] { accountName, eventType, new String(payloads, payloadOffset, payloadLength, Charsets.UTF_8), e }); /* */ /* */ /* 1627 */ throw e; /* */ } /* */ /* 1630 */ if (resp.hasFailures()) { /* 1631 */ throw com.appdynamics.analytics.processor.elasticsearch.exception.ElasticSearchExceptionUtils .getBulkFailureException(resp); /* */ } /* */ }
From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java
protected void runServer(int port, boolean serverSsl, boolean clientSsl, String httpAuth, Callable<Void> test) throws Exception { Server server = createServer(port, serverSsl, clientSsl); ServletContextHandler contextHandler = new ServletContextHandler(); if (!httpAuth.equals("none")) { File realmFile = new File(getConfDir(), httpAuth + ".properties"); LoginService loginService = new HashLoginService(httpAuth, realmFile.getAbsolutePath()); server.addBean(loginService);/*from w w w .jav a 2s .c o m*/ ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); switch (httpAuth) { case "basic": securityHandler.setAuthenticator(new BasicAuthenticator()); break; case "digest": securityHandler.setAuthenticator(new DigestAuthenticator()); break; } securityHandler.setLoginService(loginService); Constraint constraint = new Constraint(); constraint.setName("auth"); constraint.setAuthenticate(true); constraint.setRoles(new String[] { "user" }); ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/*"); mapping.setConstraint(constraint); securityHandler.addConstraintMapping(mapping); contextHandler.setSecurityHandler(securityHandler); } MockCyberArkServlet servlet = new MockCyberArkServlet(); contextHandler.addServlet(new ServletHolder(servlet), "/AIMWebService/api/Accounts"); contextHandler.setContextPath("/"); server.setHandler(contextHandler); try { server.start(); test.call(); } finally { server.stop(); } }