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:com.sysunite.nifi.XmlSplit.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {

    FlowFile flowFile = session.get();/*from w  w  w  .  ja va 2 s .co m*/

    if (flowFile == null) {
        return;
    }

    //read the flow file and save it contents
    final AtomicReference<InputStream> theXml = new AtomicReference<>();

    session.read(flowFile, new InputStreamCallback() {

        @Override
        public void process(InputStream isIn) throws IOException {

            //System.out.println("contact!");

            try {

                String contents = IOUtils.toString(isIn);

                XML xmlNode = new XMLDocument(contents);

                InputStream is = new ByteArrayInputStream(xmlNode.toString().getBytes());

                theXml.set(is);

            } catch (IOException e) {
                System.out.println("w00t");// + e.getMessage());
            } catch (IllegalArgumentException e) {
                System.out.println("is xml niet geldig?");
            } catch (IndexOutOfBoundsException e) {
                System.out.println("bah! de node waar gezocht naar moet worden is niet gevonden!");
            }

        }
    });

    //fetch the xml content again

    try {

        InputStream orig_xml = theXml.get();

        String xml_contents = IOUtils.toString(orig_xml);

        try {

            //loop through the relations and get each value (xpath)
            final Map<Relationship, PropertyValue> propMap = propertyMap;

            for (final Map.Entry<Relationship, PropertyValue> entry : propMap.entrySet()) {

                final PropertyValue pv = entry.getValue();
                String xpath = pv.getValue();

                final Relationship rel = entry.getKey();
                String relName = rel.getName();

                if (xpath != null) {

                    System.out.println(xpath);

                    //create new xml
                    XML file = new XMLDocument(xml_contents);

                    //if we want an attribute of a node
                    //we reconize the monkeytail in xpath i.e. /Node/@id - Route On Attribute (ori FileContent not changed)
                    if (xpath.matches("(.*)\u0040(.*)")) {
                        String v = file.xpath(xpath).get(0);
                        //System.out.println(v);

                        FlowFile fNew = session.clone(flowFile);
                        //create attribute
                        fNew = session.putAttribute(fNew, relName, v);
                        //transfer
                        session.transfer(fNew, rel);

                    } else {

                        //extract all nodes and transfer them to the appropriate relation - Route On Content (ori FileContent changed)
                        for (XML ibr : file.nodes(xpath)) {

                            //              System.out.println("match!");
                            //              System.out.println(ibr.toString());

                            FlowFile fNew = session.clone(flowFile);
                            //create attribute
                            //fNew = session.putAttribute(fNew, relName, ibr.toString());

                            InputStream in = new ByteArrayInputStream(ibr.toString().getBytes());

                            fNew = session.importFrom(in, fNew);
                            //transfer
                            session.transfer(fNew, rel);

                        }

                    }

                }

            }

        } catch (IllegalArgumentException e) {
            System.out.println("is xml niet geldig?");
        } catch (IndexOutOfBoundsException e) {
            System.out.println("bah! de node waar gezocht naar moet worden is niet gevonden!");
        }

    } catch (IOException e) {
        System.out.println("cannot read xml");
    }

    session.transfer(flowFile, ORIGINAL);

}

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

/**
 * Output a text version of fetched data. Deduplication is done on the fly so we don't decode twice.
 * //from w w w.  j a v a  2  s .  c  om
 */
