Example usage for java.lang Runnable run

List of usage examples for java.lang Runnable run

Introduction

In this page you can find the example usage for java.lang Runnable run.

Prototype

public abstract void run();

Source Link

Document

When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

Usage

From source file:org.sakaiproject.genericdao.hibernate.HibernateGenericDao.java

public void invokeTransactionalAccess(Runnable toinvoke) {
    toinvoke.run();
}

From source file:com.qiscus.sdk.presenter.QiscusChatPresenter.java

private void doInIo(Runnable runnable) {
    Observable.just(null).doOnNext(o -> runnable.run()).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).compose(bindToLifecycle()).subscribe(o -> {
            }, throwable -> {//from w  ww  .  ja va2  s  .c om
            });
}

From source file:com.juick.android.MessageMenu.java

public static void confirmAction(int resId, Context context, boolean alwaysConfirm, final Runnable r) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (sp.getBoolean("confirmActions", true) || alwaysConfirm) {
        new AlertDialog.Builder(context).setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage(context.getResources().getString(resId))
                .setPositiveButton(R.string.OK, new OnClickListener() {

                    @Override//from   w w w . j ava  2  s.c  o m
                    public void onClick(DialogInterface dialog, int which) {
                        r.run();
                    }

                }).setNegativeButton(R.string.Cancel, null).show();
    } else {
        r.run();
    }
}

From source file:com.haulmont.cuba.web.gui.components.WebAbstractTree.java

@Override
public void setLookupSelectHandler(Runnable selectHandler) {
    component.setDoubleClickMode(true);/*from   w w  w.  j ava 2  s  .c o  m*/
    component.addItemClickListener(event -> {
        if (event.isDoubleClick()) {
            if (event.getItem() != null) {
                component.setValue(event.getItemId());
                selectHandler.run();
            }
        }
    });
}

From source file:dhbw.clippinggorilla.userinterface.windows.NewSourceWindow.java

public Component getFooter(Runnable cancelRunnable, Runnable nextRunnable, Component... extraComponents) {
    Label placeholder = new Label();
    Button cancel = new Button(Language.get(Word.CANCEL), VaadinIcons.CLOSE);
    cancel.addClickListener(ce -> cancelRunnable.run());
    Button next = new Button(Language.get(Word.NEXT), VaadinIcons.ARROW_RIGHT);
    next.addClickListener(ce -> nextRunnable.run());
    GridLayout footer = new GridLayout(3 + extraComponents.length, 1);
    footer.setSpacing(true);//w ww . j a  va  2s.  c o m
    footer.addStyleName(ValoTheme.WINDOW_BOTTOM_TOOLBAR);
    footer.setWidth(100.0f, Sizeable.Unit.PERCENTAGE);
    footer.setSizeUndefined();
    footer.setWidth("100%");
    for (Component extraComponent : extraComponents) {
        footer.addComponent(extraComponent);
        footer.setComponentAlignment(extraComponent, Alignment.MIDDLE_CENTER);
    }
    footer.addComponents(placeholder, cancel, next);
    footer.setColumnExpandRatio(footer.getColumns() - 1 - 2, 1);//ExpandRatio(placeholder, 1);
    footer.setComponentAlignment(cancel, Alignment.MIDDLE_CENTER);
    footer.setComponentAlignment(next, Alignment.MIDDLE_CENTER);
    return footer;
}

From source file:com.intellij.util.net.HttpConfigurable.java

@SuppressWarnings("MethodMayBeStatic")
private void runAboveAll(final Runnable runnable) {
    final Runnable throughSwing = new Runnable() {
        @Override/*from w  w w  .j  a  v a  2 s.  c o  m*/
        public void run() {
            if (SwingUtilities.isEventDispatchThread()) {
                runnable.run();
                return;
            }
            try {
                SwingUtilities.invokeAndWait(runnable);
            } catch (InterruptedException e) {
                LOG.info(e);
            } catch (InvocationTargetException e) {
                LOG.info(e);
            }
        }
    };
    if (ProgressManager.getInstance().getProgressIndicator() != null) {
        if (ProgressManager.getInstance().getProgressIndicator().isModal()) {
            WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(runnable);
        } else {
            throughSwing.run();
        }
    } else {
        throughSwing.run();
    }
}

From source file:org.martus.client.swingui.FxInSwingMainWindow.java

public void runInUiThreadAndWait(Runnable toRun) throws InterruptedException, InvocationTargetException {
    if (SwingUtilities.isEventDispatchThread()) {
        toRun.run();
        return;/* ww  w .  j a  va  2 s . co m*/
    }

    SwingUtilities.invokeAndWait(toRun);
}

From source file:com.twitter.finagle.common.zookeeper.ZooKeeperClient.java

/**
 * Clients that need to re-establish state after session expiration can register an
 * {@code onExpired} command to execute.
 *
 * @param onExpired the {@code Runnable} to register
 * @return the new {@link Watcher} which can later be passed to {@link #unregister} for
 *     removal./*from ww w . j  a  v  a2s  . com*/
 */
public Watcher registerExpirationHandler(final Runnable onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                onExpired.run();
            }
        }
    };
    register(watcher);
    return watcher;
}

From source file:com.mobicage.rogerthat.xmpp.CallBackApiXMPPListener.java

/**
 * Establish an XMPP connection to XmppService and listen for Rogerthat API callbacks.
 *//*from  w w  w . ja  va  2s  .c  o m*/
