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:com.hardincoding.sonar.subsonic.service.SubsonicMusicService.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);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;//from  w w  w .j av  a 2s .c  om
        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, Util.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);
            }
        }

        try {
            HttpResponse response = mHttpClient.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:de.sainth.recipe.backend.db.repositories.UserRepository.java

public User save(User user) {
    AtomicReference<User> u = new AtomicReference<>();
    create.transaction(configuration -> {
        Long id = using(configuration).select(USERS.ID).from(USERS).where(USERS.NAME.eq(user.getUsername()))
                .forUpdate().fetchOneInto(Long.class);
        UsersRecord record;/*from   ww  w  .  ja v  a 2  s .  c  o m*/
        if (id == null) {
            String encrypted = ScryptPasswordEncoder.sEncode(user.getPassword());
            record = using(configuration)
                    .insertInto(USERS, USERS.NAME, USERS.EMAIL, USERS.PASSWORD, USERS.PERMISSION)
                    .values(user.getUsername(), user.getEmail(), encrypted, user.getPermission()).returning()
                    .fetchOne();
        } else {
            record = using(configuration).update(USERS).set(USERS.EMAIL, user.getEmail())
                    .set(USERS.PERMISSION, user.getPermission()).where(USERS.ID.eq(id)).returning().fetchOne();
        }
        u.set(new User(record.getId(), record.getName(), record.getEmail(), record.getPermission()));
    });

    return u.get();
}

From source file:org.apache.nifi.processors.kite.InferAvroSchema.java

/**
 * Infers the Avro schema from the input Flowfile content. To infer an Avro schema for CSV content a header line is
 * required. You can configure the processor to pull that header line from the first line of the CSV data if it is
 * present OR you can manually supply the desired header line as a property value.
 *
 * @param inputFlowFile/*w  w w  . ja  v a  2  s  .c o  m*/
 *  The original input FlowFile containing the CSV content as it entered this processor.
 *
 * @param context
 *  ProcessContext to pull processor configurations.
 *
 * @param session
 *  ProcessSession to transfer FlowFiles
 */
private String inferAvroSchemaFromCSV(final FlowFile inputFlowFile, final ProcessContext context,
        final ProcessSession session) {

    //Determines the header line either from the property input or the first line of the delimited file.
    final AtomicReference<String> header = new AtomicReference<>();
    final AtomicReference<Boolean> hasHeader = new AtomicReference<>();

    if (context.getProperty(GET_CSV_HEADER_DEFINITION_FROM_INPUT).asBoolean() == Boolean.TRUE) {
        //Read the first line of the file to get the header value.
        session.read(inputFlowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                header.set(br.readLine());
                hasHeader.set(Boolean.TRUE);
                br.close();
            }
        });
        hasHeader.set(Boolean.TRUE);
    } else {
        header.set(context.getProperty(CSV_HEADER_DEFINITION).evaluateAttributeExpressions(inputFlowFile)
                .getValue());
        hasHeader.set(Boolean.FALSE);
    }

    //Prepares the CSVProperties for kite
    CSVProperties props = new CSVProperties.Builder()
            .charset(context.getProperty(CHARSET).evaluateAttributeExpressions(inputFlowFile).getValue())
            .delimiter(context.getProperty(DELIMITER).evaluateAttributeExpressions(inputFlowFile).getValue())
            .quote(context.getProperty(QUOTE_STRING).evaluateAttributeExpressions(inputFlowFile).getValue())
            .escape(context.getProperty(ESCAPE_STRING).evaluateAttributeExpressions(inputFlowFile).getValue())
            .linesToSkip(context.getProperty(HEADER_LINE_SKIP_COUNT).evaluateAttributeExpressions(inputFlowFile)
                    .asInteger())
            .header(header.get()).hasHeader(hasHeader.get()).build();

    final AtomicReference<String> avroSchema = new AtomicReference<>();

    session.read(inputFlowFile, new InputStreamCallback() {
        @Override
        public void process(InputStream in) throws IOException {
            avroSchema.set(CSVUtil
                    .inferSchema(context.getProperty(RECORD_NAME).evaluateAttributeExpressions(inputFlowFile)
                            .getValue(), in, props)
                    .toString(context.getProperty(PRETTY_AVRO_OUTPUT).asBoolean()));
        }
    });

    return avroSchema.get();
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void test2Clients() throws Exception {
    CuratorFramework client1 = null;//from w ww .  ja  v a2s . c o m
    CuratorFramework client2 = null;
    try {
        client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client1.start();
        client2.start();

        final InterProcessLock mutexForClient1 = makeLock(client1);
        final InterProcessLock mutexForClient2 = makeLock(client2);

        final CountDownLatch latchForClient1 = new CountDownLatch(1);
        final CountDownLatch latchForClient2 = new CountDownLatch(1);
        final CountDownLatch acquiredLatchForClient1 = new CountDownLatch(1);
        final CountDownLatch acquiredLatchForClient2 = new CountDownLatch(1);

        final AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>();

        ExecutorService service = Executors.newCachedThreadPool();
        Future<Object> future1 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    mutexForClient1.acquire(10, TimeUnit.SECONDS);
                    acquiredLatchForClient1.countDown();
                    latchForClient1.await(10, TimeUnit.SECONDS);
                    mutexForClient1.release();
                } catch (Exception e) {
                    exceptionRef.set(e);
                }
                return null;
            }
        });
        Future<Object> future2 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    mutexForClient2.acquire(10, TimeUnit.SECONDS);
                    acquiredLatchForClient2.countDown();
                    latchForClient2.await(10, TimeUnit.SECONDS);
                    mutexForClient2.release();
                } catch (Exception e) {
                    exceptionRef.set(e);
                }
                return null;
            }
        });

        while (!mutexForClient1.isAcquiredInThisProcess() && !mutexForClient2.isAcquiredInThisProcess()) {
            Thread.sleep(1000);
            Assert.assertFalse(future1.isDone() && future2.isDone());
        }

        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess());
        Thread.sleep(1000);
        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() || mutexForClient2.isAcquiredInThisProcess());
        Assert.assertTrue(
                mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess());

        Exception exception = exceptionRef.get();
        if (exception != null) {
            throw exception;
        }

        if (mutexForClient1.isAcquiredInThisProcess()) {
            latchForClient1.countDown();
            Assert.assertTrue(acquiredLatchForClient2.await(10, TimeUnit.SECONDS));
            Assert.assertTrue(mutexForClient2.isAcquiredInThisProcess());
        } else {
            latchForClient2.countDown();
            Assert.assertTrue(acquiredLatchForClient1.await(10, TimeUnit.SECONDS));
            Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess());
        }
    } finally {
        IOUtils.closeQuietly(client1);
        IOUtils.closeQuietly(client2);
    }
}

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;/*from  ww w  . j  av a2 s .co  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: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//ww  w.  j  a  v  a 2  s  . c om
 */
