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

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

Introduction

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

Prototype

public final void set(boolean newValue) 

Source Link

Document

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

Usage

From source file:brooklyn.networking.cloudstack.legacy.LegacyJcloudsCloudstackSubnetLocation.java

@Override
protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(ComputeService computeService,
        NodeMetadata node, Optional<Template> template, LoginCredentials userCredentials,
        HostAndPort managementHostAndPort, ConfigBag setup) throws IOException {
    String subnetSpecificHostname = null;
    String vmHostname = managementHostAndPort.getHostText();
    String sshHost = vmHostname;/*from  w  ww.j  av  a2  s.  co m*/
    Integer sshPort = null;
    PortForwardManager pfw = null;
    String publicIpId = null;

    final String serviceNetworkId = getConfig(CLOUDSTACK_SERVICE_NETWORK_ID);
    boolean portForwardingMode = Strings.isBlank(serviceNetworkId);
    LOG.debug("creating subnet JcloudsSshMachineLocation -- port forwarding={}, node={}",
            new Object[] { node, portForwardingMode });
    if (!portForwardingMode) {
        LOG.debug(
                "Using service network for Brooklyn access - service network ID is {} - searching for NIC connected to this network",
                serviceNetworkId);

        CloudStackApi cloudStackApi = getComputeService().getContext().unwrapApi(CloudStackApi.class);
        VirtualMachineApi vmClient = cloudStackApi.getVirtualMachineApi();
        VirtualMachine vm = vmClient.getVirtualMachine(node.getProviderId());

        Iterable<NIC> allNics = vm.getNICs();
        Predicate<NIC> isServiceNetwork = new Predicate<NIC>() {
            @Override
            public boolean apply(@Nullable NIC input) {
                return input != null && serviceNetworkId.equals(input.getNetworkId());
            }
        };
        Optional<NIC> serviceNic = Iterables.tryFind(allNics, isServiceNetwork);
        Iterable<NIC> otherNics = Iterables.filter(allNics, Predicates.not(isServiceNetwork));

        checkState(serviceNic.isPresent(),
                "unable to identify NIC connected to service network " + serviceNetworkId);
        String ipAddress = serviceNic.get().getIPAddress();
        checkState(Strings.isNonBlank(ipAddress),
                "no IP address on the NIC connected to service network " + serviceNetworkId);

        checkState(!Iterables.isEmpty(otherNics), "VM needs another NIC, in addition to the service network");
        // NIC anotherNic = Iterables.get(otherNics, 0);

        sshHost = ipAddress;
        sshPort = 22;
    } else {
        pfw = getRequiredConfig(PORT_FORWARDING_MANAGER);
        publicIpId = getRequiredConfig(CLOUDSTACK_TIER_PUBLIC_IP_ID);
        Cidr cidr = getConfig(MANAGEMENT_ACCESS_CIDR);

        // others, besides 22!
        int privatePort = 22;
        int publicPort = pfw.acquirePublicPort(publicIpId);

        systemCreatePortForwarding(cidr, publicPort, node, privatePort);

        sshPort = publicPort;
        sshHost = checkNotNull(pfw.getPublicIpHostname(publicIpId), "No ip recorded for id %s", publicIpId);
    }
    LOG.info("Created VM in " + this + " in subnet at " + node + ", ssh accessible via " + sshHost + ":"
            + sshPort);

    // and wait for it to be reachable

    LOG.debug("  waiting for new VM " + node + " in " + this + " to be port reachable on " + sshHost + ":"
            + sshPort);
    boolean isReachable = NetworkMultiAddressUtils2.isAccessible(sshHost, sshPort,
            TimeUnit.MINUTES.toMillis(15));
    if (!isReachable) {
        throw new IllegalStateException("Unable to contact forwarded SSH port for new VM " + node + " in "
                + this + " on " + sshHost + ":" + sshPort);
    }

    if (!NetworkMultiAddressUtils2.isResolveable(vmHostname)) {
        String oldHostname = vmHostname;
        vmHostname = Iterables.getFirst(Iterables.concat(node.getPublicAddresses(), node.getPrivateAddresses()),
                null);
        LOG.info("Renaming unresolvable hostname " + oldHostname + " to " + vmHostname);
    }

    // "public hostname" might be different
    // - sometimes it is not pingable from brooklyn (making sensors hard)
    // - sometimes furthest is the public one, we might want it
    //   (eg if we are in different 10.x subnet - closest not always accessible)
    //   or we might want nearest (if public is not accessible);
    //   and also consider we are on /16 subnet with host, host has another 10.x/8 address, but no public address;
    //   ie furthest might be inaccessible for other reasons
    // TODO i think the "right" way to do this is to have a pluggable "address chooser" ?

    LOG.debug("  vmHostname: " + vmHostname);

    // supply forwarded host and port
    Map<String, Object> sshConfig = extractSshConfig(setup, node);
    sshConfig.put(SshMachineLocation.SSH_HOST.getName(), sshHost);
    if (sshPort != null)
        sshConfig.put(SshMachineLocation.SSH_PORT.getName(), sshPort);

    if (LOG.isDebugEnabled()) {
        LOG.debug(
                "creating JcloudsSshMachineLocation in subnet {}, service network {}, for {}@{} for {} with {}",
                new Object[] { getRequiredConfig(CLOUDSTACK_SUBNET_NETWORK_ID),
                        getConfig(CLOUDSTACK_SERVICE_NETWORK_ID), userCredentials.getUser(), vmHostname,
                        setup.getDescription(), Sanitizer.sanitize(sshConfig) });
    }

    final JcloudsSshMachineLocation l = new AbstractJcloudsSubnetSshMachineLocation(
            MutableMap.builder().put("address", Networking.getInetAddressWithFixedName(vmHostname))
                    .put("displayName", vmHostname).put("user", userCredentials.getUser())
                    // don't think "config" does anything
                    .putAll(sshConfig).put("config", sshConfig).put("jcloudsParent", this)
                    .put(SshMachineLocation.PASSWORD, userCredentials.getOptionalPassword().orNull())
                    .put(SshMachineLocation.PRIVATE_KEY_DATA, userCredentials.getOptionalPrivateKey().orNull())
                    .put("node", node).put("template", template.orNull()).put("port", sshPort)
                    .put(CALLER_CONTEXT, setup.get(CALLER_CONTEXT)).build(),
            this, node) {
        @Override
        public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort) {
            return getPortForwardingTo(accessor, this, privatePort);
        }
    };
    l.init();
    getManagementContext().getLocationManager().manage(l);

    l.config().set(SUBNET_HOSTNAME_CONFIG, subnetSpecificHostname);
    l.config().set(VM_IDENTIFIER, node.getId());

    if (portForwardingMode) {
        // record port 22 forwarding
        pfw.associate(publicIpId, sshPort, l, 22);
    }

    LOG.debug("  waiting for new VM {} in {} to be SSH reachable on {}:{}",
            new Object[] { node, this, sshHost, sshPort });
    final AtomicBoolean isActive = new AtomicBoolean(false);
    Repeater.create().repeat(new Runnable() {
        @Override
        public void run() {
            try {
                int rc = l.execCommands("test accessibility", ImmutableList.of("hostname"));
                isActive.set(rc == 0);
            } catch (Throwable t) {
                isActive.set(false);
            }
        }
    }).every(Duration.FIVE_SECONDS).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return isActive.get();
        }
    }).limitTimeTo(Duration.FIVE_MINUTES).run();
    LOG.debug("  waited  for new VM {} in {} to be SSH reachable on {}:{}, result={}",
            new Object[] { node, this, sshHost, sshPort, isActive.get() });

    OperatingSystem operatingSystem = l.getNode().getOperatingSystem();
    if (operatingSystem != null) {
        OsFamily family = operatingSystem.getFamily();
        LOG.info("VM {}: OS family is {}", new Object[] { node, family });
        if (family != OsFamily.WINDOWS && family != OsFamily.UNRECOGNIZED) {
            LOG.warn("VM {}: disabling iptables", new Object[] { node });
            l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty",
                    Arrays.asList(BashCommands.dontRequireTtyForSudo()));
            l.execScript("disabling iptables",
                    Arrays.asList("sudo /etc/init.d/iptables stop", "sudo chkconfig iptables off"));
        } else {
            LOG.warn("VM {}: NOT disabling iptables because OS family is {}", new Object[] { node, family });
        }
    } else {
        LOG.warn("VM {}: NOT disabling iptables because OS is not detected", new Object[] { node });
    }

    String setupScript = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_URL);
    if (Strings.isNonBlank(setupScript)) {
        String setupVarsString = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_VARS);
        Map<String, String> substitutions = (setupVarsString != null)
                ? Splitter.on(",").withKeyValueSeparator(":").split(setupVarsString)
                : ImmutableMap.<String, String>of();
        String scriptContent = ResourceUtils.create(this).getResourceAsString(setupScript);
        String script = TemplateProcessor.processTemplateContents(scriptContent, substitutions);
        l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty",
                Arrays.asList(BashCommands.dontRequireTtyForSudo()));
        l.execCommands("Customizing node " + this, ImmutableList.of(script));
    }

    return l;
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

