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:it.anyplace.sync.bep.IndexFinder.java

public SearchCompletedEvent doSearch(final String term) throws InterruptedException {
    final Object lock = new Object();
    final AtomicReference<SearchCompletedEvent> reference = new AtomicReference<>();
    final Object eventListener = new Object() {
        @Subscribe//  ww  w. j  a va 2s  . c  o m
        public void handleSearchCompletedEvent(SearchCompletedEvent event) {
            if (equal(event.getQuery(), term)) {
                synchronized (lock) {
                    reference.set(event);
                    lock.notify();
                }
            }
        }
    };
    synchronized (lock) {
        eventBus.register(eventListener);
        submitSearch(term);
        try {
            while (!Thread.currentThread().isInterrupted() && reference.get() == null) {
                lock.wait();
            }
            checkNotNull(reference.get());
            return reference.get();
        } finally {
            eventBus.unregister(eventListener);
        }
    }
}

From source file:com.jeremydyer.nifi.ObjectDetectionProcessor.java

final public Mat detectObjects(final ProcessSession session, FlowFile original, final JSONObject dd,
        final Mat image) {

    CascadeClassifier objectDetector = new CascadeClassifier(dd.getString("opencv_xml_cascade_path"));
    MatOfRect objectDetections = new MatOfRect();
    objectDetector.detectMultiScale(image, objectDetections);
    //getLogger().error("Detected " + objectDetections.toArray().length + " " + dd.getString("name") + " objects in the input flowfile");

    final AtomicReference<Mat> croppedImageReference = new AtomicReference<>();

    int counter = 0;
    for (int i = 0; i < objectDetections.toArray().length; i++) {
        final Rect rect = objectDetections.toArray()[i];
        FlowFile detection = session.write(session.create(original), new OutputStreamCallback() {
            @Override//from   w ww. j  a va 2 s  .  c o m
            public void process(OutputStream outputStream) throws IOException {

                Mat croppedImage = null;

                //Should the image be cropped? If so there is no need to draw bounds because that would be the same as the cropping
                if (dd.getBoolean("crop")) {
                    Rect rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
                    croppedImage = new Mat(image, rectCrop);
                    MatOfByte updatedImage = new MatOfByte();
                    Imgcodecs.imencode(".jpg", croppedImage, updatedImage);
                    croppedImageReference.set(croppedImage);
                    outputStream.write(updatedImage.toArray());
                } else {
                    //Should the image have a border drawn around it?
                    if (dd.getBoolean("drawBounds")) {
                        Mat imageWithBorder = image.clone();
                        Imgproc.rectangle(imageWithBorder, new Point(rect.x, rect.y),
                                new Point(rect.x + rect.width, rect.y + rect.height),
                                new Scalar(255, 255, 255));
                        MatOfByte updatedImage = new MatOfByte();
                        Imgcodecs.imencode(".jpg", imageWithBorder, updatedImage);
                        outputStream.write(updatedImage.toArray());
                    } else {
                        MatOfByte updatedImage = new MatOfByte();
                        Imgcodecs.imencode(".jpg", image, updatedImage);
                        outputStream.write(updatedImage.toArray());
                    }
                }

            }
        });

        Map<String, String> atts = new HashMap<>();
        atts.put("object.detection.name", dd.getString("name"));
        atts.put("object.detection.id", new Long(System.currentTimeMillis() + counter).toString());

        counter++;

        detection = session.putAllAttributes(detection, atts);
        session.transfer(detection, REL_OBJECT_DETECTED);
    }

    Mat childResponse = null;

    if (croppedImageReference.get() != null) {
        childResponse = croppedImageReference.get();
    } else {
        childResponse = image;
    }

    if (dd.has("children")) {
        JSONArray children = dd.getJSONArray("children");
        if (children != null) {

            for (int i = 0; i < children.length(); i++) {
                JSONObject ddd = children.getJSONObject(i);
                childResponse = detectObjects(session, original, ddd, childResponse);
            }
        }
    }

    return childResponse;
}

From source file:com.networknt.openapi.ValidatorHandlerTest.java

@Test
public void testInvalidPost() throws Exception {
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from w  w w  . ja va 2s  .  c o  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);
    }

    try {
        String post = "{\"name\":\"Pinky\", \"photoUrl\": \"http://www.photo.com/1.jpg\"}";
        connection.getIoThread().execute(new Runnable() {
            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                connection.sendRequest(request, client.createClientCallback(reference, latch, post));
            }
        });

        latch.await(10, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}

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  . j a va  2s.  c  o 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:com.lambdaworks.redis.support.ConnectionPoolSupport.java

