Java 类java.util.concurrent.Callable 实例源码

项目:DailyTech    文件:AppDbHelper.java   
@Override
public Observable<Article> returnArticleByUrl(final String url) {
    return Observable.fromCallable(new Callable<Article>() {
        @Override
        public Article call() throws Exception {
            List<Article> articles = mDaoSession.getArticleDao().queryBuilder()
                    .where(ArticleDao.Properties.Url.eq(url))
                    .list();

            if (articles.isEmpty()) {
                return null;
            } else {
                return articles.get(0);
            }
        }
    });
}
项目:oscm    文件:BillingDataRetrievalServiceBeanPriceModel2IT.java   
@Test
public void loadNextActiveSubscriptionHistoryForPriceModel_FpEndsAtUpgradeTime()
        throws Exception {
    // given
    setupSubAndPmHistoriesForAsyncUpgrade();

    // when
    SubscriptionHistory subHistory = runTX(
            new Callable<SubscriptionHistory>() {
                @Override
                public SubscriptionHistory call() throws Exception {
                    return bdr
                            .loadNextActiveSubscriptionHistoryForPriceModel(
                                    PRICEMODEL1_KEY,
                                    dateToMillis("2012-10-03 10:20:00"));
                }
            });

    // then
    assertNull(subHistory);
}
项目:RxJava3-preview    文件:ObservableFromCompletableTest.java   
@Test
public void disposedOnCallThrows() {
    List<Throwable> errors = TestCommonHelper.trackPluginErrors();
    try {
        final TestObserver<Integer> to = new TestObserver<Integer>();

        Observable.fromCallable(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                to.cancel();
                throw new TestException();
            }
        })
        .subscribe(to);

        to.assertEmpty();

        TestCommonHelper.assertUndeliverable(errors, 0, TestException.class);
    } finally {
        RxJavaCommonPlugins.reset();
    }
}
项目:ditb    文件:SecureTestUtil.java   
/**
 * Grant permissions globally to the given user. Will wait until all active
 * AccessController instances have updated their permissions caches or will
 * throw an exception upon timeout (10 seconds).
 */
public static void grantGlobal(final HBaseTestingUtility util, final String user,
    final Permission.Action... actions) throws Exception {
  SecureTestUtil.updateACLs(util, new Callable<Void>() {
    @Override
    public Void call() throws Exception {
      try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) {
        try (Table acl = connection.getTable(AccessControlLists.ACL_TABLE_NAME)) {
          BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
          AccessControlService.BlockingInterface protocol =
              AccessControlService.newBlockingStub(service);
          ProtobufUtil.grant(null, protocol, user, actions);
        }
      }
      return null;
    }
  });
}
项目:oscm    文件:TagIT.java   
/**
 * <b>Test case:</b> Add a new tag entry<br>
 * <b>ExpectedResult:</b>
 * <ul>
 * <li>The tag entry can be retrieved from DB and is identical to the
 * provided object</li>
 * <li>A history object is created for the tag entry</li>
 * </ul>
 * 
 * @throws Exception
 */
