Example usage for java.util.concurrent.atomic AtomicInteger set

List of usage examples for java.util.concurrent.atomic AtomicInteger set

Introduction

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

Prototype

public final void set(int newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java

private File createSubsystemBaseFile(Feature feature, AtomicInteger startLevelHolder)
        throws MojoExecutionException {
    File subsystemFile = new File(getTmpDir(), feature.getName() + ".subsystem-base");
    if (subsystemFile.exists()) {
        // This subsystem has already been created
        // TODO is there a better way to avoid calling this multiple times?
        return null;
    }/* w  ww  . ja v  a2 s  .  c  o m*/

    startLevelHolder.set(-1);

    // The runmodes information has to be the first item in the archive so that we always have it available when the
    // archive is being processed. For this reason a Jar file is used here as it's guaranteed to store the manifest
    // first.
    Manifest runModesManifest = getRunModesManifest(feature);

    getLog().info("Creating subsystem base file: " + subsystemFile.getName());
    subsystemFile.getParentFile().mkdirs();

    try (JarOutputStream os = new JarOutputStream(new FileOutputStream(subsystemFile), runModesManifest)) {
        Map<String, Integer> bsnStartOrderMap = new HashMap<>();

        for (RunMode rm : feature.getRunModes()) {
            for (ArtifactGroup ag : rm.getArtifactGroups()) {
                int startOrder = ag.getStartLevel(); // For subsystems the start level on the artifact group is used as start order.

                for (org.apache.sling.provisioning.model.Artifact a : ag) {
                    Artifact artifact = ModelUtils.getArtifact(this.project, this.mavenSession,
                            this.artifactHandlerManager, this.resolver, a.getGroupId(), a.getArtifactId(),
                            a.getVersion(), a.getType(), a.getClassifier());
                    File artifactFile = artifact.getFile();
                    String entryName = getEntryName(artifactFile, startOrder);

                    ZipEntry ze = new ZipEntry(entryName);
                    try {
                        os.putNextEntry(ze);
                        Files.copy(artifactFile.toPath(), os);
                    } finally {
                        os.closeEntry();
                    }
                }
            }
        }

        int sl = createSubsystemManifest(feature, bsnStartOrderMap, os);
        if (sl != -1)
            startLevelHolder.set(sl);
        addReadme(os);
    } catch (IOException ioe) {
        throw new MojoExecutionException("Problem creating subsystem .esa file " + subsystemFile, ioe);
    }
    return subsystemFile;
}

From source file:org.apache.bookkeeper.client.BookieInfoReader.java

Map<BookieSocketAddress, BookieInfo> getBookieInfo() throws BKException, InterruptedException {
    BookieClient bkc = bk.getBookieClient();
    final AtomicInteger totalSent = new AtomicInteger();
    final AtomicInteger totalCompleted = new AtomicInteger();
    final ConcurrentMap<BookieSocketAddress, BookieInfo> map = new ConcurrentHashMap<BookieSocketAddress, BookieInfo>();
    final CountDownLatch latch = new CountDownLatch(1);
    long requested = BookkeeperProtocol.GetBookieInfoRequest.Flags.TOTAL_DISK_CAPACITY_VALUE
            | BookkeeperProtocol.GetBookieInfoRequest.Flags.FREE_DISK_SPACE_VALUE;

    Collection<BookieSocketAddress> bookies;
    bookies = bk.bookieWatcher.getBookies();
    bookies.addAll(bk.bookieWatcher.getReadOnlyBookies());

    totalSent.set(bookies.size());
    for (BookieSocketAddress b : bookies) {
        bkc.getBookieInfo(b, requested, new GetBookieInfoCallback() {
            @Override//from  w w  w .ja  va2  s. co  m
            public void getBookieInfoComplete(int rc, BookieInfo bInfo, Object ctx) {
                BookieSocketAddress b = (BookieSocketAddress) ctx;
                if (rc != BKException.Code.OK) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Reading bookie info from bookie {} failed due to {}", b,
                                BKException.codeLogger(rc));
                    }
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Free disk space on bookie {} is {}.", b, bInfo.getFreeDiskSpace());
                    }
                    map.put(b, bInfo);
                }
                if (totalCompleted.incrementAndGet() == totalSent.get()) {
                    latch.countDown();
                }
            }
        }, b);
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.error("Received InterruptedException ", e);
        throw e;
    }
    return map;
}