/**
 * Creates a new {@link SoftReferenceObjectPool} using the {@link Supplier}.
 *
 * @param connectionSupplier must not be {@literal null}.
 * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using
 *        {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the
 *        pool when invoking {@link StatefulConnection#close()}.
 * @param <T> connection type./*from ww  w  .  j  av a2s .com*/
 * @return the connection pool.
 */
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> SoftReferenceObjectPool<T> createSoftReferenceObjectPool(
        Supplier<T> connectionSupplier, boolean wrapConnections) {

    LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");

    AtomicReference<ObjectPool<T>> poolRef = new AtomicReference<>();

    SoftReferenceObjectPool<T> pool = new SoftReferenceObjectPool<T>(
            new RedisPooledObjectFactory<>(connectionSupplier)) {
        @Override
        public synchronized T borrowObject() throws Exception {
            return wrapConnections ? wrapConnection(super.borrowObject(), this) : super.borrowObject();
        }

        @Override
        public synchronized void returnObject(T obj) throws Exception {

            if (wrapConnections && obj instanceof HasTargetConnection) {
                super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                return;
            }
            super.returnObject(obj);
        }
    };
    poolRef.set(pool);

    return pool;
}

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

@Test
public void should_batch_several_entities_async() throws Exception {
    CompleteBean bean = CompleteBeanTestBuilder.builder().randomId().name("name").buid();
    Tweet tweet1 = TweetTestBuilder.tweet().randomId().content("tweet1").buid();
    Tweet tweet2 = TweetTestBuilder.tweet().randomId().content("tweet2").buid();

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    final AtomicReference<Throwable> exceptionSpy = new AtomicReference<>();

    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override// w ww .ja  va 2 s.c o m
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    };

    FutureCallback<Object> errorCallBack = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            exceptionSpy.getAndSet(t);
            latch.countDown();
        }
    };

    // Start batch
    AsyncBatch batch = asyncManager.createBatch();
    batch.startBatch();

    batch.insert(bean);
    batch.insert(tweet1);
    batch.insert(tweet2);
    batch.insert(user);

    CompleteBean foundBean = asyncManager.find(CompleteBean.class, bean.getId()).getImmediately();
    Tweet foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately();
    Tweet foundTweet2 = asyncManager.find(Tweet.class, tweet2.getId()).getImmediately();
    User foundUser = asyncManager.find(User.class, user.getId()).getImmediately();

    assertThat(foundBean).isNull();
    assertThat(foundTweet1).isNull();
    assertThat(foundTweet2).isNull();
    assertThat(foundUser).isNull();

    // Flush
    batch.asyncEndBatch(successCallBack, errorCallBack);

    latch.await();

    final ResultSet resultSet = asyncManager.getNativeSession().execute(
            "SELECT id,favoriteTweets,followers,friends,age_in_years,name,welcomeTweet,label,preferences FROM CompleteBean WHERE id=:id",
            bean.getId());
    assertThat(resultSet.all()).hasSize(1);

    foundBean = asyncManager.find(CompleteBean.class, bean.getId()).getImmediately();
    foundTweet1 = asyncManager.find(Tweet.class, tweet1.getId()).getImmediately();
    foundTweet2 = asyncManager.find(Tweet.class, tweet2.getId()).getImmediately();
    foundUser = asyncManager.find(User.class, user.getId()).getImmediately();

    assertThat(foundBean.getName()).isEqualTo("name");
    assertThat(foundTweet1.getContent()).isEqualTo("tweet1");
    assertThat(foundTweet2.getContent()).isEqualTo("tweet2");
    assertThat(foundUser.getFirstname()).isEqualTo("fn");
    assertThat(foundUser.getLastname()).isEqualTo("ln");
    assertThatBatchContextHasBeenReset(batch);

    assertThat(successSpy.get()).isNotNull().isSameAs(Empty.INSTANCE);
    assertThat(exceptionSpy.get()).isNull();
}

From source file:it.ecubecenter.processors.sentiment.SentimentAnalyzer.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ComponentLog log = getLogger();
    final AtomicReference<String> atomicStringToAnalyze = new AtomicReference<>();

    FlowFile flowFile = session.get();//from  ww w  .j  av a 2 s . c o m
    if (flowFile == null) {
        return;
    }
    String attributeToBeUsed = context.getProperty(ATTRIBUTE_TO_ANALYZE_PROPERTY).getValue();
    if (attributeToBeUsed == null || attributeToBeUsed.equals("")) {
        attributeToBeUsed = "";
        log.info("Start reading the flow file content in order to perform the sentiment analysis.");
        session.read(flowFile, new InputStreamCallback() {

            @Override
            public void process(InputStream in) throws IOException {
                atomicStringToAnalyze.set(IOUtils.toString(in));
            }
        });
    } else {
        log.info("Getting the content of attribute " + attributeToBeUsed
                + "in order to perform the sentiment analysis.");
        atomicStringToAnalyze.set(flowFile.getAttribute(attributeToBeUsed));
    }
    String stringToAnalyze = atomicStringToAnalyze.get();
    if (stringToAnalyze == null || stringToAnalyze.equals("")) {
        log.warn("The attribute to be analyzed doesn't exist or it is empty.");
        session.transfer(flowFile, FAILURE_RELATIONSHIP);
        return;
    }

    SentimentModel model = SentimentModel.getInstance();

    List<double[]> sentiments = model.getSentencesSentiment(stringToAnalyze);
    flowFile = session.putAttribute(flowFile, attributeToBeUsed + ".sentiment.category",
            SentimentModel.getOverallSentiment(sentiments));
    flowFile = session.putAttribute(flowFile, attributeToBeUsed + ".sentiment.sentences.scores",
            stringifyListOfSentiments(sentiments));

    session.transfer(flowFile, SUCCESS_RELATIONSHIP);
}