@Test
public void testAdd() throws Exception {
    runTX(new Callable<Void>() {
        public Void call() throws Exception {
            doTestAdd();
            return null;
        }
    });
    runTX(new Callable<Void>() {
        public Void call() throws Exception {
            doTestAddCheck();
            return null;
        }
    });
}
项目:Flora    文件:CompressEngine.java   
Callable<C> $(I i, CompressSpec spec) throws Exception {
    BitmapFactory.Options decodeBoundsOptions = BitmapOptionsCompat.getDefaultDecodeBoundsOptions();

    getDecodeOptions(i, decodeBoundsOptions);

    spec.options.inSampleSize =
            spec.calculation.calculateInSampleSize(
                    decodeBoundsOptions.outWidth,
                    decodeBoundsOptions.outHeight);
    Logger.i("inSampleSize-->" + spec.options.inSampleSize);
    spec.options.quality =
            spec.calculation.calculateQuality(
                    decodeBoundsOptions.outWidth,
                    decodeBoundsOptions.outHeight,
                    decodeBoundsOptions.outWidth / spec.options.inSampleSize,
                    decodeBoundsOptions.outHeight / spec.options.inSampleSize);
    Logger.i("quality-->" + spec.options.quality);
    while (!MemoryUtil.memoryEnough(
            decodeBoundsOptions.outWidth / spec.options.inSampleSize,
            decodeBoundsOptions.outHeight / spec.options.inSampleSize,
            decodeBoundsOptions.inPreferredConfig,
            spec.safeMemory));

    Callable<C> callable = getCallable(i, spec);
    return callable;
}
项目:oscm    文件:IdentityServiceBeanLdapWithDbIT.java   
@Test(expected = UnsupportedOperationException.class)
public void createUser_LDAPUsed() throws Exception {
    try {
        final VOUserDetails userToCreate = new VOUserDetails();
        userToCreate.setUserId("newUser");
        runTX(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                idMgmt.createUser(userToCreate, Collections.singletonList(
                        UserRoleType.ORGANIZATION_ADMIN), null);
                return null;
            }
        });
    } catch (EJBException e) {
        throw e.getCausedByException();
    }
}
项目:openjdk-jdk10    文件:ScriptObjectMirror.java   
@Override
public boolean isInstance(final Object instance) {
    if (! (instance instanceof ScriptObjectMirror)) {
        return false;
    }

    final ScriptObjectMirror mirror = (ScriptObjectMirror)instance;
    // if not belongs to my global scope, return false
    if (global != mirror.global) {
        return false;
    }

    return inGlobal(new Callable<Boolean>() {
        @Override public Boolean call() {
            return sobj.isInstance(mirror.sobj);
        }
    });
}
项目:oscm    文件:ProductIT.java   
/**
 * <b>Testcase:</b> Try to insert two products with the same productId<br>
 * <b>ExpectedResult:</b> SaasNonUniqueBusinessKeyException
 * 
 * @throws Throwable
 */
@Test(expected = NonUniqueBusinessKeyException.class)
public void testViolateUniqueConstraint() throws Throwable {
    try {
        runTX(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                doTestViolateUniqueConstraintPrepare();
                return null;
            }
        });
        runTX(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                doTestViolateUniqueConstraint();
                return null;
            }
        });
    } catch (EJBException e) {
        throw e.getCause();
    }
}
项目:oscm    文件:BillingServiceBeanIT.java   
@Test
public void testPerformBillingRunForOrganizationNoCosts() throws Exception {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            Scenario.setup(container, false, true);

            PriceModel priceModel = Scenario.getPriceModel();
            priceModel = mgr.getReference(PriceModel.class,
                    priceModel.getKey());

            priceModel.setType(PriceModelType.FREE_OF_CHARGE);
            return null;
        }
    });

    BillingResult res = serviceBill.generateBillingForAnyPeriod(
            System.currentTimeMillis(), System.currentTimeMillis() + 20,
            Scenario.getCustomer().getKey()).get(0);

    Assert.assertNotNull("Result must not be null", res);
    checkEquals("Wrong costs contained", new BigDecimal("0.68"),
            res.getGrossAmount(), PriceConverter.NORMALIZED_PRICE_SCALING);
}
项目:oscm    文件:SecurityInvocationHandlerTest.java   
@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;
        }
    };
}
项目:snowflake    文件:PartnerStore.java   
public void addPartner(String key, Partner partner) {
    String partnerPath = ZKPaths.makePath(partnerStorePath, key);
    RetryRunner.create().onFinalError(e -> {
        LOGGER.error("addPartner.error", e);
        ReporterHolder.incException(e);
        throw new ServiceErrorException(ErrorCode.SYSTEM_ERROR);
    }).run((Callable<Void>) () -> {
        if (client.checkExists().creatingParentsIfNeeded().forPath(partnerPath) != null) {
            client.setData()
                  .forPath(partnerPath, JSONObject.toJSONBytes(partner));
        } else {
            client.create()
                  .creatingParentsIfNeeded()
                  .withMode(CreateMode.PERSISTENT)
                  .forPath(partnerPath, JSONObject.toJSONBytes(partner));
        }
        return null;
    });
}
项目:oscm    文件:ServiceProvisioningConcurrencyIT.java   
private void createMarketingPermission(final long tpKey,
        final long orgRefKey) throws Exception {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            TechnicalProduct technicalProduct = dm.find(
                    TechnicalProduct.class, tpKey);
            OrganizationReference reference = dm.find(
                    OrganizationReference.class, orgRefKey);

            MarketingPermission permission = new MarketingPermission();
            permission.setOrganizationReference(reference);
            permission.setTechnicalProduct(technicalProduct);
            dm.persist(permission);
            return null;
        }
    });
}
项目:oscm    文件:MarketplaceServiceBeanGetMarketplaceAndOrganizationIT.java   
@Test
public void getMarketplacesForOrganization_InitialSupplier()
        throws Exception {
    Long suppInitialUserKey = runTX(new Callable<Long>() {

        @Override
        public Long call() throws Exception {
            Organization org = Organizations.createOrganization(mgr,
                    OrganizationRoleType.SUPPLIER);
            PlatformUser user = Organizations.createUserForOrg(mgr, org,
                    true, "testGetMarketplaces_InitialSupplier");
            mgr.flush();
            return Long.valueOf(user.getKey());
        }
    });
    container.login(suppInitialUserKey.longValue(), ROLE_SERVICE_MANAGER);
    List<VOMarketplace> list = marketplaceService
            .getMarketplacesForOrganization();
    assertNotNull(list);
    assertEquals("Created user may at least publish to open mp", 1,
            list.size());
    assertEquals("Created user may at least publish to open mp",
            OPEN_MP_ID, list.get(0).getMarketplaceId());
}
项目:oscm    文件:TechnicalProductOperationIT.java   
private TechnicalProductOperation doModify(
        final TechnicalProductOperation op) throws Exception {

    final TechnicalProductOperation read = runTX(new Callable<TechnicalProductOperation>() {

        @Override
        public TechnicalProductOperation call() throws Exception {
            TechnicalProductOperation tpo = mgr.getReference(
                    TechnicalProductOperation.class, op.getKey());
            tpo.setActionUrl("someOtherUlr");
            return mgr.getReference(TechnicalProductOperation.class,
                    tpo.getKey());
        }
    });
    Assert.assertEquals("ID", read.getOperationId());
    Assert.assertEquals("someOtherUlr", read.getActionUrl());
    return read;
}
项目:oscm    文件:PricedProductRoleIT.java   
/**
 * Test role definition creation.
 * 
 * @throws Exception
 */
