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:org.zodiark.publisher.PublisherTest.java

@Test(enabled = false)
public void startStreamingSession() 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<>();

    // Fake Wowza Client

    wowzaClient.handler(new OnEnvelopHandler() {
        @Override//from   www.j av a2s. co m
        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:
                Envelope publisherOk = Envelope
                        .newClientToServerRequest(new Message(new Path(""), e.getMessage().getData()));
                wowzaClient.send(publisherOk);
                break;
            default:
                // ERROR
            }

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

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

    // Publisher

    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("OK", answer.get().getResults());

}

From source file:com.sybase365.mobiliser.custom.project.handlers.authentication.GtalkAuthenticationHandler.java

@Override
public void authenticate(final SubTransaction transaction, final String authToken, final boolean payer)
        throws AuthenticationException {

    lazyInit();// ww w .  j  av a  2 s .co m

    final Customer customer;
    final String otherName;
    if (payer) {
        customer = transaction.getTransaction().getPayer();
        otherName = transaction.getTransaction().getPayee().getDisplayName();
    } else {
        customer = transaction.getTransaction().getPayee();
        otherName = transaction.getTransaction().getPayer().getDisplayName();
    }

    final String email = this.notificationLogic.getCustomersEmail(customer, 0).get(0);

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

    final ChatManager chatmanager = this.connection.getChatManager();

    final MessageListener messageListener = new MessageListener() {

        @Override
        public void processMessage(Chat chat, Message message) {
            synchronized (userResponse) {
                LOG.info("got user response: " + message.getBody());
                userResponse.set(message.getBody());
                userResponse.notify();
            }
        }

    };

    final Chat newChat = chatmanager.createChat(email, messageListener);

    try {
        try {
            newChat.sendMessage("Please confirm payment to " + otherName + " by entering yes.");
        } catch (final XMPPException e) {
            LOG.info("can not send message to user " + email + ": " + e.getMessage(), e);

            throw new AuthenticationFailedPermanentlyException(StatusCodes.ERROR_IVR_NO_PICKUP);
        }

        synchronized (userResponse) {
            try {
                userResponse.wait(10000);
            } catch (final InterruptedException e) {
                LOG.info("Interrupted while waiting", e);
                Thread.currentThread().interrupt();
            }
        }

        if (userResponse.get() == null) {
            LOG.info("did not receive a response in time.");

            throw new AuthenticationFailedPermanentlyException("did not receive a response in time.",
                    StatusCodes.ERROR_IVR_NO_USER_INPUT, new HashMap<String, String>());
        }

        if ("yes".equalsIgnoreCase(userResponse.get())) {

            LOG.debug("received confirmation.");

            try {
                newChat.sendMessage("Thank You.");
            } catch (final XMPPException e1) {
                LOG.debug("Thank you Response was not sent. Ignored", e1);
            }

            return;
        }

        LOG.debug("received unknown response: " + userResponse.get());

        try {
            newChat.sendMessage("Transaction will be cancelled.");
        } catch (final XMPPException e2) {
            LOG.debug("Response was not sent. Ignored", e2);
        }

        throw new AuthenticationFailedPermanentlyException(StatusCodes.ERROR_IVR_HANGUP);

    } finally {
        newChat.removeMessageListener(messageListener);
    }

}

From source file:io.soabase.web.filters.LanguageFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        AtomicReference<String> fixedQueryString = new AtomicReference<>();
        String queryStringCode = getFromQueryString(httpRequest.getQueryString(), fixedQueryString);
        String expectedLanguageCode = MoreObjects.firstNonNull(queryStringCode,
                getLanguageCode(null, getCookie(httpRequest)));
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Optional<String> foundCookie = getCookie(httpRequest);
        if (!foundCookie.isPresent() || !foundCookie.get().equals(expectedLanguageCode)) {
            Cookie cookie = new Cookie(cookieName, expectedLanguageCode);
            httpResponse.addCookie(cookie);
        }//from  w w w. j av  a  2  s  . c o m

        if (queryStringCode != null) {
            StringBuffer redirectUrl = httpRequest.getRequestURL();
            if (!fixedQueryString.get().isEmpty()) {
                redirectUrl.append("?").append(fixedQueryString.get());
            }
            ((HttpServletResponse) response).sendRedirect(redirectUrl.toString());
            return;
        }
    }
    chain.doFilter(request, response);
}