From source file:io.fabric8.agent.download.DownloadManagerTest.java

private StreamProvider download(DownloadManager manager, String url) throws Exception {
    final AtomicReference<StreamProvider> ref = new AtomicReference<>();
    Downloader downloader = manager.createDownloader();
    downloader.download(url, new DownloadCallback() {
        @Override/*w  w  w .j  ava 2  s .  c  om*/
        public void downloaded(StreamProvider provider) throws Exception {
            synchronized (ref) {
                ref.set(provider);
                ref.notifyAll();
            }
        }
    });
    synchronized (ref) {
        ref.wait(30000);
        return ref.get();
    }
}

From source file:info.archinnov.achilles.embedded.ServerStarter.java

private void start(final TypedMap parameters) {
    if (isAlreadyRunning()) {
        log.debug("Cassandra is already running, not starting new one");
        return;//from  w  ww . ja  v  a 2s  .  c om
    }

    final String triggersDir = createTriggersFolder();

    log.info(" Random embedded Cassandra RPC port/Thrift port = {}",
            parameters.<Integer>getTyped(CASSANDRA_THRIFT_PORT));
    log.info(" Random embedded Cassandra Native port/CQL port = {}",
            parameters.<Integer>getTyped(CASSANDRA_CQL_PORT));
    log.info(" Random embedded Cassandra Storage port = {}",
            parameters.<Integer>getTyped(CASSANDRA_STORAGE_PORT));
    log.info(" Random embedded Cassandra Storage SSL port = {}",
            parameters.<Integer>getTyped(CASSANDRA_STORAGE_SSL_PORT));
    log.info(" Random embedded Cassandra Remote JMX port = {}",
            System.getProperty("com.sun.management.jmxremote.port", "null"));
    log.info(" Embedded Cassandra triggers directory = {}", triggersDir);

    log.info("Starting Cassandra...");

    System.setProperty("cassandra.triggers_dir", triggersDir);
    System.setProperty("cassandra-foreground", "true");
    System.setProperty("cassandra.embedded.concurrent.reads",
            parameters.getTypedOr(CASSANDRA_CONCURRENT_READS, 32).toString());
    System.setProperty("cassandra.embedded.concurrent.writes",
            parameters.getTypedOr(CASSANDRA_CONCURRENT_WRITES, 32).toString());
    System.setProperty("cassandra-foreground", "true");

    final boolean useUnsafeCassandra = parameters.getTyped(USE_UNSAFE_CASSANDRA_DAEMON);

    if (useUnsafeCassandra) {
        System.setProperty("cassandra-num-tokens", "1");
    }

    System.setProperty("cassandra.config.loader", "info.archinnov.achilles.embedded.AchillesCassandraConfig");

    final CountDownLatch startupLatch = new CountDownLatch(1);
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final AtomicReference<CassandraDaemon> daemonRef = new AtomicReference<>();
    executor.execute(() -> {
        if (useUnsafeCassandra) {
            LOGGER.warn(
                    "******* WARNING, starting unsafe embedded Cassandra deamon. This should be only used for unit testing or development and not for production !");
        }

        CassandraDaemon cassandraDaemon = useUnsafeCassandra == true ? new AchillesCassandraDaemon()
                : new CassandraDaemon();

        cassandraDaemon.completeSetup();
        cassandraDaemon.activate();
        daemonRef.getAndSet(cassandraDaemon);
        startupLatch.countDown();
    });

    try {
        startupLatch.await(30, SECONDS);
    } catch (InterruptedException e) {
        log.error("Timeout starting Cassandra embedded", e);
        throw new IllegalStateException("Timeout starting Cassandra embedded", e);
    }

    // Generate an OrderedShutdownHook to shutdown all connections from java clients before closing the server
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            log.info("Calling stop on Embedded Cassandra server");
            daemonRef.get().stop();

            log.info("Calling shutdown on all Cluster instances");
            // First call shutdown on all registered Java driver Cluster instances
            orderedShutdownHook.callShutDown();

            log.info("Shutting down embedded Cassandra server");
            // Then shutdown the server
            executor.shutdownNow();
        }
    });
}

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

@Test
public void testUnmatchedScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from   ww w .  ja  v  a 2s  .c  om
        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("/v1/pets/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());
    }
}