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

Source Link

Document

Creates a new AtomicReference with null initial value.

Usage

From source file:com.networknt.security.JwtVerifyHandlerTest.java

@Test
public void testUnmatchedScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//  ww  w  .  j a  va2 s . co m
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet/111").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiTVJiZHdlQ295eG13a2ZUM3lVWGloQSIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6ImVyaWMiLCJ1c2VyX3R5cGUiOiJFTVBMT1lFRSIsImNsaWVudF9pZCI6ImY3ZDQyMzQ4LWM2NDctNGVmYi1hNTJkLTRjNTc4NzQyMWU3MiIsInNjb3BlIjpbIkFUTVAxMDAwLnciLCJBVE1QMTAwMC5yIl19.VOEggO6UIMHNJLrxShGivCh7sGyHiz7h9FqDjlKwywGP9xKbVTTODy2-FitUaS1Y2vjiHlJ0TNyxmj1SO11YwYnJlW1zn-6vfKWKI70DyvRwsvSX_8Z2fj0jPUiBqezwKRtLCHSsmiEpMrW6YQHYw0qzZ9kkMhiH2uFpZNCekOQWL1piRn1xVQkUmeFiTDvJQESHadFzw-9x0klO7-SxgKeHHDroxnpbLv2j795oMTB1gM_wJP6HO_M-gK6N1Uh6zssfnbyFReRNWkhZFOp3Y8DvwpfKhqXIVGUc_5WsO9M-y66icClVNl5zwLSmjsrNtqZkmeBCwQ6skBnRLfMocQ");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(403, statusCode);
    if (statusCode == 403) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10005", status.getCode());
    }
}

From source file:com.fiadot.springjsoncrypt.json.CryptMappingJacson2HttpMessageConverter.java

@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
    JavaType javaType = getJavaType(type, contextClass);
    if (!jackson23Available || !logger.isWarnEnabled()) {
        return (this.objectMapper.canDeserialize(javaType) && canRead(mediaType));
    }// w w  w  .j a  v  a  2 s  .co  m
    AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    if (this.objectMapper.canDeserialize(javaType) && canRead(mediaType)) {
        return true;
    }
    Throwable cause = causeRef.get();
    if (cause != null) {
        String msg = "Failed to evaluate deserialization for type " + javaType;
        if (logger.isDebugEnabled()) {
            logger.warn(msg, cause);
        } else {
            logger.warn(msg + ": " + cause);
        }
    }
    return false;
}

From source file:com.sysunite.nifi.StringSplit.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    //position 4/*from  w  w w . ja v a2  s  .  com*/

    FlowFile flowFile = session.get();

    if (flowFile == null) {
        return;
    }

    int totalDynamicRelations = this.getRelationships().size();

    System.out.println("rels= " + totalDynamicRelations);

    //-------reading
    final AtomicReference<String> flowFileContentStore = new AtomicReference<>();

    session.read(flowFile, new InputStreamCallback() {

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

            System.out.println("read");

            try {

                String flowFileContent = IOUtils.toString(inputStream);
                flowFileContentStore.set(flowFileContent);

            } catch (Exception e) {

            }

        }
    });

    //-------using en editing
    try {

        //get contents
        String flowFileContent = flowFileContentStore.get();

        //split contents by delimiter
        String regexForSplit = context.getProperty(SPLIT).getValue();
        String[] splittedFlowFileContents = flowFileContent.split(regexForSplit);

        //count splits
        int totalSplits = splittedFlowFileContents.length;

        System.out.println("split= " + totalSplits);

        //get list of dynamic props
        final Map<Relationship, PropertyValue> propMap = this.propertyMap;

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

            final PropertyValue value = entry.getValue();
            String oriValue = value.getValue();

            //use only splits not empty
            if (oriValue != null) {

                try {

                    int partFromSplittedFlowFileContents = Integer.parseInt(oriValue);

                    //parts only in range are allowed
                    if (partFromSplittedFlowFileContents < totalSplits) {

                        String splittedPart = splittedFlowFileContents[partFromSplittedFlowFileContents];

                        String relationName = entry.getKey().getName();

                        System.out.println("relationship (" + relationName + ") -> " + splittedPart);

                        //now we can tranfer splitted part to the relation

                        FlowFile fNew = session.clone(flowFile);
                        fNew = session.putAttribute(fNew, relationName, splittedPart);
                        session.transfer(fNew, entry.getKey());

                    }

                } catch (Exception e) {

                }

            }

        }

    } catch (Exception e) {

    }

    session.transfer(flowFile, ORIGINAL);

}