From source file:io.lettuce.core.support.ConnectionPoolSupport.java

/**
 * Creates a new {@link GenericObjectPool} using the {@link Supplier}.
 *
 * @param connectionSupplier must not be {@literal null}.
 * @param config 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.//w  w  w  .ja  v a2  s. co  m
 * @return the connection pool.
 */
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
        Supplier<T> connectionSupplier, GenericObjectPoolConfig config, boolean wrapConnections) {

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

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

    GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<T>(connectionSupplier),
            config) {

        @Override
        public T borrowObject() throws Exception {
            return wrapConnections ? ConnectionWrapping.wrapConnection(super.borrowObject(), poolRef.get())
                    : super.borrowObject();
        }

        @Override
        public void returnObject(T obj) {

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

    poolRef.set(new ObjectPoolWrapper<>(pool));

    return pool;
}

From source file:com.sysunite.weaver.nifi.GetXMLNodes.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {

    final FlowFile flowFileIn = session.get();

    if (flowFileIn == null) {
        return;/*from   w ww.  ja va 2  s  .c o m*/
    }

    //System.out.println("i am here!!!");

    final AtomicReference<InputStream> savedNodes = new AtomicReference<>();

    //inlezen van flowFileIn
    session.read(flowFileIn, new InputStreamCallback() {

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

            try {

                String contents = IOUtils.toString(isIn);

                XML xml = new XMLDocument(contents); //"<error>\n<fout a=\"poo\">\n<tiger>Bla</tiger>\n</fout>\n</error>");

                String aPath = context.getProperty(PROP_XPATH).getValue();

                //System.out.println(aPath);

                StringBuffer buffer = new StringBuffer();
                buffer.append("<root>");

                int counter = 0;

                for (XML ibr : xml.nodes(aPath)) {

                    //              if(counter == 3){
                    //               break;
                    //              }

                    buffer.append(ibr.toString());
                    //System.out.println(ibr.toString());

                    //
                    //              FlowFile flowfileOut = session.create();
                    //
                    //        InputStream data = new ByteArrayInputStream(ibr.toString().getBytes());
                    //        flowfileOut = session.importFrom(data, flowfileOut);
                    //
                    //
                    //       session.transfer(flowfileOut, MY_RELATIONSHIP);
                    //      session.commit();

                    //counter++;

                }

                buffer.append("</root>");

                InputStream is = new ByteArrayInputStream(buffer.toString().getBytes()); // geen extra parameters, want dit zorgt voor 'too much output too process'

                savedNodes.set(is);

            } catch (Exception e) {

                System.out.println("??????");
                //System.out.println(e.getMessage());
            }

        }

    });

    session.remove(flowFileIn);

    try {

        String contents = IOUtils.toString(savedNodes.get());

        XML xml = new XMLDocument(contents);

        String aPath = context.getProperty(PROP_XPATH).getValue();
        String parts[] = aPath.split("/");

        int size = parts.length;
        String lastNode = parts[size - 1]; //FunctionalPhysicalObject"

        for (XML node : xml.nodes("root/" + lastNode)) {

            //System.out.println(node.toString());

            FlowFile flowfileOut = session.create();

            InputStream data = new ByteArrayInputStream(node.toString().getBytes());
            flowfileOut = session.importFrom(data, flowfileOut);

            session.transfer(flowfileOut, MY_RELATIONSHIP);
            session.commit();

        }

    } catch (IOException e) {
        System.out.println("w00t");// + e.getMessage());
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
    } catch (FlowFileHandlingException e) {
        System.out.println(e.getMessage());
    }

    //---------------

    //            for (XML ibr : xml.nodes("//fout")) {
    //
    //              System.out.println(ibr.toString());
    //            }

    //            List<XML> nodes = xml.nodes(aPath);
    //
    //            if(nodes.size() == 0){
    //              System.out.println("geen nodes gevonden!!");
    //            }else{
    //
    //
    //              System.out.println("more nodes!!!");
    //
    ////              ListSaver ls = new ListSaver();
    ////
    //              StringBuffer buffer = new StringBuffer();
    //
    //              int counter = 0;
    //              for(;counter<nodes.size();counter++){
    //                XML node = nodes.get(counter);
    ////                ls.add(""+counter, node);
    //                buffer.append(node.node().toString());
    //             }
    //
    //              InputStream isOut = new ByteArrayInputStream(buffer.toString().getBytes());
    //
    //              xpath_nodes.set(isOut);
    //            }

    //      savedNodes.get().
    //      //System.out.println(ibr.toString());
    //      //remove flowFileIn from session otherwise fail to transfer new flowfile
    //      session.remove(flowFileIn);
    //
    //      FlowFile flowfileOut = session.create();
    //////
    //      InputStream data = new ByteArrayInputStream(ibr.toString().getBytes());
    //      flowfileOut = session.importFrom(data, flowfileOut);
    //      session.transfer(flowfileOut, MY_RELATIONSHIP);
    //session.transfer(flowFileIn, MY_RELATIONSHIP);

    //      System.out.println("going to make individual nodes");
    //
    //      //create flow files from every node in xpath_nodes

    //System.out.println(xpath_nodes.toString());
    //
    //      for(XML aNodeXML : nodes.xmlList){
    ////
    //       System.out.println(aNodeXML.toString());
    ////
    ////        //XMLDocument doc = new XMLDocument(aNodeXML.node());
    ////
    ////        //System.out.println(doc.node());
    ////
    ////        //FlowFile flowfileOut = session.create();
    ////
    ////        //InputStream data = new ByteArrayInputStream(doc.node().toString().getBytes());
    ////        //flowfileOut = session.importFrom(data, flowfileOut);
    ////
    ////        //session.transfer(flowfileOut, MY_RELATIONSHIP);
    ////
    //      }

    //session.transfer(flowFileIn, MY_RELATIONSHIP);

}

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