From source file:org.apache.bookkeeper.bookie.LedgerCacheTest.java

/**
 * Race where a flush would fail because a garbage collection occurred at
 * the wrong time.//from  www .j ava 2 s  .  c  om
 * {@link https://issues.apache.org/jira/browse/BOOKKEEPER-604}
 */
@Test(timeout = 60000)
public void testFlushDeleteRace() throws Exception {
    newLedgerCache();
    final AtomicInteger rc = new AtomicInteger(0);
    final LinkedBlockingQueue<Long> ledgerQ = new LinkedBlockingQueue<Long>(1);
    final byte[] masterKey = "masterKey".getBytes();
    Thread newLedgerThread = new Thread() {
        public void run() {
            try {
                for (int i = 0; i < 1000 && rc.get() == 0; i++) {
                    ledgerCache.setMasterKey(i, masterKey);
                    ledgerQ.put((long) i);
                }
            } catch (Exception e) {
                rc.set(-1);
                LOG.error("Exception in new ledger thread", e);
            }
        }
    };
    newLedgerThread.start();

    Thread flushThread = new Thread() {
        public void run() {
            try {
                while (true) {
                    Long id = ledgerQ.peek();
                    if (id == null) {
                        continue;
                    }
                    LOG.info("Put entry for {}", id);
                    try {
                        ledgerCache.putEntryOffset((long) id, 1, 0);
                    } catch (Bookie.NoLedgerException nle) {
                        //ignore
                    }
                    ledgerCache.flushLedger(true);
                }
            } catch (Exception e) {
                rc.set(-1);
                LOG.error("Exception in flush thread", e);
            }
        }
    };
    flushThread.start();

    Thread deleteThread = new Thread() {
        public void run() {
            try {
                while (true) {
                    long id = ledgerQ.take();
                    LOG.info("Deleting {}", id);
                    ledgerCache.deleteLedger(id);
                }
            } catch (Exception e) {
                rc.set(-1);
                LOG.error("Exception in delete thread", e);
            }
        }
    };
    deleteThread.start();

    newLedgerThread.join();
    assertEquals("Should have been no errors", rc.get(), 0);

    deleteThread.interrupt();
    flushThread.interrupt();
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

static Integer findUniqueNumber(AbstractFilter searchFilter, final String uniqueNumberField,
        AtomicInteger uniqueNumber, LdapTemplate ldapTemplate) {
    if (uniqueNumberField == null || uniqueNumberField.trim().isEmpty()) {
        return null;
    }/*w w w.  j av a 2 s. c  om*/
    if (uniqueNumber.get() < 0) {
        @SuppressWarnings("unchecked")
        final List<Integer> uniqueIds = ldapTemplate.search(DistinguishedName.EMPTY_PATH, searchFilter.encode(),
                new AttributesMapper() {
                    @Override
                    public Object mapFromAttributes(Attributes attributes) throws NamingException {
                        final Attribute attribute = attributes.get(uniqueNumberField);
                        if (attribute == null) {
                            return 0;
                        }
                        final Object number = attribute.get();
                        if (number != null) {
                            try {
                                return Integer.valueOf(number.toString());
                            } catch (NumberFormatException e) {
                                return 0;
                            }
                        }
                        return 0;
                    }
                });

        for (Integer uniqueId : uniqueIds) {
            if (uniqueId != null && uniqueId > uniqueNumber.get()) {
                uniqueNumber.set(uniqueId);
            }
        }
        if (uniqueNumber.get() < 0) {
            uniqueNumber.set(0);
        }
        uniqueNumber.incrementAndGet();
    }

    boolean isUnique = false;
    while (!isUnique) {
        AndFilter filter = new AndFilter();
        filter.and(searchFilter);
        filter.and(new EqualsFilter(uniqueNumberField, uniqueNumber.get()));
        isUnique = ldapTemplate
                .search(DistinguishedName.EMPTY_PATH, filter.encode(), new AccountContextMapper("")).isEmpty();
        uniqueNumber.incrementAndGet();
    }
    return uniqueNumber.get();
}

From source file:org.deeplearning4j.patent.TrainPatentClassifier.java

/**
 * JCommander entry point/*w ww  . j av  a  2s.  c  o m*/
 */
protected void entryPoint(String[] args) throws Exception {
    JCommanderUtils.parseArgs(this, args);

    //Azure storage account naming rules: https://blogs.msdn.microsoft.com/jmstall/2014/06/12/azure-storage-naming-rules/
    //The default exceptions aren't helpful, we'll validate this here
    if (!azureStorageAcct.matches("^[a-z0-9]+$") || azureStorageAcct.length() < 3
            || azureStorageAcct.length() > 24) {
        throw new IllegalStateException("Invalid storage account name: must be alphanumeric, lowercase, "
                + "3 to 24 characters. Got option azureStorageAcct=\"" + azureStorageAcct + "\"");
    }
    if (!azureContainerPreproc.matches("^[a-z0-9-]+$") || azureContainerPreproc.length() < 3
            || azureContainerPreproc.length() > 63) {
        throw new IllegalStateException(
                "Invalid Azure container name: must be alphanumeric or dash, lowercase, "
                        + "3 to 63 characters. Got option azureContainerPreproc=\"" + azureContainerPreproc
                        + "\"");
    }

    StringBuilder results = new StringBuilder(); //To store results/timing - will be written to disk on completion

    long startTime = System.currentTimeMillis();

    // Prepare neural net
    ComputationGraph net = new ComputationGraph(NetworkConfiguration.getConf());
    net.init();
    log.info("Parameters: {}", net.params().length());

    // Configure Spark
    SparkConf sparkConf = new SparkConf();
    sparkConf.setAppName(sparkAppName);
    JavaSparkContext sc = new JavaSparkContext();
    int numWorkers = this.numNodes * this.numWorkersPerNode;

    //Prepare dataset RDDs
    String dirName = "seqLength" + maxSequenceLength + "_mb" + minibatch;
    String containerRoot = "wasbs://" + azureContainerPreproc + "@" + azureStorageAcct
            + ".blob.core.windows.net/";
    String baseOutPath = containerRoot + dirName;
    String trainDataPathRootDir = baseOutPath + "/train/";
    String testDataPathRootDir = baseOutPath + "/test/";
    JavaRDD<String> trainDataPaths = SparkUtils.listPaths(sc, trainDataPathRootDir);
    JavaRDD<String> testDataPaths = totalExamplesTest <= 0 ? null
            : listPathsSubset(sc, testDataPathRootDir, totalExamplesTest, 12345);
    trainDataPaths.cache();
    if (testDataPaths != null)
        testDataPaths.cache();

    //If only doing evaluation: perform it here and exit
    if (evalOnly) {
        evaluateOnly(sc, net, testDataPaths);
        return;
    }

    //Write configuration to output directory. Also determine output base directory for results
    writeConfig(sc);

    //Set up TrainingMaster for gradient sharing training
    VoidConfiguration voidConfiguration = VoidConfiguration.builder().unicastPort(port) // Should be open for IN/OUT communications on all Spark nodes
            .networkMask(networkMask) // Local network mask
            .controllerAddress(masterIP).build();
    TrainingMaster tm = new SharedTrainingMaster.Builder(voidConfiguration, minibatch).rngSeed(12345)
            .collectTrainingStats(false).batchSizePerWorker(minibatch) // Minibatch size for each worker
            .workersPerNode(numWorkersPerNode) // Workers per node
            .thresholdAlgorithm(new AdaptiveThresholdAlgorithm(gradientThreshold)).build();
    tm.setCollectTrainingStats(false);

    //If continueTraining==true and checkpoints are available available: Load checkpoint to continue training
    int firstSubsetIdx = 0;
    if (continueTraining) {
        Pair<Integer, ComputationGraph> p = loadCheckpoint();
        if (p != null) {
            firstSubsetIdx = p.getFirst();
            net = p.getSecond();
        }
    }

    //Setup saving of parameter snapshots. This is so we can calculate accuracy vs. time
    final AtomicBoolean isTraining = new AtomicBoolean(false);
    final File baseParamSaveDir = new File(outputPath, "paramSnapshots");
    if (!baseParamSaveDir.exists())
        baseParamSaveDir.mkdirs();

    //Prepare Spark version of neural net
    SparkComputationGraph sparkNet = new SparkComputationGraph(sc, net, tm);
    sparkNet.setCollectTrainingStats(tm.getIsCollectTrainingStats());

    // Add listeners
    sparkNet.setListeners(new PerformanceListener(listenerFrequency, true));

    // Time setup
    long endTimeMs = System.currentTimeMillis();
    double elapsedSec = (endTimeMs - startTime) / MILLISEC_PER_SEC;
    log.info("Setup timing: {} s", elapsedSec);
    results.append("Setup timing: ").append(elapsedSec).append(" sec\n");

    String resultsFile = FilenameUtils.concat(outputPath, "results.txt");
    if (new File(resultsFile).exists()) {
        String str = "\n\n\n============================================================================"
                + results.toString();
        FileUtils.writeStringToFile(new File(resultsFile), str, Charset.forName("UTF-8"), true);
    } else {
        FileUtils.writeStringToFile(new File(resultsFile), results.toString(), Charset.forName("UTF-8"));
    }

    //Random split into RDDs of exactly "convNumBatches" objects
    long countTrain = trainDataPaths.count();
    JavaRDD<String>[] trainSubsets;
    if (batchesBtwCheckpoints > 1) {
        trainSubsets = SparkUtils.balancedRandomSplit((int) countTrain, batchesBtwCheckpoints, trainDataPaths);
    } else {
        trainSubsets = (JavaRDD<String>[]) new JavaRDD[] { trainDataPaths };
    }

    DataSetLoader datasetLoader = new LoadDataSetsFunction(wordVectorsPath,
            PatentLabelGenerator.classLabelFilteredCounts().size(), 300);

    //Before training starts: start the thread to track convergence. This thread asyncronously saves params periodically for later evaluation
    AtomicInteger currentSubset = new AtomicInteger(0);
    Queue<ToEval> toEvalQueue = ConvergenceRunnable.startConvergenceThread(baseParamSaveDir, currentSubset,
            isTraining, saveFreqSec, sparkNet.getNetwork().params());
    log.info("Network saving thread started: saving copy every {} sec", saveFreqSec);

    boolean firstSave = true;
    long startTrain = System.currentTimeMillis();
    for (int epoch = 0; epoch < numEpochs; epoch++) {
        for (int i = firstSubsetIdx; i < trainSubsets.length; i++) {
            currentSubset.set(i);
            log.info("Starting training: epoch {} of {}, subset {} of {} ({} minibatches)", (epoch + 1),
                    numEpochs, (i + 1), trainSubsets.length, batchesBtwCheckpoints);
            long start = System.currentTimeMillis();
            isTraining.set(true);
            sparkNet.fitPaths(trainSubsets[i], datasetLoader);
            isTraining.set(false);
            long end = System.currentTimeMillis();
            log.info("Finished training: epoch {} of {}, subset {} of {} ({} minibatches) in {} sec",
                    (epoch + 1), numEpochs, (i + 1), trainSubsets.length, batchesBtwCheckpoints,
                    (end - start) / 1000);

            String fileName = "netCheckpoint_" + System.currentTimeMillis() + "_epoch" + epoch + "_subset" + i
                    + ".zip";
            String outpath = FilenameUtils.concat(outputPath, "nets/" + fileName);
            File f = new File(outpath);
            if (firstSave) {
                firstSave = false;
                f.getParentFile().mkdirs();
            }
            ModelSerializer.writeModel(sparkNet.getNetwork(), f, true);
            log.info("Saved network checkpoint to {}", outpath);

            //Now, evaluate the saved checkpoint files
            List<ToEval> toEval = new ArrayList<>();
            while (toEvalQueue.size() > 0) {
                toEval.add(toEvalQueue.remove());
            }

            if (totalExamplesTest > 0 && toEval.size() > 0) {
                log.info("Starting evaluation of {} checkpoint files", toEval.size());
                ComputationGraph cgForEval = sparkNet.getNetwork().clone();
                SparkComputationGraph scgForEval = new SparkComputationGraph(sc, cgForEval, null);
                for (ToEval te : toEval) {
                    INDArray params = Nd4j.readBinary(te.getFile());
                    cgForEval.params().assign(params);

                    long startEval = System.currentTimeMillis();
                    IEvaluation[] evals = scgForEval.doEvaluation(testDataPaths, 4, minibatch, datasetLoader,
                            new Evaluation());
                    long endEval = System.currentTimeMillis();

                    StringBuilder sb = new StringBuilder();
                    Evaluation e = (Evaluation) evals[0];
                    sb.append("network ").append(te.getCount()).append(" trainingMs ")
                            .append(te.getDurationSoFar()).append(" evalMS ").append(endEval - startEval)
                            .append(" accuracy ").append(e.accuracy()).append(" f1 ").append(e.f1())
                            .append("\n");

                    FileUtils.writeStringToFile(new File(resultsFile), sb.toString(), Charset.forName("UTF-8"),
                            true); //Append new output to file
                    saveEvaluation(false, evals, sc);
                    log.info("Evaluation: {}", sb.toString());

                }
            }

            if (maxRuntimeSec > 0
                    && (System.currentTimeMillis() - startTrain) / MILLISEC_PER_SEC > maxRuntimeSec) {
                log.info("Terminating due to exceeding max runtime");
                epoch = numEpochs;
                break;
            }
        }
        firstSubsetIdx = 0;
    }

    log.info("----- Example Complete -----");
    sc.stop();
    System.exit(0);
}

From source file:org.apache.hedwig.server.delivery.TestThrottlingDelivery.java

private void throttleWithFilter(Publisher pub, final Subscriber sub, ByteString topic, ByteString subid,
        final int X) throws Exception {
    // publish numbers with header (so only 3 messages would be delivered)
    publishNums(pub, topic, 0, 3 * X, X);

    // subscribe the topic with filter
    PubSubProtocol.Map userOptions = PubSubProtocol.Map.newBuilder().addEntries(PubSubProtocol.Map.Entry
            .newBuilder().setKey(OPT_MOD).setValue(ByteString.copyFromUtf8(String.valueOf(X)))).build();
    SubscriptionOptions opts = SubscriptionOptions.newBuilder().setCreateOrAttach(CreateOrAttach.ATTACH)
            .setOptions(userOptions).setMessageFilter(ModMessageFilter.class.getName()).build();
    sub.subscribe(topic, subid, opts);/*from  ww w .j a v a  2 s .  c om*/

    final AtomicInteger expected = new AtomicInteger(X);
    final CountDownLatch latch = new CountDownLatch(1);
    sub.startDelivery(topic, subid, new MessageHandler() {
        @Override
        public synchronized void deliver(ByteString topic, ByteString subscriberId, Message msg,
                Callback<Void> callback, Object context) {
            try {
                int value = Integer.valueOf(msg.getBody().toStringUtf8());
                logger.debug("Received message {},", value);

                if (value == expected.get()) {
                    expected.addAndGet(X);
                } else {
                    // error condition
                    logger.error("Did not receive expected value, expected {}, got {}", expected.get(), value);
                    expected.set(0);
                    latch.countDown();
                }
                if (value == 3 * X) {
                    latch.countDown();
                }
                callback.operationFinished(context, null);
                sub.consume(topic, subscriberId, msg.getMsgId());
            } catch (Exception e) {
                logger.error("Received bad message", e);
                latch.countDown();
            }
        }
    });

    assertTrue("Timed out waiting for messages " + 3 * X, latch.await(10, TimeUnit.SECONDS));
    assertEquals("Should be expected message with " + 4 * X, 4 * X, expected.get());

    sub.stopDelivery(topic, subid);
    sub.closeSubscription(topic, subid);
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

@FXML
public void initialize() {
    this.rootItem = new TreeItem<>(new TreeNode("[root]"));
    this.root.setRoot(this.rootItem);
    this.root.setCellFactory(new TreeCellFactory<>(node -> {
        if (node.getParent() == null) {
            ContextMenu export = new ContextMenu();

            MenuItem exportItem = new MenuItem("Export");

            export.setOnAction(e -> {
                File file = messageHandler.chooseFile().withInitialDirectory(new File("."))
                        .withTitle(Message.GENERIC_CHOOSE_EXPORT_LOCATION_JAR.format())
                        .withExtensionFilter(new FileFilter(Message.FILETYPE_JAVA_ARCHIVE.format(), "*.jar"),
                                true)/*from  www  . j  av  a2s .c  om*/
                        .promptSave();

                OpenedFile openedFile = (OpenedFile) node.getMetadata().get(OpenedFile.OPENED_FILE);

                Map<String, byte[]> clone = new HashMap<>(openedFile.getContents());

                backgroundTaskHelper.submit(
                        new BackgroundTask(Message.TASK_SAVING_FILE.format(node.getDisplayName()), true, () -> {
                            try {
                                if (!file.exists()) {
                                    if (!file.createNewFile()) {
                                        throw new IOException("Could not create export file");
                                    }
                                }

                                try (ZipOutputStream zipOutputStream = new ZipOutputStream(
                                        new FileOutputStream(file))) {
                                    for (Map.Entry<String, byte[]> ent : clone.entrySet()) {
                                        ZipEntry zipEntry = new ZipEntry(ent.getKey());
                                        zipOutputStream.putNextEntry(zipEntry);
                                        zipOutputStream.write(ent.getValue());
                                        zipOutputStream.closeEntry();
                                    }
                                }

                                messageHandler.handleMessage(Message.GENERIC_EXPORTED.format());
                            } catch (IOException ex) {
                                messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), ex);
                            }
                        }));
            });

            export.getItems().add(exportItem);
            return export;
        }
        return null;
    }));

    root.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
        if (event.getCode() == KeyCode.ENTER) {
            TreeItem<TreeNode> selected = this.root.getSelectionModel().getSelectedItem();
            if (selected != null) {
                if (selected.getChildren().size() != 0) {
                    selected.setExpanded(!selected.isExpanded());
                } else {
                    getParentController().getAllFilesViewerController().handleClick(selected.getValue());
                }
            }
        }
    });

    Tooltip tooltip = new Tooltip();
    StringBuilder search = new StringBuilder();

    List<TreeItem<TreeNode>> searchContext = new ArrayList<>();
    AtomicInteger searchIndex = new AtomicInteger();

    root.focusedProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue) {
            tooltip.hide();
            search.setLength(0);
        }
    });

    root.boundsInLocalProperty().addListener((observable, oldValue, newValue) -> {
        Bounds bounds = root.localToScreen(newValue);
        tooltip.setAnchorX(bounds.getMinX());
        tooltip.setAnchorY(bounds.getMinY());
    });

    root.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
        if (tooltip.isShowing() && event.getCode() == KeyCode.UP) {
            if (searchIndex.decrementAndGet() < 0) {
                searchIndex.set(searchContext.size() - 1);
            }
        } else if (tooltip.isShowing() && event.getCode() == KeyCode.DOWN) {
            if (searchIndex.incrementAndGet() >= searchContext.size()) {
                searchIndex.set(0);
            }
        } else {
            return;
        }
        event.consume();

        root.scrollTo(root.getRow(searchContext.get(searchIndex.get())));
        root.getSelectionModel().select(searchContext.get(searchIndex.get()));
    });

    root.addEventHandler(KeyEvent.KEY_TYPED, event -> {
        if (event.getCharacter().charAt(0) == '\b') {
            if (search.length() > 0) {
                search.setLength(search.length() - 1);
            }
        } else if (event.getCharacter().charAt(0) == '\u001B') { //esc
            tooltip.hide();
            search.setLength(0);
            return;
        } else if (search.length() > 0
                || (search.length() == 0 && StringUtils.isAlphanumeric(event.getCharacter()))) {
            search.append(event.getCharacter());
            if (!tooltip.isShowing()) {
                tooltip.show(root.getScene().getWindow());
            }
        }

        if (!tooltip.isShowing())
            return;

        String str = search.toString();
        tooltip.setText("Search for: " + str);

        searchContext.clear();

        ArrayDeque<TreeItem<TreeNode>> deque = new ArrayDeque<>();
        deque.addAll(rootItem.getChildren());

        while (!deque.isEmpty()) {
            TreeItem<TreeNode> item = deque.poll();
            if (item.getValue().getDisplayName().contains(str)) {
                searchContext.add(item);
            }
            if (item.isExpanded() && item.getChildren().size() > 0)
                deque.addAll(item.getChildren());
        }

        searchIndex.set(0);
        if (searchContext.size() > 0) {
            root.scrollTo(root.getRow(searchContext.get(0)));
            root.getSelectionModel().select(searchContext.get(0));
        }
    });

    openedFileController.loadedFiles().addListener((MapChangeListener<String, OpenedFile>) change -> {
        if (change.getValueAdded() != null) {
            updateTree(change.getValueAdded());
        }
        if (change.getValueRemoved() != null) {
            this.rootItem.getChildren()
                    .removeIf(ti -> ti.getValue().equals(change.getValueRemoved().getRoot()));
        }
    });
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testMultiClient() throws Exception {
    final Timing timing = new Timing();
    final CountDownLatch postEnterLatch = new CountDownLatch(QTY);
    final CountDownLatch postLeaveLatch = new CountDownLatch(QTY);
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicInteger max = new AtomicInteger(0);
    List<Future<Void>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < QTY; ++i) {
        Future<Void> future = service.submit(new Callable<Void>() {
            @Override//from ww w .  ja  v  a2s  . c o  m
            public Void call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        timing.session(), timing.connection(), new RetryOneTime(1));
                try {
                    client.start();
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                    synchronized (TestDistributedDoubleBarrier.this) {
                        int thisCount = count.incrementAndGet();
                        if (thisCount > max.get()) {
                            max.set(thisCount);
                        }
                    }

                    postEnterLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                    Assert.assertEquals(count.get(), QTY);

                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    count.decrementAndGet();

                    postLeaveLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));
                } finally {
                    IOUtils.closeQuietly(client);
                }

                return null;
            }
        });
        futures.add(future);
    }

    for (Future<Void> f : futures) {
        f.get();
    }
    Assert.assertEquals(count.get(), 0);
    Assert.assertEquals(max.get(), QTY);
}