@Test
public void testConfigurationUpdateWithMergeIssue_Edit(TestContext tc) throws IOException, GitAPIException {
    add(git, root, new File("src/test/resources/files/a.json"), "dir");
    push(git);/*from  w ww  . j  av a 2  s.  c o  m*/

    retriever = ConfigRetriever.create(vertx,
            new ConfigRetrieverOptions().setScanPeriod(1000).addStore(new ConfigStoreOptions().setType("git")
                    .setConfig(new JsonObject().put("url", bareRoot.getAbsolutePath())
                            .put("path", "target/junk/work").put("filesets",
                                    new JsonArray().add(new JsonObject().put("pattern", "dir/*.json"))))));

    AtomicBoolean done = new AtomicBoolean();
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isTrue();
        assertThat(ar.result().getString("a.name")).isEqualTo("A");
        done.set(true);
    });
    await().untilAtomic(done, is(true));

    // Edit the file in the work dir
    File a = new File("target/junk/work/dir/a.json");
    assertThat(a).isFile();
    FileUtils.write(a, new JsonObject().put("a.name", "A-modified").put("conflict", "A").encodePrettily(),
            StandardCharsets.UTF_8);

    done.set(false);
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isTrue();
        assertThat(ar.result().getString("a.name")).isEqualTo("A-modified");
        done.set(true);
    });
    await().untilAtomic(done, is(true));

    updateA();

    Async async = tc.async();
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isFalse();
        assertThat(ar.cause().getMessage()).containsIgnoringCase("conflict");
        async.complete();
    });
}