/*  @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:org.springframework.cloud.sleuth.instrument.web.client.TraceWebClientAutoConfiguration.java

Mono<HttpClientResponse> wrapHttpClientRequestSending(ProceedingJoinPoint pjp,
        BiFunction<? super HttpClientRequest, ? super NettyOutbound, ? extends Publisher<Void>> function)
        throws Throwable {
    // add headers and set CS
    final Span currentSpan = this.tracer.currentSpan();
    final AtomicReference<Span> span = new AtomicReference<>();
    BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> combinedFunction = (req, nettyOutbound) -> {
        try (Tracer.SpanInScope spanInScope = this.tracer.withSpanInScope(currentSpan)) {
            io.netty.handler.codec.http.HttpHeaders originalHeaders = req.requestHeaders().copy();
            io.netty.handler.codec.http.HttpHeaders tracedHeaders = req.requestHeaders();
            span.set(this.handler.handleSend(this.injector, tracedHeaders, req));
            if (log.isDebugEnabled()) {
                log.debug("Handled send of " + span.get());
            }/*from   www  .  j  av  a2  s. co m*/
            io.netty.handler.codec.http.HttpHeaders addedHeaders = tracedHeaders.copy();
            originalHeaders.forEach(header -> addedHeaders.remove(header.getKey()));
            try (Tracer.SpanInScope clientInScope = this.tracer.withSpanInScope(span.get())) {
                if (log.isDebugEnabled()) {
                    log.debug("Created a new client span for Netty client");
                }
                return handle(function, new TracedHttpClientRequest(req, addedHeaders), nettyOutbound);
            }
        }
    };
    // run
    Mono<HttpClientResponse> responseMono = (Mono<HttpClientResponse>) pjp
            .proceed(new Object[] { combinedFunction });
    // get response
    return responseMono.doOnSuccessOrError((httpClientResponse, throwable) -> {
        try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.get())) {
            // status codes and CR
            if (span.get() != null) {
                this.handler.handleReceive(httpClientResponse, throwable, span.get());
                if (log.isDebugEnabled()) {
                    log.debug("Setting client sent spans");
                }
            }
        }
    });
}