@Test
public void testCreate() throws Exception {

    final BigDecimal pricePerUser = BigDecimal.valueOf(40L);
    final String roleID = "roleID";

    runTX(new Callable<Void>() {
        public Void call() throws Exception {
            final long key = doCreate(roleID, pricePerUser);

            PricedProductRole pricedRole = mgr.find(PricedProductRole.class,
                    key);

            Assert.assertEquals(key, pricedRole.getKey());
            Assert.assertEquals(pricePerUser, pricedRole.getPricePerUser());

            return null;
        }
    });
}
项目:incubator-netbeans    文件:Exceptions.java   
private static String extractLocalizedMessage(final Throwable t) {
    String msg = null;
    if (t instanceof Callable) {
        Object res = null;
        try {
            res = ((Callable) t).call();
        } catch (Exception ex) {
            LOG.log(Level.WARNING, null, t); // NOI18N
        }
        if (res instanceof LogRecord[]) {
            for (LogRecord r : (LogRecord[])res) {
                ResourceBundle b = r.getResourceBundle();
                if (b != null) {
                    msg = b.getString(r.getMessage());
                    break;
                }
            }
        }
    }
    return msg;
}
项目:oscm    文件:DataServiceBeanIT.java   
@Test(expected = InvalidUserSession.class)
public void testGetCurrentUserExistingButNoAdminClientCert()
        throws Exception {
    String dn = "dn=1";
    createOrgAndUserForWS(dn, false,
            OrganizationRoleType.TECHNOLOGY_PROVIDER);
    container.login(dn);
    PlatformUser user = runTX(new Callable<PlatformUser>() {
        @Override
        public PlatformUser call() throws Exception {
            return mgr.getCurrentUserIfPresent();
        }
    });
    Assert.assertNull("No valid user object expected", user);
    try {
        runTX(new Callable<PlatformUser>() {
            @Override
            public PlatformUser call() throws Exception {
                return mgr.getCurrentUser();
            }
        });
    } catch (EJBException e) {
        throw e.getCausedByException();
    }
}
项目:the-vigilantes    文件:BlobRegressionTest.java   
/**
 * Tests fix for BUG#20453671 - CLOB.POSITION() API CALL WITH CLOB INPUT RETURNS EXCEPTION
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug20453671() throws Exception {
    this.rs = this.stmt.executeQuery("select 'abcd', 'a', 'b', 'c', 'd', 'e'");
    this.rs.next();

    final Clob in = this.rs.getClob(1);
    final ResultSet locallyScopedRs = this.rs;
    assertThrows(SQLException.class, "Illegal starting position for search, '0'", new Callable<Void>() {
        public Void call() throws Exception {
            in.position(locallyScopedRs.getClob(2), 0);
            return null;
        }
    });
    assertThrows(SQLException.class, "Starting position for search is past end of CLOB", new Callable<Void>() {
        public Void call() throws Exception {
            in.position(locallyScopedRs.getClob(2), 10);
            return null;
        }
    });

    assertEquals(1, in.position(this.rs.getClob(2), 1));
    assertEquals(2, in.position(this.rs.getClob(3), 1));
    assertEquals(3, in.position(this.rs.getClob(4), 1));
    assertEquals(4, in.position(this.rs.getClob(5), 1));
    assertEquals(-1, in.position(this.rs.getClob(6), 1));
}
项目:spanner-jdbc-converter    文件:DataCopier.java   
private ConversionResult runWorkers(List<? extends Callable<ConversionResult>> callables)
{
    Exception exception = null;
    ExecutorService service = Executors.newFixedThreadPool(config.getNumberOfTableWorkers());
    List<Future<ConversionResult>> futures = new ArrayList<>(callables.size());
    long startTime = System.currentTimeMillis();
    for (Callable<ConversionResult> callable : callables)
    {
        futures.add(service.submit(callable));
    }
    service.shutdown();
    try
    {
        service.awaitTermination(config.getTableWorkerMaxWaitInMinutes(), TimeUnit.MINUTES);
    }
    catch (InterruptedException e)
    {
        exception = e;
        service.shutdownNow();
        log.severe("Error while waiting for workers to finish: " + e.getMessage());
    }
    long endTime = System.currentTimeMillis();
    return ConversionResult.collect(futures, startTime, endTime, exception);
}
项目:incubator-freemarker-online-tester    文件:FreeMarkerServiceTest.java   
@Test
public void testTemplateExecutionTimeout() throws InterruptedException, ExecutionException {
    serviceBuilder.setMaxTemplateExecutionTime(200);

    // To avoid blocking the CI server forever without giving error:
    Future<FreeMarkerServiceResponse> future = Executors.newSingleThreadExecutor().submit(
            new Callable<FreeMarkerServiceResponse>() {

                @Override
                public FreeMarkerServiceResponse call() throws Exception {
                    return getService().calculateTemplateOutput(
                            "<#list 1.. as _></#list>", Collections.<String, Object>emptyMap(), null, null, null);
                }

            });
    FreeMarkerServiceResponse serviceResponse;
    try {
        serviceResponse = future.get(BLOCKING_TEST_TIMEOUT, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        throw new AssertionError("The template execution wasn't aborted (within the timeout).");
    }
    assertThat(serviceResponse.isSuccesful(), is(false));
    assertThat(serviceResponse.getFailureReason(), instanceOf(TimeoutException.class));
}
项目:oscm    文件:PaymentProcessServiceIntIT.java   
/**
 * Creates an initial payment result object for the given billing result
 * object with the given status.
 * 
 * @param br
 *            The billing result object the payment processing was based on.
 * @param status
 *            The status the payment result object should have.
 * @return Returns the initialized payment result.
 * @throws Exception
 */