From source file:org.apache.hadoop.hbase.client.TestAsyncSingleRequestRpcRetryingCaller.java

@Test
public void testLocateError() throws IOException, InterruptedException, ExecutionException {
    AtomicBoolean errorTriggered = new AtomicBoolean(false);
    AtomicInteger count = new AtomicInteger(0);
    HRegionLocation loc = CONN.getRegionLocator(TABLE_NAME).getRegionLocation(ROW).get();
    AsyncRegionLocator mockedLocator = new AsyncRegionLocator(CONN, AsyncConnectionImpl.RETRY_TIMER) {
        @Override/*from   w  w  w . j a  v a2 s .c om*/
        CompletableFuture<HRegionLocation> getRegionLocation(TableName tableName, byte[] row,
                RegionLocateType locateType, long timeoutNs) {
            if (tableName.equals(TABLE_NAME)) {
                CompletableFuture<HRegionLocation> future = new CompletableFuture<>();
                if (count.getAndIncrement() == 0) {
                    errorTriggered.set(true);
                    future.completeExceptionally(new RuntimeException("Inject error!"));
                } else {
                    future.complete(loc);
                }
                return future;
            } else {
                return super.getRegionLocation(tableName, row, locateType, timeoutNs);
            }
        }

        @Override
        void updateCachedLocation(HRegionLocation loc, Throwable exception) {
        }
    };
    try (AsyncConnectionImpl mockedConn = new AsyncConnectionImpl(CONN.getConfiguration(), CONN.registry,
            CONN.registry.getClusterId().get(), User.getCurrent()) {

        @Override
        AsyncRegionLocator getLocator() {
            return mockedLocator;
        }
    }) {
        RawAsyncTable table = mockedConn.getRawTableBuilder(TABLE_NAME)
                .setRetryPause(100, TimeUnit.MILLISECONDS).setMaxRetries(5).build();
        table.put(new Put(ROW).addColumn(FAMILY, QUALIFIER, VALUE)).get();
        assertTrue(errorTriggered.get());
        errorTriggered.set(false);
        count.set(0);
        Result result = table.get(new Get(ROW).addColumn(FAMILY, QUALIFIER)).get();
        assertArrayEquals(VALUE, result.getValue(FAMILY, QUALIFIER));
        assertTrue(errorTriggered.get());
    }
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

@Test
public void testConfigurationUpdateWithMergeIssue_Commit(TestContext tc) throws IOException, GitAPIException {
    add(git, root, new File("src/test/resources/files/a.json"), "dir");
    push(git);/* www  .  ja va2 s .c  om*/

    retriever = ConfigRetriever.create(vertx,
            new ConfigRetrieverOptions().setScanPeriod(1000).addStore(new ConfigStoreOptions().setType("git")
                    .setConfig(new JsonObject().put("url", bareRoot.getAbsolutePath())
                            .put("path", "target/junk/work").put("filesets",
                                    new JsonArray().add(new JsonObject().put("pattern", "dir/*.json"))))));

    AtomicBoolean done = new AtomicBoolean();
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isTrue();
        assertThat(ar.result().getString("a.name")).isEqualTo("A");
        done.set(true);
    });
    await().untilAtomic(done, is(true));

    // Edit the file in the work dir
    File a = new File("target/junk/work/dir/a.json");
    assertThat(a).isFile();
    FileUtils.write(a,
            new JsonObject().put("a.name", "A").put("conflict", "A").put("added", "added").encodePrettily(),
            StandardCharsets.UTF_8);
    git.add().addFilepattern("dir/a.json").call();
    git.commit().setMessage("update A").setAuthor("clement", "clement@apache.org")
            .setCommitter("clement", "clement@apache.org").call();

    done.set(false);
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isTrue();
        assertThat(ar.result().getString("a.name")).isEqualTo("A");
        assertThat(ar.result().getString("added")).isEqualTo("added");
        done.set(true);
    });
    await().untilAtomic(done, is(true));

    updateA();

    Async async = tc.async();
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isFalse();
        assertThat(ar.cause().getMessage()).containsIgnoringCase("conflict");
        async.complete();
    });
}