private static void textDump(PrintWriter pw, GTSDecoderIterator iter, long now, long timespan, boolean raw,
        boolean dedup, boolean signed, boolean showAttributes, AtomicReference<Metadata> lastMeta,
        AtomicLong lastCount, boolean sortMeta) throws IOException {

    String name = null;
    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 (!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);
            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 (showAttributes) {
                Metadata meta = decoder.getMetadata();
                if (meta.getAttributesSize() > 0) {

                    if (sortMeta) {
                        meta.setAttributes(new TreeMap<String, String>(meta.getAttributes()));
                    }

                    GTSHelper.labelsToString(sb, meta.getAttributes());
                } else {
                    sb.append("{}");
                }
            }
        }

        long timestamp = 0L;
        long location = GeoTimeSerie.NO_LOCATION;
        long elevation = GeoTimeSerie.NO_ELEVATION;
        Object value = null;

        boolean dup = true;

        long decoded = 0;

        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
            //

            long newTimestamp = decoder.getTimestamp();

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

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

            long newLocation = decoder.getLocation();
            long newElevation = decoder.getElevation();
            Object newValue = decoder.getValue();

            dup = true;

            if (dedup) {
                if (location != newLocation || elevation != newElevation) {
                    dup = false;
                } else {
                    if (null == newValue) {
                        // Consider nulls as duplicates (can't happen!)
                        dup = false;
                    } else if (newValue instanceof Number) {
                        if (!((Number) newValue).equals(value)) {
                            dup = false;
                        }
                    } else if (newValue instanceof String) {
                        if (!((String) newValue).equals(value)) {
                            dup = false;
                        }
                    } else if (newValue instanceof Boolean) {
                        if (!((Boolean) newValue).equals(value)) {
                            dup = false;
                        }
                    }
                }
            }

            decoded++;

            location = newLocation;
            elevation = newElevation;
            timestamp = newTimestamp;
            value = newValue;

            if (raw) {
                if (!dedup || !dup) {
                    pw.println(GTSHelper.tickToString(sb, timestamp, location, elevation, value));
                }
            } else {
                // Display the name only if we have at least one value to display
                // We force 'dup' to be false when we must show the name
                if (displayName) {
                    pw.println(GTSHelper.tickToString(sb, decoder.getTimestamp(), decoder.getLocation(),
                            decoder.getElevation(), decoder.getValue()));
                    displayName = false;
                    dup = false;
                } else {
                    if (!dedup || !dup) {
                        pw.print("=");
                        pw.println(GTSHelper.tickToString(timestamp, location, elevation, value));
                    }
                }
            }
        } while (decoder.next());

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

        // Print any remaining value
        if (dedup && dup) {
            if (raw) {
                pw.println(GTSHelper.tickToString(sb, timestamp, location, elevation, value));
            } else {
                pw.print("=");
                pw.println(GTSHelper.tickToString(timestamp, location, elevation, value));
            }
        }

        //
        // 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;
        }
    }

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

From source file:com.collaborne.jsonschema.generator.pojo.PojoClassGenerator.java