From source file:it.anyplace.sync.bep.BlockPusher.java

public FileUploadObserver pushFile(final DataSource dataSource, @Nullable FileInfo fileInfo,
        final String folder, final String path) {
    checkArgument(connectionHandler.hasFolder(folder),
            "supplied connection handler %s will not share folder %s", connectionHandler, folder);
    checkArgument(fileInfo == null || equal(fileInfo.getFolder(), folder));
    checkArgument(fileInfo == null || equal(fileInfo.getPath(), path));
    try {/*  w w  w. j  av  a  2  s . c  om*/
        final ExecutorService monitoringProcessExecutorService = Executors.newCachedThreadPool();
        final long fileSize = dataSource.getSize();
        final Set<String> sentBlocks = Sets.newConcurrentHashSet();
        final AtomicReference<Exception> uploadError = new AtomicReference<>();
        final AtomicBoolean isCompleted = new AtomicBoolean(false);
        final Object updateLock = new Object();
        final Object listener = new Object() {
            @Subscribe
            public void handleRequestMessageReceivedEvent(RequestMessageReceivedEvent event) {
                BlockExchageProtos.Request request = event.getMessage();
                if (equal(request.getFolder(), folder) && equal(request.getName(), path)) {
                    try {
                        final String hash = BaseEncoding.base16().encode(request.getHash().toByteArray());
                        logger.debug("handling block request = {}:{}-{} ({})", request.getName(),
                                request.getOffset(), request.getSize(), hash);
                        byte[] data = dataSource.getBlock(request.getOffset(), request.getSize(), hash);
                        checkNotNull(data, "data not found for hash = %s", hash);
                        final Future future = connectionHandler.sendMessage(
                                Response.newBuilder().setCode(BlockExchageProtos.ErrorCode.NO_ERROR)
                                        .setData(ByteString.copyFrom(data)).setId(request.getId()).build());
                        monitoringProcessExecutorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    future.get();
                                    sentBlocks.add(hash);
                                    synchronized (updateLock) {
                                        updateLock.notifyAll();
                                    }
                                    //TODO retry on error, register error and throw on watcher
                                } catch (InterruptedException ex) {
                                    //return and do nothing
                                } catch (ExecutionException ex) {
                                    uploadError.set(ex);
                                    synchronized (updateLock) {
                                        updateLock.notifyAll();
                                    }
                                }
                            }
                        });
                    } catch (Exception ex) {
                        logger.error("error handling block request", ex);
                        connectionHandler.sendMessage(Response.newBuilder()
                                .setCode(BlockExchageProtos.ErrorCode.GENERIC).setId(request.getId()).build());
                        uploadError.set(ex);
                        synchronized (updateLock) {
                            updateLock.notifyAll();
                        }
                    }
                }
            }
        };
        connectionHandler.getEventBus().register(listener);
        logger.debug("send index update for file = {}", path);
        final Object indexListener = new Object() {

            @Subscribe
            public void handleIndexRecordAquiredEvent(IndexHandler.IndexRecordAquiredEvent event) {
                if (equal(event.getFolder(), folder)) {
                    for (FileInfo fileInfo : event.getNewRecords()) {
                        if (equal(fileInfo.getPath(), path)
                                && equal(fileInfo.getHash(), dataSource.getHash())) { //TODO check not invalid
                            //                                sentBlocks.addAll(dataSource.getHashes());
                            isCompleted.set(true);
                            synchronized (updateLock) {
                                updateLock.notifyAll();
                            }
                        }
                    }
                }
            }
        };
        if (indexHandler != null) {
            indexHandler.getEventBus().register(indexListener);
        }
        final IndexUpdate indexUpdate = sendIndexUpdate(folder,
                BlockExchageProtos.FileInfo.newBuilder().setName(path).setSize(fileSize)
                        .setType(BlockExchageProtos.FileInfoType.FILE).addAllBlocks(dataSource.getBlocks()),
                fileInfo == null ? null : fileInfo.getVersionList()).getRight();
        final FileUploadObserver messageUploadObserver = new FileUploadObserver() {
            @Override
            public void close() {
                logger.debug("closing upload process");
                try {
                    connectionHandler.getEventBus().unregister(listener);
                    monitoringProcessExecutorService.shutdown();
                    if (indexHandler != null) {
                        indexHandler.getEventBus().unregister(indexListener);
                    }
                } catch (Exception ex) {
                }
                if (closeConnection && connectionHandler != null) {
                    connectionHandler.close();
                }
                if (indexHandler != null) {
                    FileInfo fileInfo = indexHandler.pushRecord(indexUpdate.getFolder(),
                            Iterables.getOnlyElement(indexUpdate.getFilesList()));
                    logger.info("sent file info record = {}", fileInfo);
                }
            }

            @Override
            public double getProgress() {
                return isCompleted() ? 1d : sentBlocks.size() / ((double) dataSource.getHashes().size());
            }

            @Override
            public String getProgressMessage() {
                return (Math.round(getProgress() * 1000d) / 10d) + "% " + sentBlocks.size() + "/"
                        + dataSource.getHashes().size();
            }

            @Override
            public boolean isCompleted() {
                //                    return sentBlocks.size() == dataSource.getHashes().size();
                return isCompleted.get();
            }

            @Override
            public double waitForProgressUpdate() throws InterruptedException {
                synchronized (updateLock) {
                    updateLock.wait();
                }
                if (uploadError.get() != null) {
                    throw new RuntimeException(uploadError.get());
                }
                return getProgress();
            }

            @Override
            public DataSource getDataSource() {
                return dataSource;
            }

        };
        return messageUploadObserver;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testMissingToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from ww  w  .jav a  2s .  com
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(401, statusCode);
    if (statusCode == 401) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10002", status.getCode());
    }
}

