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

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

Introduction

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

Prototype

public final V get() 

Source Link

Document

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

Usage

From source file:io.warp10.continuum.egress.EgressFetchHandler.java

private static void rawDump(PrintWriter pw, GTSDecoderIterator iter, boolean dedup, boolean signed,
        long timespan, AtomicReference<Metadata> lastMeta, AtomicLong lastCount, boolean sortMeta)
        throws IOException {

    String name = null;//  w w  w.  j a v a 2s.co m
    Map<String, String> labels = null;

    StringBuilder sb = new StringBuilder();

    Metadata lastMetadata = lastMeta.get();
    long currentCount = lastCount.get();

    while (iter.hasNext()) {
        GTSDecoder decoder = iter.next();

        if (dedup) {
            decoder = decoder.dedup();
        }

        if (!decoder.next()) {
            continue;
        }

        long toDecodeCount = Long.MAX_VALUE;

        if (timespan < 0) {
            Metadata meta = decoder.getMetadata();
            if (!meta.equals(lastMetadata)) {
                lastMetadata = meta;
                currentCount = 0;
            }
            toDecodeCount = Math.max(0, -timespan - currentCount);
        }

        GTSEncoder encoder = decoder.getEncoder(true);

        //
        // Only display the class + labels if they have changed since the previous GTS
        //

        Map<String, String> lbls = decoder.getLabels();

        //
        // Compute the name
        //

        name = decoder.getName();
        labels = lbls;
        sb.setLength(0);
        GTSHelper.encodeName(sb, name);
        sb.append("{");
        boolean first = true;

        if (sortMeta) {
            lbls = new TreeMap<String, String>(lbls);
        }

        for (Entry<String, String> entry : lbls.entrySet()) {
            //
            // Skip owner/producer labels and any other 'private' labels
            //
            if (!signed) {
                if (Constants.PRODUCER_LABEL.equals(entry.getKey())) {
                    continue;
                }
                if (Constants.OWNER_LABEL.equals(entry.getKey())) {
                    continue;
                }
            }

            if (!first) {
                sb.append(",");
            }
            GTSHelper.encodeName(sb, entry.getKey());
            sb.append("=");
            GTSHelper.encodeName(sb, entry.getValue());
            first = false;
        }
        sb.append("}");

        if (encoder.getCount() > toDecodeCount) {
            // We have too much data, shrink the encoder
            GTSEncoder enc = new GTSEncoder();
            enc.safeSetMetadata(decoder.getMetadata());
            while (decoder.next() && toDecodeCount > 0) {
                enc.addValue(decoder.getTimestamp(), decoder.getLocation(), decoder.getElevation(),
                        decoder.getValue());
                toDecodeCount--;
            }
            encoder = enc;
        }

        if (timespan < 0) {
            currentCount += encoder.getCount();
        }

        if (encoder.size() > 0) {
            pw.print(encoder.getBaseTimestamp());
            pw.print("//");
            pw.print(encoder.getCount());
            pw.print(" ");
            pw.print(sb.toString());
            pw.print(" ");

            //pw.println(new String(OrderPreservingBase64.encode(encoder.getBytes())));
            OrderPreservingBase64.encodeToWriter(encoder.getBytes(), pw);
            pw.write('\r');
            pw.write('\n');
        }
    }

    lastMeta.set(lastMetadata);
    lastCount.set(currentCount);
}

From source file:org.zodiark.subscriber.SubscriberTest.java

