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

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

Introduction

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

Prototype

public final void set(V newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:org.apache.nifi.processors.att.m2x.PutM2XStream.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;//w  ww  .j  av  a  2 s.  c  om
    }

    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/")
            .append(deviceId).append("/streams/").append(streamName).append("/value").toString();

    try {
        final AtomicReference<String> postBodyRef = new AtomicReference<>();
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream is) {
                try {
                    String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp");
                    if (StringUtils.isEmpty(timestamp)) {
                        timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate());
                    }
                    final String value = IOUtils.toString(is, StandardCharsets.UTF_8);

                    final M2XStreamValue m2xValue = new M2XStreamValue();
                    m2xValue.setValue(value);
                    m2xValue.setTimestamp(timestamp);

                    final ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(new JodaModule());
                    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

                    final String postBody = mapper.writeValueAsString(m2xValue);
                    logger.warn("POST body is {}", new Object[] { postBody });
                    postBodyRef.set(postBody);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });

        final String postBody = postBodyRef.get();
        if (StringUtils.isEmpty(postBody)) {
            logger.error("FlowFile {} contents didn't produce a valid M2X stream value",
                    new Object[] { flowFile });
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey)
                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            session.penalize(flowFile);
            return;
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        session.penalize(flowFile);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
}

From source file:github.madmarty.madsonic.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);// w ww .  j av a2  s . c om

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.WorkspaceVersionTable.java

private void add(final WorkspaceLocalItem lvEntry, final boolean fromLoad) {
    final AtomicReference<WorkspaceLocalItem> atomicMatch = new AtomicReference<WorkspaceLocalItem>();

    // Create a callback.
    final ModifyInPlaceCallback<WorkspaceLocalItemPair> callback = new ModifyInPlaceCallback<WorkspaceLocalItemPair>() {
        @Override/*from   ww w .  j  a  va 2  s  .c o m*/
        public WorkspaceLocalItemPair invoke(final String token, WorkspaceLocalItemPair pair,
                final Object param) {
            if (pair == null) {
                pair = new WorkspaceLocalItemPair();
            }

            if (lvEntry.isCommitted()) {
                atomicMatch.set(pair.getCommitted());
                pair.setCommitted(lvEntry);
            } else {
                atomicMatch.set(pair.getUncommitted());
                pair.setUncommitted(lvEntry);
            }

            return pair;
        }
    };

    // Insert by the primary key (ServerItem, IsCommitted).
    server.modifyInPlace(lvEntry.getServerItem(), callback, null);
    final WorkspaceLocalItem matchingEntry = atomicMatch.get();

    setDirty(!fromLoad);

    // Remove the replaced entry from other indexes.
    if (null != matchingEntry) {
        final String localItem = matchingEntry.getLocalItem();
        if (localItem != null && localItem.length() > 0) {
            local.remove(localItem, false);
        }

        if (matchingEntry.isPendingReconcile()) {
            pendingReconcileCount--;
        }
    }

    if (lvEntry.isPendingReconcile()) {
        pendingReconcileCount++;
    }

    // Add the entry to the LocalItem tree if necessary.
    final String localItem = lvEntry.getLocalItem();
    if (localItem != null && localItem.length() > 0) {
        local.add(localItem, lvEntry, true);
    }
}

From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java

/**
 * Retrieves certificate chain of specified host:port using https protocol.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to//from  w ww. j a  va 2  s.c  o m
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception {
    checkNotNull(host);

    log.info("Retrieving certificate from https://{}:{}", host, port);

    // setup custom connection manager so we can configure SSL to trust-all
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null);
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory())
            .register(HttpSchemes.HTTPS, sslSocketFactory).build();
    final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

    try {
        final AtomicReference<Certificate[]> certificates = new AtomicReference<>();

        HttpClient httpClient = httpClientManager.create(new Customizer() {
            @Override
            public void customize(final HttpClientPlan plan) {
                // replace connection-manager with customized version needed to fetch SSL certificates
                plan.getClient().setConnectionManager(connectionManager);

                // add interceptor to grab peer-certificates
                plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() {
                    @Override
                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        ManagedHttpClientConnection connection = HttpCoreContext.adapt(context)
                                .getConnection(ManagedHttpClientConnection.class);

                        // grab the peer-certificates from the session
                        if (connection != null) {
                            SSLSession session = connection.getSSLSession();
                            if (session != null) {
                                certificates.set(session.getPeerCertificates());
                            }
                        }
                    }
                });
            }
        });

        httpClient.execute(new HttpGet("https://" + host + ":" + port));

        return certificates.get();
    } finally {
        // shutdown single-use connection manager
        connectionManager.shutdown();
    }
}

From source file:org.jasig.ssp.service.impl.ScheduledTaskWrapperServiceImpl.java

/**
 * Basically a deferred form of {@link #execWithTaskContext(Runnable)}.
 * Useful when you have a scheduled job that does its work in batches and
 * you'd like the effect of {@link #execWithTaskContext(Runnable)}
 * (except for the thread naming decoration) applied
 * independently for each batch. This is advisable for any long-running
 * job (which is probably why it was batched in the first place) b/c
 * otherwise you can end up with a system doing a great impression of
 * a memory leak as the Hib session grows indefinitely.
 *
 * <p>Batched jobs often need results from each batch to know what to
 * do next, hence the use of {@code Callable} rather than
 * {@link Runnable} here.</p>// ww  w. jav  a  2s.c o  m
 *
 * <p>Since thread naming needs to happen prior to individual batch
 * executions, the caller is responsible for wrapping the actual
 * task invocation with that behavior, if necessary. E.g. see
 * {@link #execBatchedTaskWithName(String, org.jasig.ssp.service.external.BatchedTask)}</p>
 *
 * @param batchReturnType
 * @param <T>
 * @return
 */
