Example usage for java.util.concurrent Callable call

List of usage examples for java.util.concurrent Callable call

Introduction

In this page you can find the example usage for java.util.concurrent Callable call.

Prototype

V call() throws Exception;

Source Link

Document

Computes a result, or throws an exception if unable to do so.

Usage

From source file:com.jivesoftware.os.upena.deployable.UpenaMain.java

public AmzaService startAmza(String workingDir, AmzaStats amzaStats, BAInterner baInterner, int writerId,
        RingHost ringHost, RingMember ringMember, OAuthSigner authSigner,
        TenantAwareHttpClient<String> systemTakeClient, TenantAwareHttpClient<String> stripedTakeClient,
        TenantAwareHttpClient<String> ringClient, AtomicReference<Callable<RingTopology>> topologyProvider,
        String clusterDiscoveryName, String multicastGroup, int multicastPort) throws Exception {

    //Deployable deployable = new Deployable(new String[0]);

    SnowflakeIdPacker idPacker = new SnowflakeIdPacker();
    JiveEpochTimestampProvider timestampProvider = new JiveEpochTimestampProvider();

    SickThreads sickThreads = new SickThreads();
    SickPartitions sickPartitions = new SickPartitions();
    //deployable.addHealthCheck(new SickThreadsHealthCheck(deployable.config(AmzaSickThreadsHealthConfig.class), sickThreads));
    //deployable.addHealthCheck(new SickPartitionsHealthCheck(sickPartitions));

    TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(new ConstantWriterIdProvider(writerId),
            idPacker, timestampProvider);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, false);

    PartitionPropertyMarshaller partitionPropertyMarshaller = new PartitionPropertyMarshaller() {

        @Override/*from   www . j a v  a  2 s . c om*/
        public PartitionProperties fromBytes(byte[] bytes) {
            try {
                return mapper.readValue(bytes, PartitionProperties.class);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public byte[] toBytes(PartitionProperties partitionProperties) {
            try {
                return mapper.writeValueAsBytes(partitionProperties);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    };

    BinaryPrimaryRowMarshaller primaryRowMarshaller = new BinaryPrimaryRowMarshaller(); // hehe you cant change this :)
    BinaryHighwaterRowMarshaller highwaterRowMarshaller = new BinaryHighwaterRowMarshaller(baInterner);

    RowsTakerFactory systemRowsTakerFactory = () -> new HttpRowsTaker(amzaStats, systemTakeClient, mapper,
            baInterner);
    RowsTakerFactory rowsTakerFactory = () -> new HttpRowsTaker(amzaStats, stripedTakeClient, mapper,
            baInterner);

    AvailableRowsTaker availableRowsTaker = new HttpAvailableRowsTaker(ringClient, baInterner, mapper);
    AquariumStats aquariumStats = new AquariumStats();

    QuorumTimeouts quorumTimeoutsConfig = bindDefault(QuorumTimeouts.class);
    HealthTimer quorumLatency = HealthFactory.getHealthTimer(QuorumLatency.class, TimerHealthChecker.FACTORY);

    TriggerTimeoutHealthCheck quorumTimeoutHealthCheck = new TriggerTimeoutHealthCheck(
            () -> amzaStats.getGrandTotal().quorumTimeouts.longValue(), quorumTimeoutsConfig);
    //deployable.addHealthCheck(quorumTimeoutHealthCheck);

    //LABPointerIndexConfig amzaLabConfig = deployable.config(LABPointerIndexConfig.class);
    LABPointerIndexConfig amzaLabConfig = bindDefault(UpenaLABPointerIndexConfig.class);

    AmzaServiceConfig amzaServiceConfig = new AmzaServiceConfig();
    amzaServiceConfig.systemRingSize = 1;
    amzaServiceConfig.workingDirectories = new String[] { new File(workingDir, "state").getAbsolutePath() };
    amzaServiceConfig.aquariumLivelinessFeedEveryMillis = 5_000;
    amzaServiceConfig.checkIfCompactionIsNeededIntervalInMillis = 30_000;
    amzaServiceConfig.deltaMergeThreads = 2;
    amzaServiceConfig.maxUpdatesBeforeDeltaStripeCompaction = 10_000;
    amzaServiceConfig.numberOfTakerThreads = 2;
    amzaServiceConfig.hardFsync = true;
    amzaServiceConfig.takeSlowThresholdInMillis = 1_000;
    amzaServiceConfig.rackDistributionEnabled = false;

    Set<RingMember> blacklistRingMembers = Sets.newHashSet();
    AmzaService amzaService = new AmzaServiceInitializer().initialize(amzaServiceConfig, baInterner,
            aquariumStats, amzaStats, quorumLatency, () -> {
                Callable<RingTopology> ringTopologyCallable = topologyProvider.get();
                if (ringTopologyCallable != null) {
                    try {
                        return ringTopologyCallable.call().entries.size();
                    } catch (Exception x) {
                        LOG.error("issue determining system ring size", x);
                    }
                }
                return -1;
            }, sickThreads, sickPartitions, primaryRowMarshaller, highwaterRowMarshaller, ringMember, ringHost,
            blacklistRingMembers, orderIdProvider, idPacker, partitionPropertyMarshaller,
            (workingIndexDirectories, indexProviderRegistry, ephemeralRowIOProvider, persistentRowIOProvider,
                    partitionStripeFunction) -> {

                indexProviderRegistry
                        .register(
                                new BerkeleyDBWALIndexProvider(BerkeleyDBWALIndexProvider.INDEX_CLASS_NAME,
                                        partitionStripeFunction, workingIndexDirectories),
                                persistentRowIOProvider);

                indexProviderRegistry.register(new LABPointerIndexWALIndexProvider(amzaLabConfig,
                        LABPointerIndexWALIndexProvider.INDEX_CLASS_NAME, partitionStripeFunction,
                        workingIndexDirectories), persistentRowIOProvider);
            }, availableRowsTaker, systemRowsTakerFactory, rowsTakerFactory,
            Optional.<TakeFailureListener>absent(), rowsChanged -> {
            });

    topologyProvider.set(() -> amzaService.getRingReader().getRing(AmzaRingReader.SYSTEM_RING, -1));

    amzaService.start(ringMember, ringHost);
    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Amza Service Started");
    LOG.info("-----------------------------------------------------------------------");

    if (clusterDiscoveryName != null) {
        AmzaDiscovery amzaDiscovery = new AmzaDiscovery(amzaService.getRingReader(),
                amzaService.getRingWriter(), clusterDiscoveryName, multicastGroup, multicastPort,
                new AtomicInteger(amzaService.getRingReader().getRingSize(AmzaRingReader.SYSTEM_RING, -1)) // Grrr
        );
        amzaDiscovery.start();
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      Amza Service Discovery Online");
        LOG.info("-----------------------------------------------------------------------");
    } else {
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|     Amza Service is in manual Discovery mode.  No cluster discovery name was specified");
        LOG.info("-----------------------------------------------------------------------");
    }

    return amzaService;
}

From source file:org.pentaho.di.repository.pur.PurRepositoryIT.java

private void testDoesNotChangeFileWhenFailsToRename(RepositoryElementInterface element1,
        RepositoryElementInterface element2, Callable<RepositoryElementInterface> loader) throws Exception {
    final String name1 = "name1";
    final String name2 = "name2";

    element1.setName(name1);//  w w  w.  j av a 2  s . co  m
    element2.setName(name2);

    repository.save(element1, "", null);
    repository.save(element2, "", null);

    element2.setName(name1);
    try {
        repository.save(element2, "", null, true);
        fail("A naming conflict should occur");
    } catch (KettleException e) {
        // expected to be thrown
        element2.setName(name2);
    }
    RepositoryElementInterface loaded = loader.call();
    assertEquals(element2, loaded);
}

From source file:nl.b3p.viewer.stripes.AttributesActionBean.java

private int lookupTotalCountCache(Callable<Integer> countProducer) throws Exception {
    HttpSession session = context.getRequest().getSession();

    Integer total = null;/*from ww w .ja  va2 s.  c om*/
    Long age = null;
    Long cacheAppLayerId = (Long) session.getAttribute(CACHE_APPLAYER);
    if (appLayer.getId().equals(cacheAppLayerId)) {
        if ((filter == null && session.getAttribute(CACHE_FILTER) == null)
                || (filter != null && filter.equals(session.getAttribute(CACHE_FILTER)))) {
            Long time = (Long) session.getAttribute(CACHE_TIME);
            if (time != null) {
                age = System.currentTimeMillis() - time;
                if (age <= CACHE_MAX_AGE) {
                    total = (Integer) session.getAttribute(CACHE_COUNT);
                }
            }
        }
    }

    if (total != null) {
        log.debug(String.format(
                "Returning cached total count value %d which was cached %s ms ago for app layer id %d", total,
                age, appLayer.getId()));
        return total;
    } else {
        long startTime = System.currentTimeMillis();
        total = countProducer.call();
        log.debug(String.format("Caching total count value %d which took %d ms to get for app layer id %d",
                total, System.currentTimeMillis() - startTime, appLayer.getId()));

        // Maybe only cache if getting total took longer than threshold?

        // Now a new feature is only counted for all users after CACHE_MAX_AGE 
        // If clearTotalCountCache() is called then the new feature will be 
        // counted for the current user/session).

        session.setAttribute(CACHE_APPLAYER, appLayer.getId());
        session.setAttribute(CACHE_FILTER, filter);
        session.setAttribute(CACHE_TIME, System.currentTimeMillis());
        session.setAttribute(CACHE_COUNT, total);

        return total;
    }
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

@Override
public void undeployEvent() {
    super.undeployEvent();
    for (Callable c : undeployingEventListeners) {
        try {/*from  ww  w .j a va  2 s.  com*/
            c.call();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:org.pentaho.di.repository.pur.PurRepositoryTest.java

private void testDeletedFlagForObject(Callable<RepositoryElementInterface> elementProvider) throws Exception {
    TransDelegate transDelegate = new TransDelegate(repository, repo);
    JobDelegate jobDelegate = new JobDelegate(repository, repo);
    FieldUtils.writeField(repository, "transDelegate", transDelegate, true);
    FieldUtils.writeField(repository, "jobDelegate", jobDelegate, true);

    RepositoryElementInterface element = elementProvider.call();
    RepositoryDirectoryInterface directory = repository
            .findDirectory(element.getRepositoryDirectory().getPath());
    element.setRepositoryDirectory(directory);

    repository.save(element, null, null);
    assertNotNull("Element was saved", element.getObjectId());

    RepositoryObject information;//from  ww w .j  av  a  2s .c o m
    information = repository.getObjectInformation(element.getObjectId(), element.getRepositoryElementType());
    assertNotNull(information);
    assertFalse(information.isDeleted());

    repository.deleteTransformation(element.getObjectId());
    assertNotNull("Element was moved to Trash", repo.getFileById(element.getObjectId().getId()));

    information = repository.getObjectInformation(element.getObjectId(), element.getRepositoryElementType());
    assertNotNull(information);
    assertTrue(information.isDeleted());
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

public boolean isAlive() throws Exception {
    if (stopping) {
        // when we are stopping, don't check for member alive since the system might be in
        // inconsistent state and we should not "bother" it with checking for liveness
        return true;
    }/*www  .j a va2 s . c  o  m*/
    if (memberAliveIndicators == null || memberAliveIndicators.length == 0) {
        if (logger.isDebugEnabled())
            logger.debug("PUServiceBeanImpl.isAlive() returned true - no memberAliveIndicators");
        return true;
    }
    boolean alive = false;

    int count = 0;
    for (Callable<Boolean> memberAliveIndicator : memberAliveIndicators) {
        alive = memberAliveIndicator.call();
        if (logger.isDebugEnabled())
            logger.debug(
                    "PUServiceBeanImpl.isAlive() memberAliveIndicators[" + count++ + "] returned " + alive);
        if (!alive) {
            break;
        }
    }
    return alive;
}

From source file:org.pentaho.di.ui.repository.repositoryexplorer.controllers.BrowseController.java

protected void confirmDialog(Callable<Void> callback, String title, String msg, String yes, String no)
        throws Exception {
    MessageDialog confirmDialog = new MessageDialog(getShell(), title, null, msg, MessageDialog.NONE,
            new String[] { yes, no }, 0) {
        @Override/*from   ww w  . j a  v  a 2s  .c  om*/
        protected Point getInitialSize() {
            return new Point(DIALOG_WIDTH, DIALOG_HEIGHT);
        }

        @Override
        protected void configureShell(Shell shell) {
            super.configureShell(shell);
            shell.setBackground(shell.getDisplay().getSystemColor(DIALOG_COLOR));
            shell.setBackgroundMode(SWT.INHERIT_FORCE);
        }
    };
    int result = confirmDialog.open();
    if (result == 0) {
        try {
            callback.call();
        } catch (Exception e) {
            if (mainController == null || !mainController.handleLostRepository(e)) {
                messageBox.setTitle(BaseMessages.getString(PKG, "Dialog.Error"));
                messageBox.setAcceptLabel(BaseMessages.getString(PKG, "Dialog.Ok"));
                messageBox.setMessage(BaseMessages.getString(PKG, e.getLocalizedMessage()));
                messageBox.open();
            }
        }
    }
}

From source file:org.pentaho.platform.engine.security.SecurityHelper.java

/**
 * Utility method that allows you to run a block of code as the given user. Regardless of success or exception
 * situation, the original session and authentication will be restored once your block of code is finished executing,
 * i.e. the given user will apply only to your {@link Callable}, then the system environment will return to the user
 * present prior to you calling this method.
 *
 * @param <T>      the return type of your operation, specify this type as <code>T</code>
 * @param callable {@link Callable#call()} contains the code you wish to run as the given user
 * @return the value returned by your implementation of {@link Callable#call()}
 * @throws Exception/* ww w  .  j  a  va 2  s .  c  o m*/
 * @see {@link Callable}
 */
@Override
public <T> T runAsAnonymous(final Callable<T> callable) throws Exception {
    IPentahoSession origSession = PentahoSessionHolder.getSession();
    SecurityContext originalContext = SecurityContextHolder.getContext();
    try {
        PentahoSessionHolder.setSession(new StandaloneSession());

        // get anonymous username/role defined in pentaho.xml
        String user = PentahoSystem.getSystemSetting("anonymous-authentication/anonymous-user", //$NON-NLS-1$
                "anonymousUser"); //$NON-NLS-1$
        String role = PentahoSystem.getSystemSetting("anonymous-authentication/anonymous-role", "Anonymous"); //$NON-NLS-1$//$NON-NLS-2$
        GrantedAuthority[] authorities = new GrantedAuthority[] { new GrantedAuthorityImpl(role) };

        Authentication auth = new AnonymousAuthenticationToken("anonymousUser",
                new User(user, "ignored", true, true, true, true, authorities), authorities);

        // 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 {
        PentahoSessionHolder.setSession(origSession);
        SecurityContextHolder.setContext(originalContext);
    }
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

public PUMonitors getPUMonitors() throws RemoteException {
    ArrayList<Object> monitors = new ArrayList<Object>();
    synchronized (serviceMonitors) {
        for (Callable call : serviceMonitors) {
            try {
                Collections.addAll(monitors, (Object[]) call.call());
            } catch (Exception e) {
                logger.error(logMessage("Failed to get monitor information, ignoring it"), e);
            }/*from   w w w  .  ja  va  2 s  .c o  m*/
        }
    }
    return new PUMonitors(monitors.toArray(new Object[monitors.size()]));
}

From source file:org.springframework.integration.handler.advice.AdvisedMessageHandlerTests.java

@Test
public void testInappropriateAdvice() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    Advice advice = new AbstractRequestHandlerAdvice() {
        @Override/*from w ww  . jav  a 2 s . c  o  m*/
        protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message)
                throws Exception {
            called.set(true);
            return callback.execute();
        }
    };
    PollableChannel inputChannel = new QueueChannel();
    PollingConsumer consumer = new PollingConsumer(inputChannel, new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
        }
    });
    consumer.setAdviceChain(Collections.singletonList(advice));
    consumer.setTaskExecutor(
            new ErrorHandlingTaskExecutor(Executors.newSingleThreadExecutor(), new ErrorHandler() {
                @Override
                public void handleError(Throwable t) {
                }
            }));
    consumer.afterPropertiesSet();

    Callable<?> pollingTask = TestUtils.getPropertyValue(consumer, "poller.pollingTask", Callable.class);
    assertTrue(AopUtils.isAopProxy(pollingTask));
    Log logger = TestUtils.getPropertyValue(advice, "logger", Log.class);
    logger = spy(logger);
    when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE);
    final AtomicReference<String> logMessage = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            logMessage.set((String) invocation.getArguments()[0]);
            return null;
        }
    }).when(logger).warn(Mockito.anyString());
    DirectFieldAccessor accessor = new DirectFieldAccessor(advice);
    accessor.setPropertyValue("logger", logger);

    pollingTask.call();
    assertFalse(called.get());
    assertNotNull(logMessage.get());
    assertTrue(logMessage.get()
            .endsWith("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in "
                    + "'org.springframework.integration.endpoint.AbstractPollingEndpoint$1' is ignored"));
}