Example usage for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean AtomicBoolean.

Prototype

public AtomicBoolean() 

Source Link

Document

Creates a new AtomicBoolean with initial value false .

Usage

From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.java

/**
 * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read).
 * Test this both with successful and failed reads.
 *//*w w  w. ja va2 s. co  m*/
@Test
public void testDependents() {
    final Duration waitTimeout = Duration.ofSeconds(5);
    TestStorage storage = new TestStorage();
    CompletableFuture<Integer> signal = new CompletableFuture<>();
    AtomicBoolean wasReadInvoked = new AtomicBoolean();
    storage.readImplementation = () -> {
        if (wasReadInvoked.getAndSet(true)) {
            Assert.fail(
                    "Read was invoked multiple times, which is a likely indicator that the requests were not chained.");
        }
        return signal;
    };

    @Cleanup
    StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReadManager.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReadManager.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReadManager.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReadManager.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT));

    Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone());

    signal.completeExceptionally(new IntentionalException());
    AssertExtensions.assertThrows("The first read was not failed with the correct exception.",
            () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);

    AssertExtensions.assertThrows("The second read was not failed with the correct exception.",
            () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);
}

From source file:com.antsdb.saltedfish.util.UberUtil.java

public static <T> Iterable<T> once(final Iterator<T> source) {
    return new Iterable<T>() {
        private AtomicBoolean exhausted = new AtomicBoolean();

        public Iterator<T> iterator() {
            Preconditions.checkState(!exhausted.getAndSet(true));
            return source;
        }/*from w w  w .  j  a va2  s . c  o  m*/
    };
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.workers.GetDownloadWorker.java

/**
 * {@inheritDoc}/*  ww w.j a  v  a  2 s . c  o m*/
 */
@Override
public WorkerStatus call() throws Exception {
    /*
     * Try not to run any code outside this try block, so our Throwable
     * catch below can report every error (even RuntimeExceptions).
     */
    try {
        if (getCancelMonitor().isCanceled()) {
            return new WorkerStatus(this, FinalState.CANCELED);
        }

        final AtomicBoolean targetSymLink = new AtomicBoolean();
        final AtomicBoolean targetSymLinkDestinationUnmapped = new AtomicBoolean();

        // Get the target file, updating local workspace baselines if
        // appropriate.
        downloadFile(targetSymLink, targetSymLinkDestinationUnmapped);

        // Sends version updates to the server, sets attributes
        completeGetOperation(targetSymLink.get(), targetSymLinkDestinationUnmapped.get());
    } catch (final VersionControlException e) {
        // Convert to a non-fatal (this handles IOExceptions wrapped as
        // VersionControlExceptions)

        log.warn("Converted to non-fatal", e); //$NON-NLS-1$

        getEngine.onNonFatalError(
                new VersionControlException(
                        MessageFormat.format(Messages.getString("GetEngineDownloadWorker.AColonBFormat"), //$NON-NLS-1$
                                operation.getTargetLocalItem(), e.getLocalizedMessage()),
                        e),
                asyncOp.getWorkspace());
    } catch (final CanceledException e) {
        /*
         * CoreCancelException is thrown if the user cancels during the
         * download or completion. There's no cleanup to do because all
         * temporary resources were cleaned up as the exception travelled
         * through the stack.
         */
        return new WorkerStatus(this, FinalState.CANCELED);
    } catch (final Throwable t) {
        /*
         * An unexpected (fatal) error happened. We have to communicate this
         * problem to the thread submitting tasks so it can take the correct
         * action (shut down other workers).
         *
         * VS checks for certain kinds of fatal vs. non-fatal exceptions
         * here, but we'll just consider them all fatal for now.
         */
        asyncOp.setFatalError(t);
        return new WorkerStatus(this, FinalState.ERROR);
    }

    return new WorkerStatus(this, FinalState.NORMAL);
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.CheckinEngine.java

/**
 * Uploads changes to the server for a checkin or shelve operation.
 * <p>//from w  w w .j  a v a2 s. co m
 * <!-- Event Origination Info -->
 * <p>
 * This method is an <b>core event origination point</b>. The
 * {@link EventSource} object that accompanies each event fired by this
 * method describes the execution context (current thread, etc.) when and
 * where this method was invoked.
 *
 * @param changes
 *        the changes to upload (must not be <code>null</code>)
 * @param forShelve
 *        if the upload is for a shelve, set to true so the correct event is
 *        raised, if for a normal checkin set to false.
 * @param saveUploadedContentAsBaselines
 *        if <code>true</code> the uploaded files are stored in the local
 *        workspace baseline folders, if <code>false</code> they are not.
 *        Pass <code>false</code> when calling for shelve (not check-in) and
 *        for check-in on server workspaces.
 * @throws CheckinException
 *         if conflicts caused the checkin to fail or if other errors
 *         occurred.
 * @throws CoreCancelException
 *         if the upload was cancelled by the user.
 */
public void uploadChanges(final PendingChange[] changes, final boolean forShelve,
        final boolean saveUploadedContentAsBaselines) throws CheckinException, CoreCancelException {
    Check.notNull(changes, "changes"); //$NON-NLS-1$

    /*
     * If this is a local workspace, and we are checking in (not shelving),
     * then the caller will have set the flag saveUploadedContentAsBaselines
     * to true. In that case we need to take a workspace lock over the
     * entire upload process, since we will be putting baselines into the
     * baseline folders during the upload process.
     */
    final WorkspaceLock workspaceLock = saveUploadedContentAsBaselines ? this.workspace.lock() : null;
    try {
        final TaskMonitor monitor = TaskMonitorService.getTaskMonitor();
        monitor.begin("", changes.length); //$NON-NLS-1$

        // We need to reconcile before uploading pending change content
        // because
        // the upload handler will reject uploads for items that don't have
        // pending change rows on the server.
        final AtomicBoolean pendingChangesUpdatedByServer = new AtomicBoolean();
        workspace.reconcile(false /* reconcileMissingLocalItems */, pendingChangesUpdatedByServer);

        // if the server updated pending changes behind our back, abort so
        // that
        // the user confirms that what they are checking in is correct.
        if (pendingChangesUpdatedByServer.get()) {
            throw new VersionControlException(Messages.getString("CheckinEngine.PendingChangesModified")); //$NON-NLS-1$
        }

        /*
         * Since we will dispatch some uploads to be completed in a
         * different thread (managed by an Executor), we have to keep track
         * of them here. The completion service wraps the bounded executor
         * shared by all GetEngines that use the same VersionControlClients.
         * The completion service only tracks the jobs we have submitted for
         * execution, so we can simply count the completed jobs to know when
         * they have all been processed.
         */
        final AccountingCompletionService<WorkerStatus> completions = new AccountingCompletionService<WorkerStatus>(
                client.getUploadDownloadWorkerExecutor());

        final AsyncCheckinOperation asyncOp = new AsyncCheckinOperation(workspaceLock);

        try {
            int uploadedCount = 0;

            for (final PendingChange change : changes) {
                throwIfCanceled(monitor);

                throwIfFatalError(asyncOp);

                final ChangeType changeType = change.getChangeType();

                final PendingChangeEvent event = new PendingChangeEvent(EventSource.newFromHere(), workspace,
                        change, OperationStatus.GETTING, ChangePendedFlags.UNKNOWN);

                if (forShelve) {
                    client.getEventEngine().fireBeforeShelvePendingChange(event);
                } else {
                    client.getEventEngine().fireBeforeCheckinPendingChange(event);
                }

                /*
                 * The edit flag will always be set for changes of type Add
                 * and Edit. During a merge, a delete flag and an edit flag
                 * may both exist on one item.
                 */

                if (changeType.contains(ChangeType.EDIT) && (changeType.contains(ChangeType.MERGE)
                        && changeType.contains(ChangeType.DELETE)) == false) {
                    // Upload the file.
                    monitor.setCurrentWorkDescription(
                            MessageFormat.format(Messages.getString("CheckinEngine.UploadingFormat"), //$NON-NLS-1$
                                    change.getServerItem()));

                    /*
                     * In a strange circumstance in which a user pends a
                     * change on a file, changes his workspace so that the
                     * directory for that file points to somewhere else in
                     * the repository, then pends an add on the same file,
                     * the server loses the local item location of a pending
                     * change this can also happen if the user has made
                     * incorrect calls to update local version
                     */
                    if (change.getLocalItem() == null) {
                        throw new VersionControlException(MessageFormat.format(
                                Messages.getString("CheckinEngine.NoLocalFileForPendingChangeFormat"), //$NON-NLS-1$
                                change.getServerItem()));
                    }

                    /*
                     * In a local workspace, uploading changes is a
                     * yieldable operation. Check every N pending changes
                     * for a waiter and yield.
                     */
                    if (null != asyncOp.getBaselineFolders() && 0 == (uploadedCount++ % UPLOAD_YIELD_COUNT)) {
                        asyncOp.getWorkspaceLock().yield();
                    }

                    uploadFile(change, completions, asyncOp);
                } else if (changeType.contains(ChangeType.DELETE) == false
                        && changeType.contains(ChangeType.LOCK) == false
                        && changeType.contains(ChangeType.RENAME) == false
                        && changeType.contains(ChangeType.UNDELETE) == false
                        && changeType.contains(ChangeType.BRANCH) == false
                        && changeType.contains(ChangeType.ENCODING) == false
                        && changeType.contains(ChangeType.MERGE) == false) {
                }

                monitor.worked(1);
            }
        } finally {
            /*
             * Wait for all the background threads to finish.
             */
            waitForCompletions(completions);

            monitor.done();
        }

        throwIfCanceled(monitor);

        throwIfFatalError(asyncOp);
    } finally {
        if (workspaceLock != null) {
            workspaceLock.close();
        }
    }
}

From source file:ch.entwine.weblounge.preview.phantomjs.PhantomJsPagePreviewGenerator.java

/**
 * {@inheritDoc}//w  ww  . j  a  v a 2s  . co m
 * 
 * @see ch.entwine.weblounge.common.content.PreviewGenerator#createPreview(ch.entwine.weblounge.common.content.Resource,
 *      ch.entwine.weblounge.common.site.Environment,
 *      ch.entwine.weblounge.common.language.Language,
 *      ch.entwine.weblounge.common.content.image.ImageStyle, String,
 *      java.io.InputStream, java.io.OutputStream)
 */
public void createPreview(Resource<?> resource, Environment environment, Language language, ImageStyle style,
        String format, InputStream is, OutputStream os) throws IOException {

    // We don't need the input stream
    IOUtils.closeQuietly(is);

    // Find a suitable image preview generator for scaling
    ImagePreviewGenerator imagePreviewGenerator = null;
    synchronized (previewGenerators) {
        for (ImagePreviewGenerator generator : previewGenerators) {
            if (generator.supports(format)) {
                imagePreviewGenerator = generator;
                break;
            }
        }
        if (imagePreviewGenerator == null) {
            logger.debug("Unable to generate page previews since no image renderer is available");
            return;
        }
    }

    // Find the relevant metadata to start the request
    ResourceURI uri = resource.getURI();
    long version = resource.getVersion();
    Site site = uri.getSite();

    // Create the url
    URL pageURL = new URL(UrlUtils.concat(site.getHostname(environment).toExternalForm(), PAGE_HANDLER_PREFIX,
            uri.getIdentifier()));
    if (version == Resource.WORK) {
        pageURL = new URL(
                UrlUtils.concat(pageURL.toExternalForm(), "work_" + language.getIdentifier() + ".html"));
    } else {
        pageURL = new URL(
                UrlUtils.concat(pageURL.toExternalForm(), "index_" + language.getIdentifier() + ".html"));
    }

    // Create a temporary file
    final File rendererdFile = File.createTempFile("phantomjs-", "." + format, phantomTmpDir);
    final URL finalPageURL = pageURL;
    final AtomicBoolean success = new AtomicBoolean();

    // Call PhantomJS to render the page
    try {
        final PhantomJsProcessExecutor phantomjs = new PhantomJsProcessExecutor(scriptFile.getAbsolutePath(),
                pageURL.toExternalForm(), rendererdFile.getAbsolutePath()) {
            @Override
            protected void onProcessFinished(int exitCode) throws IOException {
                super.onProcessFinished(exitCode);
                switch (exitCode) {
                case 0:
                    if (rendererdFile.length() > 0) {
                        success.set(true);
                        logger.debug("Page preview of {} created at {}", finalPageURL,
                                rendererdFile.getAbsolutePath());
                    } else {
                        logger.warn("Error creating page preview of {}", finalPageURL);
                        success.set(false);
                        FileUtils.deleteQuietly(rendererdFile);
                    }
                    break;
                default:
                    success.set(false);
                    logger.warn("Error creating page preview of {}", finalPageURL);
                    FileUtils.deleteQuietly(rendererdFile);
                }
            }
        };

        // Finally have PhantomJS create the preview
        logger.debug("Creating preview of {}", finalPageURL);
        phantomjs.execute();

    } catch (ProcessExcecutorException e) {
        logger.warn("Error creating page preview of {}: {}", pageURL, e.getMessage());
        throw new IOException(e);
    } finally {
        // If page preview rendering failed, there is no point in scaling the
        // images
        if (!success.get()) {
            logger.debug("Skipping scaling of failed preview rendering {}", pageURL);
            FileUtils.deleteQuietly(rendererdFile);
            return;
        }
    }

    FileInputStream imageIs = null;

    // Scale the image to the correct size
    try {
        imageIs = new FileInputStream(rendererdFile);
        imagePreviewGenerator.createPreview(resource, environment, language, style, PREVIEW_FORMAT, imageIs,
                os);
    } catch (IOException e) {
        logger.error("Error reading original page preview from " + rendererdFile, e);
        throw e;
    } catch (Throwable t) {
        logger.warn("Error scaling page preview at " + uri + ": " + t.getMessage(), t);
        throw new IOException(t);
    } finally {
        IOUtils.closeQuietly(imageIs);
        FileUtils.deleteQuietly(rendererdFile);
    }

}

From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing Hadoop job w/ {@code asakusa-resources.xml}.
 *//*from w ww  .  ja  v  a2s.  co  m*/
@Test
public void executeJob_w_resources() {
    prepareJobflow();
    AtomicBoolean call = new AtomicBoolean();
    MockHadoopJob.callback((args, conf) -> {
        call.set(true);
        assertThat(conf.get("com.example.testing"), is("true"));
        return 0;
    });

    JobExecutor executor = new InProcessJobExecutor(context);
    deploy("dummy.xml", new File(framework.getHome(), InProcessJobExecutor.PATH_ASAKUSA_RESOURCES));
    try {
        executor.execute(job(MockHadoopJob.class.getName()), Collections.emptyMap());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    assertThat(call.get(), is(true));
}

From source file:com.eventsourcing.repository.RepositoryTest.java

@Test
@SneakyThrows/*from   ww  w. j a  v a  2  s. c  o m*/
public void subscribe() {
    final AtomicBoolean gotEvent = new AtomicBoolean();
    final AtomicBoolean gotCommand = new AtomicBoolean();
    repository.addEntitySubscriber(new ClassEntitySubscriber<TestEvent>(TestEvent.class) {
        @Override
        public void onEntity(EntityHandle<TestEvent> entity) {
            gotEvent.set(journal.get(entity.uuid()).isPresent());
        }
    });
    repository
            .addEntitySubscriber(new ClassEntitySubscriber<RepositoryTestCommand>(RepositoryTestCommand.class) {
                @Override
                public void onEntity(EntityHandle<RepositoryTestCommand> entity) {
                    gotCommand.set(journal.get(entity.uuid()).isPresent());
                }
            });
    repository.publish(RepositoryTestCommand.builder().build()).get();
    assertTrue(gotEvent.get());
    assertTrue(gotCommand.get());
}

From source file:com.clank.launcher.swing.SwingHelper.java

/**
 * Asks the user a binary yes or no question.
 *
 * @param parentComponent the component/*from w  w  w .  j  ava2  s .co m*/
 * @param message the message to display
 * @param title the title string for the dialog
 * @return whether 'yes' was selected
 */
public static boolean confirmDialog(final Component parentComponent, @NonNull final String message,
        @NonNull final String title) {
    if (SwingUtilities.isEventDispatchThread()) {
        return JOptionPane.showConfirmDialog(parentComponent, message, title,
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
    } else {
        // Use an AtomicBoolean to pass the result back from the
        // Event Dispatcher Thread
        final AtomicBoolean yesSelected = new AtomicBoolean();

        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    yesSelected.set(confirmDialog(parentComponent, title, message));
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return yesSelected.get();
    }
}

From source file:com.microsoft.alm.plugin.idea.git.ui.simplecheckout.SimpleCheckoutModel.java

public void cloneRepo() {
    final ModelValidationInfo validationInfo = validate();
    if (validationInfo == null) {
        final Task.Backgroundable createCloneTask = new Task.Backgroundable(project,
                TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_DIALOG_TITLE), true,
                PerformInBackgroundOption.DEAF) {
            final AtomicBoolean cloneResult = new AtomicBoolean();

            @Override/*from  w  w  w.  j  av a 2s. co m*/
            public void run(@NotNull final ProgressIndicator progressIndicator) {
                progressIndicator.setText(TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_DIALOG_TITLE));
                // get context from manager, and store in active context
                final ServerContext context = ServerContextManager.getInstance().getUpdatedContext(gitUrl,
                        true);

                if (context == null) {
                    logger.warn("No context could be found");
                    VcsNotifier.getInstance(project).notifyError(
                            TfPluginBundle
                                    .message(TfPluginBundle.KEY_CHECKOUT_ERRORS_AUTHENTICATION_FAILED_TITLE),
                            TfPluginBundle.message(TfPluginBundle.KEY_ERRORS_AUTH_NOT_SUCCESSFUL, gitUrl));
                    return;
                }

                final String gitRepositoryStr = context.getUsableGitUrl();
                final Git git = ServiceManager.getService(Git.class);
                logger.info("Cloning repo " + gitRepositoryStr);
                cloneResult.set(git4idea.checkout.GitCheckoutProvider.doClone(project, git, getDirectoryName(),
                        getParentDirectory(), gitRepositoryStr));

                // Add Telemetry for the clone call along with it's success/failure
                TfsTelemetryHelper.getInstance().sendEvent(COMMANDLINE_CLONE_ACTION,
                        new TfsTelemetryHelper.PropertyMapBuilder().currentOrActiveContext(context)
                                .actionName(COMMANDLINE_CLONE_ACTION).success(cloneResult.get()).build());
            }

            @Override
            public void onSuccess() {
                logger.info("Simple clone was a success");
                // if clone was successful then complete the checkout process which gives the option to open the project
                if (cloneResult.get()) {
                    final VirtualFile destinationParent = LocalFileSystem.getInstance()
                            .findFileByIoFile(new File(getParentDirectory()));
                    final File projectDirectory = new File(parentDirectory, directoryName);

                    DvcsUtil.addMappingIfSubRoot(project,
                            FileUtil.join(new String[] { parentDirectory, directoryName }), "Git");
                    destinationParent.refresh(true, true, new Runnable() {
                        public void run() {
                            if (project.isOpen() && !project.isDisposed() && !project.isDefault()) {
                                VcsDirtyScopeManager mgr = VcsDirtyScopeManager.getInstance(project);
                                mgr.fileDirty(destinationParent);
                            }

                        }
                    });

                    listener.directoryCheckedOut(projectDirectory, GitVcs.getKey());
                    listener.checkoutCompleted();

                    // the project has changed since a new project was created above during the directoryCheckedOut process
                    // finding the new project based on the repo path
                    final Project currentProject = IdeaHelper.getCurrentProject();

                    // check if ref is not master and if currentProject is not null
                    // if currentProject is null that means the user chose not to create the project so not checking the branch out
                    if (StringUtils.isNotEmpty(ref) && !StringUtils.equals(ref, MASTER_BRANCH)
                            && currentProject != null) {
                        logger.info("Non-master branch detected to checkout");
                        checkoutBranch(ref, currentProject, projectDirectory);
                    }
                }
            }

            private void checkoutBranch(final String ref, final Project lastOpenedProject,
                    final File projectDirectory) {
                // adds a post initialization step to the project to checkout the given branch
                final ProjectLevelVcsManagerImpl manager = (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager
                        .getInstance(lastOpenedProject);

                // add step to refresh the root mapping so the new root is found for the repo
                // TODO: refactor to use existing call instead of calling twice. Current call happens too late currently
                // TODO: so that's why we need to call this beforehand so we can checkout the branch
                manager.addInitializationRequest(VcsInitObject.MAPPINGS, new Runnable() {
                    @Override
                    public void run() {
                        manager.setDirectoryMapping(projectDirectory.getPath(), "Git");
                        manager.fireDirectoryMappingsChanged();
                    }
                });

                // step to checkout the desired branch
                manager.addInitializationRequest(VcsInitObject.AFTER_COMMON, new DumbAwareRunnable() {
                    public void run() {
                        final GitRepositoryManager gitRepositoryManager = ServiceManager
                                .getService(lastOpenedProject, GitRepositoryManager.class);
                        ArgumentHelper.checkNotNull(gitRepositoryManager, "GitRepositoryManager");
                        ArgumentHelper.checkNotNullOrEmpty(gitRepositoryManager.getRepositories(),
                                "gitRepositoryManager.getRepositories()");
                        // TODO: use more direct manner to get repo but right now due to timing we can't
                        final GitRepository gitRepository = gitRepositoryManager.getRepositories().get(0);
                        ArgumentHelper.checkNotNull(gitRepository, "GitRepository");
                        String fullRefName = StringUtils.EMPTY;

                        // find remote red name from given name
                        for (final GitRemoteBranch remoteBranch : gitRepository.getInfo().getRemoteBranches()) {
                            final String remoteBranchName = remoteBranch.getName()
                                    .replaceFirst(remoteBranch.getRemote().getName() + "/", StringUtils.EMPTY);
                            if (ref.equals(remoteBranchName)) {
                                fullRefName = remoteBranch.getName();
                            }
                        }

                        if (StringUtils.isNotEmpty(fullRefName)) {
                            final String remoteRef = fullRefName;
                            // Checking out a branch using the brancher has to start on the UI thread but moves to the background
                            IdeaHelper.runOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    logger.info("Checking out branch " + remoteRef);
                                    final GitBrancher brancher = ServiceManager.getService(lastOpenedProject,
                                            GitBrancher.class);
                                    brancher.checkoutNewBranchStartingFrom(ref, remoteRef,
                                            Collections.singletonList(gitRepository), null);
                                }
                            });
                        } else {
                            throw new IllegalArgumentException(String.format(
                                    "Ref %s was not found remotely so could not be checked out.", fullRefName));
                        }
                    }
                });
            }
        };
        createCloneTask.queue();
    }
}