From source file:org.apache.marmotta.splash.common.ui.SelectionDialog.java

public static int select(String title, String message, String description, List<Option> options,
        int defaultOption) {
    final JDialog dialog = new JDialog((Frame) null, title);
    dialog.setModal(true);// w w  w.  j  a  v a 2 s  .co  m
    dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    final AtomicInteger result = new AtomicInteger(Math.max(defaultOption, -1));

    JButton defaultBtn = null;

    final JPanel root = new JPanel(new GridBagLayout());
    root.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    dialog.getRootPane().setContentPane(root);

    JLabel lblMsg = new JLabel("<html>" + StringEscapeUtils.escapeHtml3(message).replaceAll("\\n", "<br>"));
    lblMsg.setFont(lblMsg.getFont().deriveFont(Font.BOLD, 16f));
    GridBagConstraints cLabel = new GridBagConstraints();
    cLabel.gridx = 0;
    cLabel.gridy = 0;
    cLabel.fill = GridBagConstraints.BOTH;
    cLabel.weightx = 1;
    cLabel.weighty = 0.5;
    cLabel.insets = new Insets(5, 5, 5, 5);
    root.add(lblMsg, cLabel);

    JLabel lblDescr = new JLabel(
            "<html>" + StringEscapeUtils.escapeHtml3(description).replaceAll("\\n", "<br>"));
    cLabel.gridy++;
    cLabel.insets = new Insets(0, 5, 5, 5);
    root.add(lblDescr, cLabel);

    // All the options
    cLabel.ipadx = 10;
    cLabel.ipady = 10;
    cLabel.insets = new Insets(5, 15, 0, 15);
    for (int i = 0; i < options.size(); i++) {
        cLabel.gridy++;

        final Option o = options.get(i);
        final JButton btn = new JButton(
                "<html>" + StringEscapeUtils.escapeHtml3(o.label).replaceAll("\\n", "<br>"),
                MessageDialog.loadIcon(o.icon));
        if (StringUtils.isNotBlank(o.info)) {
            btn.setToolTipText("<html>" + StringEscapeUtils.escapeHtml3(o.info).replaceAll("\\n", "<br>"));
        }

        btn.setHorizontalAlignment(AbstractButton.LEADING);
        btn.setVerticalTextPosition(AbstractButton.CENTER);
        btn.setHorizontalTextPosition(AbstractButton.TRAILING);

        final int myAnswer = i;
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                result.set(myAnswer);
                dialog.setVisible(false);
            }
        });

        root.add(btn, cLabel);
        if (i == defaultOption) {
            dialog.getRootPane().setDefaultButton(btn);
            defaultBtn = btn;
        }
    }

    final Icon icon = MessageDialog.loadIcon();
    if (icon != null) {
        JLabel lblIcn = new JLabel(icon);

        GridBagConstraints cIcon = new GridBagConstraints();
        cIcon.gridx = 1;
        cIcon.gridy = 0;
        cIcon.gridheight = 2 + options.size();
        cIcon.fill = GridBagConstraints.NONE;
        cIcon.weightx = 0;
        cIcon.weighty = 1;
        cIcon.anchor = GridBagConstraints.NORTH;
        cIcon.insets = new Insets(10, 5, 5, 0);
        root.add(lblIcn, cIcon);
    }

    final JButton close = new JButton("Cancel");
    close.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            result.set(-1);
            dialog.setVisible(false);
        }
    });
    GridBagConstraints cClose = new GridBagConstraints();
    cClose.gridx = 0;
    cClose.gridy = 2 + options.size();
    cClose.gridwidth = 2;
    cClose.weightx = 1;
    cClose.weighty = 0;
    cClose.insets = new Insets(15, 5, 5, 5);

    root.add(close, cClose);
    if (defaultOption < 0) {
        dialog.getRootPane().setDefaultButton(close);
        defaultBtn = close;
    }

    dialog.pack();
    dialog.setLocationRelativeTo(null);
    defaultBtn.requestFocusInWindow();

    dialog.setVisible(true);
    dialog.dispose();

    return result.get();
}

