Example usage for java.util.concurrent ArrayBlockingQueue take

List of usage examples for java.util.concurrent ArrayBlockingQueue take

Introduction

In this page you can find the example usage for java.util.concurrent ArrayBlockingQueue take.

Prototype

public E take() throws InterruptedException 

Source Link

Usage

From source file:io.teak.sdk.TeakNotification.java

/**
 * Cancel a push notification that was scheduled with {@link TeakNotification#scheduleNotification(String, String, long)}
 *
 * @param scheduleId//from w  w w .j  a  v  a 2  s  . com
 * @return
 */
@SuppressWarnings("unused")
public static FutureTask<String> cancelNotification(final String scheduleId) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring cancelNotification().");
        return null;
    }

    if (scheduleId == null || scheduleId.isEmpty()) {
        Log.e(LOG_TAG, "scheduleId cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("id", scheduleId);

            new Request("/me/cancel_local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }
                    ret.run();
                }
            }.run();
        }
    });

    return ret;
}

From source file:io.teak.sdk.TeakNotification.java

/**
 * Schedules a push notification for some time in the future.
 *
 * @param creativeId     The identifier of the notification in the Teak dashboard (will create if not found).
 * @param defaultMessage The default message to send, may be over-ridden in the dashboard.
 * @param delayInSeconds The delay in seconds from now to send the notification.
 * @return The identifier of the scheduled notification (see {@link TeakNotification#cancelNotification(String)} or null.
 */// www.j  a v  a  2 s  .  co  m
@SuppressWarnings("unused")
public static FutureTask<String> scheduleNotification(final String creativeId, final String defaultMessage,
        final long delayInSeconds) {
    if (!Teak.isEnabled()) {
        Log.e(LOG_TAG, "Teak is disabled, ignoring scheduleNotification().");
        return null;
    }

    if (creativeId == null || creativeId.isEmpty()) {
        Log.e(LOG_TAG, "creativeId cannot be null or empty");
        return null;
    }

    if (defaultMessage == null || defaultMessage.isEmpty()) {
        Log.e(LOG_TAG, "defaultMessage cannot be null or empty");
        return null;
    }

    final ArrayBlockingQueue<String> q = new ArrayBlockingQueue<>(1);
    final FutureTask<String> ret = new FutureTask<>(new Callable<String>() {
        public String call() {
            try {
                return q.take();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            }
            return null;
        }
    });

    Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
        @Override
        public void run(Session session) {
            HashMap<String, Object> payload = new HashMap<>();
            payload.put("identifier", creativeId);
            payload.put("message", defaultMessage);
            payload.put("offset", delayInSeconds);

            new Request("/me/local_notify.json", payload, session) {
                @Override
                protected void done(int responseCode, String responseBody) {
                    try {
                        JSONObject response = new JSONObject(responseBody);
                        if (response.getString("status").equals("ok")) {
                            q.offer(response.getJSONObject("event").getString("id"));
                        } else {
                            q.offer("");
                        }
                    } catch (Exception ignored) {
                        q.offer("");
                    }

                    ret.run();
                }
            }.run();
        }
    });
    return ret;
}

From source file:org.apache.nifi.processors.standard.util.TestPutTCPCommon.java

private void checkReceivedAllData(final ArrayBlockingQueue<List<Byte>> recvQueue, final String[] sentData,
        final int iterations) throws Exception {
    // check each sent FlowFile was successfully sent and received.
    for (int i = 0; i < iterations; i++) {
        for (String item : sentData) {
            List<Byte> message = recvQueue.take();
            assertNotNull(message);//from w  w w  .j a  v  a 2  s . c o m
            Byte[] messageBytes = new Byte[message.size()];
            assertArrayEquals(item.getBytes(), ArrayUtils.toPrimitive(message.toArray(messageBytes)));
        }
    }

    runner.assertTransferCount(PutTCP.REL_SUCCESS, sentData.length * iterations);
    runner.clearTransferState();

    // Check that we have no unexpected extra data.
    assertNull(recvQueue.poll());
}

From source file:com.simplymeasured.prognosticator.HiveJDBCQueryImpl.java

