Java Code Examples for java.util.concurrent.Callable

The following are top voted examples for showing how to use java.util.concurrent.Callable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: DailyTech   File: AppDbHelper.java   View source code 6 votes vote down vote up
@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);
            }
        }
    });
}
 
Example 2
Project: oscm   File: BillingDataRetrievalServiceBeanPriceModel2IT.java   View source code 6 votes vote down vote up
@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);
}
 
Example 3
Project: RxJava3-preview   File: ObservableFromCompletableTest.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 4
Project: ditb   File: SecureTestUtil.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
  });
}
 
Example 5
Project: oscm   File: TagIT.java   View source code 6 votes vote down vote up
/**
 * <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;
        }
    });
}
 
Example 6
Project: Flora   File: CompressEngine.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: oscm   File: IdentityServiceBeanLdapWithDbIT.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 8
Project: openjdk-jdk10   File: ScriptObjectMirror.java   View source code 6 votes vote down vote up
@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);
        }
    });
}
 
Example 9
Project: oscm   File: ProductIT.java   View source code 6 votes vote down vote up
/**
 * <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();
    }
}
 
Example 10
Project: oscm   File: BillingServiceBeanIT.java   View source code 6 votes vote down vote up
@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);
}
 
Example 11
Project: oscm   File: SecurityInvocationHandlerTest.java   View source code 6 votes vote down vote up
@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;
        }
    };
}
 
Example 12
Project: snowflake   File: PartnerStore.java   View source code 6 votes vote down vote up
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;
	});
}
 
Example 13
Project: oscm   File: ServiceProvisioningConcurrencyIT.java   View source code 6 votes vote down vote up
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;
        }
    });
}
 
Example 14
Project: oscm   File: MarketplaceServiceBeanGetMarketplaceAndOrganizationIT.java   View source code 6 votes vote down vote up
@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());
}
 
Example 15
Project: oscm   File: TechnicalProductOperationIT.java   View source code 6 votes vote down vote up
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;
}
 
Example 16
Project: oscm   File: PricedProductRoleIT.java   View source code 6 votes vote down vote up
/**
 * 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;
        }
    });
}
 
Example 17
Project: incubator-netbeans   File: Exceptions.java   View source code 6 votes vote down vote up
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;
}
 
Example 18
Project: oscm   File: DataServiceBeanIT.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 19
Project: the-vigilantes   File: BlobRegressionTest.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 20
Project: spanner-jdbc-converter   File: DataCopier.java   View source code 6 votes vote down vote up
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);
}
 
Example 21
Project: incubator-freemarker-online-tester   File: FreeMarkerServiceTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 22
Project: oscm   File: PaymentProcessServiceIntIT.java   View source code 6 votes vote down vote up
/**
 * 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;
        }
    });
}
 
Example 23
Project: UDOOBluLib-android   File: UdooBluManager.java   View source code 6 votes vote down vote up
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");
}
 
Example 24
Project: oscm-app   File: AsynchronousProvisioningProxyIT.java   View source code 6 votes vote down vote up
@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());
}
 
Example 25
Project: neoscada   File: ScriptDataSource.java   View source code 6 votes vote down vote up
@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;
}
 
Example 26
Project: UDOOBluLib-android   File: UdooBluManager.java   View source code 5 votes vote down vote up
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));
    }
}
 
Example 27
Project: RxJava3-preview   File: ObservableWindowBoundarySupplier.java   View source code 5 votes vote down vote up
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);
}
 
Example 28
Project: indigo   File: DetailedReportCategory.java   View source code 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 29
Project: oscm   File: SubscriptionDaoSubscriptionsIT.java   View source code 5 votes vote down vote up
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);
        }
    });
}
 
Example 30
Project: oscm   File: ServiceProvisioningPartnerServiceLocalBeanContainerIT.java   View source code 5 votes vote down vote up
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;
        }
    });
}
 
Example 31
Project: oscm   File: LdapSettingsMangementServiceBeanIT.java   View source code 5 votes vote down vote up
@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());
}
 
Example 32
Project: aliyun-cloudphotos-android-demo   File: MyAlbum.java   View source code 5 votes vote down vote up
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);
        }
    });
}
 
Example 33
Project: openjdk-jdk10   File: ScheduledExecutorTest.java   View source code 5 votes vote down vote up
/**
 * 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) {}
    }
}
 
Example 34
Project: ditb   File: SecureTestUtil.java   View source code 5 votes vote down vote up
@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;
    }
  });
}
 
Example 35
Project: RxJava3-preview   File: FlowableGenerateTest.java   View source code 5 votes vote down vote up
@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()));
}
 
Example 36
Project: RxJava3-preview   File: ObservableBufferBoundary.java   View source code 5 votes vote down vote up
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();
}
 
Example 37
Project: GitHub   File: RxTransaction.java   View source code 5 votes vote down vote up
/**
 * 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;
        }
    });
}
 
Example 38
Project: oscm   File: AccountServiceBeanIT.java   View source code 5 votes vote down vote up
@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;
        }
    });
}
 
Example 39
Project: oscm   File: UsageLicenseHistoryIT.java   View source code 5 votes vote down vote up
@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();
}
 
Example 40
Project: OpenVertretung   File: ResultSetTest.java   View source code 5 votes vote down vote up
/**
 * 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;
        }
    });
}