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:org.lendingclub.mercator.docker.SwarmScanner.java

public void scanServicesForSwarm(String swarmClusterId) {

    JsonNode response = getRestClient().getServices();

    AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
    AtomicBoolean error = new AtomicBoolean(false);
    response.forEach(it -> {//w  w w. j a v  a 2 s.c o  m
        try {
            ObjectNode n = flattenService(it);
            n.put("swarmClusterId", swarmClusterId);
            dockerScanner.getNeoRxClient().execCypher(
                    "merge (x:DockerService {serviceId:{serviceId}}) set x+={props}, x.updateTs=timestamp() return x",
                    "serviceId", n.get("serviceId").asText(), "props", n).forEach(svc -> {
                        removeDockerLabels("DockerService", "serviceId", n.get("serviceId").asText(), n, svc);
                        earlistUpdate.set(
                                Math.min(earlistUpdate.get(), svc.path("updateTs").asLong(Long.MAX_VALUE)));
                    });
            dockerScanner.getNeoRxClient().execCypher(
                    "match (swarm:DockerSwarm {swarmClusterId:{swarmClusterId}}),(service:DockerService{serviceId:{serviceId}}) merge (swarm)-[x:CONTAINS]->(service) set x.updateTs=timestamp()",
                    "swarmClusterId", swarmClusterId, "serviceId", n.path("serviceId").asText());

        } catch (Exception e) {
            logger.warn("problem updating service", e);
            error.set(true);
        }
    });
    if (error.get() == false) {
        if (earlistUpdate.get() < System.currentTimeMillis()) {
            dockerScanner.getNeoRxClient().execCypher(
                    "match (x:DockerService) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x",
                    "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId);
        }
    }

}

From source file:org.apache.hadoop.mapred.JobHistory.java

static Path[] filteredStat2Paths(FileStatus[] stats, boolean dirs, AtomicBoolean hasMismatches) {
    int resultCount = 0;

    if (hasMismatches == null) {
        hasMismatches = new AtomicBoolean(false);
    }// w w  w.ja  v  a  2 s .  c o  m

    for (int i = 0; i < stats.length; ++i) {
        if (stats[i].isDir() == dirs) {
            stats[resultCount++] = stats[i];
        } else {
            hasMismatches.set(true);
        }
    }

    Path[] paddedResult = FileUtil.stat2Paths(stats);

    Path[] result = new Path[resultCount];

    System.arraycopy(paddedResult, 0, result, 0, resultCount);

    return result;
}

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

/**
 * If the workspace name and owner provided correspond to a local workspace
 * on this computer, that local workspace will be reconciled.
 *//*from  w w w . j ava  2 s .c  o  m*/
protected Workspace reconcileIfLocal(final String workspaceName, final String ownerName,
        final boolean unscannedReconcile, final boolean reconcileMissingLocalItems,
        final boolean skipIfAccessDenied, final AtomicBoolean reconciled) {
    if (reconciled != null) {
        reconciled.set(false);
    }

    if (workspaceName == null || workspaceName.length() == 0 || ownerName == null || ownerName.length() == 0) {
        return null;
    }

    Workspace localWorkspace = null;

    if ((localWorkspace = getLocalWorkspace(workspaceName, ownerName)) != null) {
        final AtomicReference<Failure[]> failures = new AtomicReference<Failure[]>();
        final AtomicBoolean pendingChangesUpdatedByServer = new AtomicBoolean();

        try {
            final boolean wasReconciled = LocalDataAccessLayer.reconcileLocalWorkspace(localWorkspace, this,
                    unscannedReconcile, reconcileMissingLocalItems, failures, pendingChangesUpdatedByServer);

            if (wasReconciled) {
                localWorkspace.invalidateMappings();
                localWorkspace.refreshMappingsIfNeeded();
            }

            if (reconciled != null) {
                reconciled.set(wasReconciled);
            }
        } catch (final ResourceAccessException e) {
            if (!skipIfAccessDenied) {
                throw e;
            }

            return null;
        }

        getVersionControlClient().reportFailures(localWorkspace, failures.get());
    }

    return localWorkspace;
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

private boolean authenticateRequest(ServletRequest request, ServletResponse response,
        final AtomicReference<ServletRequest> wrappedRequest) throws IOException {
    boolean requestContinues = false;
    final AtomicBoolean isAuthenticated = new AtomicBoolean(false);
    AuthenticationPlugin authenticationPlugin = cores.getAuthenticationPlugin();
    if (authenticationPlugin == null) {
        return true;
    } else {//from  w w  w . j av a  2 s.c  o  m
        // /admin/info/key must be always open. see SOLR-9188
        // tests work only w/ getPathInfo
        //otherwise it's just enough to have getServletPath()
        if (PKIAuthenticationPlugin.PATH.equals(((HttpServletRequest) request).getServletPath())
                || PKIAuthenticationPlugin.PATH.equals(((HttpServletRequest) request).getPathInfo()))
            return true;
        String header = ((HttpServletRequest) request).getHeader(PKIAuthenticationPlugin.HEADER);
        if (header != null && cores.getPkiAuthenticationPlugin() != null)
            authenticationPlugin = cores.getPkiAuthenticationPlugin();
        try {
            log.debug("Request to authenticate: {}, domain: {}, port: {}", request, request.getLocalName(),
                    request.getLocalPort());
            // upon successful authentication, this should call the chain's next filter.
            requestContinues = authenticationPlugin.doAuthenticate(request, response, (req, rsp) -> {
                isAuthenticated.set(true);
                wrappedRequest.set(req);
            });
        } catch (Exception e) {
            log.info("Error authenticating", e);
            throw new SolrException(ErrorCode.SERVER_ERROR, "Error during request authentication, ", e);
        }
    }
    // requestContinues is an optional short circuit, thus we still need to check isAuthenticated.
    // This is because the AuthenticationPlugin doesn't always have enough information to determine if
    // it should short circuit, e.g. the Kerberos Authentication Filter will send an error and not
    // call later filters in chain, but doesn't throw an exception.  We could force each Plugin
    // to implement isAuthenticated to simplify the check here, but that just moves the complexity to
    // multiple code paths.
    if (!requestContinues || !isAuthenticated.get()) {
        response.flushBuffer();
        return false;
    }
    return true;
}

From source file:com.jayway.maven.plugins.android.AbstractAndroidMojo.java

/**
 * Undeploys an apk, specified by package name, from a connected emulator
 * or usb device. Also deletes the application's data and cache
 * directories on the device.//w w  w . j av a 2 s. com
 *
 * @param packageName the package name to undeploy.
 * @return <code>true</code> if successfully undeployed, <code>false</code> otherwise.
 */
protected boolean undeployApk(final String packageName) throws MojoExecutionException, MojoFailureException {

    final AtomicBoolean result = new AtomicBoolean(true); // if no devices are present, it counts as successful

    doWithDevices(new DeviceCallback() {
        public void doWithDevice(final IDevice device) throws MojoExecutionException {
            String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix(device);
            try {
                device.uninstallPackage(packageName);
                getLog().info(deviceLogLinePrefix + "Successfully uninstalled " + packageName);
                getLog().debug(" from " + DeviceHelper.getDescriptiveName(device));
                result.set(true);
            } catch (InstallException e) {
                result.set(false);
                throw new MojoExecutionException(
                        deviceLogLinePrefix + "Uninstall of " + packageName + " failed.", e);
            }
        }
    });

    return result.get();
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

public Path download(ChromiumVersion version) {
    final Path destinationRoot = getChromiumPath(version);
    final Path executable = getExecutable(version);

    String url;/*ww  w  .j a  v a 2  s . c  om*/
    if (WINDOWS) {
        url = format("%s/Win_x64/%d/chrome-win.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (LINUX) {
        url = format("%s/Linux_x64/%d/chrome-linux.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (MAC) {
        url = format("%s/Mac/%d/chrome-mac.zip", DOWNLOAD_HOST, version.getRevision());
    } else {
        throw new CdpException("Unsupported OS found - " + OS);
    }

    try {
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("HEAD");
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        if (conn.getResponseCode() != 200) {
            throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
        }
        long contentLength = conn.getHeaderFieldLong("x-goog-stored-content-length", 0);
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")) + "-r"
                + version.getRevision() + ".zip";
        Path archive = get(getProperty("java.io.tmpdir")).resolve(fileName);
        if (exists(archive) && contentLength != size(archive)) {
            delete(archive);
        }
        if (!exists(archive)) {
            logger.info("Downloading Chromium [revision=" + version.getRevision() + "] 0%");
            u = new URL(url);
            if (conn.getResponseCode() != 200) {
                throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
            conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            Thread thread = null;
            AtomicBoolean halt = new AtomicBoolean(false);
            Runnable progress = () -> {
                try {
                    long fileSize = size(archive);
                    logger.info("Downloading Chromium [revision={}] {}%", version.getRevision(),
                            round((fileSize * 100L) / contentLength));
                } catch (IOException e) {
                    // ignore
                }
            };
            try (InputStream is = conn.getInputStream()) {
                logger.info("Download location: " + archive.toString());
                thread = new Thread(() -> {
                    while (true) {
                        try {
                            if (halt.get()) {
                                break;
                            }
                            progress.run();
                            sleep(1000);
                        } catch (Throwable e) {
                            // ignore
                        }
                    }
                });
                thread.setName("cdp4j");
                thread.setDaemon(true);
                thread.start();
                copy(conn.getInputStream(), archive);
            } finally {
                if (thread != null) {
                    progress.run();
                    halt.set(true);
                }
            }
        }
        logger.info("Extracting to: " + destinationRoot.toString());
        if (exists(archive)) {
            createDirectories(destinationRoot);
            unpack(archive.toFile(), destinationRoot.toFile());
        }

        if (!exists(executable) || !isExecutable(executable)) {
            throw new CdpException("Chromium executable not found: " + executable.toString());
        }

        if (!WINDOWS) {
            Set<PosixFilePermission> permissions = getPosixFilePermissions(executable);
            if (!permissions.contains(OWNER_EXECUTE)) {
                permissions.add(OWNER_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
            if (!permissions.contains(GROUP_EXECUTE)) {
                permissions.add(GROUP_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
        }
    } catch (IOException e) {
        throw new CdpException(e);
    }
    return executable;
}

From source file:io.pravega.client.stream.impl.ControllerImplTest.java

@Test
public void testParallelCreateStream() throws Exception {
    final ExecutorService executorService = Executors.newFixedThreadPool(10);
    Semaphore createCount = new Semaphore(-19);
    AtomicBoolean success = new AtomicBoolean(true);
    for (int i = 0; i < 10; i++) {
        executorService.submit(() -> {
            for (int j = 0; j < 2; j++) {
                try {
                    CompletableFuture<Boolean> createStreamStatus;
                    createStreamStatus = controllerClient
                            .createStream(StreamConfiguration.builder().streamName("streamparallel")
                                    .scope("scope1").scalingPolicy(ScalingPolicy.fixed(1)).build());
                    log.info("{}", createStreamStatus.get());
                    assertTrue(createStreamStatus.get());
                    createCount.release();
                } catch (Exception e) {
                    log.error("Exception when creating stream: {}", e);

                    // Don't wait for other threads to complete.
                    success.set(false);
                    createCount.release(20);
                }//from w w w. j  a va  2  s  .  c  o m
            }
        });
    }
    createCount.acquire();
    executorService.shutdownNow();
    assertTrue(success.get());
}

From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java

private boolean isSvnPropertiesDefined(final File file) {
    try {/*  www .  jav  a2 s .c  o  m*/
        final AtomicBoolean eol = new AtomicBoolean();
        svnWCClient_.doGetProperty(file, null, SVNRevision.WORKING, SVNRevision.WORKING, SVNDepth.EMPTY,
                new ISVNPropertyHandler() {

                    @Override
                    public void handleProperty(final long revision, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final SVNURL url, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final File path, final SVNPropertyData property) {
                        final String name = property.getName();
                        final String value = property.getValue().getString();
                        if ("svn:eol-style".equals(name) && "native".equals(value)) {
                            eol.set(true);
                        }
                    }
                }, null);

        final String fileName = file.getName().toLowerCase(Locale.ROOT);

        for (final String extension : SVN.getEolExtenstions()) {
            if (fileName.endsWith(extension)) {
                return eol.get();
            }
        }
        return true;
    } catch (final Exception e) {
        //nothing
    }
    final String path = file.getAbsolutePath();
    // automatically generated and is outside SVN control
    return (path.contains("jQuery") && path.contains("WEB-INF") && path.contains("cgi"))
            || (path.contains("jQuery") && path.contains("csp.log"));
}

From source file:org.apache.hadoop.hdfs.server.namenode.bookkeeper.TestBookKeeperEditLogInputStream.java

/**
 * Test "tailing" an in-progress ledger that is later finalized, i.e., a
 * typical primary/standby high-availability scenario.
 * Spawns two threads: a consumer (which writes transactions with
 * monotonically increasing transaction ids to the log), and consumer
 * (which keeps reading from the log, refreshing when encountering the end of
 * the log until the producer is shut down). Verifies that transactions have
 * been written in the correct order.//  w w  w. ja v a 2s.  c  o  m
 */
@Test
public void testTailing() throws Exception {
    // Unlike the other unit test, numEdits here is constant as this is
    // a longer running test
    final int numEdits = 10000;
    final AtomicBoolean finishedProducing = new AtomicBoolean(false);
    final LedgerHandle ledgerOut = createLedger();
    final long ledgerId = ledgerOut.getId();

    Callable<Void> producerThread = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            try {
                BookKeeperEditLogOutputStream out = new BookKeeperEditLogOutputStream(ledgerOut);
                out.create(); // Writes version to the ledger output stream

                for (int i = 1; i <= numEdits; i++) {
                    FSEditLogOp op = FSEditLogTestUtil.getNoOpInstance();
                    // Set an increasing transaction id to verify correctness
                    op.setTransactionId(i);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Writing " + op);
                    }

                    FSEditLogTestUtil.writeToStreams(op, out);

                    if (i % 1000 == 0) {
                        Thread.sleep(500);
                        FSEditLogTestUtil.flushStreams(out);
                    }
                }
                FSEditLogTestUtil.flushStreams(out);
                FSEditLogTestUtil.closeStreams(out);
            } finally {
                // Let the producer know that we've reached the end.
                finishedProducing.set(true);
            }
            return null;
        }
    };
    Callable<Void> consumerThread = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            BookKeeperEditLogInputStream in = new BookKeeperEditLogInputStream(ledgerProvider, ledgerId, 0, 1,
                    -1, true);

            long numOps = 0;
            long maxTxId = -1;
            FSEditLogOp op;
            long lastPos = in.getPosition();
            do {
                op = in.readOp();
                if (op == null) { // If we've reached the end prematurely...
                    Thread.sleep(1000);
                    LOG.info("Refreshing to " + lastPos);

                    in.refresh(lastPos, -1); // Then refresh to last known good position
                } else {
                    long txId = op.getTransactionId();
                    if (txId > maxTxId) {
                        // Standby ingest contains similar logic: transactions
                        // with ids lower than what is already read are ignored.
                        numOps++;
                        maxTxId = txId;
                    }

                    // Remember the last known safe position that we can refresh to
                    lastPos = in.getPosition();
                }
            } while (op != null || !finishedProducing.get());
            Thread.sleep(1000);

            // Once producer is shutdown, scan again from last known good position
            // until the end of the ledger. This mirrors the Ingest logic (last
            // read when being quiesced).
            in.refresh(lastPos, -1);
            do {
                op = in.readOp();
                if (op != null) {
                    long txId = op.getTransactionId();
                    if (txId > maxTxId) {
                        numOps++;
                        maxTxId = txId;
                    }
                }
            } while (op != null);

            assertEquals("Must have read " + numEdits + " edits", numEdits, numOps);
            assertEquals("Must end at txid = " + numEdits, maxTxId, numEdits);
            return null;
        }
    };
    // Allow producer and consumer to run concurrently
    ExecutorService executor = Executors.newFixedThreadPool(2);
    Future<Void> producerFuture = executor.submit(producerThread);
    Future<Void> consumerFuture = executor.submit(consumerThread);

    // Calling a .get() on the future will rethrow any exceptions thrown in
    // the future.
    producerFuture.get();
    consumerFuture.get();
}

From source file:org.apache.nifi.processors.ocr.TesseractOCRProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;// w  w w .  ja va2 s.c  om
    }

    //Transfer the original
    session.transfer(session.clone(flowFile), REL_ORIGINAL);
    final AtomicBoolean errors = new AtomicBoolean(false);

    FlowFile ff = session.write(flowFile, new StreamCallback() {
        @Override
        public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
            tesseract.setDatapath(
                    context.getProperty(TESS_DATA_PATH).evaluateAttributeExpressions(flowFile).getValue());

            //Builds the list of Tesseract configs.
            Map<String, String> configs = buildTesseractConfigs(
                    context.getProperty(TESSERACT_CONFIGS).getValue());
            for (Map.Entry<String, String> entry : configs.entrySet()) {
                getLogger().debug("Tesseract Config Key : '" + entry.getKey() + "' Tesseract Config Value : '"
                        + entry.getValue() + "'");
                tesseract.setTessVariable(entry.getKey(), entry.getValue());
            }

            try {
                BufferedImage imBuff = ImageIO.read(inputStream);
                outputStream.write(tesseract.doOCR(imBuff).getBytes());
            } catch (TesseractException te) {
                getLogger().error(te.getMessage());
                if (te.getCause().getMessage().equals("image == null!")) {
                    session.transfer(flowFile, REL_UNSUPPORTED_IMAGE_FORMAT);
                } else {
                    session.transfer(session.penalize(flowFile), REL_FAILURE);
                }
                errors.set(true);

            } catch (Exception ex) {
                getLogger().error(ex.getMessage());
                session.transfer(flowFile, REL_FAILURE);
                errors.set(true);
            }
        }
    });

    if (!errors.get()) {
        session.transfer(ff, REL_SUCCESS);
    }

}