private PaymentResult initPaymentResult(final BillingResult br,
        final PaymentProcessingStatus status) throws Exception {
    return runTX(new Callable<PaymentResult>() {
        @Override
        public PaymentResult call() throws Exception {
            PaymentResult pr = new PaymentResult();
            pr.setProcessingStatus(status);
            pr.setProcessingTime(TIMESTAMP);
            pr.setBillingResult(br);

            br.setPaymentResult(pr);

            mgr.persist(pr);
            return pr;
        }
    });
}
项目:UDOOBluLib-android    文件:UdooBluManager.java   
private void setNotification(final String address, final UDOOBLESensor udoobleSensor, final INotificationListener<byte[]> iNotificationListener) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                UUID servUuid = udoobleSensor.getService();
                UUID dataUuid = udoobleSensor.getData();
                BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);
                    mINotificationListenerMap.put(address + charac.getUuid().toString(), iNotificationListener);
                    mUdooBluService.setCharacteristicNotification(address, charac, true);
                    Log.i(TAG, "setNotification: ");
                } else if (iNotificationListener != null)
                    iNotificationListener.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                return null;
            }
        });
    } else if (BuildConfig.DEBUG)
        Log.i(TAG, "BluManager not ready");
}
项目:oscm-app    文件:AsynchronousProvisioningProxyIT.java   
@Ignore
@Test
public void testAsyncCreateTimerInitFailure() throws Exception {
    final InstanceDescription descr = new InstanceDescription();
    descr.setInstanceId("appId123");
    descr.setBaseUrl("http://here/");
    when(
            controllerMock.createInstance(Matchers
                    .any(ProvisioningSettings.class))).thenReturn(descr);

    doThrow(new APPlatformException("TimerInitFailure")).when(timerService)
            .initTimers();
    final BaseResult result = runTX(new Callable<BaseResult>() {
        @Override
        public BaseResult call() {
            final InstanceRequest rq = basicInstanceRequest;
            rq.setOrganizationId("org123");
            rq.setSubscriptionId("sub123");
            rq.setDefaultLocale("de");
            rq.setLoginUrl("http://bes/");
            return proxy.asyncCreateInstance(rq, null);
        }
    });
    assertEquals(1, result.getRc());
    assertEquals("TimerInitFailure", result.getDesc());
}
项目:neoscada    文件:ScriptDataSource.java   
@Override
public NotifyFuture<WriteAttributeResults> startWriteAttributes ( final Map<String, Variant> attributes, final OperationParameters operationParameters )
{
    final ScriptExecutor writeCommand = this.writeCommand;
    if ( writeCommand == null )
    {
        return new InstantErrorFuture<WriteAttributeResults> ( new OperationException ( "Not supported" ) );
    }

    final FutureTask<WriteAttributeResults> task = new FutureTask<WriteAttributeResults> ( new Callable<WriteAttributeResults> () {
        @Override
        public WriteAttributeResults call () throws Exception
        {
            return convertAttributeResult ( attributes, performWrite ( writeCommand, null, attributes, operationParameters ) );
        }
    } );
    this.executor.execute ( task );
    return task;
}
项目:UDOOBluLib-android    文件:UdooBluManager.java   
public void readDigital(final String address, final IReaderListener<byte[]> readerListener) {
    if (isBluManagerReady) {
        addOperation(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                UUID servUuid = UDOOBLE.UUID_IOPIN_SERV;
                UUID dataUuid = UDOOBLE.UUID_IOPIN_DIGITAL_DATA;
                BluetoothGattService serv = mUdooBluService.getService(address, servUuid);

                if (serv != null) {
                    BluetoothGattCharacteristic charac = serv.getCharacteristic(dataUuid);
                    mUdooBluService.readCharacteristic(address, charac);
                    mIReaderListenerMap.put(address + charac.getUuid().toString(), readerListener);
                } else {
                    if (readerListener != null)
                        readerListener.onError(new UdooBluException(UdooBluException.BLU_GATT_SERVICE_NOT_FOUND));
                }
                return null;
            }
        });
    } else {
        if (BuildConfig.DEBUG)
            Log.i(TAG, "BluManager not ready");

        if (readerListener != null)
            readerListener.onError(new UdooBluException(UdooBluException.BLU_SERVICE_NOT_READY));
    }
}
项目:RxJava3-preview    文件:ObservableWindowBoundarySupplier.java   
WindowBoundaryMainObserver(Observer<? super Observable<T>> actual, Callable<? extends ObservableSource<B>> other,
        int bufferSize) {
    super(actual, new MpscLinkedQueue<Object>());
    this.other = other;
    this.bufferSize = bufferSize;
    windows.lazySet(1);
}
项目:indigo    文件:DetailedReportCategory.java   
/**
 * Sets a detail.
 *
 * @param key the key
 * @param value the value supplier
 * @return this category
 */