@Test
public void testInvalidRequstPath() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from ww w.  j a  va2  s .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("/api").setMethod(Methods.GET);
        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(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}

From source file:com.jeremydyer.processors.salesforce.GenerateSOQL.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;//w  w  w.java2 s.co m
    }

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

    session.read(flowFile, new InputStreamCallback() {
        @Override
        public void process(InputStream inputStream) throws IOException {
            String jsonString = IOUtils.toString(inputStream);
            JSONObject json = new JSONObject(jsonString);

            JSONArray fields = json.getJSONArray("fields");

            StringBuffer buffer = new StringBuffer();
            buffer.append(context.getProperty(SALESFORCE_SERVER_INSTANCE).evaluateAttributeExpressions(flowFile)
                    .getValue());
            buffer.append("/services/data/v36.0/queryAll/?q=");
            buffer.append("SELECT ");

            //Loops through the fields and builds the SOQL
            for (int i = 0; i < fields.length() - 1; i++) {
                buffer.append(fields.getJSONObject(i).getString("name"));
                buffer.append(",");
            }

            //Append the last field name
            buffer.append(fields.getJSONObject(fields.length() - 1).getString("name"));

            buffer.append(" FROM " + TABLE_NAME);
            buffer.append(" WHERE SYSTEMMODSTAMP > ");
            buffer.append(
                    context.getProperty(LAST_SYNC_TIME).evaluateAttributeExpressions(flowFile).getValue());
            buffer.append(" order by SYSTEMMODSTAMP asc");

            String soql = buffer.toString();
            //Replace all spaces with + as required by Salesforce
            soql = soql.replace(" ", "+");

            query_url.set(soql);
        }
    });

    FlowFile ff = session.putAttribute(flowFile, "SOQL_QUERY_URL", query_url.get());

    session.transfer(ff, REL_SUCCESS);
}