From source file:org.apache.hedwig.server.filter.TestMessageFilter.java

private void receiveNumModM(final ByteString topic, final ByteString subid, final String filterClassName,
        final ClientMessageFilter filter, final int start, final int num, final int M, final boolean consume)
        throws Exception {
    PubSubProtocol.Map userOptions = PubSubProtocol.Map.newBuilder().addEntries(PubSubProtocol.Map.Entry
            .newBuilder().setKey(OPT_MOD).setValue(ByteString.copyFromUtf8(String.valueOf(M)))).build();
    SubscriptionOptions.Builder optionsBuilder = SubscriptionOptions.newBuilder()
            .setCreateOrAttach(CreateOrAttach.ATTACH).setOptions(userOptions);
    if (null != filterClassName) {
        optionsBuilder.setMessageFilter(filterClassName);
    }//  ww w  .  j av  a  2 s .com
    subscriber.subscribe(topic, subid, optionsBuilder.build());

    final int base = start + M - start % M;

    final AtomicInteger expected = new AtomicInteger(base);
    final CountDownLatch latch = new CountDownLatch(1);
    MessageHandler msgHandler = new MessageHandler() {
        synchronized public void deliver(ByteString topic, ByteString subscriberId, Message msg,
                Callback<Void> callback, Object context) {
            try {
                int value = Integer.valueOf(msg.getBody().toStringUtf8());
                // duplicated messages received, ignore them
                if (value > start) {
                    if (value == expected.get()) {
                        expected.addAndGet(M);
                    } else {
                        logger.error("Did not receive expected value, expected {}, got {}", expected.get(),
                                value);
                        expected.set(0);
                        latch.countDown();
                    }
                    if (expected.get() == (base + num * M)) {
                        latch.countDown();
                    }
                }
                callback.operationFinished(context, null);
                if (consume) {
                    subscriber.consume(topic, subid, msg.getMsgId());
                }
            } catch (Exception e) {
                logger.error("Received bad message", e);
                latch.countDown();
            }
        }
    };
    if (null != filter) {
        subscriber.startDeliveryWithFilter(topic, subid, msgHandler, filter);
    } else {
        subscriber.startDelivery(topic, subid, msgHandler);
    }
    assertTrue("Timed out waiting for messages mod " + M + " expected is " + expected.get(),
            latch.await(10, TimeUnit.SECONDS));
    assertEquals("Should be expected message with " + (base + num * M), (base + num * M), expected.get());
    subscriber.stopDelivery(topic, subid);
    subscriber.closeSubscription(topic, subid);
}