@Nonnull
default DetailedReportCategory detail(@Nonnull final String key, @Nonnull final Callable<String> value) {
  try {
    return this.detail(key, value.call());
  } catch(final Throwable t) {
    return this.detail(key, t);
  }
}
项目:oscm    文件:SubscriptionDaoSubscriptionsIT.java   
private List<ReportResultData> retrieveSubscriptionReportData(
        final String organizationId) throws Exception {
    return runTX(new Callable<List<ReportResultData>>() {
        @Override
        public List<ReportResultData> call() throws Exception {
            return dao.retrieveSubscriptionReportData(organizationId);
        }
    });
}
项目:oscm    文件:ServiceProvisioningPartnerServiceLocalBeanContainerIT.java   
private CatalogEntry getCatalogEntryForProduct(final long productKey)
        throws Exception {
    return runTX(new Callable<CatalogEntry>() {
        @Override
        public CatalogEntry call() throws Exception {
            Product product = ds.getReference(Product.class, productKey);
            CatalogEntry catalogEntry = product.getCatalogEntries().get(0);
            catalogEntry.setBrokerPriceModel(unproxyEntity(catalogEntry.getBrokerPriceModel()));
            catalogEntry.setResellerPriceModel(unproxyEntity(catalogEntry.getResellerPriceModel()));
            return catalogEntry;
        }
    });
}
项目:oscm    文件:LdapSettingsMangementServiceBeanIT.java   
@Test
public void resetOrganizationSettings_orgPropertiesDefined_platformPropertiesDefined()
        throws Throwable {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            ldapSettingsMgmtSvc.resetOrganizationSettings(customerOrgId);
            return null;
        }
    });

    assertEquals(
            "Exactly one organization-specific properties must be defined",
            1, getOrganizationSettings(customerOrg, null).size());
    assertEquals(
            "Returned value must be empty (to bind it to platform property)",
            "",
            getOrganizationSettings(customerOrg,
                    SettingType.LDAP_CONTEXT_FACTORY).get(0)
                    .getSettingValue());
    // platform settings must be left unchanged
    assertEquals("Exactly one platform property must be defined", 1,
            getPlatformSettings(null).size());
    assertEquals(
            "Returned value must correspond to value set during setup",
            "myLdapContextFactory",
            getPlatformSettings(SettingType.LDAP_CONTEXT_FACTORY).get(0)
                    .getSettingValue());
}
项目:aliyun-cloudphotos-android-demo    文件:MyAlbum.java   
public static void updateCover(final long albumId, final long coverPhotoId, final boolean isCoverVideo, final DatabaseCallback<Long> callback) {
    DatabaseHelper.getInstance().execute(new Runnable() {
        @Override
        public void run() {
            final RuntimeExceptionDao<MyAlbum, Long> dao = DatabaseHelper.getInstance().getCachedRuntimeExceptionDao(MyAlbum.class);
            dao.callBatchTasks(new Callable() {
                @Override
                public Void call() throws Exception {
                    try {
                        if (dao.idExists(albumId)) {
                            UpdateBuilder<MyAlbum, Long> ub = dao.updateBuilder();
                            ub.where().eq("id", albumId);
                            ub.updateColumnValue("coverPhotoId", coverPhotoId);
                            ub.updateColumnValue("isCoverVideo", isCoverVideo);
                            ub.update();
                        }
                    } catch (Exception e) {
                        Log.w(TAG, e.getMessage());
                    }
                    return null;
                }
            });

            List<Long> changed = new ArrayList<>();
            changed.add(albumId);

            callback.onCompleted(0, changed);
        }
    });
}
项目:openjdk-jdk10    文件:ScheduledExecutorTest.java   
/**
 * timed invokeAll(,,null) throws NPE
 */