@Test(enabled = false)
public void sucessfulRequestForAction() throws IOException, InterruptedException {
    final CountDownLatch completed = new CountDownLatch(1);

    final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch connected = new CountDownLatch(1);
    final AtomicReference<String> uuid = new AtomicReference<>();
    final AtomicReference<String> paths = new AtomicReference<>();

    // =============== Wowza

    paths.set("");
    wowzaClient.handler(new OnEnvelopHandler() {
        @Override//from w ww.  j a v  a  2  s . c  o  m
        public boolean onEnvelop(Envelope e) throws IOException {

            Message m = e.getMessage();
            switch (m.getPath()) {
            case Paths.WOWZA_CONNECT:
                // Connected. Listen
                uuid.set(e.getUuid());
                break;
            case Paths.SERVER_VALIDATE_OK:
                Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(paths.get()), e.getMessage().getData()));
                wowzaClient.send(publisherOk);
                break;
            case Paths.WOWZA_OBFUSCATE:
                WowzaMessage wm = mapper.readValue(m.getData(), WowzaMessage.class);
                Envelope ok = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.WOWZA_OBFUSCATE_OK), e.getMessage().getData()));
                System.out.println("Obfuscating Subscribers");
                wowzaClient.send(ok);
            case Paths.WOWZA_DEOBFUSCATE:
                wm = mapper.readValue(m.getData(), WowzaMessage.class);
                System.out.println("De-obfuscating Subscribers");
                ok = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.WOWZA_DEOBFUSCATE_OK), e.getMessage().getData()));
                wowzaClient.send(ok);
            default:
                // ERROR
            }

            connected.countDown();
            return false;
        }
    }).open();

    Envelope wowzaConnect = Envelope.newClientToServerRequest(new Message(new Path(Paths.WOWZA_CONNECT),
            mapper.writeValueAsString(new UserPassword("wowza", "bar"))));
    wowzaClient.send(wowzaConnect);
    connected.await();

    // ================ Publisher

    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> publisherUUID = new AtomicReference<>();
    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            publisherUUID.set(e.getUuid());
            latch.countDown();
            return true;
        }
    }).open();

    // ================ Publisher create the session

    Envelope createSessionMessage = Envelope.newClientToServerRequest(
            new Message(new Path(""), mapper.writeValueAsString(new UserPassword("publisherex", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
    answer.set(null);

    final CountDownLatch tlatch = new CountDownLatch(1);
    final AtomicReference<String> finalMessage = new AtomicReference<>();

    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {

            switch (e.getMessage().getPath()) {
            case Paths.BEGIN_STREAMING_SESSION:
                answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
                tlatch.countDown();
                break;
            case Paths.PUBLISHER_ACTION_ACCEPT:
                Action a = mapper.readValue(e.getMessage().getData(), Action.class);
                Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.ZODIARK_ACTION_ACCEPTED), e.getMessage().getData()));
                publisherClient.send(publisherOk);
                break;
            case Paths.ACTION_START:
                // Start action
                PublisherResults results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);
                System.out.println("==> Start Action " + results.getResults());

                publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.ACTION_START_OK), e.getMessage().getData()));
                publisherClient.send(publisherOk);
                break;
            case Paths.ACTION_TIMER:
                Time t = mapper.readValue(e.getMessage().getData(), Time.class);
                System.out.println("Publisher ===>" + t);
                break;
            case Paths.ACTION_COMPLETED:
                results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);
                System.out.println("Publisher Action completed");
                completed.countDown();
                break;
            case Paths.PUBLISHER_ABOUT_READY:
                results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);

                finalMessage.set(results.getResults());
                break;
            }
            return false;
        }
    });

    // ================ Prepare for streaming, handshake with Wowza

    Envelope startStreamingSession = Envelope
            .newClientToServerRequest(new Message(new Path(Paths.VALIDATE_PUBLISHER_STREAMING_SESSION),
                    mapper.writeValueAsString(new WowzaUUID(uuid.get()))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(startStreamingSession);

    tlatch.await();

    assertEquals("OK", answer.get().getResults());

    // ================ Subscriber

    paths.set(Paths.JOIN_SUBSCRIBER_STREAMING_SESSION);
    final AtomicReference<SubscriberResults> sanswer = new AtomicReference<>();
    final ZodiarkClient subscriberClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch platch = new CountDownLatch(1);
    final AtomicReference<String> subscriberUUID = new AtomicReference<>();

    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            subscriberUUID.set(e.getUuid());
            platch.countDown();
            return true;
        }
    }).open();

    // ================ Subscriber create the session

    createSessionMessage = Envelope.newClientToServerRequest(subscriberUUID.get(),
            new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("123456", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(createSessionMessage);
    platch.await();
    assertEquals("OK", sanswer.get().getResults());
    sanswer.set(null);

    final CountDownLatch elatch = new CountDownLatch(1);
    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            elatch.countDown();
            return true;
        }
    });

    // ================ Join the Publisher Session

    StreamingRequest request = new StreamingRequestImpl(publisherUUID.get(), uuid.get());
    startStreamingSession = Envelope.newClientToServerRequest(subscriberUUID.get(), new Message(
            new Path(Paths.VALIDATE_SUBSCRIBER_STREAMING_SESSION), mapper.writeValueAsString(request)));
    startStreamingSession.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(startStreamingSession);

    elatch.await();

    assertEquals("OK", sanswer.get().getResults());

    // ================ Ask for an Action the Publisher Session

    Action action = new Action();
    action.setPath("/action/doSomething");
    action.setData("{ \"foo\":\"bar\"");
    Envelope e = Envelope.newClientToServerRequest(subscriberUUID.get(),
            new Message(new Path(Paths.SUBSCRIBER_ACTION), mapper.writeValueAsString(action)));
    e.setFrom(new From(ActorValue.SUBSCRIBER));
    final CountDownLatch actionLatch = new CountDownLatch(1);
    final AtomicReference<Envelope> response = new AtomicReference<>();
    final AtomicBoolean timerCalled = new AtomicBoolean();
    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            switch (e.getMessage().getPath()) {
            case Paths.MESSAGE_ACTION_VALIDATE:
                response.set(e);
                actionLatch.countDown();
                break;
            case Paths.ACTION_TIMER:
                Time t = mapper.readValue(e.getMessage().getData(), Time.class);
                System.out.println("Subscriber ===>" + t);
                timerCalled.set(true);
                break;
            case Paths.ACTION_COMPLETED:
                SubscriberResults results = mapper.readValue(e.getMessage().getData(), SubscriberResults.class);
                System.out.println("Action completed");
                break;
            }

            return false;
        }
    });
    subscriberClient.send(e);

    actionLatch.await();

    assertEquals(Paths.MESSAGE_ACTION_VALIDATE, response.get().getMessage().getPath());
    assertEquals("{\"results\":\"OK\",\"uuid\":null}", response.get().getMessage().getData());

    completed.await();

    assertTrue(timerCalled.get());
    assertEquals("READY", finalMessage.get());
}