From source file:com.drextended.actionhandler.action.CompositeAction.java

/**
 * Prepares popup menu to show given menu items
 *
 * @param context    The Context, which generally get from view by {@link View#getContext()}
 * @param view       The View, which can be used for prepare any visual effect (like animation),
 *                   Generally it is that view which was clicked and initiated action to fire.
 * @param actionType The action type/*from   w w  w.  j  a  v a 2  s .c o  m*/
 * @param model      The model which should be handled by the action.
 * @param menuItems  list of items which will be shown in a menu
 * @return popup menu to show given menu items
 */
protected PopupMenu buildPopupMenu(final Context context, final View view, final String actionType,
        final M model, final List<ActionItem> menuItems) {
    final PopupMenu popupMenu = new PopupMenu(context, view);
    final Menu menu = popupMenu.getMenu();
    int count = menuItems.size();
    for (int index = 0; index < count; index++) {
        final ActionItem item = menuItems.get(index);
        //noinspection unchecked
        menu.add(0, index, 0, item.titleProvider.getTitle(context, model));
        if (mShowNonAcceptedActions) {
            menu.getItem(index).setEnabled(item.action.isModelAccepted(model));
        }
    }
    final AtomicBoolean activated = new AtomicBoolean(false);
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            activated.set(true);
            final ActionItem actionItem = menuItems.get(item.getItemId());
            if (item.isEnabled()) {
                fireActionItem(context, view, actionItem.actionType, model, actionItem);
            } else {
                notifyOnActionDismiss("The model is not accepted for selected action", view, actionType, model);
            }
            return true;
        }
    });
    popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
        @Override
        public void onDismiss(PopupMenu menu) {
            if (!activated.get()) {
                notifyOnActionDismiss("CompositeAction menu dismissed", view, actionType, model);
            }
        }
    });
    return popupMenu;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleSheet.java