@Override
public void generateType(PojoCodeGenerationContext context, SchemaTree schema, JavaWriter writer)
        throws IOException, CodeGenerationException {
    Mapping mapping = context.getMapping();

    // Process the properties into PropertyGenerators
    List<PojoPropertyGenerator> propertyGenerators = new ArrayList<>();

    visitProperties(schema, new PropertyVisitor<CodeGenerationException>() {
        @Override/*from ww w  .j av a  2  s  . c o m*/
        public void visitProperty(String propertyName, URI type, SchemaTree schema)
                throws CodeGenerationException {
            String defaultValue;
            JsonNode defaultValueNode = schema.getNode().path("default");
            if (defaultValueNode.isMissingNode() || defaultValueNode.isNull()) {
                defaultValue = null;
            } else if (defaultValueNode.isTextual()) {
                defaultValue = '"' + defaultValueNode.textValue() + '"';
            } else {
                defaultValue = defaultValueNode.asText();
            }

            PojoPropertyGenerator propertyGenerator = context.createPropertyGenerator(type, propertyName,
                    defaultValue);
            propertyGenerators.add(propertyGenerator);
        }

        @Override
        public void visitProperty(String propertyName, URI type) throws CodeGenerationException {
            propertyGenerators.add(context.createPropertyGenerator(type, propertyName, null));
        }
    });

    for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
        propertyGenerator.generateImports(writer);
    }

    // check whether we need to work with additionalProperties:
    // - schema can say "yes", or "yes-with-this-type"
    // - mapping can say "yes", or "ignore"
    // Ultimately if we have to handle them we let the generated class extend AbstractMap<String, TYPE>,
    // where TYPE is either the one from the schema, or Object (if the schema didn't specify anything.
    // XXX: "Object" should probably be "whatever our factory/reader would produce"
    // XXX: Instead an AbstractMap, should we have a standard class in our support library?
    ClassName additionalPropertiesValueClassName = null;
    ClassName extendedClass = mapping.getExtends();
    JsonNode additionalPropertiesNode = schema.getNode().path("additionalProperties");
    if (!additionalPropertiesNode.isMissingNode() && !additionalPropertiesNode.isNull()
            && !mapping.isIgnoreAdditionalProperties()) {
        if (additionalPropertiesNode.isBoolean()) {
            if (additionalPropertiesNode.booleanValue()) {
                additionalPropertiesValueClassName = ClassName.create(Object.class);
            }
        } else {
            assert additionalPropertiesNode.isContainerNode();

            AtomicReference<ClassName> ref = new AtomicReference<>();
            SchemaTree additionalPropertiesSchema = schema.append(JsonPointer.of("additionalProperties"));
            URI additionalPropertiesUri = additionalPropertiesSchema.getLoadingRef().toURI()
                    .resolve("#" + additionalPropertiesSchema.getPointer().toString());
            visitSchema(additionalPropertiesUri, additionalPropertiesSchema,
                    new SchemaVisitor<CodeGenerationException>() {
                        @Override
                        public void visitSchema(URI type, SchemaTree schema) throws CodeGenerationException {
                            visitSchema(type);
                        }

                        @Override
                        public void visitSchema(URI type) throws CodeGenerationException {
                            ref.set(context.getGenerator().generate(type));
                        }
                    });
            additionalPropertiesValueClassName = ref.get();
        }

        if (additionalPropertiesValueClassName != null) {
            if (extendedClass != null) {
                // FIXME: handle this by using an interface instead
                throw new CodeGenerationException(context.getType(),
                        "additionalProperties is incompatible with 'extends'");
            }
            extendedClass = ClassName.create(AbstractMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(extendedClass);
            ClassName mapClass = ClassName.create(Map.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(mapClass);
            ClassName hashMapClass = ClassName.create(HashMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(hashMapClass);
            ClassName mapEntryClass = ClassName.create(Map.Entry.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeImport(mapEntryClass);
            ClassName setMapEntryClass = ClassName.create(Set.class, mapEntryClass);
            writer.writeImport(setMapEntryClass);
        }
    }

    if (mapping.getImplements() != null) {
        for (ClassName implementedInterface : mapping.getImplements()) {
            writer.writeImport(implementedInterface);
        }
    }

    writeSchemaDocumentation(schema, writer);
    writer.writeClassStart(mapping.getGeneratedClassName(), extendedClass, mapping.getImplements(), Kind.CLASS,
            Visibility.PUBLIC, mapping.getModifiers());
    try {
        // Write properties
        for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
            propertyGenerator.generateFields(writer);
        }
        if (additionalPropertiesValueClassName != null) {
            ClassName mapClass = ClassName.create(Map.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            ClassName hashMapClass = ClassName.create(HashMap.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            writer.writeField(Visibility.PRIVATE, mapClass, "additionalPropertiesMap", () -> {
                writer.write(" = new ");
                // XXX: If code generation would know about java 7/8, we could use diamond here
                writer.writeClassName(hashMapClass);
                writer.write("()");
            });
        }

        // Write accessors
        // TODO: style to create them: pairs, or ordered?
        // TODO: whether to generate setters in the first place, or just getters
        for (PojoPropertyGenerator propertyGenerator : propertyGenerators) {
            propertyGenerator.generateGetter(writer);
            propertyGenerator.generateSetter(writer);
        }

        if (additionalPropertiesValueClassName != null) {
            ClassName mapEntryClass = ClassName.create(Map.Entry.class, ClassName.create(String.class),
                    additionalPropertiesValueClassName);
            ClassName setMapEntryClass = ClassName.create(Set.class, mapEntryClass);
            writer.writeAnnotation(ClassName.create(Override.class));
            writer.writeMethodBodyStart(Visibility.PUBLIC, setMapEntryClass, "entrySet");
            writer.writeCode("return additionalPropertiesMap.entrySet();");
            writer.writeMethodBodyEnd();
        }
    } finally {
        writer.writeClassEnd();
    }
}

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

@Override
public V put(K key, V value) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);//w  ww.  ja va  2s  .c  o  m
    checkNotNull(value, ERROR_NULL_VALUE);

    String encodedKey = encodeKey(key);
    byte[] encodedValue = encodeValue(value);

    MapValue newValue = new MapValue(encodedValue, timestampProvider.get(Maps.immutableEntry(key, value)));

    counter.incrementCount();
    AtomicReference<byte[]> oldValue = new AtomicReference<>();
    AtomicBoolean updated = new AtomicBoolean(false);
    items.compute(encodedKey, (k, existing) -> {
        if (existing == null || newValue.isNewerThan(existing)) {
            updated.set(true);
            oldValue.set(existing != null ? existing.get() : null);
            return newValue;
        }
        return existing;
    });

    if (updated.get()) {
        notifyPeers(new UpdateEntry(encodedKey, newValue),
                peerUpdateFunction.select(Maps.immutableEntry(key, value), membershipService));
        if (oldValue.get() == null) {
            notifyListeners(new MapDelegateEvent<>(INSERT, key, value));
        } else {
            notifyListeners(new MapDelegateEvent<>(UPDATE, key, value));
        }
        return decodeValue(oldValue.get());
    }
    return value;
}

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

@Test
public void should_notify_listener_when_failing_cas_update() throws Exception {
    //Given/*from w  w w.  j ava2 s  .c  om*/
    final AtomicReference<LWTResultListener.LWTResult> atomicCASResult = new AtomicReference(null);
    LWTResultListener listener = new LWTResultListener() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(LWTResult lwtResult) {
            atomicCASResult.compareAndSet(null, lwtResult);
        }
    };

    final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "John", EACH_QUORUM);
    final EntityWithEnum managed = manager.insert(entityWithEnum);
    Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false,
            "consistency_level", EACH_QUORUM.name(), "name", "John");
    managed.setName("Helen");

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

    final LWTResultListener.LWTResult LWTResult = atomicCASResult.get();
    assertThat(LWTResult).isNotNull();
    assertThat(LWTResult.operation()).isEqualTo(UPDATE);
    assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues);
    assertThat(LWTResult.toString()).isEqualTo(
            "CAS operation UPDATE cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, name=John}");
}