From source file:org.apache.hadoop.hdfs.TestMultiThreadedHflush.java

/**
 * Test case where a bunch of threads are continuously calling hflush() while another
 * thread appends some data and then closes the file.
 *
 * The hflushing threads should eventually catch an IOException stating that the stream
 * was closed -- and not an NPE or anything like that.
 *//*from   www . j av  a 2 s  .  c  om*/
@Test
public void testHflushWhileClosing() throws Throwable {
    Configuration conf = new Configuration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
    FileSystem fs = cluster.getFileSystem();
    Path p = new Path("/hflush-and-close.dat");

    final FSDataOutputStream stm = createFile(fs, p, 1);

    ArrayList<Thread> flushers = new ArrayList<Thread>();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    try {
        for (int i = 0; i < 10; i++) {
            Thread flusher = new Thread() {
                public void run() {
                    try {
                        while (true) {
                            try {
                                stm.hflush();
                            } catch (IOException ioe) {
                                if (!ioe.toString().contains("DFSOutputStream is closed")) {
                                    throw ioe;
                                } else {
                                    return;
                                }
                            }
                        }
                    } catch (Throwable t) {
                        thrown.set(t);
                    }
                }
            };
            flusher.start();
            flushers.add(flusher);
        }

        // Write some data
        for (int i = 0; i < 10000; i++) {
            stm.write(1);
        }

        // Close it while the flushing threads are still flushing
        stm.close();

        // Wait for the flushers to all die.
        for (Thread t : flushers) {
            t.join();
        }

        // They should have all gotten the expected exception, not anything
        // else.
        if (thrown.get() != null) {
            throw thrown.get();
        }

    } finally {
        fs.close();
        cluster.shutdown();
    }
}

From source file:net.java.sip.communicator.impl.googlecontacts.OAuth2TokenStore.java

/**
 * Acquire a new credential instance.//  w  w  w  .  j  a  v a  2 s. c  o m
 *
 * @param store credential store to update upon refreshing and other
 *            operations
 * @param identity the identity to which the refresh token belongs
 * @return Acquires and returns the credential instance.
 * @throws URISyntaxException In case of bad redirect URI.
 * @throws IOException 
 * @throws ClientProtocolException 
 */
private static void acquireCredential(final AtomicReference<Credential> store, final String identity)
        throws URISyntaxException, ClientProtocolException, IOException {
    final TokenData token;
    String refreshToken = restoreRefreshToken(identity);
    if (refreshToken == null) {
        LOGGER.info("No credentials available yet. Requesting user to "
                + "approve access to Contacts API for identity " + identity + " using URL: " + APPROVAL_URL);
        final OAuthApprovalDialog dialog = new OAuthApprovalDialog(identity);
        // Synchronize on OAuth approval dialog CLASS, to ensure that only
        // one dialog shows at a time.
        synchronized (OAuthApprovalDialog.class) {
            dialog.setVisible(true);
        }
        switch (dialog.getResponse()) {
        case CONFIRMED:
            // dialog is confirmed, so process entered approval code
            final String approvalCode = dialog.getApprovalCode();
            LOGGER.debug("Approval code from user: " + approvalCode);
            token = requestAuthenticationToken(approvalCode);
            saveRefreshToken(token, identity);
            break;
        case CANCELLED:
        default:
            // user one time cancellation
            // let token remain null, as we do not have new information
            // yet
            token = null;
            break;
        }
    } else {
        token = new TokenData(null, refreshToken, 0);
    }
    store.set(createCredential(store, token));
}

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);/*from  w ww.  ja v  a2 s. c  om*/
    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;
}