@Override
public Iterator<Map<String, Object>> runQuery(String resultTable, String queryStatement,
        Map<String, Object> parameters) {
    final ArrayBlockingQueue<Map<String, Object>> rowQueue = new ArrayBlockingQueue<Map<String, Object>>(1000);

    ThreadedQueryRunnable runnable = new ThreadedQueryRunnable(dataSource, queryStatement, parameters,
            rowQueue);/* w w w.  j a va 2 s.  c o  m*/

    executorService.submit(runnable);

    return new Iterator<Map<String, Object>>() {
        private boolean done = false;
        private Map<String, Object> cachedRow = null;
        private final Map<String, Object> emptyMap = Collections.emptyMap();

        @Override
        public boolean hasNext() {
            try {
                if (done)
                    return false;

                cachedRow = rowQueue.take();

                if (cachedRow == null || cachedRow == emptyMap) {
                    done = true;
                    return false;
                }

                return true;
            } catch (InterruptedException ie) {
                throw new RuntimeException("Iterator thread killed!", ie);
            }
        }

        @Override
        public Map<String, Object> next() {
            if (done || cachedRow == emptyMap) {
                throw new IllegalStateException("End of iterator reached");
            } else if (cachedRow == null) {
                boolean hasMore = hasNext();

                if (!hasMore) {
                    done = true;
                    throw new IllegalStateException("End of iterator reached");
                }
            }

            return cachedRow;
        }

        @Override
        public void remove() {
            // intentionally non-op
        }
    };
}

From source file:com.esri.geoevent.clusterSimulator.ui.CertificateCheckerDialog.java

@Override
public boolean allowConnection(final X509Certificate[] chain) {
    if (trustedCerts.contains(chain[0])) {
        return true;
    }//from  w  w w  . j  a  va2 s  . co m
    final ArrayBlockingQueue<Boolean> responseQueue = new ArrayBlockingQueue<Boolean>(1);
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                final Stage dialog = new Stage();
                dialog.initModality(Modality.APPLICATION_MODAL);
                dialog.initOwner(MainApplication.primaryStage);
                dialog.setTitle("Certificate Check");
                FXMLLoader loader = new FXMLLoader(getClass().getResource("CertificateCheckerDialog.fxml"));
                Parent parent = (Parent) loader.load();
                CertCheckController controller = (CertCheckController) loader.getController();
                controller.certText.setText(chain[0].toString());
                Scene scene = new Scene(parent);
                dialog.setScene(scene);
                dialog.showAndWait();
                responseQueue.put(Boolean.valueOf(controller.allowConnection));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
    if (Platform.isFxApplicationThread()) {
        runnable.run();
    } else {
        Platform.runLater(runnable);
    }

    try {
        boolean retVal = responseQueue.take();
        if (retVal) {
            trustedCerts.add(chain[0]);
        }
        return retVal;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.twofortyfouram.locale.sdk.host.test.Junit4SupportLoaderTestCase.java

/**
 * Runs a Loader synchronously and returns the result of the load. The loader will
 * be started, stopped, and destroyed by this method so it cannot be reused.
 *
 * @param loader The loader to run synchronously
 * @return The result from the loader//from  w  ww.j a  v  a  2  s. c  o  m
 */
public <T> T getLoaderResultSynchronously(final Loader<T> loader) {
    // The test thread blocks on this queue until the loader puts it's result in
    final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);

    // This callback runs on the "main" thread and unblocks the test thread
    // when it puts the result into the blocking queue
    final Loader.OnLoadCompleteListener<T> listener = new Loader.OnLoadCompleteListener<T>() {
        @Override
        public void onLoadComplete(Loader<T> completedLoader, T data) {
            // Shut the loader down
            completedLoader.unregisterListener(this);
            completedLoader.stopLoading();
            completedLoader.reset();

            // Store the result, unblocking the test thread
            queue.add(data);
        }
    };

    // This handler runs on the "main" thread of the process since AsyncTask
    // is documented as needing to run on the main thread and many Loaders use
    // AsyncTask
    final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            loader.registerListener(0, listener);
            loader.startLoading();
        }
    };

    // Ask the main thread to start the loading process
    mainThreadHandler.sendEmptyMessage(0);

    // Block on the queue waiting for the result of the load to be inserted
    T result;
    while (true) {
        try {
            result = queue.take();
            break;
        } catch (InterruptedException e) {
            throw new RuntimeException("waiting thread interrupted", e);
        }
    }

    return result;
}

From source file:org.mozilla.gecko.background.fxa.TestAccountLoader.java

/**
 * Runs a Loader synchronously and returns the result of the load. The loader will
 * be started, stopped, and destroyed by this method so it cannot be reused.
 *
 * @param loader The loader to run synchronously
 * @return The result from the loader//from  w ww .  j av a2s .  c om
 */
