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

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

Introduction

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

Prototype

public AtomicReference(V initialValue) 

Source Link

Document

Creates a new AtomicReference with the given initial value.

Usage

From source file:com.aol.advertising.qiao.management.metrics.StatisticsStore.java

public void incr(String key, IntervalMetric delta) {
    if (intvalStats.containsKey(key)) {
        intvalStats.get(key).get().incr(delta);
    } else {//w w  w .j  a va2 s  .  co m
        intvalStats.put(key, new AtomicReference<IntervalMetric>(delta));
    }

}

From source file:com.kixeye.janus.client.http.rest.DefaultRestHttpClientTest.java

@Test
public void postParamListTest() throws Exception {
    Janus janus = new Janus(VIP_TEST, new ConstServerList(VIP_TEST, "http://localhost:" + server1Port),
            new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class, new MetricRegistry()));

    DefaultRestHttpClient client = new DefaultRestHttpClient(janus, 0, DefaultRestHttpClient.UTF8_STRING_SER_DE,
            "text/plain");

    final AtomicReference<String> requestMethod = new AtomicReference<>(null);
    final AtomicReference<String> requestPath = new AtomicReference<>(null);

    testContainer = new Container() {
        public void handle(Request req, Response resp) {
            requestMethod.set(req.getMethod());
            requestPath.set(req.getTarget());

            try {
                resp.getByteChannel().write(ByteBuffer.wrap(IOUtils.toByteArray(req.getInputStream())));
            } catch (IOException e) {
                logger.error("Unable to write to channel.");
            }//from  w w w  . ja v  a  2  s . co  m
        }
    };

    String result = client.post("/test_params/{}", "body", String.class, "goofy").getBody().deserialize();
    Assert.assertEquals("body", result);

    Assert.assertEquals("POST", requestMethod.get());
    Assert.assertEquals("/test_params/goofy", requestPath.get());
}

From source file:com.aol.advertising.qiao.management.metrics.StatisticsStore.java

public void set(String key, IntervalMetric stats) {
    if (intvalStats.containsKey(key)) {
        intvalStats.get(key).set(stats);
    } else {/*from ww  w.jav  a  2 s.  c  om*/
        intvalStats.put(key, new AtomicReference<IntervalMetric>(stats));
    }

}

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  .  ja v  a 2  s .c o m
        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());
}

From source file:com.yahoo.pulsar.broker.loadbalance.SimpleLoadManagerImplTest.java

@Test(enabled = true)
public void testBasicBrokerSelection() throws Exception {
    LoadManager loadManager = new SimpleLoadManagerImpl(pulsar1);
    PulsarResourceDescription rd = new PulsarResourceDescription();
    rd.put("memory", new ResourceUsage(1024, 4096));
    rd.put("cpu", new ResourceUsage(10, 100));
    rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024));
    rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024));

    ResourceUnit ru1 = new SimpleResourceUnit("http://prod2-broker7.messaging.usw.example.com:8080", rd);
    Set<ResourceUnit> rus = new HashSet<ResourceUnit>();
    rus.add(ru1);//w  w w .j  a  v a  2  s . com
    LoadRanker lr = new ResourceAvailabilityRanker();
    AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRankingsInstance = new AtomicReference<>(
            Maps.newTreeMap());
    sortedRankingsInstance.get().put(lr.getRank(rd), rus);

    Field sortedRankings = SimpleLoadManagerImpl.class.getDeclaredField("sortedRankings");
    sortedRankings.setAccessible(true);
    sortedRankings.set(loadManager, sortedRankingsInstance);

    ResourceUnit found = ((SimpleLoadManagerImpl) loadManager)
            .getLeastLoaded(new NamespaceName("pulsar/use/primary-ns.10"));
    // broker is not active so found should be null
    assertEquals(found, null, "found a broker when expected none to be found");

}

From source file:com.hurence.logisland.processor.EvaluateJsonPath.java

