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

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

Introduction

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

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:com.microsoft.tfs.core.ws.runtime.client.SOAPService.java

/**
 * Execute a SOAP request that was built via
 * {@link #createSOAPRequest(String, SOAPMethodRequestWriter)}
 *
 * @param request/*from   ww  w .j  a  v a2s.  c o  m*/
 *        the request to execute (not null).
 * @param responseName
 *        the name of the SOAP response message for this request (not null)
 * @param responseReader
 *        the response reader that will do the work of reading the response
 *        (except the SOAP envelope). If null, no response stream reader is
 *        invoked (no response data is read except for the SOAP envelope and
 *        body elements).
 * @throws SOAPFault
 *         if a SOAP fault was returned by the server.
 * @throws UnauthorizedException
 *         if the client could not contact the server because of an
 *         authorization error (HTTP 401).
 * @throws ProxyUnauthorizedException
 *         if the client could not authenticate to the HTTP proxy
 * @throws FederatedAuthException
 *         if the client could not contact the server because it lacks the
 *         proper federated authentication (ACS) cookies and the federated
 *         authentication handler (set by
 *         {@link #setTransportAuthHandler(TransportAuthHandler)} ) did not
 *         handle the exception. The caller is expected to obtain the
 *         cookies and resubmit.
 * @throws InvalidServerResponseException
 *         if the server returned data that could not be parsed as XML or
 *         SOAP.
 * @throws EndpointNotFoundException
 *         if the server returned HTTP 404 when the request was executed.
 * @throws TransportException
 *         if some other an IO error occurred.
 * @throws TransportRequestHandlerCanceledException
 *         if the user cancelled the prompt for credentials
 */
protected void executeSOAPRequest(final SOAPRequest request, final String responseName,
        final SOAPMethodResponseReader responseReader) throws SOAPFault, UnauthorizedException,
        ProxyUnauthorizedException, FederatedAuthException, InvalidServerResponseException,
        EndpointNotFoundException, TransportException, TransportRequestHandlerCanceledException {
    /*
     * Duplicate the transport request handler map so we needn't keep a lock
     * and so that we have a consistent set throughout execution.
     */
    final List<TransportRequestHandler> requestHandlers = new ArrayList<TransportRequestHandler>();

    synchronized (transportRequestHandlers) {
        requestHandlers.addAll(transportRequestHandlers);
    }

    /*
     * Allow the transport authentication handler to process initial
     * credentials. This can happen if we're lazily authenticating and we do
     * not yet have a full set of credentials.
     */
    final AtomicBoolean cancel = new AtomicBoolean(false);

    for (final TransportRequestHandler requestHandler : requestHandlers) {
        // cancel doesn't stop us from invoking handlers
        if (requestHandler.prepareRequest(this, request, cancel) == Status.COMPLETE) {
            break;
        }
    }

    if (cancel.get()) {
        throw new TransportRequestHandlerCanceledException();
    }

    /*
     * Execute this method in a retry loop. On exceptions, we can delegate
     * to a user configured exception handler, which may modify the method
     * and allow us to resubmit.
     *
     * The typical use case for this is ACS authentication - it can expire
     * in the middle of a call and we want to prompt the user to
     * reauthenticate.
     */

    RuntimeException failure = null;
    do {
        try {
            executeSOAPRequestInternal(request, responseName, responseReader);
            break;
        } catch (final RuntimeException e) {
            // Give the handlers a chance to handle/correct/cancel this
            // exception

            boolean exceptionHandled = false;
            cancel.set(false);

            for (final TransportRequestHandler requestHandler : requestHandlers) {
                // cancel doesn't stop us from invoking handlers
                if (requestHandler.handleException(this, request, e, cancel) == Status.COMPLETE) {
                    /*
                     * This handler handled the exception - defer all others
                     * from attempting to handle it and reset the auth
                     * state.
                     */
                    request.getPostMethod().getHostAuthState().invalidate();

                    failure = null;
                    exceptionHandled = true;
                    break;
                }

                // Status was CONTINUE, continue with next handler
            }

            // Wasn't handled, prepare to throw it
            if (!exceptionHandled) {
                // The user wants to cancel, convert to a cancel
                if (cancel.get()) {
                    failure = new TransportRequestHandlerCanceledException();
                } else {
                    failure = e;
                }
                break;
            }

            // Exception handled, loop to retry
        }
    } while (true);

    if (failure != null) {
        throw failure;
    }

    for (final TransportRequestHandler requestHandler : requestHandlers) {
        requestHandler.handleSuccess(this, request);
    }
}

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

public void scanTasksForSwarm(String swarmClusterId) {

    logger.info("scanning tasks for swarm: {}", swarmClusterId);

    AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
    AtomicBoolean error = new AtomicBoolean(false);
    JsonNode response = getRestClient().getTasks();
    response.forEach(it -> {//from  w ww.  j av  a  2 s.  co  m
        try {
            earlistUpdate.set(Math.min(earlistUpdate.get(), saveTask(it)));

        } catch (Exception e) {
            logger.warn("problem updating task", e);
            error.set(true);
        }
    });

    if (error.get() == false) {
        if (earlistUpdate.get() < System.currentTimeMillis()) {
            dockerScanner.getNeoRxClient().execCypher(
                    "match (x:DockerTask) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x",
                    "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId);
        }
    }

}

From source file:info.archinnov.achilles.it.TestCRUDSimpleEntity.java

@Test
public void should_delete_if_exists() throws Exception {
    //Given// w  w  w .jav  a 2 s .c  o  m
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final Date date = buildDateKey();

    final AtomicBoolean error = new AtomicBoolean(false);
    final AtomicBoolean applied = new AtomicBoolean(true);

    final LWTResultListener lwtListener = new LWTResultListener() {

        @Override
        public void onSuccess() {

        }

        @Override
        public void onError(LWTResult lwtResult) {
            error.getAndSet(true);
            applied.getAndSet(lwtResult.currentValues().getTyped("[applied]"));
        }
    };

    //When
    manager.crud().deleteById(id, date).ifExists().withLwtResultListener(lwtListener).execute();

    //Then
    assertThat(error.get()).isTrue();
    assertThat(applied.get()).isFalse();
}

From source file:eu.europa.ec.markt.dss.validation102853.pades.PAdESSignature.java

private boolean hasDocumentTimestamp() {
    boolean levelReached;
    final PDFSignatureService pdfTimestampSignatureService = PdfObjFactory.getInstance()
            .newTimestampSignatureService();
    try {//from   ww  w .  ja  v a  2s  .c  o m
        final AtomicBoolean atomicLevelReached = new AtomicBoolean(false);
        pdfTimestampSignatureService.validateSignatures(document.openStream(),
                new SignatureValidationCallback() {
                    @Override
                    public void validate(PdfDict catalog, PdfDict outerCatalog, X509Certificate signingCert,
                            Date signingDate, Certificate[] certs, PdfDict signatureDictionary,
                            PdfSignatureInfo pk) {
                        try {
                            final byte[] subFilters = signatureDictionary.get("SubFilter");
                            if (subFilters != null) {
                                String pdfSubFilter = new String(subFilters); //
                                if (StringUtils.equals("/ETSI.RFC3161", pdfSubFilter)) {
                                    atomicLevelReached.set(true);
                                }
                            }
                        } catch (IOException e) {
                            throw new DSSException(e);
                        }
                    }
                });
        levelReached = atomicLevelReached.get();
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (SignatureException e) {
        throw new DSSException(e);
    }
    return levelReached;
}

From source file:io.nats.client.ITClusterTest.java

@Test
public void testProperFalloutAfterMaxAttemptsWithAuthMismatch() throws Exception {
    final String[] myServers = { "nats://localhost:1222", "nats://localhost:4443" };

    Options opts = new Options.Builder(defaultOptions()).dontRandomize().maxReconnect(5)
            .reconnectWait(25, TimeUnit.MILLISECONDS).build();
    opts.servers = Nats.processUrlArray(myServers);

    final CountDownLatch dcLatch = new CountDownLatch(1);
    opts.disconnectedCb = new DisconnectedCallback() {
        public void onDisconnect(ConnectionEvent event) {
            dcLatch.countDown();/*  ww  w .j a  va  2 s .co  m*/
        }
    };

    final AtomicBoolean closedCbCalled = new AtomicBoolean(false);
    final CountDownLatch ccLatch = new CountDownLatch(1);
    opts.closedCb = new ClosedCallback() {
        public void onClose(ConnectionEvent event) {
            closedCbCalled.set(true);
            ccLatch.countDown();
        }
    };

    try (NatsServer s1 = runServerOnPort(1222)) {
        try (NatsServer s2 = runServerWithConfig("tlsverify.conf")) {
            try (ConnectionImpl nc = (ConnectionImpl) opts.connect()) {
                s1.shutdown();

                // wait for disconnect
                assertTrue("Did not receive a disconnect callback message",
                        await(dcLatch, 5, TimeUnit.SECONDS));

                // Wait for ClosedCB
                assertTrue("Did not receive a closed callback message", await(ccLatch, 5, TimeUnit.SECONDS));

                // Make sure we are not still reconnecting.
                assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get());

                // Make sure we have not exceeded MaxReconnect
                assertEquals("Wrong number of reconnects", nc.getOptions().getMaxReconnect(),
                        nc.getStats().getReconnects());

                // Make sure we are not still reconnecting
                assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get());

                // Expect connection to be closed...
                assertTrue("Wrong status: " + nc.getState(), nc.isClosed());
            }
        }
    }
}

From source file:io.github.jeddict.jpa.modeler.properties.convert.OverrideConvertPanel.java

private boolean validateField() {
    //        if (this.converter_EditorPane.getText().trim().length() <= 0 && !disableConversion_CheckBox.isSelected()) {
    //            JOptionPane.showMessageDialog(this, getMessage(OverrideConvertPanel.class, "MSG_Validation"), "Invalid Value", javax.swing.JOptionPane.WARNING_MESSAGE);
    //            return false;
    //        }/* w  w  w.  ja  v  a 2 s. c o m*/

    if (attribute_ComboBox.isEnabled()
            && this.attribute_ComboBox.getSelectedItem().toString().trim().length() <= 0
            && !disableConversion_CheckBox.isSelected()) {
        JOptionPane.showMessageDialog(this, "Attribute name can't be empty", "Invalid Value",
                javax.swing.JOptionPane.WARNING_MESSAGE);
        return false;
    }

    AtomicBoolean validated = new AtomicBoolean(false);
    importAttributeConverter(converter_EditorPane.getText(), validated, modelerFile);

    return validated.get();
}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

private static HttpClient prepareMockedClient(final int responseCode, final String etag,
        final HttpRange.Response contentRange, final Long contentLength, final HttpEntity entity)
        throws IOException {
    final HttpClient client = mock(HttpClient.class);
    final AtomicBoolean responded = new AtomicBoolean(false);

    when(client.execute(any(HttpUriRequest.class), any(HttpContext.class))).then(invocation -> {
        if (!responded.compareAndSet(false, true)) {
            throw new IllegalStateException("this mocked client only provides a single response");
        }//from   w ww.  j  a va2s .c o  m

        final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, "mocked");

        if (etag != null) {
            response.setHeader(ETAG, etag);
        }

        if (contentRange != null) {
            response.setHeader(CONTENT_RANGE, contentRange.render());
        }

        if (contentLength != null) {
            response.setHeader(CONTENT_LENGTH, contentLength.toString());
        }

        if (entity != null) {
            response.setEntity(entity);
        }

        return response;
    });

    return client;
}

From source file:com.cerema.cloud2.operations.UploadFileOperation.java

public void cancel() {
    mCancellationRequested = new AtomicBoolean(true);
    if (mUploadOperation != null) {
        mUploadOperation.cancel();
    }
}

From source file:com.adaptris.core.fs.FsMessageConsumerTest.java

public void testRedmine481_SubDirInConsumeDirectory() throws Exception {
    String consumeDir = new GuidGenerator().safeUUID();
    File parentDir = FsHelper/*from  www .  j  a v  a 2  s .c om*/
            .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true));

    String subDir = parentDir.getCanonicalPath() + "/" + consumeDir + "/" + new GuidGenerator().safeUUID();
    File subDirectory = new File(subDir);
    subDirectory.mkdirs();
    FsConsumer fs = createConsumer(consumeDir);
    fs.setReacquireLockBetweenMessages(true);
    AtomicBoolean pollFired = new AtomicBoolean(false);
    fs.setPoller(
            new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS)).withPollerCallback(e -> {
                pollFired.set(true);
            }));
    File wipDirectory = new File(subDir + fs.getWipSuffix());
    MockMessageListener stub = new MockMessageListener(0);
    StandaloneConsumer sc = new StandaloneConsumer(fs);
    sc.registerAdaptrisMessageListener(stub);
    try {
        start(sc);
        waitForPollCallback(pollFired);
        assertEquals(true, subDirectory.exists());
        assertEquals(true, subDirectory.isDirectory());
        assertEquals(false, wipDirectory.exists());
    } finally {
        stop(sc);
        FileUtils.deleteQuietly(new File(PROPERTIES.getProperty(BASE_KEY), consumeDir));
    }
}