From source file:com.networknt.client.oauth.OauthHelper.java

public static Result<TokenResponse> getTokenFromSamlResult(SAMLBearerRequest tokenRequest) {
    final AtomicReference<Result<TokenResponse>> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from   w  w w. j a v a 2  s. co m
        connection = client.connect(new URI(tokenRequest.getServerUrl()), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL,
                tokenRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                        : OptionMap.EMPTY)
                .get();
    } catch (Exception e) {
        logger.error("cannot establish connection:", e);
        return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR));
    }
    try {
        IClientRequestComposable requestComposer = ClientRequestComposerProvider.getInstance()
                .getComposer(ClientRequestComposerProvider.ClientRequestComposers.SAML_BEARER_REQUEST_COMPOSER);

        connection.getIoThread()
                .execute(new TokenRequestAction(tokenRequest, requestComposer, connection, reference, latch));

        latch.await(4, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        return Failure.of(new Status(FAIL_TO_SEND_REQUEST));
    } finally {
        IoUtils.safeClose(connection);
    }
    //if reference.get() is null at this point, mostly likely couldn't get token within latch.await() timeout.
    return reference.get() == null ? Failure.of(new Status(GET_TOKEN_TIMEOUT)) : reference.get();
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private void processUpdates(Collection<UpdateEntry> updates) {
    if (closed) {
        return;/*w  w  w . j  a  v  a 2 s.c  o  m*/
    }
    updates.forEach(update -> {
        final String key = update.key();
        final MapValue value = update.value() == null ? null : update.value().copy();
        if (value == null || value.isTombstone()) {
            MapValue previousValue = removeInternal(key, Optional.empty(), Optional.ofNullable(value));
            if (previousValue != null && previousValue.isAlive()) {
                notifyListeners(
                        new MapDelegateEvent<>(REMOVE, decodeKey(key), previousValue.get(this::decodeValue)));
            }
        } else {
            counter.incrementCount();
            AtomicReference<byte[]> oldValue = new AtomicReference<>();
            AtomicBoolean updated = new AtomicBoolean(false);
            items.compute(key, (k, existing) -> {
                if (existing == null || value.isNewerThan(existing)) {
                    updated.set(true);
                    oldValue.set(existing != null ? existing.get() : null);
                    return value;
                }
                return existing;
            });

            if (updated.get()) {
                if (oldValue.get() == null) {
                    notifyListeners(new MapDelegateEvent<>(INSERT, decodeKey(key), decodeValue(value.get())));
                } else {
                    notifyListeners(new MapDelegateEvent<>(UPDATE, decodeKey(key), decodeValue(value.get())));
                }
            }
        }
    });
}

From source file:io.termd.core.telnet.TelnetHandlerTest.java

@Test
public void testRejectNAWS() throws Exception {
    final AtomicReference<Boolean> serverValue = new AtomicReference<>();
    WindowSizeOptionHandler optionHandler = new WindowSizeOptionHandler(20, 10, false, false, false, false);
    testOptionValue(new Supplier<TelnetHandler>() {
        @Override/*  ww  w.j av a2s .c o  m*/
        public TelnetHandler get() {
            return new TelnetHandler() {
                @Override
                protected void onOpen(TelnetConnection conn) {
                    conn.writeDoOption(Option.NAWS);
                }

                @Override
                protected void onNAWS(boolean naws) {
                    serverValue.set(naws);
                    testComplete();
                }

                @Override
                protected void onSize(int width, int height) {
                    super.onSize(width, height);
                }
            };
        }
    }, optionHandler);
    assertEquals(false, serverValue.get());
    assertEquals(false, optionHandler.getAcceptLocal());
}

From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java

@Test
public void should_notify_listener_on_LWT_update_failure() throws Exception {
    //Given/*w w  w .  j a  va 2s. co m*/
    final AtomicReference<LWTResultListener.LWTResult> atomicLWTResult = new AtomicReference(null);
    LWTResultListener listener = new LWTResultListener() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(LWTResult lwtResult) {
            atomicLWTResult.compareAndSet(null, lwtResult);
        }
    };
    Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false, "name",
            "John");

    CompleteBean entity = builder().randomId().name("John").addFollowers("Paul", "Andrew").buid();
    final CompleteBean managed = manager.insert(entity);
    managed.getFollowers().add("Helen");

    //When
    manager.update(managed, ifEqualCondition("name", "Helen").lwtResultListener(listener));

    //Then
    final LWTResultListener.LWTResult LWTResult = atomicLWTResult.get();
    assertThat(LWTResult).isNotNull();
    assertThat(LWTResult.operation()).isEqualTo(UPDATE);
    assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues);

}