/**
 * Provides cleanup of the map for any JsonPath values that may have been created. This will remove common values shared between multiple instances, but will be regenerated when the next
 * validation cycle occurs as a result of isStale()
 *
 * @param processContext context/*from w w  w .  j a va 2s  .  co m*/
 */
/*  @OnRemoved
  public void onRemoved(ProcessContext processContext) {
for (PropertyDescriptor propertyDescriptor : getPropertyDescriptors()) {
    if (propertyDescriptor.isDynamic()) {
        cachedJsonPathMap.remove(processContext.getProperty(propertyDescriptor).getValue());
    }
}
  }*/
@Override
public Collection<Record> process(ProcessContext processContext, Collection<Record> records)
        throws ProcessException {
    String returnType = processContext.getPropertyValue(RETURN_TYPE).asString();

    String representationOption = processContext.getPropertyValue(NULL_VALUE_DEFAULT_REPRESENTATION).asString();
    final String nullDefaultValue = NULL_REPRESENTATION_MAP.get(representationOption);

    /* Build the JsonPath expressions from attributes */
    final Map<String, JsonPath> attributeToJsonPathMap = new HashMap<>();

    for (final Map.Entry<PropertyDescriptor, String> entry : processContext.getProperties().entrySet()) {
        if (!entry.getKey().isDynamic()) {
            continue;
        }
        final JsonPath jsonPath = JsonPath.compile(entry.getValue());
        attributeToJsonPathMap.put(entry.getKey().getName(), jsonPath);
    }

    String jsonInputField = processContext.getPropertyValue(JSON_INPUT_FIELD).asString();

    records.forEach(record -> {
        if (record.hasField(jsonInputField)) {
            DocumentContext documentContext = null;
            try {
                documentContext = validateAndEstablishJsonContext(record.getField(jsonInputField).asString());
            } catch (InvalidJsonException e) {
                logger.error("Record {} did not have valid JSON content.", record);
                record.addError(ERROR_INVALID_JSON_FIELD,
                        "unable to parse content of field : " + jsonInputField);
            }

            final Map<String, String> jsonPathResults = new HashMap<>();
            for (final Map.Entry<String, JsonPath> attributeJsonPathEntry : attributeToJsonPathMap.entrySet()) {

                final String jsonPathAttrKey = attributeJsonPathEntry.getKey();
                final JsonPath jsonPathExp = attributeJsonPathEntry.getValue();
                final String pathNotFound = processContext.getPropertyValue(PATH_NOT_FOUND).asString();

                final AtomicReference<Object> resultHolder = new AtomicReference<>(null);
                try {
                    final Object result = documentContext.read(jsonPathExp);
                    if (returnType.equals(RETURN_TYPE_SCALAR) && !isJsonScalar(result)) {
                        String error = String.format(
                                "Unable to return a scalar value for the expression %s "
                                        + "for Record %s. Evaluated value was %s.",
                                jsonPathExp.getPath(), record.getId(), result.toString());

                        logger.error(error);
                        record.addError(ERROR_INVALID_JSON_FIELD, error);
                    }
                    resultHolder.set(result);
                } catch (PathNotFoundException e) {

                    if (pathNotFound.equals(PATH_NOT_FOUND_WARN)) {

                        String error = String.format("Record %s could not find path %s for field %s..",
                                record.getId(), jsonPathExp.getPath(), jsonPathAttrKey);
                        logger.error(error);
                        record.addError(ERROR_INVALID_JSON_FIELD, error);
                    }
                    jsonPathResults.put(jsonPathAttrKey, StringUtils.EMPTY);

                }

                final FieldType resultType = getResultType(resultHolder.get());
                if (resultType != FieldType.STRING)
                    record.setField(jsonPathAttrKey, resultType, resultHolder.get());
                else
                    record.setField(jsonPathAttrKey, resultType,
                            getResultRepresentation(resultHolder.get(), nullDefaultValue));

            }

        } else {
            String error = String.format("Record %s has no field %s.", record.getId(), jsonInputField);
            logger.error(error);
            record.addError(ERROR_INVALID_JSON_FIELD, error);
        }
    });

    return records;
}