public void startListening() {

    if (connectionThread != null) {
        throw new RuntimeException("Previous connection has not yet been closed!");
    }

    if (xmppUsername == null || xmppService == null || xmppPassword == null || sik == null)
        throw new RuntimeException("Not enough information present to setup an xmpp connection");

    final ConnectionListener connectionListener = new ConnectionListener() {
        @Override
        public void reconnectionSuccessful() {
            log.info("Reconnection to jabber server succeeded.");
            status = XmppConnectionStatus.Connected;
        }

        @Override
        public void reconnectionFailed(Exception e) {
            log.info("Reconnection to jabber server failed.");
        }

        @Override
        public void reconnectingIn(int seconds) {
            log.info("Reconnecting to jabber in " + seconds + " seconds ...");
            status = XmppConnectionStatus.Reconnecting;
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            log.info("Connection closed to jabber due to " + e.toString());
        }

        @Override
        public void connectionClosed() {
            log.info("Connection to jabber closed.");
        }
    };

    tasks.clear();

    connectionThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    Runnable task = tasks.take();
                    task.run();
                }
            } catch (StopListeningException e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "";
            } catch (Throwable e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "Connection interrupted.";
            } finally {
                connectionThread = null;
            }
        }
    });
    connectionThread.setName("Rogerthat callback listener");
    connectionThread.setDaemon(true);
    connectionThread.start();

    tasks.add(new Runnable() {
        @Override
        public void run() {
            ConnectionConfiguration conf = new ConnectionConfiguration(xmppService);

            status = XmppConnectionStatus.Connecting;

            log.info("Connecting to jabber server ...");
            conn = new XMPPConnection(conf);
            try {
                conn.connect();
            } catch (XMPPException e) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to reach Rogerthat servers.\n" + e.getMessage();
                conn = null;
                connectionThread = null;
                if (onConnectionFailed != null)
                    try {
                        onConnectionFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onConnectionFailed handler.", t);
                    }
                throw new RuntimeException(e); // Stop thread.
            }

            if (onConnected != null)
                try {
                    onConnected.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onConnected handler.", t);
                }

            conn.addConnectionListener(connectionListener);

            SASLAuthentication.supportSASLMechanism("PLAIN", 0);

            PacketFilter filter = new PacketFilter() {
                @Override
                public boolean accept(Packet packet) {
                    boolean accept = packet instanceof Message
                            && ROGERTHAT_CALLBACK_BOT.equals(packet.getFrom());
                    if (!accept)
                        log.info("Dropping packet:\n" + packet.toXML());
                    return accept;
                }
            };

            conn.addPacketListener(new PacketListener() {
                @Override
                public void processPacket(Packet packet) {
                    log.info("Processing packet:\n" + packet.toXML());
                    if (!(packet instanceof Message)) {
                        log.info("Ignoring non message packet.");
                        return;
                    }
                    Message message = (Message) packet;
                    PacketExtension extension = packet.getExtension("call", "mobicage:comm");
                    if (extension == null || !(extension instanceof CallbackRequestExtension)) {
                        log.info("Ignoring incomplete packet.");
                        return;
                    }
                    CallbackRequestExtension call = (CallbackRequestExtension) extension;
                    if (!sik.equals(call.getSik())) {
                        log.info("Ignoring packet with incorrect sik.");
                        return;
                    }
                    String json;
                    try {
                        json = new String(DatatypeConverter.parseBase64Binary(call.getBase64Body()), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        log.log(Level.WARNING, "Could not decode base64 packet.", e);
                        return;
                    }
                    final JSONObject request = (JSONObject) JSONValue.parse(json);

                    if (logTraffic)
                        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sik, json));

                    final String id = (String) request.get("id");

                    if (callbackDedup != null) {
                        byte[] response = callbackDedup.getResponse(id);
                        if (response != null) {
                            Message resultMessage = new Message(message.getFrom());
                            resultMessage.setFrom(message.getTo());
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            log.info("Sending message:\n" + resultMessage.toXML());
                            conn.sendPacket(resultMessage);
                            return;
                        }
                    }

                    final JSONObject result = new JSONObject();
                    final RequestContext requestContext = new RequestContext(id, sik);
                    try {
                        processor.process(request, result, requestContext);
                    } finally {
                        try {
                            StringWriter writer = new StringWriter();
                            try {
                                result.writeJSONString(writer);
                                writer.flush();
                                json = writer.toString();

                                if (logTraffic)
                                    log.info("Returning result:\n" + json);

                            } finally {
                                writer.close();
                            }
                        } catch (IOException e) {
                            log.log(Level.SEVERE, "Could not write json object to string", e);
                            return;
                        }
                        Message resultMessage = new Message(message.getFrom());
                        resultMessage.setFrom(message.getTo());
                        try {
                            byte[] response = json.getBytes("UTF-8");
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            if (callbackDedup != null) {
                                callbackDedup.storeResponse(id, response);
                            }
                        } catch (UnsupportedEncodingException e) {
                            log.log(Level.SEVERE, "Could not add result to message packet", e);
                            return;
                        }
                        log.info("Sending message:\n" + resultMessage.toXML());
                        conn.sendPacket(resultMessage);
                    }

                }
            }, filter);

            try {
                conn.login(xmppUsername, xmppPassword);
            } catch (XMPPException e1) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to authenticate jabber connection. Verify your configuration.\n"
                        + e1.getMessage();
                conn = null;
                connectionThread = null;
                if (onAuthenticationFailed != null)
                    try {
                        onAuthenticationFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onAuthenticationFailed handler.", t);
                    }
                throw new RuntimeException(); // Stop thread.
            }

            status = XmppConnectionStatus.Connected;

            if (onAuthenticated != null)
                try {
                    onAuthenticated.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onAuthenticated handler.", t);
                }
        }
    });

}