From source file:org.zenoss.zep.index.impl.EventIndexerImpl.java

private int doIndex(long throughTime) throws ZepException {
    final EventPostIndexContext context = new EventPostIndexContext() {
        @Override/*from w  w w . j  a  va2 s .  co m*/
        public boolean isArchive() {
            return !isSummary;
        }
    };
    final List<EventPostIndexPlugin> plugins = this.pluginService.getPluginsByType(EventPostIndexPlugin.class);
    final AtomicBoolean calledStartBatch = new AtomicBoolean();
    final List<Long> indexQueueIds = queueDao.indexEvents(new EventIndexHandler() {
        @Override
        public void handle(EventSummary event) throws Exception {
            indexDao.stage(event);
            if (shouldRunPostprocessing(event)) {
                boolean shouldStartBatch = calledStartBatch.compareAndSet(false, true);
                for (EventPostIndexPlugin plugin : plugins) {
                    try {
                        if (shouldStartBatch) {
                            plugin.startBatch(context);
                        }
                        plugin.processEvent(event, context);
                    } catch (Exception e) {
                        // Post-processing plug-in failures are not fatal errors.
                        logger.warn("Failed to run post-processing plug-in on event: " + event, e);
                    }
                }
            }
        }

        @Override
        public void handleDeleted(String uuid) throws Exception {
            indexDao.stageDelete(uuid);
        }

        @Override
        public void handleComplete() throws Exception {
            if (calledStartBatch.get()) {
                for (EventPostIndexPlugin plugin : plugins) {
                    plugin.endBatch(context);
                }
            }
            indexDao.commit();
        }
    }, limit, throughTime);

    if (!indexQueueIds.isEmpty()) {
        logger.debug("Completed indexing {} events on {}", indexQueueIds.size(), indexDao.getName());
        try {
            DaoUtils.deadlockRetry(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return queueDao.deleteIndexQueueIds(indexQueueIds);
                }
            });
        } catch (ZepException e) {
            throw e;
        } catch (Exception e) {
            throw new ZepException(e.getLocalizedMessage(), e);
        }
    }
    return indexQueueIds.size();
}