protected <T> CallableExecutor<T> newTaskBatchExecutor(final Class<T> batchReturnType,
        final boolean isStatusedTask, final UUID runAsId) {
    return new CallableExecutor<T>() {
        @Override
        public T exec(final Callable<T> work) throws Exception {
            final AtomicReference<T> resultHolder = new AtomicReference<T>();
            final AtomicReference<Exception> exceptionHolder = new AtomicReference<Exception>();
            execWithTaskContext(null, new Runnable() {
                @Override
                public void run() {
                    try {
                        resultHolder.set(work.call());
                    } catch (Exception e) {
                        exceptionHolder.set(e);
                    }
                }
            }, isStatusedTask, runAsId);
            if (exceptionHolder.get() != null) {
                throw exceptionHolder.get();
            }
            return resultHolder.get();
        }
    };
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.IndexCopierTest.java

@Test
public void cowPoolClosedWithTaskInQueue() throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    Directory baseDir = new CloseSafeDir();
    IndexDefinition defn = new IndexDefinition(root, builder.getNodeState());
    IndexCopier copier = new RAMIndexCopier(baseDir, executorService, getWorkDir());

    final Set<String> toPause = Sets.newHashSet();
    final CountDownLatch pauseCopyLatch = new CountDownLatch(1);
    Directory remote = new CloseSafeDir() {
        @Override/*from   w w w  .  j ava 2  s.  co  m*/
        public IndexOutput createOutput(String name, IOContext context) throws IOException {
            if (toPause.contains(name)) {
                try {
                    pauseCopyLatch.await();
                } catch (InterruptedException ignore) {

                }
            }
            return super.createOutput(name, context);
        }
    };

    final Directory local = copier.wrapForWrite(defn, remote, false);
    toPause.add("t2");
    byte[] t1 = writeFile(local, "t1");
    byte[] t2 = writeFile(local, "t2");
    byte[] t3 = writeFile(local, "t3");
    byte[] t4 = writeFile(local, "t4");

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    Thread closer = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                local.close();
            } catch (Throwable e) {
                e.printStackTrace();
                error.set(e);
            }
        }
    });

    closer.start();

    copier.close();
    executorService.shutdown();
    executorService.awaitTermination(100, TimeUnit.MILLISECONDS);

    pauseCopyLatch.countDown();
    closer.join();
    assertNotNull("Close should have thrown an exception", error.get());
}

From source file:org.commoncrawl.service.parser.client.ParserNode.java

public ParseResult dispatchRequest(final ParseRequest request) throws IOException {
    final AtomicReference<ParseResult> result = new AtomicReference<ParseResult>();

    if (_online.get()) {
        //      LOG.info("Dispatching Parse Request for URL:" + request.getDocURL() 
        //          + " to Node:" + _nodeName);  
        final Semaphore requestSemaphore = new Semaphore(0);

        _eventLoop.queueAsyncCallback(new org.commoncrawl.async.Callback() {

            @Override//from w w  w .  ja  v  a 2s .c  o  m
            public void execute() {
                try {
                    _asyncStub.parseDocument(request, new Callback<ParseRequest, ParseResult>() {

                        @Override
                        public void requestComplete(AsyncRequest<ParseRequest, ParseResult> request) {
                            try {
                                //                  LOG.info("Parse Request for URL:" + request.getInput().getDocURL() 
                                //                      + " recvd responseStatus:" + request.getStatus() 
                                //                      + " from Node:" + _nodeName); 

                                if (request.getStatus() == Status.Success) {
                                    result.set(request.getOutput());
                                }
                            } finally {
                                //                  LOG.info("Releasing Request Semaphore for URL:" + request.getInput().getDocURL());
                                requestSemaphore.release();
                            }
                        }
                    });
                } catch (Exception e) {
                    LOG.error(CCStringUtils.stringifyException(e));
                    LOG.info("Releasing Request Semaphore for URL:" + request.getDocURL());
                    requestSemaphore.release();
                }
            }
        });

        //      LOG.info("Waiting on ParseReq Semaphore for URL:"+ request.getDocURL());
        requestSemaphore.acquireUninterruptibly();
        //      LOG.info("ParseReq Semaphore signlaed for URL:"+ request.getDocURL());
    }
    return result.get();
}