From source file:org.opennms.newts.gsod.ImportRunner.java

public void execute(String... args) throws Exception {

    CmdLineParser parser = new CmdLineParser(this);
    try {//from w w  w . ja  v  a 2  s. c  om
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        // handling of wrong arguments
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        return;
    }

    // Setup the slf4j metrics reporter
    MetricRegistry metrics = new MetricRegistry();

    final long start = System.currentTimeMillis();
    metrics.register("elapsed-seconds", new Gauge<Double>() {

        @Override
        public Double getValue() {
            return (System.currentTimeMillis() - start) / 1000.0;
        }

    });

    final ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).outputTo(System.err)
            .convertRatesTo(SECONDS).convertDurationsTo(MILLISECONDS).build();

    reporter.start(10, SECONDS);

    if (m_restUrl == null) {
        // we are using a direct importer so use a NewtsReporter for storing metrics
        NewtsReporter newtsReporter = NewtsReporter.forRegistry(metrics).name("importer")
                .convertRatesTo(SECONDS).convertDurationsTo(MILLISECONDS).build(repository());

        newtsReporter.start(1, SECONDS);
    }

    LOG.debug("Scanning {} for GSOD data files...", m_source);

    // walk the files in the directory given
    Observable<Sample> samples = fileTreeWalker(m_source.toPath()).subscribeOn(Schedulers.io())

            // set up a meter for each file processed
            .map(meter(metrics.meter("files"), Path.class))

            // report file
            .map(reportFile())

            // read all the files and convert them into lines
            .mergeMap(lines())
            // excluding the header lines
            .filter(exclude("YEARMODA"))

            // turn each line into a list of samples
            .mergeMap(samples())

            // adjust time on samples according to arguments
            .map(adjustTime())

            // meter the samples
            .map(meter(metrics.meter("samples"), Sample.class));

    Observable<List<Sample>> batches = samples
            // create batches each second or of size m_samplesPerBatch whichever comes first
            .buffer(m_samplesPerBatch);

    Observable<Boolean> doImport = m_restUrl != null ? restPoster(batches, metrics)
            : directPoster(batches, metrics);

    System.err.println("doImport = " + doImport);

    // GO!!!
    final AtomicReference<Subscription> subscription = new AtomicReference<>();
    final AtomicBoolean failed = new AtomicBoolean(false);

    final CountDownLatch latch = new CountDownLatch(1);

    Subscription s = doImport.subscribe(new Observer<Boolean>() {

        @Override
        public void onCompleted() {
            System.err.println("Finished Importing Everything!");
            reporter.report();
            latch.countDown();
            System.exit(0);
        }

        @Override
        public void onError(Throwable e) {
            failed.set(true);
            System.err.println("Error importing!");
            e.printStackTrace();
            try {
                //latch.await();
                Subscription s = subscription.get();
                if (s != null)
                    s.unsubscribe();

            } catch (Exception ex) {
                System.err.println("Failed to close httpClient!");
                ex.printStackTrace();
            } finally {
                //dumpThreads();
            }
        }

        @Override
        public void onNext(Boolean t) {
            System.err.println("Received a boolen: " + t);
        }
    });

    subscription.set(s);
    if (failed.get()) {
        s.unsubscribe();
    }
    //latch.countDown();
    System.err.println("Return from Subscribe!");

    latch.await();

    //dumpThreads();

}

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