From source file:com.vmware.admiral.adapter.docker.service.SystemImageRetrievalManagerTest.java

@Test
public void testGetFromUserResources() throws Throwable {
    Path testXenonImagesPath = Files.createTempDirectory("test-xenon-images");

    HostInitCommonServiceConfig.startServices(host);
    waitForServiceAvailability(ConfigurationFactoryService.SELF_LINK);
    waitForServiceAvailability(UriUtils.buildUriPath(UriUtils
            .buildUriPath(ConfigurationFactoryService.SELF_LINK, FileUtil.USER_RESOURCES_PATH_VARIABLE)));

    // Set expected configuration
    ConfigurationState config = new ConfigurationState();
    config.documentSelfLink = UriUtils.buildUriPath(ConfigurationFactoryService.SELF_LINK,
            FileUtil.USER_RESOURCES_PATH_VARIABLE);
    config.key = FileUtil.USER_RESOURCES_PATH_VARIABLE;
    config.value = testXenonImagesPath.toAbsolutePath().toString();

    doPost(config, ConfigurationFactoryService.SELF_LINK);

    File imageDir = new File(UriUtils.buildUriPath(testXenonImagesPath.toString(),
            SystemImageRetrievalManager.SYSTEM_IMAGES_PATH));
    imageDir.mkdir();/*w w  w.java2  s.c o m*/

    byte[] content = IOUtils
            .toByteArray(Thread.currentThread().getContextClassLoader().getResourceAsStream(TEST_IMAGE));
    // Basically, rename it so it must be loaded from user resources for sure
    File tmpFile = new File(UriUtils.buildUriPath(imageDir.getAbsolutePath(), TEST_IMAGE_RES));
    tmpFile.createNewFile();
    try (OutputStream os = new FileOutputStream(tmpFile)) {
        os.write(content);
    }

    AdapterRequest req = new AdapterRequest();
    req.resourceReference = host.getUri();

    AtomicReference<byte[]> retrievedImageRef = new AtomicReference<>();

    TestContext ctx = testCreate(1);
    retrievalManager.retrieveAgentImage(TEST_IMAGE_RES, req, (image) -> {
        retrievedImageRef.set(image);
        ctx.completeIteration();
    });

    ctx.await();

    byte[] image = retrievedImageRef.get();
    Assert.assertEquals("Unexpected content", new String(content), new String(image));
}

From source file:com.igormaznitsa.ideamindmap.utils.IdeaUtils.java

@Nullable
public static VirtualFile findKnowledgeFolderForModule(@Nullable final Module module,
        final boolean createIfMissing) {
    final VirtualFile rootFolder = IdeaUtils.findPotentialRootFolderForModule(module);
    final AtomicReference<VirtualFile> result = new AtomicReference<VirtualFile>();
    if (rootFolder != null) {
        result.set(rootFolder.findChild(PROJECT_KNOWLEDGE_FOLDER_NAME));
        if (result.get() == null || !result.get().isDirectory()) {
            if (createIfMissing) {
                CommandProcessor.getInstance().executeCommand(module.getProject(), new Runnable() {
                    @Override/*from   ww  w  .  jav a 2s. c  o m*/
                    public void run() {
                        ApplicationManager.getApplication().runWriteAction(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    result.set(VfsUtil.createDirectoryIfMissing(rootFolder,
                                            PROJECT_KNOWLEDGE_FOLDER_NAME));
                                    LOGGER.info("Created knowledge folder for " + module);
                                } catch (IOException ex) {
                                    LOGGER.error("Can't create knowledge folder for " + module, ex);
                                }
                            }
                        });
                    }
                }, null, null);
            } else {
                result.set(null);
            }
        }
    }
    return result.get();
}