From source file:org.apache.openejb.activemq.JMS2AMQTest.java

@Test
public void cdiListenerAPI() throws InterruptedException {
    final String text = TEXT + "4";

    final AtomicReference<Throwable> error = new AtomicReference<>();
    final CountDownLatch ready = new CountDownLatch(1);
    final CountDownLatch over = new CountDownLatch(1);
    new Thread() {
        {/*from  w ww  .ja  va2 s  . c  o  m*/
            setName(JMS2AMQTest.class.getName() + ".cdiListenerAPI#receiver");
        }

        @Override
        public void run() {
            final ContextsService contextsService = WebBeansContext.currentInstance().getContextsService();
            contextsService.startContext(RequestScoped.class, null);
            try {
                final JMSConsumer consumer = context.createConsumer(destination3);
                consumer.setMessageListener(new MessageListener() {
                    @Override
                    public void onMessage(final Message message) {
                        try {
                            assertEquals(text, message.getBody(String.class));
                        } catch (final Throwable e) {
                            error.set(e);
                        } finally {
                            over.countDown();
                            consumer.close();
                        }
                    }
                });
                ready.countDown();
            } catch (final Throwable t) {
                error.set(t);
            } finally {
                try {
                    over.await(1, TimeUnit.MINUTES);
                } catch (final InterruptedException e) {
                    Thread.interrupted();
                }
                contextsService.endContext(RequestScoped.class, null);
            }
        }
    }.start();

    ready.await(1, TimeUnit.MINUTES);

    // now send the message
    try (final JMSContext context = cf.createContext()) {
        context.createProducer().send(destination3, text);
    } catch (final JMSRuntimeException ex) {
        fail(ex.getMessage());
    }

    over.await(1, TimeUnit.MINUTES);

    // ensure we got the message and no exception
    final Throwable exception = error.get();
    if (exception != null) {
        exception.printStackTrace();
    }
    assertNull(exception == null ? "ok" : exception.getMessage(), exception);
}

From source file:TestFuseDFS.java

/**
 * Test concurrent creation and access of the mount
 *//*  w  w  w  .j  av a2s  .  c  o  m*/
@Test
public void testMultipleThreads() throws IOException {
    ArrayList<Thread> threads = new ArrayList<Thread>();
    final AtomicReference<String> errorMessage = new AtomicReference<String>();

    for (int i = 0; i < 10; i++) {
        Thread t = new Thread() {
            public void run() {
                try {
                    File d = new File(mountPoint, "dir" + getId());
                    execWaitRet("mkdir " + d.getAbsolutePath());
                    for (int j = 0; j < 10; j++) {
                        File f = new File(d, "file" + j);
                        final String contents = "thread " + getId() + " " + j;
                        createFile(f, contents);
                    }
                    for (int j = 0; j < 10; j++) {
                        File f = new File(d, "file" + j);
                        execWaitRet("cat " + f.getAbsolutePath());
                        execWaitRet("rm " + f.getAbsolutePath());
                    }
                    execWaitRet("rmdir " + d.getAbsolutePath());
                } catch (IOException ie) {
                    errorMessage.set(String.format("Exception %s", StringUtils.stringifyException(ie)));
                }
            }
        };
        t.start();
        threads.add(t);
    }

    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException ie) {
            fail("Thread interrupted: " + ie.getMessage());
        }
    }

    assertNull(errorMessage.get(), errorMessage.get());
}

From source file:com.vmware.admiral.host.BaseManagementHostClusterIT.java

private <T extends ServiceDocument> T doGet(ServiceHost host, String selfLink, Class<T> type, String token) {
    AtomicReference<T> result = new AtomicReference<>();

    TestContext ctx = testContext();//from www . jav  a  2 s.  c  om

    QueryTask q = QueryUtil.buildPropertyQuery(type, ServiceDocument.FIELD_NAME_SELF_LINK, selfLink);
    QueryUtil.addExpandOption(q);

    host.sendRequest(Operation
            .createGet(UriUtils.buildUri(host, ServiceUriPaths.CORE_DOCUMENT_INDEX,
                    "documentSelfLink=" + selfLink))
            .addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, token).setBody(q).setReferer(host.getUri())
            .setCompletion((o, e) -> {
                if (e != null) {
                    ctx.failIteration(e);
                } else {
                    result.set(o.getBody(type));
                    ctx.completeIteration();
                }
            }));

    ctx.await();

    return result.get();
}