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.couchbase.client.dcp.state.SessionState.java

/**
 * Check if the current sequence numbers for all partitions are equal to the ones set as end.
 *
 * @return true if all are at the end, false otherwise.
 *///from  w  w  w.  ja  v a 2  s . c  o  m
public boolean isAtEnd() {
    final AtomicBoolean atEnd = new AtomicBoolean(true);
    foreachPartition(new Action1<PartitionState>() {
        @Override
        public void call(PartitionState ps) {
            if (!ps.isAtEnd()) {
                atEnd.set(false);
            }
        }
    });
    return atEnd.get();
}

From source file:com.jeremydyer.nifi.processors.barcode.BarcodeScannerProcessor.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  .  j a  v a  2  s  . co  m
    }

    final AtomicBoolean errors = new AtomicBoolean(false);

    switch (context.getProperty(DESTINATION).getValue()) {
    case DESTINATION_ATTRIBUTE:
        final AtomicReference<String> BC = new AtomicReference<>();
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream inputStream) throws IOException {

                Map hintMap = new HashMap();
                hintMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

                try {
                    BufferedImage barCodeBufferedImage = ImageIO.read(inputStream);

                    LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage);
                    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Reader reader = new MultiFormatReader();
                    Result result = reader.decode(bitmap, hintMap);
                    BC.set(result.getText());
                } catch (Exception ex) {
                    ex.printStackTrace();
                    //session.transfer(flowFile, REL_FAILURE);
                    errors.set(true);
                }
            }
        });

        if (StringUtils.isNotEmpty(BC.get())) {
            FlowFile atFlowFile = session.putAttribute(flowFile, BARCODE_ATTRIBUTE_NAME, BC.get());
            if (!errors.get()) {
                session.transfer(atFlowFile, REL_SUCCESS);
            } else {
                session.transfer(atFlowFile, REL_FAILURE);
            }
        } else {
            if (!errors.get()) {
                session.transfer(flowFile, REL_SUCCESS);
            } else {
                session.transfer(flowFile, REL_FAILURE);
            }
        }

        break;
    case DESTINATION_CONTENT:
        FlowFile conFlowFile = session.write(flowFile, new StreamCallback() {
            @Override
            public void process(InputStream inputStream, OutputStream outputStream) throws IOException {

                Map hintMap = new HashMap();
                hintMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

                try {
                    BufferedImage barCodeBufferedImage = ImageIO.read(inputStream);

                    LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage);
                    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Reader reader = new MultiFormatReader();
                    Result result = reader.decode(bitmap, hintMap);
                    getLogger().info("Barcode Format: " + result.getBarcodeFormat().toString());
                    getLogger().info("Barcode Text is: ' " + result.getText() + "'");
                    outputStream.write(result.getText().getBytes());
                } catch (Exception ex) {
                    ex.printStackTrace();
                    //session.transfer(flowFile, REL_FAILURE);
                    errors.set(true);
                }
            }
        });

        if (!errors.get()) {
            session.transfer(conFlowFile, REL_SUCCESS);
        } else {
            session.transfer(conFlowFile, REL_FAILURE);
        }

        break;
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.CloseableBasicHttpClientConnectionManager.java

/**
 * @since 4.4/*from   w  w w .  j a va  2  s. co m*/
 */
public CloseableBasicHttpClientConnectionManager(
        final HttpClientConnectionOperator httpClientConnectionOperator,
        final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) {
    super();
    this.connectionOperator = Args.notNull(httpClientConnectionOperator, "Connection operator");
    this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE;
    this.expiry = Long.MAX_VALUE;
    this.socketConfig = SocketConfig.DEFAULT;
    this.connConfig = ConnectionConfig.DEFAULT;
    this.isShutdown = new AtomicBoolean(false);
}

From source file:org.apache.synapse.transport.passthru.core.PassThroughListeningIOReactorManager.java

private PassThroughListeningIOReactorManager() {
    portServerHandlerMapper = new ConcurrentHashMap<Integer, NHttpServerEventHandler>();
    dynamicPTTListeningEndpointMapper = new ConcurrentHashMap<Integer, ListenerEndpoint>();
    passThroughListenerIOReactorMapper = new ConcurrentHashMap<Integer, ListeningIOReactor>();
    passThroughListenerServerIODispatchMapper = new ConcurrentHashMap<Integer, ServerIODispatch>();
    serverConnectionFactoryMapper = new ConcurrentHashMap<Integer, ServerConnFactory>();

    isSharedIOReactorInitiated = new AtomicBoolean(false);
    isSharedSSLIOReactorInitiated = new AtomicBoolean(false);
    ioReactorSharingMode = PassThroughConfiguration.getInstance().isListeningIOReactorShared()
            ? IOReactorSharingMode.SHARED
            : IOReactorSharingMode.UNSHARED;
}

From source file:anhttpserver.ServerTest.java