private static boolean selectsPseudoClass(final BrowserVersion browserVersion,
        final AttributeCondition condition, final DomElement element) {
    if (browserVersion.hasFeature(QUERYSELECTORALL_NOT_IN_QUIRKS)) {
        final Object sobj = element.getPage().getScriptableObject();
        if (sobj instanceof HTMLDocument && ((HTMLDocument) sobj).getDocumentMode() < 8) {
            return false;
        }/*from  w w  w.j av a 2 s. com*/
    }

    final String value = condition.getValue();
    if ("root".equals(value)) {
        return element == element.getPage().getDocumentElement();
    } else if ("enabled".equals(value)) {
        return element instanceof DisabledElement && !((DisabledElement) element).isDisabled();
    }
    if ("disabled".equals(value)) {
        return element instanceof DisabledElement && ((DisabledElement) element).isDisabled();
    }
    if ("focus".equals(value)) {
        final HtmlPage htmlPage = element.getHtmlPageOrNull();
        if (htmlPage != null) {
            final DomElement focus = htmlPage.getFocusedElement();
            return element == focus;
        }
    } else if ("checked".equals(value)) {
        return (element instanceof HtmlCheckBoxInput && ((HtmlCheckBoxInput) element).isChecked())
                || (element instanceof HtmlRadioButtonInput && ((HtmlRadioButtonInput) element).isChecked()
                        || (element instanceof HtmlOption && ((HtmlOption) element).isSelected()));
    } else if ("first-child".equals(value)) {
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        return true;
    } else if ("last-child".equals(value)) {
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        return true;
    } else if ("first-of-type".equals(value)) {
        final String type = element.getNodeName();
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        return true;
    } else if ("last-of-type".equals(value)) {
        final String type = element.getNodeName();
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        return true;
    } else if (value.startsWith("nth-child(")) {
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if (value.startsWith("nth-last-child(")) {
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if (value.startsWith("nth-of-type(")) {
        final String type = element.getNodeName();
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if (value.startsWith("nth-last-of-type(")) {
        final String type = element.getNodeName();
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if ("only-child".equals(value)) {
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        return true;
    } else if ("only-of-type".equals(value)) {
        final String type = element.getNodeName();
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        return true;
    } else if ("empty".equals(value)) {
        return isEmpty(element);
    } else if ("target".equals(value)) {
        final String ref = element.getPage().getUrl().getRef();
        return StringUtils.isNotBlank(ref) && ref.equals(element.getId());
    } else if (value.startsWith("not(")) {
        final String selectors = value.substring(value.indexOf('(') + 1, value.length() - 1);
        final AtomicBoolean errorOccured = new AtomicBoolean(false);
        final ErrorHandler errorHandler = new ErrorHandler() {
            @Override
            public void warning(final CSSParseException exception) throws CSSException {
                // ignore
            }

            @Override
            public void fatalError(final CSSParseException exception) throws CSSException {
                errorOccured.set(true);
            }

            @Override
            public void error(final CSSParseException exception) throws CSSException {
                errorOccured.set(true);
            }
        };
        final CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
        parser.setErrorHandler(errorHandler);
        try {
            final SelectorList selectorList = parser
                    .parseSelectors(new InputSource(new StringReader(selectors)));
            if (errorOccured.get() || selectorList == null || selectorList.getLength() != 1) {
                throw new CSSException("Invalid selectors: " + selectors);
            }

            validateSelectors(selectorList, 9, element);

            return !CSSStyleSheet.selects(browserVersion, selectorList.item(0), element);
        } catch (final IOException e) {
            throw new CSSException("Error parsing CSS selectors from '" + selectors + "': " + e.getMessage());
        }
    }
    return false;
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

@Test
@SuppressWarnings("SleepWhileInLoop")
public void testSynchingLogic() throws InterruptedException {
    long sleeptime = 25L;
    final ArrayList<Object> list = new ArrayList<Object>();
    GenericOperator go = new GenericOperator();
    final GenericNode gn = new GenericNode(go,
            new com.datatorrent.stram.engine.OperatorContext(0, new DefaultAttributeMap(), null));
    gn.setId(1);//from w  ww . ja  va 2 s .  c  o  m
    AbstractReservoir reservoir1 = AbstractReservoir.newReservoir("ip1Res", 1024);
    AbstractReservoir reservoir2 = AbstractReservoir.newReservoir("ip2Res", 1024);
    Sink<Object> output = new Sink<Object>() {
        @Override
        public void put(Object tuple) {
            list.add(tuple);
        }

        @Override
        public int getCount(boolean reset) {
            return 0;
        }

    };

    gn.connectInputPort("ip1", reservoir1);
    gn.connectInputPort("ip2", reservoir2);
    gn.connectOutputPort("op", output);
    gn.firstWindowMillis = 0;
    gn.windowWidthMillis = 100;

    final AtomicBoolean ab = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            ab.set(true);
            gn.activate();
            gn.run();
            gn.deactivate();
        }

    };
    t.start();

    do {
        Thread.sleep(sleeptime);
    } while (ab.get() == false);

    Tuple beginWindow1 = new Tuple(MessageType.BEGIN_WINDOW, 0x1L);

    reservoir1.add(beginWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    reservoir2.add(beginWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    Tuple endWindow1 = new EndWindowTuple(0x1L);

    reservoir1.add(endWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    Tuple beginWindow2 = new Tuple(MessageType.BEGIN_WINDOW, 0x2L);

    reservoir1.add(beginWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(1, list.size());

    reservoir2.add(endWindow1);
    Thread.sleep(sleeptime);
    Assert.assertEquals(3, list.size());

    reservoir2.add(beginWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(3, list.size());

    Tuple endWindow2 = new EndWindowTuple(0x2L);

    reservoir2.add(endWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(3, list.size());

    reservoir1.add(endWindow2);
    Thread.sleep(sleeptime);
    Assert.assertEquals(4, list.size());

    EndStreamTuple est = new EndStreamTuple(0L);

    reservoir1.add(est);
    Thread.sleep(sleeptime);
    Assert.assertEquals(4, list.size());

    Tuple beginWindow3 = new Tuple(MessageType.BEGIN_WINDOW, 0x3L);

    reservoir2.add(beginWindow3);
    Thread.sleep(sleeptime);
    Assert.assertEquals(5, list.size());

    Tuple endWindow3 = new EndWindowTuple(0x3L);

    reservoir2.add(endWindow3);
    Thread.sleep(sleeptime);
    Assert.assertEquals(6, list.size());

    Assert.assertNotSame(Thread.State.TERMINATED, t.getState());

    reservoir2.add(est);
    Thread.sleep(sleeptime);
    Assert.assertEquals(7, list.size());

    Thread.sleep(sleeptime);

    Assert.assertEquals(Thread.State.TERMINATED, t.getState());
}

From source file:it.anyplace.sync.client.SyncthingClient.java

private BlockExchangeConnectionHandler openConnection(DeviceAddress deviceAddress) throws Exception {
    final BlockExchangeConnectionHandler connectionHandler = new BlockExchangeConnectionHandler(configuration,
            deviceAddress);/* w  ww .j a  va2s.c om*/
    connectionHandler.setIndexHandler(indexHandler);
    connectionHandler.getEventBus().register(indexHandler);
    connectionHandler.getEventBus().register(devicesHandler);
    final AtomicBoolean shouldRestartForNewFolder = new AtomicBoolean(false);
    connectionHandler.getEventBus().register(new Object() {
        @Subscribe
        public void handleConnectionClosedEvent(BlockExchangeConnectionHandler.ConnectionClosedEvent event) {
            connections.remove(connectionHandler);
            synchronized (pool) {
                pool.remove(connectionHandler);
            }
        }

        @Subscribe
        public void handleNewFolderSharedEvent(BlockExchangeConnectionHandler.NewFolderSharedEvent event) {
            shouldRestartForNewFolder.set(true);
        }
    });
    connectionHandler.connect();
    connections.add(connectionHandler);
    if (shouldRestartForNewFolder.get()) {
        logger.info("restart connection for new folder shared");
        connectionHandler.close();
        return openConnection(deviceAddress);
    } else {
        return connectionHandler;
    }
}

From source file:org.apache.solr.handler.dataimport.XPathEntityProcessor.java

private Iterator<Map<String, Object>> getRowIterator(final Reader data, final String s) {
    //nothing atomic about it. I just needed a StongReference
    final AtomicReference<Exception> exp = new AtomicReference<>();
    final BlockingQueue<Map<String, Object>> blockingQueue = new ArrayBlockingQueue<>(blockingQueueSize);
    final AtomicBoolean isEnd = new AtomicBoolean(false);
    final AtomicBoolean throwExp = new AtomicBoolean(true);
    publisherThread = new Thread() {
        @Override//from w w  w.ja v a 2  s.  com
        public void run() {
            try {
                xpathReader.streamRecords(data, (record, xpath) -> {
                    if (isEnd.get()) {
                        throwExp.set(false);
                        //To end the streaming . otherwise the parsing will go on forever
                        //though consumer has gone away
                        throw new RuntimeException("BREAK");
                    }
                    Map<String, Object> row;
                    try {
                        row = readRow(record, xpath);
                    } catch (Exception e) {
                        isEnd.set(true);
                        return;
                    }
                    offer(row);
                });
            } catch (Exception e) {
                if (throwExp.get())
                    exp.set(e);
            } finally {
                closeIt(data);
                if (!isEnd.get()) {
                    offer(END_MARKER);
                }
            }
        }

        private void offer(Map<String, Object> row) {
            try {
                while (!blockingQueue.offer(row, blockingQueueTimeOut, blockingQueueTimeOutUnits)) {
                    if (isEnd.get())
                        return;
                    LOG.debug("Timeout elapsed writing records.  Perhaps buffer size should be increased.");
                }
            } catch (InterruptedException e) {
                return;
            } finally {
                synchronized (this) {
                    notifyAll();
                }
            }
        }
    };

    publisherThread.start();

    return new Iterator<Map<String, Object>>() {
        private Map<String, Object> lastRow;
        int count = 0;

        @Override
        public boolean hasNext() {
            return !isEnd.get();
        }

        @Override
        public Map<String, Object> next() {
            Map<String, Object> row;

            do {
                try {
                    row = blockingQueue.poll(blockingQueueTimeOut, blockingQueueTimeOutUnits);
                    if (row == null) {
                        LOG.debug("Timeout elapsed reading records.");
                    }
                } catch (InterruptedException e) {
                    LOG.debug("Caught InterruptedException while waiting for row.  Aborting.");
                    isEnd.set(true);
                    return null;
                }
            } while (row == null);

            if (row == END_MARKER) {
                isEnd.set(true);
                if (exp.get() != null) {
                    String msg = "Parsing failed for xml, url:" + s + " rows processed in this xml:" + count;
                    if (lastRow != null)
                        msg += " last row in this xml:" + lastRow;
                    if (ABORT.equals(onError)) {
                        wrapAndThrow(SEVERE, exp.get(), msg);
                    } else if (SKIP.equals(onError)) {
                        wrapAndThrow(DataImportHandlerException.SKIP, exp.get());
                    } else {
                        LOG.warn(msg, exp.get());
                    }
                }
                return null;
            }
            count++;
            return lastRow = row;
        }

        @Override
        public void remove() {
            /*no op*/
        }
    };

}

From source file:io.vertx.config.git.GitConfigStoreTest.java

@After
public void tearDown() {
    AtomicBoolean done = new AtomicBoolean();
    if (retriever != null) {
        retriever.close();//from  w  ww  .j  a  v  a 2  s  .co  m
    }

    if (git != null) {
        git.close();
    }
    if (bare != null) {
        bare.close();
    }

    vertx.close(v -> done.set(true));

    await().untilAtomic(done, is(true));
}