@Test(enabled = false)
public void createSessionTest() throws IOException, InterruptedException {
    final AtomicReference<SubscriberResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);

    publisherClient.handler(new OnEnvelopHandler() {
        @Override//from   ww  w.j  ava 2 s .co  m
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            latch.countDown();
            return true;
        }
    }).open();

    Envelope createSessionMessage = Envelope
            .newClientToServerRequest(new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("foo", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
}

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

@Test
public void should_notify_listener_when_failing_cas_update_with_ttl() throws Exception {
    //Given//from  w ww  . j  av a2 s .com
    final AtomicReference<LWTResultListener.LWTResult> atomicCASResult = new AtomicReference(null);
    LWTResultListener listener = new LWTResultListener() {
        @Override
        public void onSuccess() {
        }

        @Override
        public void onError(LWTResult lwtResult) {
            atomicCASResult.compareAndSet(null, lwtResult);
        }
    };

    final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "John", EACH_QUORUM);
    final EntityWithEnum managed = manager.insert(entityWithEnum);
    Map<String, Object> expectedCurrentValues = ImmutableMap.<String, Object>of("[applied]", false,
            "consistency_level", EACH_QUORUM.name(), "name", "John");
    managed.setName("Helen");

    //When
    manager.update(managed, ifEqualCondition("name", "name").ifEqualCondition("consistency_level", EACH_QUORUM)
            .lwtResultListener(listener).withTtl(100));

    final LWTResultListener.LWTResult LWTResult = atomicCASResult.get();
    assertThat(LWTResult).isNotNull();
    assertThat(LWTResult.operation()).isEqualTo(UPDATE);
    assertThat(LWTResult.currentValues()).isEqualTo(expectedCurrentValues);
    assertThat(LWTResult.toString()).isEqualTo(
            "CAS operation UPDATE cannot be applied. Current values are: {[applied]=false, consistency_level=EACH_QUORUM, name=John}");
}

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

