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

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

Introduction

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

Prototype

public final int get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorEventListener.java

@Override
protected void processEvent(Event event) {
    if (event instanceof ConnectionStatusEvent) {
        ConnectionStatusEvent connectionStatusEvent = (ConnectionStatusEvent) event;
        String channelId = connectionStatusEvent.getChannelId();
        Integer metaDataId = connectionStatusEvent.getMetaDataId();
        String information = connectionStatusEvent.getMessage();
        Timestamp timestamp = new Timestamp(event.getDateTime());

        String connectorId = channelId + "_" + metaDataId;

        ConnectionStatusEventType eventType = connectionStatusEvent.getState();

        ConnectionStatusEventType connectionStatusEventType = eventType;
        Integer connectorCount = null;
        Integer maximum = null;//from  ww  w.  ja v  a2s. c  o  m

        if (event instanceof ConnectorCountEvent) {
            ConnectorCountEvent connectorCountEvent = (ConnectorCountEvent) connectionStatusEvent;

            maximum = connectorCountEvent.getMaximum();
            Boolean increment = connectorCountEvent.isIncrement();

            if (maximum != null) {
                maxConnectionMap.put(connectorId, maximum);
            } else {
                maximum = maxConnectionMap.get(connectorId);
            }

            AtomicInteger count = connectorCountMap.get(connectorId);

            if (count == null) {
                count = new AtomicInteger();
                connectorCountMap.put(connectorId, count);
            }

            if (increment != null) {
                if (increment) {
                    count.incrementAndGet();
                } else {
                    count.decrementAndGet();
                }
            }

            connectorCount = count.get();

            if (connectorCount == 0) {
                connectionStatusEventType = ConnectionStatusEventType.IDLE;
            } else {
                connectionStatusEventType = ConnectionStatusEventType.CONNECTED;
            }
        }

        String stateString = null;
        if (connectionStatusEventType.isState()) {
            Color color = getColor(connectionStatusEventType);
            stateString = connectionStatusEventType.toString();
            if (connectorCount != null) {
                if (maximum != null && connectorCount.equals(maximum)) {
                    stateString += " <font color='red'>(" + connectorCount + ")</font>";
                } else if (connectorCount > 0) {
                    stateString += " (" + connectorCount + ")";
                }
            }

            connectorStateMap.put(connectorId, new Object[] { color, stateString });
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        String channelName = "";
        String connectorType = "";

        LinkedList<String[]> channelLog = null;

        Channel channel = ControllerFactory.getFactory().createChannelController()
                .getDeployedChannelById(channelId);

        if (channel != null) {
            channelName = channel.getName();
            // grab the channel's log from the HashMap, if not exist, create
            // one.
            if (connectorInfoLogs.containsKey(channelId)) {
                channelLog = connectorInfoLogs.get(channelId);
            } else {
                channelLog = new LinkedList<String[]>();
            }

            if (metaDataId == 0) {
                connectorType = "Source: " + channel.getSourceConnector().getTransportName() + "  ("
                        + channel.getSourceConnector().getTransformer().getInboundDataType().toString() + " -> "
                        + channel.getSourceConnector().getTransformer().getOutboundDataType().toString() + ")";
            } else {
                Connector connector = getConnectorFromMetaDataId(channel.getDestinationConnectors(),
                        metaDataId);
                connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName();
            }
        }

        if (channelLog != null) {
            synchronized (this) {
                if (channelLog.size() == MAX_LOG_SIZE) {
                    channelLog.removeLast();
                }
                channelLog.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) {
                    entireConnectorInfoLogs.removeLast();
                }
                entireConnectorInfoLogs.addFirst(
                        new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp),
                                connectorType, ((ConnectionStatusEvent) event).getState().toString(),
                                information, channelId, Integer.toString(metaDataId) });

                logId++;

                // put the channel log into the HashMap.
                connectorInfoLogs.put(channelId, channelLog);
            }
        }

    }
}

From source file:com.spectralogic.ds3client.metadata.MetadataAccessImpl_Test.java