@Test
public void multiThreadContextIsolationTest() throws Exception {
    final String res1 = "1111111111";
    final String res2 = "1";
    final String TEST_HEADER = "TEST-HEADER";

    final AtomicBoolean testPassed = new AtomicBoolean(true);

    class ThreadTestHttpHandlerAdapter extends ByteArrayHandlerAdapter {
        private String result;
        private int timeToSleep;

        ThreadTestHttpHandlerAdapter(String result, int timeToSleep) {
            this.result = result;
            this.timeToSleep = timeToSleep;
        }//from   w w w.  ja  va 2 s .  c  om

        @Override
        public byte[] getResponseAsByteArray(HttpRequestContext httpRequestContext) throws IOException {
            setResponseHeader(TEST_HEADER, result, httpRequestContext);

            try {
                Thread.sleep(timeToSleep);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return result.getBytes();
        }
    }

    class ThreadTester implements Runnable {
        private String url;
        private String result;
        private int repeatCount;

        ThreadTester(String url, String result, int repeatCount) {
            this.url = url;
            this.result = result;
            this.repeatCount = repeatCount;
        }

        public void run() {
            try {
                for (int i = 0; i < repeatCount; i++) {
                    if (!testPassed.get()) {
                        return;
                    }

                    URLConnection connection = getConnection(url);
                    String headerValue = connection.getHeaderField(TEST_HEADER);
                    if (!headerValue.equals(result)) {
                        testPassed.set(false);
                        return;
                    }

                    if (!getResult(connection).equals(result)) {
                        testPassed.set(false);
                        return;
                    }
                }
            } catch (Exception e) {
                testPassed.set(false);
            }
        }
    }

    server.addHandler("/thread1", new ThreadTestHttpHandlerAdapter(res1, 0));
    server.addHandler("/thread2", new ThreadTestHttpHandlerAdapter(res2, 1));

    int count = 50;
    Thread[] threads = new Thread[count];

    String url1 = "http://localhost:9999/thread1";
    String url2 = "http://localhost:9999/thread2";

    for (int i = 0; i < count; i++) {
        threads[i] = new Thread(new ThreadTester(i % 2 == 0 ? url1 : url2, i % 2 == 0 ? res1 : res2, 20));
        threads[i].start();
    }

    for (int i = 0; i < count; i++) {
        threads[i].join();
    }

    assertTrue(testPassed.get());
}

From source file:com.ning.metrics.serialization.writer.DiskSpoolEventWriter.java

public DiskSpoolEventWriter(final EventHandler eventHandler, final String spoolPath, final boolean flushEnabled,
        final long flushIntervalInSeconds, final ScheduledExecutorService executor, final SyncType syncType,
        final int syncBatchSize, final CompressionCodec codec, final EventSerializer eventSerializer) {
    this.eventHandler = eventHandler;
    this.syncType = syncType;
    this.syncBatchSize = syncBatchSize;
    this.spoolDirectory = new File(spoolPath);
    this.executor = executor;
    this.tmpSpoolDirectory = new File(spoolDirectory, "_tmp");
    this.quarantineDirectory = new File(spoolDirectory, "_quarantine");
    this.lockDirectory = new File(spoolDirectory, "_lock");
    this.flushEnabled = new AtomicBoolean(flushEnabled);
    this.flushIntervalInSeconds = new AtomicLong(flushIntervalInSeconds);
    this.codec = codec;
    this.eventSerializer = eventSerializer;
    writeTimerName = new MetricName(DiskSpoolEventWriter.class, spoolPath);
    writeTimer = Metrics.newTimer(writeTimerName, TimeUnit.MILLISECONDS, TimeUnit.SECONDS);

    createSpoolDir(spoolDirectory);/*from ww w  .java  2s .  c o  m*/
    createSpoolDir(tmpSpoolDirectory);
    createSpoolDir(quarantineDirectory);
    createSpoolDir(lockDirectory);

    // Fail early
    if (!spoolDirectory.exists() || !tmpSpoolDirectory.exists() || !quarantineDirectory.exists()
            || !lockDirectory.exists()) {
        throw new IllegalArgumentException("Eventwriter misconfigured - couldn't create the spool directories");
    }

    scheduleFlush();
    recoverFiles();

    acceptsEvents = true;
}

From source file:com.streamsets.pipeline.kafka.impl.BaseKafkaConsumer09.java

public BaseKafkaConsumer09(String topic, Source.Context context, int batchSize) {
    this.topic = topic;
    this.topicPartitionToOffsetMetadataMap = new HashMap<>();
    this.recordQueue = new ArrayBlockingQueue<>(batchSize);
    this.executorService = new ScheduledThreadPoolExecutor(1);
    this.pollCommitMutex = new Object();
    this.rebalanceInProgress = new AtomicBoolean(false);
    this.needToCallPoll = new AtomicBoolean(false);
    this.context = context;
    this.rebalanceHistogram = context.createHistogram("Rebalance Time");
    this.gaugeMap = context.createGauge("Internal state").getValue();
}

From source file:org.eclipse.hono.application.HonoApplication.java

/**
 * Deploys all verticles the Hono server consists of.
 * // w  ww . j  av a 2  s.co m
 * @return true if deployment was successful
 */
private boolean registerVerticles() {

    if (vertx == null) {
        throw new IllegalStateException("no Vert.x instance has been configured");
    }

    final CountDownLatch startupLatch = new CountDownLatch(1);
    final AtomicBoolean startupSucceeded = new AtomicBoolean(false);

    // without creating a first instance here, deployment of the HonoServer verticles fails
    // TODO: find out why
    HonoServer firstInstance = serverFactory.getHonoServer();

    final int instanceCount = honoConfig.getMaxInstances();

    Future<Void> started = Future.future();
    started.setHandler(ar -> {
        if (ar.failed()) {
            LOG.error("cannot start up HonoServer", ar.cause());
        } else {
            startupSucceeded.set(true);
        }
        startupLatch.countDown();
    });

    CompositeFuture.all(deployAuthenticationService(), // we only need 1 authentication service
            deployAuthorizationService(), // we only need 1 authorization service
            deployCredentialsService(), deployRegistrationService()).setHandler(ar -> {
                if (ar.succeeded()) {
                    deployServer(firstInstance, instanceCount, started);
                } else {
                    started.fail(ar.cause());
                }
            });

    try {
        if (startupLatch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) {
            if (startupSucceeded.get()) {
                LOG.info("Hono startup completed successfully");
            } else {
                shutdown();
            }
        } else {
            LOG.error("startup timed out after {} seconds, shutting down ...", honoConfig.getStartupTimeout());
            shutdown();
            startupSucceeded.set(false);
        }
    } catch (InterruptedException e) {
        LOG.error("startup process has been interrupted, shutting down ...");
        Thread.currentThread().interrupt();
        shutdown();
        startupSucceeded.set(false);
    }
    return startupSucceeded.get();
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.TenantRoutingAuthenticationComponentFacade.java

/**
 *
 * {@inheritDoc}/*from  ww  w . j a  v  a 2 s  .  c  o m*/
 */
@Override
protected boolean implementationAllowsGuestLogin() {
    final AtomicBoolean guestLoginAllowed = new AtomicBoolean(false);

    LOGGER.debug("Checking guestUserAuthenticationAllowed for enabled tenants (until first supporting tenant)");
    for (final String tenantDomain : this.enabledTenants) {
        if (!guestLoginAllowed.get()) {
            if (TenantUtil.DEFAULT_TENANT.equals(tenantDomain)
                    || (this.tenantAdminService.existsTenant(tenantDomain)
                            && this.tenantAdminService.isEnabledTenant(tenantDomain))) {
                final AuthenticationComponent authenticationComponent = TenantBeanUtils.getBeanForTenant(
                        this.applicationContext, this.beanName, tenantDomain, AuthenticationComponent.class);
                final boolean guestUserAuthenticationAllowed = authenticationComponent
                        .guestUserAuthenticationAllowed();
                LOGGER.trace("Tenant {} allows guest user authentication: {}", tenantDomain,
                        guestUserAuthenticationAllowed);
                guestLoginAllowed.set(guestUserAuthenticationAllowed);
            }
        }
    }
    LOGGER.debug("Component allowed guest authentication: {}", guestLoginAllowed.get());

    return guestLoginAllowed.get();
}

From source file:com.alexholmes.hdfsslurper.Slurper.java

private void run() throws IOException, InterruptedException {

    FileSystemManager fileSystemManager = new FileSystemManager(config);

    log.info("event#Moving any files in work directory to error directory");

    fileSystemManager.moveWorkFilesToError();

    final List<WorkerThread> workerThreads = new ArrayList<WorkerThread>();
    for (int i = 1; i <= config.getNumThreads(); i++) {
        WorkerThread t = new WorkerThread(config, fileSystemManager, TimeUnit.MILLISECONDS, i);
        t.start();//from   ww  w  .j a v a2s. c  o m
        workerThreads.add(t);
    }

    final AtomicBoolean programmaticShutdown = new AtomicBoolean(false);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                if (programmaticShutdown.get()) {
                    log.info("event#JVM shutting down");
                } else {
                    log.info("event#External process signalled JVM shutdown, shutting down threads.");
                    log.info("event#This may take a few minutes until we let the threads complete ");
                    log.info("event#the current file being copied.");
                    for (WorkerThread workerThread : workerThreads) {
                        workerThread.shutdown();
                    }
                    log.info("event#Threads dead");
                }
            } catch (Throwable t) {
                log.error("event#Hit snag in shutdown hook", t);
            }

        }
    });

    log.info("event#Running");

    for (WorkerThread workerThread : workerThreads) {
        workerThread.join();
    }
    programmaticShutdown.set(true);
}