From source file:info.archinnov.achilles.test.integration.tests.AsyncBatchModeIT.java

@Test
public void should_reinit_batch_context_and_consistency_after_exception_async() throws Exception {
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("simple_tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("simple_tweet2").buid();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override//from   w  ww.j a v  a  2  s  .c  om
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    };

    asyncManager.insert(tweet1);

    // Start batch
    AsyncBatch batch = asyncManager.createBatch();

    batch.startBatch(EACH_QUORUM);
    batch.insert(tweet2);

    batch.asyncEndBatch(successCallBack);

    latch.await();

    assertThatBatchContextHasBeenReset(batch);

    logAsserter.prepareLogLevelForDriverConnection();
    batch.startBatch();
    batch.insert(tweet2);
    batch.asyncEndBatch();
    logAsserter.assertConsistencyLevels(ONE);

    assertThat(successSpy.get()).isEqualTo(Empty.INSTANCE);
}

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  av  a 2 s.  c o 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:io.warp10.continuum.egress.EgressFetchHandler.java

private static void jsonDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean dedup,
        boolean signed, AtomicReference<Metadata> lastMeta, AtomicLong lastCount) throws IOException {

    String name = null;/*from   w ww  .ja va2 s .c om*/
    Map<String, String> labels = null;

    pw.print("[");

    boolean hasValues = false;

    Metadata lastMetadata = lastMeta.get();
    long currentCount = lastCount.get();

    try {
        StringBuilder sb = new StringBuilder();

        JsonSerializer serializer = new JsonSerializerFactory().create();

        boolean firstgts = true;

        long mask = (long) (Math.random() * Long.MAX_VALUE);

        while (iter.hasNext()) {
            GTSDecoder decoder = iter.next();

            if (dedup) {
                decoder = decoder.dedup();
            }

            if (!decoder.next()) {
                continue;
            }

            long toDecodeCount = Long.MAX_VALUE;

            if (timespan < 0) {
                Metadata meta = decoder.getMetadata();
                if (!meta.equals(lastMetadata)) {
                    lastMetadata = meta;
                    currentCount = 0;
                }
                toDecodeCount = Math.max(0, -timespan - currentCount);
            }

            //
            // Only display the class + labels if they have changed since the previous GTS
            //

            Map<String, String> lbls = decoder.getLabels();

            //
            // Compute the new name
            //

            boolean displayName = false;

            if (null == name || (!name.equals(decoder.getName()) || !labels.equals(lbls))) {
                displayName = true;
                name = decoder.getName();
                labels = lbls;
                sb.setLength(0);

                sb.append("{\"c\":");

                //sb.append(gson.toJson(name));
                sb.append(serializer.serialize(name));

                boolean first = true;

                sb.append(",\"l\":{");

                for (Entry<String, String> entry : lbls.entrySet()) {
                    //
                    // Skip owner/producer labels and any other 'private' labels
                    //
                    if (!signed) {
                        if (Constants.PRODUCER_LABEL.equals(entry.getKey())) {
                            continue;
                        }
                        if (Constants.OWNER_LABEL.equals(entry.getKey())) {
                            continue;
                        }
                    }

                    if (!first) {
                        sb.append(",");
                    }

                    //sb.append(gson.toJson(entry.getKey()));
                    sb.append(serializer.serialize(entry.getKey()));
                    sb.append(":");
                    //sb.append(gson.toJson(entry.getValue()));
                    sb.append(serializer.serialize(entry.getValue()));
                    first = false;
                }
                sb.append("}");

                sb.append(",\"a\":{");

                first = true;
                for (Entry<String, String> entry : decoder.getMetadata().getAttributes().entrySet()) {
                    if (!first) {
                        sb.append(",");
                    }

                    //sb.append(gson.toJson(entry.getKey()));
                    sb.append(serializer.serialize(entry.getKey()));
                    sb.append(":");
                    //sb.append(gson.toJson(entry.getValue()));
                    sb.append(serializer.serialize(entry.getValue()));
                    first = false;
                }

                sb.append("}");
                sb.append(",\"i\":\"");
                sb.append(decoder.getLabelsId() & mask);
                sb.append("\",\"v\":[");
            }

            long decoded = 0L;

            do {

                if (toDecodeCount == decoded) {
                    break;
                }

                // FIXME(hbs): only display the results which match the authorized (according to token) timerange and geo zones

                //
                // Filter out any value not in the time range
                //

                if (decoder.getTimestamp() > now
                        || (timespan >= 0 && decoder.getTimestamp() <= (now - timespan))) {
                    continue;
                }

                decoded++;

                //
                // TODO(hbs): filter out values with no location or outside the selected geozone when a geozone was set
                //

                // Display the name only if we have at least one value to display
                if (displayName) {
                    if (!firstgts) {
                        pw.print("]},");
                    }
                    pw.print(sb.toString());
                    firstgts = false;
                    displayName = false;
                } else {
                    pw.print(",");
                }
                hasValues = true;
                pw.print("[");
                pw.print(decoder.getTimestamp());
                if (GeoTimeSerie.NO_LOCATION != decoder.getLocation()) {
                    double[] latlon = GeoXPLib.fromGeoXPPoint(decoder.getLocation());
                    pw.print(",");
                    pw.print(latlon[0]);
                    pw.print(",");
                    pw.print(latlon[1]);
                }
                if (GeoTimeSerie.NO_ELEVATION != decoder.getElevation()) {
                    pw.print(",");
                    pw.print(decoder.getElevation());
                }
                pw.print(",");
                Object value = decoder.getValue();

                if (value instanceof Number) {
                    pw.print(value);
                } else if (value instanceof Boolean) {
                    pw.print(Boolean.TRUE.equals(value) ? "true" : "false");
                } else {
                    //pw.print(gson.toJson(value.toString()));
                    pw.print(serializer.serialize(value.toString()));
                }
                pw.print("]");
            } while (decoder.next());

            if (timespan < 0) {
                currentCount += decoded;
            }

            //
            // If displayName is still true it means we should have displayed the name but no value matched,
            // so set name to null so we correctly display the name for the next decoder if it has values
            //

            if (displayName) {
                name = null;
            }
        }

    } catch (Throwable t) {
        throw t;
    } finally {
        if (hasValues) {
            pw.print("]}");
        }
        pw.print("]");
    }

    lastMeta.set(lastMetadata);
    lastCount.set(currentCount);
}