@Test
public void testMetadataAccessFailureHandlerWithEventHandler() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

    try {//from  w  ww .j av a 2 s  .c  o  m
        tempDirectory.toFile().setExecutable(false);

        final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();

        fileMapper.put(filePath.toString(), filePath);

        final AtomicInteger numTimesFailureHandlerCalled = new AtomicInteger(0);

        try (final InputStream inputStream = Runtime.getRuntime().exec("ls -lR").getInputStream()) {
            LOG.info(IOUtils.toString(inputStream));
        }
        new MetadataAccessImpl(fileMapper.build(), new FailureEventListener() {
            @Override
            public void onFailure(final FailureEvent failureEvent) {
                numTimesFailureHandlerCalled.incrementAndGet();
                assertEquals(FailureEvent.FailureActivity.RecordingMetadata, failureEvent.doingWhat());
            }
        }, "localhost").getMetadataValue("forceAFailureByUsingANonExistentFileBecauseTheDockerImageRunsAsRoot");

        assertEquals(1, numTimesFailureHandlerCalled.get());
    } finally {
        tempDirectory.toFile().setExecutable(true);
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:com.ning.arecibo.collector.persistent.TestDefaultTimelineDAO.java

@Test(groups = "slow")
public void testGetSampleKindsByHostName() throws Exception {
    final TimelineDAO dao = new DefaultTimelineDAO(helper.getDBI(), sampleCoder);
    final DateTime startTime = new DateTime(DateTimeZone.UTC);
    final DateTime endTime = startTime.plusSeconds(2);

    // Create the host
    final String hostName = UUID.randomUUID().toString();
    final Integer hostId = dao.getOrAddHost(hostName);
    Assert.assertNotNull(hostId);/*from  w w  w . j a v a 2  s.c o  m*/

    // Create a timeline times (needed for the join in the dashboard query)
    final Integer eventCategoryId = 123;

    // Create the samples
    final String sampleOne = UUID.randomUUID().toString();
    final Integer sampleOneId = dao.getOrAddSampleKind(hostId, eventCategoryId, sampleOne);
    Assert.assertNotNull(sampleOneId);
    final String sampleTwo = UUID.randomUUID().toString();
    final Integer sampleTwoId = dao.getOrAddSampleKind(hostId, eventCategoryId, sampleTwo);
    Assert.assertNotNull(sampleTwoId);

    // Basic retrieval tests
    final BiMap<Integer, CategoryIdAndSampleKind> sampleKinds = dao.getSampleKinds();
    Assert.assertEquals(sampleKinds.size(), 2);
    Assert.assertEquals(sampleKinds.get(sampleOneId).getEventCategoryId(), (int) eventCategoryId);
    Assert.assertEquals(sampleKinds.get(sampleOneId).getSampleKind(), sampleOne);
    Assert.assertEquals(sampleKinds.get(sampleTwoId).getEventCategoryId(), (int) eventCategoryId);
    Assert.assertEquals(sampleKinds.get(sampleTwoId).getSampleKind(), sampleTwo);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleOneId).getEventCategoryId(),
            (int) eventCategoryId);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleOneId).getSampleKind(), sampleOne);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleTwoId).getEventCategoryId(),
            (int) eventCategoryId);
    Assert.assertEquals(dao.getCategoryIdAndSampleKind(sampleTwoId).getSampleKind(), sampleTwo);

    // No samples yet
    Assert.assertEquals(ImmutableList.<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId)).size(), 0);

    dao.insertTimelineChunk(new TimelineChunk(sampleCoder, 0, hostId, sampleOneId, startTime, endTime,
            new byte[0], new byte[0], 0));
    final ImmutableList<Integer> firstFetch = ImmutableList
            .<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId));
    Assert.assertEquals(firstFetch.size(), 1);
    Assert.assertEquals(firstFetch.get(0), sampleOneId);

    dao.insertTimelineChunk(new TimelineChunk(sampleCoder, 0, hostId, sampleTwoId, startTime, endTime,
            new byte[0], new byte[0], 0));
    final ImmutableList<Integer> secondFetch = ImmutableList
            .<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId));
    Assert.assertEquals(secondFetch.size(), 2);
    Assert.assertTrue(secondFetch.contains(sampleOneId));
    Assert.assertTrue(secondFetch.contains(sampleTwoId));

    // Random sampleKind for random host
    dao.insertTimelineChunk(new TimelineChunk(sampleCoder, 0, Integer.MAX_VALUE - 100, Integer.MAX_VALUE,
            startTime, endTime, new byte[0], new byte[0], 0));
    final ImmutableList<Integer> thirdFetch = ImmutableList
            .<Integer>copyOf(dao.getSampleKindIdsByHostId(hostId));
    Assert.assertEquals(secondFetch.size(), 2);
    Assert.assertTrue(thirdFetch.contains(sampleOneId));
    Assert.assertTrue(thirdFetch.contains(sampleTwoId));

    // Test dashboard query
    final AtomicInteger chunksSeen = new AtomicInteger(0);
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(hostId),
            ImmutableList.<Integer>of(sampleOneId, sampleTwoId), startTime, startTime.plusSeconds(2),
            new TimelineChunkConsumer() {
                @Override
                public void processTimelineChunk(final TimelineChunk chunk) {
                    chunksSeen.incrementAndGet();
                    Assert.assertEquals((Integer) chunk.getHostId(), hostId);
                    Assert.assertTrue(
                            chunk.getSampleKindId() == sampleOneId || chunk.getSampleKindId() == sampleTwoId);
                }
            });
    Assert.assertEquals(chunksSeen.get(), 2);

    // Dummy queries
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(Integer.MAX_VALUE), null, startTime,
            startTime.plusDays(1), FAIL_CONSUMER);
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(hostId),
            ImmutableList.<Integer>of(Integer.MAX_VALUE), startTime, startTime.plusDays(1), FAIL_CONSUMER);
    dao.getSamplesByHostIdsAndSampleKindIds(ImmutableList.<Integer>of(hostId),
            ImmutableList.<Integer>of(sampleOneId, sampleTwoId), startTime.plusDays(1), startTime.plusDays(2),
            FAIL_CONSUMER);
}