public void testTimedInvokeAllNullTimeUnit() throws Exception {
    final ExecutorService e = new ScheduledThreadPoolExecutor(2);
    try (PoolCleaner cleaner = cleaner(e)) {
        List<Callable<String>> l = new ArrayList<>();
        l.add(new StringTask());
        try {
            e.invokeAll(l, randomTimeout(), null);
            shouldThrow();
        } catch (NullPointerException success) {}
    }
}
项目:ditb    文件:SecureTestUtil.java   
@SuppressWarnings("rawtypes")
private static void updateACLs(final HBaseTestingUtility util, Callable c) throws Exception {
  // Get the current mtimes for all access controllers
  final Map<AccessController,Long> oldMTimes = getAuthManagerMTimes(util.getHBaseCluster());

  // Run the update action
  c.call();

  // Wait until mtimes for all access controllers have incremented
  util.waitFor(WAIT_TIME, 100, new Predicate<IOException>() {
    @Override
    public boolean evaluate() throws IOException {
      Map<AccessController,Long> mtimes = getAuthManagerMTimes(util.getHBaseCluster());
      for (Map.Entry<AccessController,Long> e: mtimes.entrySet()) {
        if (!oldMTimes.containsKey(e.getKey())) {
          LOG.error("Snapshot of AccessController state does not include instance on region " +
            e.getKey().getRegion().getRegionInfo().getRegionNameAsString());
          // Error out the predicate, we will try again
          return false;
        }
        long old = oldMTimes.get(e.getKey());
        long now = e.getValue();
        if (now <= old) {
          LOG.info("AccessController on region " +
            e.getKey().getRegion().getRegionInfo().getRegionNameAsString() +
            " has not updated: mtime=" + now);
          return false;
        }
      }
      return true;
    }
  });
}
项目:RxJava3-preview    文件:FlowableGenerateTest.java   
@Test
public void badRequest() {
    TestHelper.assertBadRequestReported(Flowable.generate(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return 1;
            }
        }, new BiConsumer<Object, Emitter<Object>>() {
            @Override
            public void accept(Object s, Emitter<Object> e) throws Exception {
                e.onComplete();
            }
        }, Functions.emptyConsumer()));
}
项目:RxJava3-preview    文件:ObservableBufferBoundary.java   
BufferBoundaryObserver(Observer<? super U> actual,
        ObservableSource<? extends Open> bufferOpen,
        Function<? super Open, ? extends ObservableSource<? extends Close>> bufferClose,
                Callable<U> bufferSupplier) {
    super(actual, new MpscLinkedQueue<U>());
    this.bufferOpen = bufferOpen;
    this.bufferClose = bufferClose;
    this.bufferSupplier = bufferSupplier;
    this.buffers = new LinkedList<U>();
    this.resources = new CompositeDisposable();
}
项目:GitHub    文件:RxTransaction.java   
/**
 * Rx version of {@link AbstractDaoSession#runInTx(Runnable)} returning an Observable.
 */