From source file:com.atlassian.jira.bc.group.TestDefaultGroupService.java

@Test
public void testValidateDeleteHappyPath() {
    final AtomicBoolean isGroupNullCalled = new AtomicBoolean(false);
    final AtomicBoolean isOnlyCalled = new AtomicBoolean(false);
    final AtomicBoolean isAdminCalled = new AtomicBoolean(false);
    final AtomicBoolean getComments = new AtomicBoolean(false);
    final DefaultGroupService defaultGroupService = new DefaultGroupService(null, null, null, null, null, null,
            null, null, null, null, null, null, null, null) {
        @Override//w w w . j  av a2 s  .  com
        boolean isGroupNull(final String groupName) {
            isGroupNullCalled.set(true);
            return false;
        }

        @Override
        public boolean areOnlyGroupsGrantingUserAdminPermissions(final JiraServiceContext jiraServiceContext,
                final Collection groupNames) {
            isOnlyCalled.set(true);
            return false;
        }

        @Override
        public boolean isAdminDeletingSysAdminGroup(final JiraServiceContext jiraServiceContext,
                final String groupName) {
            isAdminCalled.set(true);
            return false;
        }

        @Override
        public long getCommentsAndWorklogsGuardedByGroupCount(final String groupName) {
            getComments.set(true);
            return 0;
        }

        @Override
        boolean userHasAdminPermission(final User user) {
            return true;
        }
    };
    final ErrorCollection errorCollection = new SimpleErrorCollection();
    final JiraServiceContext jiraServiceContext = getContext(errorCollection);
    assertTrue(defaultGroupService.validateDelete(jiraServiceContext, "TestGroup", "SwapGroup"));

    assertFalse(errorCollection.hasAnyErrors());
    assertTrue(isGroupNullCalled.get());
    assertTrue(isOnlyCalled.get());
    assertTrue(isAdminCalled.get());
    assertTrue(getComments.get());
}