From source file:io.realm.Realm.java

/**
 * Compact a Realm file. A Realm file usually contain free/unused space.
 * This method removes this free space and the file size is thereby reduced.
 * Objects within the Realm files are untouched.
 * <p>/*from w  w  w.j a  v  a2s .  c o  m*/
 * The file must be closed before this method is called.<br>
 * The file system should have free space for at least a copy of the Realm file.<br>
 * The Realm file is left untouched if any file operation fails.<br>
 *
 * @param configuration a {@link RealmConfiguration} pointing to a Realm file.
 * @return true if successful, false if any file operation failed
 *
 * @throws java.lang.IllegalStateException if trying to compact a Realm that is already open.
 */
public static boolean compactRealm(RealmConfiguration configuration) {
    if (configuration.getEncryptionKey() != null) {
        throw new IllegalArgumentException("Cannot currently compact an encrypted Realm.");
    }

    String canonicalPath = configuration.getPath();
    AtomicInteger openInstances = globalOpenInstanceCounter.get(canonicalPath);
    if (openInstances != null && openInstances.get() > 0) {
        throw new IllegalStateException("Cannot compact an open Realm");
    }
    SharedGroup sharedGroup = null;
    boolean result = false;
    try {
        sharedGroup = new SharedGroup(canonicalPath, false, configuration.getEncryptionKey());
        result = sharedGroup.compact();
    } finally {
        if (sharedGroup != null) {
            sharedGroup.close();
        }
    }
    return result;
}

From source file:org.apache.activemq.web.RestTest.java

@Test(timeout = 15 * 1000)
public void testAuth() throws Exception {
    int port = getPort();

    HttpClient httpClient = new HttpClient();
    httpClient.start();//  ww  w. ja v  a 2  s  . co  m

    final CountDownLatch latch = new CountDownLatch(1);
    final StringBuffer buf = new StringBuffer();
    final AtomicInteger status = new AtomicInteger();
    httpClient.newRequest("http://localhost:" + port + "/message/testPost?type=queue")
            .header("Authorization", "Basic YWRtaW46YWRtaW4=").method(HttpMethod.POST)
            .send(new BufferingResponseListener() {
                @Override
                public void onComplete(Result result) {
                    status.getAndSet(result.getResponse().getStatus());
                    buf.append(getContentAsString());
                    latch.countDown();
                }
            });

    latch.await();
    assertTrue("success status", HttpStatus.isSuccess(status.get()));
}

From source file:org.apache.camel.processor.LoopProcessor.java

@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    // use atomic integer to be able to pass reference and keep track on the values
    AtomicInteger index = new AtomicInteger();
    AtomicInteger count = new AtomicInteger();

    // Intermediate conversion to String is needed when direct conversion to Integer is not available
    // but evaluation result is a textual representation of a numeric value.
    String text = expression.evaluate(exchange, String.class);
    try {// www  .j a  v  a2  s .com
        int num = ExchangeHelper.convertToMandatoryType(exchange, Integer.class, text);
        count.set(num);
    } catch (NoTypeConversionAvailableException e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }

    // set the size before we start
    exchange.setProperty(Exchange.LOOP_SIZE, count);

    // loop synchronously
    while (index.get() < count.get()) {

        // and prepare for next iteration
        ExchangeHelper.prepareOutToIn(exchange);
        boolean sync = process(exchange, callback, index, count);

        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: " + exchange.getExchangeId()
                        + " is continued being processed asynchronously");
            }
            // the remainder of the routing slip will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: " + exchange.getExchangeId()
                    + " is continued being processed synchronously");
        }

        // increment counter before next loop
        index.getAndIncrement();
    }

    // we are done so prepare the result
    ExchangeHelper.prepareOutToIn(exchange);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Processing complete for exchangeId: " + exchange.getExchangeId() + " >>> " + exchange);
    }
    callback.done(true);
    return true;
}