public <T> T getLoaderResultSynchronously(final Loader<T> loader) {
    // The test thread blocks on this queue until the loader puts it's result in
    final ArrayBlockingQueue<AtomicReference<T>> queue = new ArrayBlockingQueue<AtomicReference<T>>(1);

    // This callback runs on the "main" thread and unblocks the test thread
    // when it puts the result into the blocking queue
    final OnLoadCompleteListener<T> listener = new OnLoadCompleteListener<T>() {
        @Override
        public void onLoadComplete(Loader<T> completedLoader, T data) {
            // Shut the loader down
            completedLoader.unregisterListener(this);
            completedLoader.stopLoading();
            completedLoader.reset();
            // Store the result, unblocking the test thread
            queue.add(new AtomicReference<T>(data));
        }
    };

    // This handler runs on the "main" thread of the process since AsyncTask
    // is documented as needing to run on the main thread and many Loaders use
    // AsyncTask
    final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            loader.registerListener(0, listener);
            loader.startLoading();
        }
    };

    // Ask the main thread to start the loading process
    mainThreadHandler.sendEmptyMessage(0);

    // Block on the queue waiting for the result of the load to be inserted
    T result;
    while (true) {
        try {
            result = queue.take().get();
            break;
        } catch (InterruptedException e) {
            throw new RuntimeException("waiting thread interrupted", e);
        }
    }
    return result;
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

protected Message doSendAndReceiveWithTemporary(final String exchange, final String routingKey,
        final Message message) {
    return this.execute(new ChannelCallback<Message>() {

        @Override/*from w  w  w  .j av a2 s .c  om*/
        public Message doInRabbit(Channel channel) throws Exception {
            final ArrayBlockingQueue<Message> replyHandoff = new ArrayBlockingQueue<Message>(1);

            Assert.isNull(message.getMessageProperties().getReplyTo(),
                    "Send-and-receive methods can only be used if the Message does not already have a replyTo property.");
            DeclareOk queueDeclaration = channel.queueDeclare();
            String replyTo = queueDeclaration.getQueue();
            message.getMessageProperties().setReplyTo(replyTo);

            String consumerTag = UUID.randomUUID().toString();
            DefaultConsumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    MessageProperties messageProperties = messagePropertiesConverter
                            .toMessageProperties(properties, envelope, encoding);
                    Message reply = new Message(body, messageProperties);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Message received " + reply);
                    }
                    try {
                        replyHandoff.put(reply);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            };
            channel.basicConsume(replyTo, true, consumerTag, true, true, null, consumer);
            doSend(channel, exchange, routingKey, message, null);
            Message reply = (replyTimeout < 0) ? replyHandoff.take()
                    : replyHandoff.poll(replyTimeout, TimeUnit.MILLISECONDS);
            channel.basicCancel(consumerTag);
            return reply;
        }
    });
}

From source file:org.apache.hadoop.net.unix.TestDomainSocket.java

/**
 * Test a simple client/server interaction.
 *
 * @throws IOException//  w  w w. j  a va  2  s  .c  o  m
 */
void testClientServer1(final Class<? extends WriteStrategy> writeStrategyClass,
        final Class<? extends ReadStrategy> readStrategyClass, final DomainSocket preConnectedSockets[])
        throws Exception {
    final String TEST_PATH = new File(sockDir.getDir(), "test_sock_client_server1").getAbsolutePath();
    final byte clientMsg1[] = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 };
    final byte serverMsg1[] = new byte[] { 0x9, 0x8, 0x7, 0x6, 0x5 };
    final byte clientMsg2 = 0x45;
    final ArrayBlockingQueue<Throwable> threadResults = new ArrayBlockingQueue<Throwable>(2);
    final DomainSocket serv = (preConnectedSockets != null) ? null : DomainSocket.bindAndListen(TEST_PATH);
    Thread serverThread = new Thread() {
        public void run() {
            // Run server
            DomainSocket conn = null;
            try {
                conn = preConnectedSockets != null ? preConnectedSockets[0] : serv.accept();
                byte in1[] = new byte[clientMsg1.length];
                ReadStrategy reader = readStrategyClass.newInstance();
                reader.init(conn);
                reader.readFully(in1, 0, in1.length);
                Assert.assertTrue(Arrays.equals(clientMsg1, in1));
                WriteStrategy writer = writeStrategyClass.newInstance();
                writer.init(conn);
                writer.write(serverMsg1);
                InputStream connInputStream = conn.getInputStream();
                int in2 = connInputStream.read();
                Assert.assertEquals((int) clientMsg2, in2);
                conn.close();
            } catch (Throwable e) {
                threadResults.add(e);
                Assert.fail(e.getMessage());
            }
            threadResults.add(new Success());
        }
    };
    serverThread.start();

    Thread clientThread = new Thread() {
        public void run() {
            try {
                DomainSocket client = preConnectedSockets != null ? preConnectedSockets[1]
                        : DomainSocket.connect(TEST_PATH);
                WriteStrategy writer = writeStrategyClass.newInstance();
                writer.init(client);
                writer.write(clientMsg1);
                ReadStrategy reader = readStrategyClass.newInstance();
                reader.init(client);
                byte in1[] = new byte[serverMsg1.length];
                reader.readFully(in1, 0, in1.length);
                Assert.assertTrue(Arrays.equals(serverMsg1, in1));
                OutputStream clientOutputStream = client.getOutputStream();
                clientOutputStream.write(clientMsg2);
                client.close();
            } catch (Throwable e) {
                threadResults.add(e);
            }
            threadResults.add(new Success());
        }
    };
    clientThread.start();

    for (int i = 0; i < 2; i++) {
        Throwable t = threadResults.take();
        if (!(t instanceof Success)) {
            Assert.fail(t.getMessage() + ExceptionUtils.getStackTrace(t));
        }
    }
    serverThread.join(120000);
    clientThread.join(120000);
    if (serv != null) {
        serv.close();
    }
}