private static void wrapperDump(PrintWriter pw, GTSDecoderIterator iter, boolean dedup, boolean signed,
        byte[] fetchPSK, long timespan, AtomicReference<Metadata> lastMeta, AtomicLong lastCount)
        throws IOException {

    if (!signed) {
        throw new IOException("Unsigned request.");
    }/*from ww  w .j a  v  a2 s .co  m*/

    // Labels for Sensision
    Map<String, String> labels = new HashMap<String, String>();

    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);

        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) {
            continue;
        }

        //
        // Build a GTSWrapper
        //

        GTSWrapper wrapper = GTSWrapperHelper.fromGTSEncoderToGTSWrapper(encoder, true);

        //      GTSWrapper wrapper = new GTSWrapper();
        //      wrapper.setBase(encoder.getBaseTimestamp());
        //      wrapper.setMetadata(encoder.getMetadata());
        //      wrapper.setCount(encoder.getCount());
        //      wrapper.setEncoded(encoder.getBytes());

        //
        // Serialize the wrapper
        //

        TSerializer serializer = new TSerializer(new TCompactProtocol.Factory());
        byte[] data = null;

        try {
            data = serializer.serialize(wrapper);
        } catch (TException te) {
            throw new IOException(te);
        }

        //
        // Output is GTSWrapperId <WSP> HASH <WSP> GTSWrapper
        //

        pw.write(Hex.encodeHex(GTSWrapperHelper.getId(wrapper)));

        pw.write(' ');

        if (null != fetchPSK) {
            //
            // Compute HMac for the wrapper
            //

            long hash = SipHashInline.hash24(fetchPSK, data);

            //
            // Output the MAC before the data, as hex digits
            //
            pw.write(Hex.encodeHex(Longs.toByteArray(hash)));
        } else {
            pw.write('-');
        }

        pw.write(' ');

        //
        // Base64 encode the wrapper
        //

        OrderPreservingBase64.encodeToWriter(data, pw);
        pw.write('\r');
        pw.write('\n');

        //
        // Sensision metrics
        //

        labels.clear();
        labels.put(SensisionConstants.SENSISION_LABEL_APPLICATION,
                wrapper.getMetadata().getLabels().get(Constants.APPLICATION_LABEL));

        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS, Sensision.EMPTY_LABELS,
                1);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_PERAPP, labels, 1);

        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_SIZE,
                Sensision.EMPTY_LABELS, data.length);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_SIZE_PERAPP, labels,
                data.length);

        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_DATAPOINTS,
                Sensision.EMPTY_LABELS, wrapper.getCount());
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_SFETCH_WRAPPERS_DATAPOINTS_PERAPP, labels,
                wrapper.getCount());

    }

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

From source file:com.twitter.distributedlog.client.proxy.TestProxyClientManager.java

@Test(timeout = 60000)
public void testCreateClientShouldHandshake() throws Exception {
    SocketAddress address = createSocketAddress(3000);
    MockProxyClientBuilder builder = new MockProxyClientBuilder();
    ServerInfo serverInfo = new ServerInfo();
    serverInfo.putToOwnerships(runtime.getMethodName() + "_stream", runtime.getMethodName() + "_owner");
    Pair<MockProxyClient, MockServerInfoService> mockProxyClient = createMockProxyClient(address, serverInfo);
    builder.provideProxyClient(address, mockProxyClient.getLeft());

    final AtomicReference<ServerInfo> resultHolder = new AtomicReference<ServerInfo>(null);
    final CountDownLatch doneLatch = new CountDownLatch(1);
    ProxyListener listener = new ProxyListener() {
        @Override//from w  w  w .  j a  va2 s  .  c  om
        public void onHandshakeSuccess(SocketAddress address, ProxyClient client, ServerInfo serverInfo) {
            resultHolder.set(serverInfo);
            doneLatch.countDown();
        }

        @Override
        public void onHandshakeFailure(SocketAddress address, ProxyClient client, Throwable cause) {
        }
    };

    ProxyClientManager clientManager = createProxyClientManager(builder, 0L);
    clientManager.registerProxyListener(listener);
    assertEquals("There should be no clients in the manager", 0, clientManager.getNumProxies());
    clientManager.createClient(address);
    assertEquals("Create client should build the proxy client", 1, clientManager.getNumProxies());

    // When a client is created, it would handshake with that proxy
    doneLatch.await();
    assertEquals("Handshake should return server info", serverInfo, resultHolder.get());
}