@Experimental
public Observable<Void> run(final Runnable runnable) {
    return wrap(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            daoSession.runInTx(runnable);
            return null;
        }
    });
}
项目:oscm    文件:AccountServiceBeanIT.java   
@Test(expected = OperationNotPermittedException.class)
public void testUpdateAccountInformationDifferentUsersData()
        throws Exception {
    container.login(String.valueOf(supplier1User.getKey()));
    final VOUserDetails user = idManagement.getCurrentUserDetails();
    createCustomerAndUser(true);
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            accountMgmt.updateAccountInformation(null, user, null, null);
            return null;
        }
    });
}
项目:oscm    文件:UsageLicenseHistoryIT.java   
@Test
public void testLog_ModdateModUser() throws Throwable {
    runTX(new Callable<Void>() {
        public Void call() throws Exception {
            addSubscription(false, false);
            addUsageLicense();
            return null;
        }
    });
    final String initialUserId = user.getUserId();
    runTX(new Callable<Void>() {
        public Void call() throws Exception {
            user = (PlatformUser) mgr.find(user);
            user.setUserId("NewUserId");
            return null;
        }
    });
    new LogQueryRunner() {

        @Override
        protected void assertResult(List<?> result) {
            assertEquals(2, result.size());
            for (Object object : result) {
                Object[] usageLicense = (Object[]) object;
                assertEquals(
                        "Wrong PlatformUserHistory entry (for moduser)",
                        initialUserId, usageLicense[2]);
            }
            user = (PlatformUser) mgr.find(user);
            assertEquals("NewUserId", user.getUserId());
        }
    }.run();
}
项目:OpenVertretung    文件:ResultSetTest.java   
/**
 * Test for ResultSet.updateObject(), non-updatable ResultSet behaviour.
 */
public void testNonUpdResultSetUpdateObject() throws Exception {
    this.rs = this.stmt.executeQuery("SELECT 'testResultSetUpdateObject' AS test");

    final ResultSet rsTmp = this.rs;
    assertThrows(NotUpdatable.class, "Result Set not updatable.*", new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            rsTmp.updateObject(1, rsTmp.toString(), JDBCType.VARCHAR);
            return null;
        }
    });
    assertThrows(NotUpdatable.class, "Result Set not updatable.*", new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            rsTmp.updateObject(1, rsTmp.toString(), JDBCType.VARCHAR, 10);
            return null;
        }
    });
    assertThrows(NotUpdatable.class, "Result Set not updatable.*", new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            rsTmp.updateObject("test", rsTmp.toString(), JDBCType.VARCHAR);
            return null;
        }
    });
    assertThrows(NotUpdatable.class, "Result Set not updatable.*", new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            rsTmp.updateObject("test", rsTmp.toString(), JDBCType.VARCHAR, 10);
            return null;
        }
    });
}