From source file:com.foglyn.fogbugz.FogBugzClient.java

/**
 * //w w  w . java2  s .c om
 * @param repositoryLocation
 * @param httpClient
 * @param fogbugzApiURL
 *            URL where FogBugz API is accessible, e.g.
 *            <code>https://.../api.asp?</code>. This must end with ? or
 *            &amp; because more query parameters are appended to this
 *            string when performing commands.
 * @param apiVersion version of remote API
 * @param minVersion minimum compatible version of API
 */
FogBugzClient(AbstractWebLocation repositoryLocation, HttpClient httpClient, String fogbugzApiURL,
        int apiVersion) {
    this.log = Logging.getLogger("client.url" + "@" + repositoryLocation.getUrl());

    this.tokenLock = new Object();

    this.request = new Request(httpClient, repositoryLocation);
    this.fogbugzBaseApiURL = fogbugzApiURL;
    this.apiVersion = apiVersion;

    setToken(null);

    this.data = new AtomicReference<FogBugzData>();
    this.data.set(new FogBugzData.FogBugzDataBuilder().build());
}

From source file:com.wk.lodge.composite.web.tomcat.IntegrationCompositeTests.java

@Test
public void testInit() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    URI uri = new URI("ws://localhost:" + port + "/composite");
    WebSocketStompClient stompClient = new WebSocketStompClient(uri, this.headers, sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    stompClient.connect(new StompMessageHandler() {

        private StompSession stompSession;

        @Override//from  www  . ja va  2  s  . c  o  m
        public void afterConnected(StompSession stompSession, StompHeaderAccessor headers) {
            this.stompSession = stompSession;
            this.stompSession.subscribe("/user/queue/device", null);

            try {
                this.stompSession.send("/app/init", "");
            } catch (Throwable t) {
                failure.set(t);
                latch.countDown();
            }
        }

        @Override
        public void handleMessage(Message<byte[]> message) {
            StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
            if (!"/user/queue/device".equals(headers.getDestination())) {
                failure.set(new IllegalStateException("Unexpected message: " + message));
            }
            logger.debug("Got " + new String((byte[]) message.getPayload()));
            try {
                String json = parseMessageJson(message);
                new JsonPathExpectationsHelper("type").assertValue(json, "init");
                new JsonPathExpectationsHelper("uuid").exists(json);
            } catch (Throwable t) {
                failure.set(t);
            } finally {
                this.stompSession.disconnect();
                latch.countDown();
            }
        }

        @Override
        public void handleError(Message<byte[]> message) {
            StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
            String error = "[Producer] " + accessor.getShortLogMessage(message.getPayload());
            logger.error(error);
            failure.set(new Exception(error));
        }

        @Override
        public void handleReceipt(String receiptId) {
        }

        @Override
        public void afterDisconnected() {
        }
    });

    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("Init response not received");
    } else if (failure.get() != null) {
        throw new AssertionError("", failure.get());
    }
}

