下面列出了org.junit.runner.notification.StoppedByUserException#java.util.concurrent.Callable 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Before
public void setup() {
sessionContext = new TestSessionContext(null, null);
callable = new Callable<Object>() {
@Override
public Void call() {
return null;
}
};
ctx = new IInvocationCtx() {
@Override
public TransactionManager getTransactionManager() {
return null;
}
@Override
public boolean isApplicationException(Exception e) {
return false;
}
};
}
private Set<ArtifactSpec> resolveInParallel(Collection<ArtifactSpec> toResolve) throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10);
List<Callable<ArtifactSpec>> callable = toResolve.stream()
.map(spec -> (Callable<ArtifactSpec>) (() -> this.resolve(spec)))
.collect(Collectors.toList());
List<Future<ArtifactSpec>> futures = threadPool.invokeAll(
callable
);
Set<ArtifactSpec> result = futures.stream()
.map(this::safeGet)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
threadPool.shutdown();
return result;
}
/**
* timed invokeAll(null time unit) throws NullPointerException
*/
public void testTimedInvokeAllNullTimeUnit() throws Throwable {
ExecutorService e = new ForkJoinPool(1);
PoolCleaner cleaner = null;
try {
cleaner = cleaner(e);
List<Callable<String>> l = new ArrayList<>();
l.add(new StringTask());
try {
e.invokeAll(l, randomTimeout(), null);
shouldThrow();
} catch (NullPointerException success) {}
} finally {
if (cleaner != null) {
cleaner.close();
}
}
}
@Test
public void getSubscriptionsForMyCustomersFilteredByServiceIDNoSubscriptionReturned()
throws Exception {
// given
final String not_existing_service_id = "not existing";
final int expected = 0;
Set<Filter> filterSet = createFilterSet(null, null, null, null,
not_existing_service_id);
final Pagination pagination = createPagination(0,
NUM_CUSTOMER_SUBSCRIPTIONS, null, filterSet);
// when
List<Subscription> result = runTX(new Callable<List<Subscription>>() {
@Override
public List<Subscription> call() throws Exception {
return dao.getSubscriptionsForMyCustomers(supplierUser, states,
pagination);
}
});
// then
assertEquals(expected, result.size());
}
/**
* Test that exception in one of the statements does not kill connection worker altogether.
* @throws SQLException if failed.
*/
@Test
public void testExceptionHandling() throws SQLException {
try (Connection c = c(true, NestedTxMode.ERROR)) {
try (Statement s = c.createStatement()) {
s.execute("INSERT INTO INTS(k, v) values(1, 1)");
assertEquals(1, grid(0).cache("ints").get(1));
GridTestUtils.assertThrows(null, new Callable<Void>() {
@Override public Void call() throws Exception {
s.execute("INSERT INTO INTS(x, y) values(1, 1)");
return null;
}
}, SQLException.class, "Failed to parse query");
s.execute("INSERT INTO INTS(k, v) values(2, 2)");
assertEquals(2, grid(0).cache("ints").get(2));
}
}
}
private Object unwrap(Object value) {
while (true) {
if (value instanceof Callable) {
Callable callable = (Callable) value;
try {
value = callable.call();
} catch (Exception e) {
throw UncheckedException.throwAsUncheckedException(e);
}
} else if (value instanceof Closure) {
Closure closure = (Closure) value;
value = closure.call();
} else if (value instanceof FileCollection) {
FileCollection fileCollection = (FileCollection) value;
return fileCollection.getFiles();
} else {
return value;
}
}
}
@Test
public void errorNonEager() {
Maybe.using(new Callable<Object>() {
@Override
public Object call() throws Exception {
return 1;
}
}, new Function<Object, MaybeSource<Integer>>() {
@Override
public MaybeSource<Integer> apply(Object v) throws Exception {
return Maybe.error(new TestException());
}
}, new Consumer<Object>() {
@Override
public void accept(Object d) throws Exception {
}
}, false)
.test()
.assertFailure(TestException.class);
}
public boolean delete(final String path) {
try {
retryUntilConnected(new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
_connection.delete(path);
return null;
}
});
return true;
} catch (ZkNoNodeException e) {
return false;
}
}
public Object fold(final long n, final IFn combiner, final IFn reducer, final IFn fjtask, final IFn fjfork, final IFn fjjoin) {
if (n > count()) {
List<Callable> tasks = new ArrayList();
for (int i = 0; i < 16; i++) {
final INode node = children[i];
if (node != null) {
tasks.add(new Callable() {
public Object call() throws Exception {
return node.fold(n, combiner, reducer, fjtask, fjfork, fjjoin);
}
});
}
}
return foldTasks(tasks, combiner, fjtask, fjfork, fjjoin);
} else {
return kvreduce(reducer, combiner.invoke());
}
}
/**
* Returns a Callable that calls {@link Folder#refresh()}
*/
private Callable<Void> folder_refresh(final Folder folder) {
return new Callable<Void>() {
@Override
public Void call() {
try {
startSignal.await();
Thread.sleep(random.nextInt(THREAD_WAIT_THRESHOLD));
// System.out.println(Thread.currentThread().getName() + " RERESH");
folder.refresh();
} catch (RepositoryException | InterruptedException e) {
Assert.fail(Thread.currentThread().getName() + " " + e.getMessage());
}
return null;
}
};
}
public static Object[] getChildren(final Accessible a, final Component c) {
if (a == null) return null;
return invokeAndWait(new Callable<Object[]>() {
public Object[] call() throws Exception {
final AccessibleContext ac = a.getAccessibleContext();
if (ac == null) return null;
final int numChildren = ac.getAccessibleChildrenCount();
final Object[] children = new Object[numChildren];
for (int i = 0; i < numChildren; i++) {
children[i] = ac.getAccessibleChild(i);
}
return children;
}
}, c);
}
/**
* <b>Testcase:</b> Add new Product objects <br>
* <b>ExpectedResult:</b>
* <ul>
* <li>All objects can be retrieved from DB and are identical to provided
* Product objects</li>
* <li>Cascaded objects (i.e. PriceModel) is also stored</li>
* <li>A history object is created for each product stored</li>
* <li>History objects are created for CascadeAudit-annotated associated
* objects</li>
* </ul>
*
* @throws Throwable
*/
@Test
public void testAdd() throws Throwable {
try {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doTestAdd();
return null;
}
});
runTX(new Callable<Void>() {
@Override
public Void call() {
doTestAddCheck();
return null;
}
});
} catch (EJBException e) {
throw e.getCause();
}
}
public FakeTestRule(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams buildRuleParams,
ImmutableSet<String> labels,
Optional<Path> pathToTestOutputDirectory,
boolean runTestSeparately,
ImmutableList<Step> testSteps,
Callable<TestResults> interpretedTestResults) {
super(buildTarget, projectFilesystem, buildRuleParams);
this.labels = labels;
this.pathToTestOutputDirectory = pathToTestOutputDirectory;
this.runTestSeparately = runTestSeparately;
this.testSteps = testSteps;
this.interpretedTestResults = interpretedTestResults;
}
private ElementJavadoc getJavaDocFor(
@NonNull final ElementNode node,
@NullAllowed final Callable<Boolean> cancel) {
ElementNode root = getRootNode();
if ( root == null ) {
return null;
}
final ElementHandle<? extends Element> eh = node.getDescritption().getElementHandle();
if (eh == null) {
return null;
}
final JavaSource js = JavaSource.forFileObject( root.getDescritption().fileObject );
if (js == null) {
return null;
}
final JavaDocCalculator calculator = new JavaDocCalculator(eh, cancel);
try {
js.runUserActionTask( calculator, true );
} catch( IOException ioE ) {
Exceptions.printStackTrace( ioE );
return null;
}
return calculator.doc;
}
<T> Future<T> submitAdapterCall(Callable<T> callable)
throws BillingApplicationException {
ExecutorService executor = getSingleThreadExecutor();
Future<T> future = null;
try {
future = executor.submit(callable);
} catch (RejectedExecutionException e) {
logger.logError(Log4jLogger.SYSTEM_LOG, e,
LogMessageIdentifier.ERROR_EXECUTION_OF_BILLING_APPLICATION_TASK_REJECTED);
throw new BillingApplicationException(
"Call to Billing Adapter failed",
new BillingAdapterConnectionException(
"The execution of the billing application task was rejected"));
}
return future;
}
public void asyncRemoteEditOperationData(final String id, OnEditDataIntentObtainedCallback onEditDataIntentObtainedCallback) {
ParcelUuid uuid = onEditDataIntentObtainedCallbackCallbackStore.putCallback(onEditDataIntentObtainedCallback);
doAfterConnect(new Callable<Void>() {
@Override
public Void call() throws Exception {
Message message = Message.obtain();
message.what = C.MSG_EDIT_OPERATION_DATA;
message.replyTo = inMessenger;
Bundle bundle = new Bundle();
bundle.putString(C.EXTRA_PLUGIN_ID, id);
bundle.putParcelable(C.EXTRA_MESSAGE_ID, uuid);
message.setData(bundle);
outMessenger.send(message);
return null;
}
});
}
/**
* That method starts a set of threads, each thread sends a given number of
* notifications.
* The number of threads can be set via the attribute numOfNotificationSenders.
* The number of notification sent by each thread can be set via
* the attribute numOfNotificationSenderLoops.
* Depending on the parameter customNotification we send either custom
* notification(s) or MBeanServer registration and unregistration notification(s).
* When customNotification=true the total number of notification(s) sent is
* (numOfNotificationSenders * numOfNotificationSenderLoops). They are
* sequentially of type NOTIF_TYPE_0 then NOTIF_TYPE_1 and so on.
*
* When customNotification=false the total number of notification(s) sent is
* (numOfNotificationSenders * numOfNotificationSenderLoops) registration
* notification(s)
* +
* (numOfNotificationSenders * numOfNotificationSenderLoops) unregistration
* notification(s)
*
* @throws java.lang.Exception
*/
public void sendNotificationWave(boolean customNotification) throws
Exception {
// Build the set of notification sender.
Collection<Callable<Integer>> tasks =
new HashSet<Callable<Integer>>(numOfNotificationSenders);
for (int i = 1; i <= numOfNotificationSenders; i++) {
tasks.add(new NotifSender(numOfNotificationSenderLoops,
customNotification, i));
}
// Start all notification sender in parallel.
ExecutorService execServ = null;
try {
execServ = Executors.newFixedThreadPool(numOfNotificationSenders);
List<Future<Integer>> taskHandlers = execServ.invokeAll(tasks);
checkNotifSenderThreadStatus(taskHandlers);
} finally {
if (!execServ.isShutdown()) {
execServ.shutdown();
}
}
}
/**
* {@inheritDoc}
*/
@Override
@Transactional
public <T> void deleteAll(final Class<T> type) {
doWithExceptionTranslation(new Callable<Object>() {
@Override
public Object call() {
new JpaCriteriaQuery(getSharedEntityManager()).deleteAll(type);
// If the L2 cache is enabled, items will still be served from the cache
// So, we need to flush that as well for the given type
if (sharedEntityManager.getEntityManagerFactory().getCache() != null) {
sharedEntityManager.getEntityManagerFactory().getCache().evict(type);
}
return null;
}
});
}
/**
* invokeAny(c) throws ExecutionException if no task completes
*/
public void testInvokeAny4() throws Exception {
final ExecutorService e =
new CustomTPE(2, 2,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new NPETask());
try {
e.invokeAny(l);
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof NullPointerException);
}
}
}
public static CreationResult<List<Entity>,List<String>> addChildrenStarting(final Entity parent, String yaml) {
final List<Entity> children = addChildrenUnstarted(parent, yaml);
String childrenCountString;
int size = children.size();
childrenCountString = size+" "+(size!=1 ? "children" : "child");
TaskBuilder<List<String>> taskM = Tasks.<List<String>>builder().displayName("add children")
.dynamic(true)
.tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
.body(new Callable<List<String>>() {
@Override public List<String> call() throws Exception {
return ImmutableList.copyOf(Iterables.transform(children, EntityFunctions.id()));
}})
.description("Add and start "+childrenCountString);
TaskBuilder<?> taskS = Tasks.builder().parallel(true).displayName("add (parallel)").description("Start each new entity");
// autostart if requested
for (Entity child: children) {
if (child instanceof Startable) {
taskS.add(Effectors.invocation(child, Startable.START, ImmutableMap.of("locations", ImmutableList.of())));
} else {
// include a task, just to give feedback in the GUI
taskS.add(Tasks.builder().displayName("create").description("Skipping start (not a Startable Entity)")
.body(Runnables.doNothing())
.tag(BrooklynTaskTags.tagForTargetEntity(child))
.build());
}
}
taskM.add(taskS.build());
Task<List<String>> task = Entities.submit(parent, taskM.build());
return CreationResult.of(children, task);
}
/**
* @param c Callable to run with master key change read lock.
* @return Computed result.
*/
private <T> T withMasterKeyChangeReadLock(Callable<T> c) {
masterKeyChangeLock.readLock().lock();
try {
return c.call();
}
catch (Exception e) {
throw new IgniteException(e);
}
finally {
masterKeyChangeLock.readLock().unlock();
}
}
@Override
public void clear() {
inGlobal(new Callable<Object>() {
@Override public Object call() {
sobj.clear(strict);
return null;
}
});
}
public static AccessibleText getAccessibleText(final Accessible a, final Component c) {
if (a == null) return null;
return invokeAndWait(new Callable<AccessibleText>() {
public AccessibleText call() throws Exception {
final AccessibleContext ac = a.getAccessibleContext();
if (ac == null) return null;
AccessibleText accessibleText = ac.getAccessibleText();
return accessibleText;
}
}, c);
}
static String getTextRange(final AccessibleEditableText aet, final int start, final int stop, final Component c) {
if (aet == null) return null;
return CAccessibility.invokeAndWait(new Callable<String>() {
public String call() throws Exception {
return aet.getTextRange(start, stop);
}
}, c);
}
@Test
public void testMissingDatasetName() {
TestHelpers.assertThrows("Should complain when no dataset name is given",
IllegalArgumentException.class, new Callable<Void>() {
@Override
public Void call() throws Exception {
command.run();
return null;
}
});
verifyZeroInteractions(console);
}
/**
* 高优先级同步执行:主要时get类对外操作接口
*
* @param callable
* @return
*/
public static Object syncHighPriorityExecutor(Callable callable) {
Object object = null;
FutureTask<Object> futureTask = new FutureTask<Object>(callable);
highService.execute(futureTask);
while (!futureTask.isDone() && !futureTask.isCancelled()) {
try {
object = futureTask.get();
} catch (Throwable ignore) {
ExceptionUtil.exceptionThrow(ignore);
}
}
return object;
}
/**
* <p>Executes a transaction in async mode. This method <strong>is thread safe</strong> to avoid concurrent problems. The drawback is only one transaction at time can be executed. The database will be open in write mode. This method uses default error listener to intercept errors.</p>
*
* @param transaction
* transaction to execute
* @return <code>true</code> when transaction successful finished
*/
public Future<Boolean> executeAsync(final Transaction transaction) {
return KriptonLibrary.getExecutorService().submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return execute(transaction, onErrorListener);
}
});
}
@Override
public <R> Future<R> runReadActionWhenReady(final MetadataModelAction<JndiResourcesModel, R> action) throws MetadataModelException, IOException {
return getHelper().runJavaSourceTaskWhenScanFinished(new Callable<R>() {
@Override
public R call() throws Exception {
return action.run(getModel());
}
});
}
@Override
protected Callable<Response> callable() {
return new Callable<Response>() {
@Override
public Response call() throws Exception {
String rowsIdToQuery = rowsId;
if( rowsIdToQuery == null || rowsIdToQuery.isEmpty() ) {
rowsIdToQuery = "*";
}
StringBuilder columnsURIPart = new StringBuilder( "/" );
if( column != null ) {
columnsURIPart.append( column.toURIPart() );
}
columnsURIPart.append('/');
String timeURIPart = "";
if( time != null ) {
timeURIPart = time.toString();
}
URIBuilder uri = uri( HBase.SERVICE_PATH, "/", tableName, "/", rowsIdToQuery, columnsURIPart.toString(), timeURIPart );
HttpDelete delete = new HttpDelete( uri.build() );
return new Response( execute( delete ) );
}
};
}
/** Creates new form SelectSourcesPanel */
SelectRootsPanel (
final int mode,
@NonNull final URL root,
@NonNull final List<? extends URI> attachedRoots,
@NonNull final Callable<List<? extends String>> browseCall,
@NonNull final Function<String, Collection<? extends URI>> convertor,
@NullAllowed final SourceJavadocAttacherImplementation.Definer plugin) {
assert (mode & ~1) == 0;
assert root != null;
assert browseCall != null;
assert convertor != null;
this.mode = mode;
this.root = root;
this.browseCall = browseCall;
this.convertor = convertor;
this.plugin = plugin;
initComponents();
final DefaultListModel<URI> model = new DefaultListModel<URI>();
sources.setModel(model);
sources.setCellRenderer(new RootRenderer());
sources.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
enableSelectionSensitiveActions();
}
});
for (URI r : attachedRoots) {
model.addElement(r);
}
addURL.setVisible(mode != 0);
if (plugin != null) {
download.setVisible(true);
download.setToolTipText(plugin.getDescription());
} else {
download.setVisible(false);
}
enableSelectionSensitiveActions();
}