From source file:com.twitter.aurora.scheduler.app.SchedulerIT.java

private HostAndPort awaitSchedulerReady() throws Exception {
    return executor.submit(new Callable<HostAndPort>() {
        @Override//from  w w  w.  ja v  a 2  s.c  om
        public HostAndPort call() throws Exception {
            final AtomicReference<HostAndPort> thriftEndpoint = Atomics.newReference();
            ServerSet schedulerService = new ServerSetImpl(zkClient, SERVERSET_PATH);
            final CountDownLatch schedulerReady = new CountDownLatch(1);
            schedulerService.watch(new HostChangeMonitor<ServiceInstance>() {
                @Override
                public void onChange(ImmutableSet<ServiceInstance> hostSet) {
                    if (!hostSet.isEmpty()) {
                        Endpoint endpoint = Iterables.getOnlyElement(hostSet).getServiceEndpoint();
                        thriftEndpoint.set(HostAndPort.fromParts(endpoint.getHost(), endpoint.getPort()));
                        schedulerReady.countDown();
                    }
                }
            });
            // A timeout is used because certain types of assertion errors (mocks) will not surface
            // until the main test thread exits this body of code.
            assertTrue(schedulerReady.await(5L, TimeUnit.MINUTES));
            return thriftEndpoint.get();
        }
    }).get();
}