From source file:io.syndesis.jsondb.impl.SqlJsonDB.java

@Override
public Set<String> fetchIdsByPropertyValue(final String collectionPath, final String property,
        final String value) {
    final String pathRegex = collectionPath + "/:[^/]+/" + property;

    final AtomicReference<Set<String>> ret = new AtomicReference<>();
    withTransaction(dbi -> {/*from   ww  w .  j av  a 2s . co m*/
        final String query;
        if (databaseKind == DatabaseKind.PostgreSQL) {
            query = "SELECT regexp_replace(path, '(/.+/:[^/]+).*', '\\1') from jsondb where path ~ ? and value = ?";
        } else if (databaseKind == DatabaseKind.H2) {
            query = "SELECT regexp_replace(path, '(/.+/:[^/]+).*', '$1') from jsondb where path regexp ? and value = ?";
        } else {
            throw new UnsupportedOperationException(
                    "Don't know how to use regex in a query with database: " + databaseKind);
        }

        final List<String> paths = dbi.createQuery(query).bind(0, pathRegex).bind(1, value)
                .map(StringColumnMapper.INSTANCE).list();

        ret.set(new HashSet<>(paths));
    });

    return ret.get();
}

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentTest.java

@Test
public void testRetryOnConflict() throws InterruptedException {
    final String index = "JresUpdateDocumentTest.testRetryOnConflict".toLowerCase();
    final String type = "test";
    final String id = "warzone";

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

    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    for (int i = 0; i < numThreads; i++) {
        x.submit(new Runnable() {
            @Override/*from ww  w.  j  av  a2s.c o  m*/
            public void run() {
                try {
                    for (int j = 0; j < numIterations; j++) {
                        JresUpdateDocument req = new JresUpdateDocument(index, type, id,
                                ImmutableMap.of("value", 0));
                        req.setRetryOnConflict(numIterations * 10);
                        jres.quest(req);
                    }
                } catch (Exception e) {
                    error.set(e.getMessage());
                }
            }
        });
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    Assert.assertNull("With so many retries, all of these should have gotten through without conflict error",
            error.get());
    jres.quest(new JresRefresh(index));
    JresGetDocumentReply getReply = jres.quest(new JresGetDocument(index, type, id));
    Map<String, Integer> doc = getReply.getSourceAsType(new TypeReference<Map<String, Integer>>() {
    });
    Assert.assertEquals("Should have been numThreads * numIterations versions committed",
            (Object) (numThreads * numIterations), getReply.getVersion());
}

From source file:org.zodiark.publisher.PublisherTest.java

@Test(enabled = false)
public void failedStreamingSession() throws IOException, InterruptedException {

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

    wowzaClient.handler(new OnEnvelopHandler() {
        @Override//  ww  w.  j a  v a2 s.  com
        public boolean onEnvelop(Envelope e) throws IOException {

            Message m = e.getMessage();
            switch (m.getPath()) {
            case WOWZA_CONNECT:
                // Connected. Listen
                uuid.set(e.getUuid());
                break;
            case SERVER_VALIDATE_OK:
                UUID uuid = mapper.readValue(e.getMessage().getData(), UUID.class);
                PublisherResults result = new PublisherResults("error");
                result.setUuid(uuid.getUuid());
                Envelope publisherOk = Envelope.newClientToServerRequest(new Message(
                        new Path(FAILED_PUBLISHER_STREAMING_SESSION), mapper.writeValueAsString(result)));
                wowzaClient.send(publisherOk);
                break;
            default:
                // ERROR
            }

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

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

    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);

    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            latch.countDown();
            return true;
        }
    }).open();

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

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

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

    tlatch.await();

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

}