From source file:burlov.ultracipher.swing.SwingGuiApplication.java

/**
 * @return 'true' wenn alles fehlerfrei lief
 *//*from ww w.j a  va 2 s  . c  o m*/
private boolean downloadAndMergeData() {
    if (core.getSyncCredentials() == null) {
        // Nichts zu tun, aber kein Fehler
        return true;
    }
    if (core.getCurrentCryptor() == null) {
        /*
         * Beim Sync Passwort mit Bestaetigung abfragen, weil beim falsch
         * eingegebenem Passwort keine Fehlermeldung kommt sondern einfach
         * nur leere Daten
         */
        if (!createNewCryptor(true)) {
            // Vorgang abgebrochen
            return false;
        }
    }
    final AtomicReference<SyncResult> incomingChanges = new AtomicReference<SyncResult>(SyncResult.NoData);
    Callable<String> callable = new Callable<String>() {

        @Override
        public String call() throws Exception {
            // Mit neuesten Daten vom Sync-Account mergen
            System.out.println("Download data from " + core.getSyncCredentials().getEmailaddress());
            incomingChanges.set(core.syncDatabase(true));
            synced = true;
            return null;
        }
    };
    CallableTask<String> task = new CallableTask<String>(callable);
    WaitDialog dlg = new WaitDialog(getMainFrame(), "Download data", task, 0, 0);
    dlg.start();
    try {
        task.get();
        mainPanel.init();
        if (incomingChanges.get() == SyncResult.NoData) {
            showInfo("No sync data found on the server");
        } else if (!hasChanges && incomingChanges.get() == SyncResult.IncomingChanges) {
            setNeedSave(true);
            /*
             * Wenn lokale Aenderungen nur von gerade runtergeladenen Daten
             * kommen, dann die fusionierte Daten sofort lokal abspeichern
             */
            setNeedSave(!localSaveData());
            return !hasChanges;
        }
        if (incomingChanges.get() == SyncResult.OutgoingChanges) {
            /*
             * Es existieren lokale Daten die nicht auf dem sync-Server
             * bekannt sind. Speicher-Flag setzen damit das Upload nicht
             * vergessen wird
             */
            setNeedSave(true);
        }

        return true;
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
        showError("Sync failed", e.getCause());
    }
    return false;
}

From source file:com.example.app.ui.DemoUserProfileEditor.java

@Override
public ModificationState getModificationState() {
    if (!isInited())
        return ModificationState.UNCHANGED;
    final AtomicReference<ModificationState> state = new AtomicReference<>(ModificationState.UNCHANGED);
    _forEach(value -> {/*w  w w  .  ja va  2s .  c om*/
        if (!state.get().isModified() && value.getModificationState().isModified())
            state.set(ModificationState.CHANGED);
    });
    return state.get();
}

From source file:com.datatorrent.lib.db.jdbc.AbstractJdbcPollInputOperator.java

protected void pollRecords() {
    if (isPolled) {
        return;/*w  ww  . j  a va2  s  .  c  om*/
    }
    try {
        if (isPollerPartition) {
            int nextOffset = getRecordsCount();
            while (lastOffset < nextOffset) {
                PreparedStatement preparedStatement = store.getConnection().prepareStatement(
                        buildRangeQuery(lastOffset, resultLimit), TYPE_FORWARD_ONLY, CONCUR_READ_ONLY);
                insertDbDataInQueue(preparedStatement);
                lastOffset = lastOffset + resultLimit;
            }
            lastOffset = nextOffset;
        } else {
            insertDbDataInQueue(ps);
        }
        isPolled = true;
    } catch (SQLException ex) {
        execute = false;
        threadException = new AtomicReference<Throwable>(ex);
    } catch (InterruptedException e) {
        threadException = new AtomicReference<Throwable>(e);
    } finally {
        if (!isPollerPartition) {
            store.disconnect();
        }
    }
    isPolled = true;
}