From source file:com.github.gfx.android.orma.example.fragment.BenchmarkFragment.java

Single<Result> startSelectAllWithOrma() {
    return Single.fromCallable(() -> {
        long result = runWithBenchmark(() -> {
            final AtomicInteger count = new AtomicInteger();

            Todo_Selector todos = orma.selectFromTodo().orderByCreatedTimeAsc();

            for (Todo todo : todos) {
                @SuppressWarnings("unused")
                String title = todo.title;
                @SuppressWarnings("unused")
                String content = todo.content;
                @SuppressWarnings("unused")
                Date createdTime = todo.createdTime;

                count.incrementAndGet();
            }//from   w  w  w . j a  v a 2  s. c  o m

            if (todos.count() != count.get()) {
                throw new AssertionError("unexpected get: " + count.get());
            }
            Log.d(TAG, "Orma/forEachAll count: " + count);
        });
        return new Result("Orma/forEachAll", result);
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

From source file:com.predic8.membrane.core.interceptor.apimanagement.AMRateLimitInterceptorTest.java

@Test
public void testHandleRequestRateLimit5SecondConcurrency() throws Exception {

    final Exchange exc = new Exchange(null);
    exc.setResponse(Response.ResponseBuilder.newInstance().build());
    exc.setProperty(Exchange.API_KEY, "junit");
    exc.setRule(new ServiceProxy());
    exc.getRule().setName("junit API");

    final AMRateLimiter rli = new AMRateLimiter();
    ApiManagementConfiguration amc = new ApiManagementConfiguration(System.getProperty("user.dir"),
            "src\\test\\resources\\apimanagement\\api.yaml");
    rli.setAmc(amc);//from   w  w  w .  j  a va 2 s  .  c o m

    ArrayList<Thread> threads = new ArrayList<Thread>();
    final AtomicInteger continues = new AtomicInteger();
    final AtomicInteger returns = new AtomicInteger();
    for (int i = 0; i < 1000; i++) {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Outcome out = rli.handleRequest(exc);
                    if (out == Outcome.CONTINUE) {
                        continues.incrementAndGet();
                    } else if (out == Outcome.RETURN) {
                        returns.incrementAndGet();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        threads.add(t);
        t.start();
    }
    for (Thread t : threads) {
        t.join();
    }
    assertEquals(5, continues.get());
    assertEquals(995, returns.get());
    Thread.sleep(2000);
    assertEquals(Outcome.CONTINUE, rli.handleRequest(exc));
}

From source file:com.indeed.lsmtree.recordlog.TestBlockCompressedRecordFile.java

public void testRandom() throws IOException {
    final BlockCompressedRecordFile<String> recordFile = createBlockCache();
    final AtomicInteger done = new AtomicInteger(8);
    for (int i = 0; i < 8; i++) {
        final int index = i;
        new Thread(new Runnable() {
            @Override//from  w w w.j a  v a 2  s . c  om
            public void run() {
                try {
                    final Random r = new Random(index);
                    for (int i = 0; i < 10000000; i++) {
                        int rand = r.nextInt(positions.size());
                        assertTrue(recordFile.get(positions.get(rand)).equals(strings.get(rand)));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    done.decrementAndGet();
                }
            }
        }).start();
    }
    while (done.get() > 0) {
        Thread.yield();
    }
    recordFile.close();
}

From source file:dk.statsbiblioteket.util.xml.XMLStepperTest.java

public void testIterateTags() throws Exception {
    XMLStreamReader xml = xmlFactory.createXMLStreamReader(new StringReader(SAMPLE));
    assertTrue("The first 'bar' should be findable", XMLStepper.findTagStart(xml, "bar"));
    xml.next();/*from w ww.  j  a  va  2s.com*/

    final AtomicInteger count = new AtomicInteger(0);
    XMLStepper.iterateTags(xml, new XMLStepper.Callback() {
        @Override
        public boolean elementStart(XMLStreamReader xml, List<String> tags, String current)
                throws XMLStreamException {
            count.incrementAndGet();
            return false;
        }
    });
    assertEquals("Only a single content should be visited", 1, count.get());
    assertTrue("The second 'bar' should be findable", XMLStepper.findTagStart(xml, "bar"));
}