From source file:org.apache.hadoop.net.unix.TestDomainSocket.java

/**
 * Test file descriptor passing.//from w  w w .  j av a 2 s.  c o m
 *
 * @throws IOException
 */
@Test(timeout = 180000)
public void testFdPassing() throws Exception {
    final String TEST_PATH = new File(sockDir.getDir(), "test_sock").getAbsolutePath();
    final byte clientMsg1[] = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 };
    final byte serverMsg1[] = new byte[] { 0x31, 0x30, 0x32, 0x34, 0x31, 0x33, 0x44, 0x1, 0x1, 0x1, 0x1, 0x1 };
    final ArrayBlockingQueue<Throwable> threadResults = new ArrayBlockingQueue<Throwable>(2);
    final DomainSocket serv = DomainSocket.bindAndListen(TEST_PATH);
    final PassedFile passedFiles[] = new PassedFile[] { new PassedFile(1), new PassedFile(2) };
    final FileDescriptor passedFds[] = new FileDescriptor[passedFiles.length];
    for (int i = 0; i < passedFiles.length; i++) {
        passedFds[i] = passedFiles[i].getInputStream().getFD();
    }
    Thread serverThread = new Thread() {
        public void run() {
            // Run server
            DomainSocket conn = null;
            try {
                conn = serv.accept();
                byte in1[] = new byte[clientMsg1.length];
                InputStream connInputStream = conn.getInputStream();
                IOUtils.readFully(connInputStream, in1, 0, in1.length);
                Assert.assertTrue(Arrays.equals(clientMsg1, in1));
                DomainSocket domainConn = (DomainSocket) conn;
                domainConn.sendFileDescriptors(passedFds, serverMsg1, 0, serverMsg1.length);
                conn.close();
            } catch (Throwable e) {
                threadResults.add(e);
                Assert.fail(e.getMessage());
            }
            threadResults.add(new Success());
        }
    };
    serverThread.start();

    Thread clientThread = new Thread() {
        public void run() {
            try {
                DomainSocket client = DomainSocket.connect(TEST_PATH);
                OutputStream clientOutputStream = client.getOutputStream();
                InputStream clientInputStream = client.getInputStream();
                clientOutputStream.write(clientMsg1);
                DomainSocket domainConn = (DomainSocket) client;
                byte in1[] = new byte[serverMsg1.length];
                FileInputStream recvFis[] = new FileInputStream[passedFds.length];
                int r = domainConn.recvFileInputStreams(recvFis, in1, 0, in1.length - 1);
                Assert.assertTrue(r > 0);
                IOUtils.readFully(clientInputStream, in1, r, in1.length - r);
                Assert.assertTrue(Arrays.equals(serverMsg1, in1));
                for (int i = 0; i < passedFds.length; i++) {
                    Assert.assertNotNull(recvFis[i]);
                    passedFiles[i].checkInputStream(recvFis[i]);
                }
                for (FileInputStream fis : recvFis) {
                    fis.close();
                }
                client.close();
            } catch (Throwable e) {
                threadResults.add(e);
            }
            threadResults.add(new Success());
        }
    };
    clientThread.start();

    for (int i = 0; i < 2; i++) {
        Throwable t = threadResults.take();
        if (!(t instanceof Success)) {
            Assert.fail(t.getMessage() + ExceptionUtils.getStackTrace(t));
        }
    }
    serverThread.join(120000);
    clientThread.join(120000);
    serv.close();
    for (PassedFile pf : passedFiles) {
        pf.cleanup();
    }
}