Example usage for java.lang Thread interrupt

List of usage examples for java.lang Thread interrupt

Introduction

In this page you can find the example usage for java.lang Thread interrupt.

Prototype

public void interrupt() 

Source Link

Document

Interrupts this thread.

Usage

From source file:org.jivesoftware.sparkimpl.updater.CheckUpdates.java

public void downloadUpdate(final File downloadedFile, final SparkVersion version) {
    final java.util.Timer timer = new java.util.Timer();

    // Prepare HTTP post
    final GetMethod post = new GetMethod(version.getDownloadURL());

    // Get HTTP client
    Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    final HttpClient httpclient = new HttpClient();
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if (ModelUtil.hasLength(proxyHost) && ModelUtil.hasLength(proxyPort)) {
        try {/*  ww w . j  av  a2 s  .com*/
            httpclient.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        } catch (NumberFormatException e) {
            Log.error(e);
        }
    }

    // Execute request

    try {
        int result = httpclient.executeMethod(post);
        if (result != 200) {
            return;
        }

        long length = post.getResponseContentLength();
        int contentLength = (int) length;

        bar = new JProgressBar(0, contentLength);
    } catch (IOException e) {
        Log.error(e);
    }

    final JFrame frame = new JFrame(Res.getString("title.downloading.im.client"));

    frame.setIconImage(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE).getImage());

    titlePanel = new TitlePanel(Res.getString("title.upgrading.client"),
            Res.getString("message.version", version.getVersion()),
            SparkRes.getImageIcon(SparkRes.SEND_FILE_24x24), true);

    final Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                InputStream stream = post.getResponseBodyAsStream();
                long size = post.getResponseContentLength();
                ByteFormat formater = new ByteFormat();
                sizeText = formater.format(size);
                titlePanel.setDescription(Res.getString("message.version", version.getVersion()) + " \n"
                        + Res.getString("message.file.size", sizeText));

                downloadedFile.getParentFile().mkdirs();

                FileOutputStream out = new FileOutputStream(downloadedFile);
                copy(stream, out);
                out.close();

                if (!cancel) {
                    downloadComplete = true;
                    promptForInstallation(downloadedFile, Res.getString("title.download.complete"),
                            Res.getString("message.restart.spark"));
                } else {
                    out.close();
                    downloadedFile.delete();
                }

                UPDATING = false;
                frame.dispose();
            } catch (Exception ex) {
                // Nothing to do
            } finally {
                timer.cancel();
                // Release current connection to the connection pool once you are done
                post.releaseConnection();
            }
        }
    });

    frame.getContentPane().setLayout(new GridBagLayout());
    frame.getContentPane().add(titlePanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
    frame.getContentPane().add(bar, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));

    JEditorPane pane = new JEditorPane();
    boolean displayContentPane = version.getChangeLogURL() != null || version.getDisplayMessage() != null;

    try {
        pane.setEditable(false);
        if (version.getChangeLogURL() != null) {
            pane.setEditorKit(new HTMLEditorKit());
            pane.setPage(version.getChangeLogURL());
        } else if (version.getDisplayMessage() != null) {
            pane.setText(version.getDisplayMessage());
        }

        if (displayContentPane) {
            frame.getContentPane().add(new JScrollPane(pane), new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0,
                    GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
        }
    } catch (IOException e) {
        Log.error(e);
    }

    frame.getContentPane().setBackground(Color.WHITE);
    frame.pack();
    if (displayContentPane) {
        frame.setSize(600, 400);
    } else {
        frame.setSize(400, 100);
    }
    frame.setLocationRelativeTo(SparkManager.getMainWindow());
    GraphicUtils.centerWindowOnScreen(frame);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent windowEvent) {
            thread.interrupt();
            cancel = true;

            UPDATING = false;

            if (!downloadComplete) {
                JOptionPane.showMessageDialog(SparkManager.getMainWindow(),
                        Res.getString("message.updating.cancelled"), Res.getString("title.cancelled"),
                        JOptionPane.ERROR_MESSAGE);
            }

        }
    });
    frame.setVisible(true);
    thread.start();

    timer.scheduleAtFixedRate(new TimerTask() {
        int seconds = 1;

        public void run() {
            ByteFormat formatter = new ByteFormat();
            long value = bar.getValue();
            long average = value / seconds;
            String text = formatter.format(average) + "/Sec";

            String total = formatter.format(value);
            titlePanel.setDescription(Res.getString("message.version", version.getVersion()) + " \n"
                    + Res.getString("message.file.size", sizeText) + "\n"
                    + Res.getString("message.transfer.rate") + ": " + text + "\n"
                    + Res.getString("message.total.downloaded") + ": " + total);
            seconds++;
        }
    }, 1000, 1000);
}

From source file:de.hpi.i2b2.girix.GIRIXService.java

private OMElement execute(RequestHandler handler, RequestMessageType message) throws I2B2Exception {

    // Extract wait time. If no waitTime is given it defaults to 0 which is equivalent to an infinite waitTime
    long waitTime = 0;
    if (message.getRequestHeader() != null) {
        waitTime = message.getRequestHeader().getResultWaittimeMs();
    }/* ww  w .j  a v  a 2  s .  c  om*/

    // Do query processing inside thread, so that service could send back message with timeout error
    String unknownErrorMessage = "Error message delivered from the remote server: Unknown exception. See log file for stack trace.";
    ExecutorRunnable er = new ExecutorRunnable();
    er.setInput(message);
    er.setRequestHandler(handler);
    Thread t = new Thread(er);
    String girixDataResponse = null;
    // Start thread...
    synchronized (t) {
        t.start();
        // ...meanwhile in main thread: count time and check for timeout
        try {
            long startTime = System.currentTimeMillis();
            long deltaTime = -1;
            while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) {
                if (waitTime > 0) {
                    t.wait(waitTime - deltaTime);
                    deltaTime = System.currentTimeMillis() - startTime;
                } else {
                    // wait until job is completed
                    t.wait();
                }
            }
            // Now try to extract the result...
            girixDataResponse = er.getOutputString();
            // ...which is null if there was an error
            if (girixDataResponse == null) {
                // Error case 1: There was an exception during thread execution
                if (er.getJobException() != null) {
                    // Error case 1.1: Causing exception was set -> Default unknown error message & logging stack trace
                    if (er.getJobException().getCause() != null) {
                        log.error("Exception stack trace:\n"
                                + GIRIXUtil.getStackTraceAsString(er.getJobException()));
                        ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                                unknownErrorMessage);
                        girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                    } else {
                        // Error case 1.2: Causing exception wasn't set -> Custom error message. Logging is done by throwing method
                        ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                                er.getJobException().getMessage());
                        girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                    }
                    // Error case 2: Timeout
                } else if (er.isJobCompleteFlag() == false) {
                    String timeOuterror = "Remote server timed out \nResult waittime = " + waitTime
                            + " ms elapsed\nPlease try again";
                    log.error(timeOuterror);
                    log.debug("girix waited " + deltaTime + "ms for "
                            + er.getRequestHandler().getClass().getName());
                    ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                            timeOuterror);
                    girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                    // Error case 3: Result was set to null by the thread
                } else {
                    log.error("girix data response is null");
                    log.debug("girix waited " + deltaTime + "ms for "
                            + er.getRequestHandler().getClass().getName());
                    ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null,
                            "Error message delivered from the remote server: Result was set to null.");
                    girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType);
                }
            }
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            throw new I2B2Exception("Thread error while running GIRIX job");
        } finally {
            t.interrupt();
            er = null;
            t = null;
        }
    }
    // Send back answer. girixDataResponse contains either an error message or the proper response if there was no critical error
    return MessageUtil.convertXMLToOMElement(girixDataResponse);
}

From source file:org.alfresco.repo.tagging.TaggingServiceImplTest.java

/**
 * Test that when multiple threads do tag updates, the right thing still
 * happens//from w  w  w.j  a va 2s  . co  m
 */
public void test94MultiThreaded() throws Exception {
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
        @Override
        public Void execute() throws Throwable {
            taggingService.addTagScope(folder);
            taggingService.addTagScope(subFolder);
            return null;
        }
    });

    // Reset the action count
    asyncOccurs.wantedActionsCount = 0;

    // Prepare a bunch of threads to do tagging
    final List<Thread> threads = new ArrayList<Thread>();
    final String[] tags = new String[] { TAG_1, TAG_2, TAG_3, TAG_4, TAG_5, "testTag06", "testTag07",
            "testTag08", "testTag09", "testTag10", "testTag11", "testTag12", "testTag13", "testTag14",
            "testTag15", "testTag16", "testTag17", "testTag18", "testTag19", "testTag20" };
    for (String tmpTag : tags) {
        final String tag = tmpTag;
        Thread t = new Thread(new Runnable() {
            @Override
            public synchronized void run() {
                // Let everything catch up
                try {
                    wait();
                } catch (InterruptedException e) {
                }
                logger.debug(Thread.currentThread() + " - About to start tagging for " + tag);

                // Do the updates
                AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
                RetryingTransactionCallback<Void> txnCallback = new RetryingTransactionCallback<Void>() {
                    @Override
                    public Void execute() throws Throwable {
                        taggingService.addTag(folder, tag);
                        taggingService.addTag(subFolder, tag);
                        taggingService.addTag(subDocument, tag);
                        logger.debug(Thread.currentThread() + " - Tagging for " + tag);
                        return null;
                    }
                };
                try {
                    transactionService.getRetryingTransactionHelper().doInTransaction(txnCallback);
                } catch (Throwable e) {
                    logger.error("Tagging failed: " + e);
                }
                logger.debug(Thread.currentThread() + " - Done tagging for " + tag);

                // Wait briefly for thing to catch up, before we
                //  declare ourselves to be done
                try {
                    Thread.sleep(150);
                } catch (InterruptedException e) {
                }
            }
        });
        threads.add(t);
        t.start();
    }

    // Release the threads
    logger.info("Releasing tagging threads");
    for (Thread t : threads) {
        t.interrupt();
    }

    // Wait for the threads to finish (and they will finish)
    // The threads will generate further asynchronous actions
    for (Thread t : threads) {
        t.join();
    }
    logger.info("All threads should have finished");

    // Have a brief pause, while we wait for their related
    //  async actions to kick off
    Thread.sleep(150);

    // Wait until we've had 20 async tagging actions run (One per Thread)
    // Not all of the actions will do something, but we just need to
    //  wait for all of them!
    // As a backup check, also ensure that the action tracking service
    //  shows none of them running either
    for (int i = 0; i < 600; i++) {
        try {
            if (asyncOccurs.wantedActionsCount < tags.length) {
                if (i % 50 == 0) {
                    logger.info("Done " + asyncOccurs.wantedActionsCount + " of " + tags.length);
                }
                Thread.sleep(100);
                continue;
            }
            if (actionTrackingService.getAllExecutingActions().size() > 0) {
                if (i % 50 == 0) {
                    List<ExecutionSummary> actions = actionTrackingService.getAllExecutingActions();
                    logger.info("Waiting on " + actions.size() + " actions: " + actions);
                }
                Thread.sleep(100);
                continue;
            }
            break;
        } catch (InterruptedException e) {
        }
    }

    // Extra sleep just to be sure things are quiet before we continue
    // (Allows anything that runs after the async actions commit to
    //  finish up for example)
    Thread.sleep(175);
    System.out.println("Done waiting for tagging, now checking");

    // Now check that things ended up as planned
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
        @Override
        public Void execute() throws Throwable {
            TagScope ts1 = taggingService.findTagScope(folder);
            TagScope ts2 = taggingService.findTagScope(subFolder);
            assertEquals("Wrong tags on folder tagscope: " + ts1.getTags(), tags.length, ts1.getTags().size());
            assertEquals("Wrong tags on subfolder tagscope: " + ts2.getTags(), tags.length,
                    ts2.getTags().size());

            // Each tag should crop up 3 times on the folder
            // and twice for the subfolder
            for (String tag : tags) {
                assertEquals(3, ts1.getTag(tag.toLowerCase()).getCount());
                assertEquals(2, ts2.getTag(tag.toLowerCase()).getCount());
            }

            // All done
            return null;
        }
    });
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);//from  www .j av  a  2  s.c  o  m

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}

From source file:org.kurento.test.browser.WebRtcTestPage.java

@SuppressWarnings({ "unchecked", "deprecation" })
protected void initWebRtc(final WebRtcConfigurer webRtcConfigurer, final WebRtcChannel channel,
        final WebRtcMode mode, final WebRtcCandidateType candidateType, boolean useDataChannels)
        throws InterruptedException {
    // ICE candidates
    Thread t1 = new Thread() {
        @Override//from  w w w.  j  a  va 2  s . c  o  m
        public void run() {
            JsonParser parser = new JsonParser();
            int numCandidate = 0;
            while (true) {
                try {
                    ArrayList<Object> iceCandidates = (ArrayList<Object>) browser
                            .executeScript("return iceCandidates;");

                    for (int i = numCandidate; i < iceCandidates.size(); i++) {
                        JsonObject jsonCandidate = (JsonObject) parser.parse(iceCandidates.get(i).toString());
                        IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").getAsString(),
                                jsonCandidate.get("sdpMid").getAsString(),
                                jsonCandidate.get("sdpMLineIndex").getAsInt());
                        // log.debug("Adding candidate {}: {}", i, jsonCandidate);
                        webRtcConfigurer.addIceCandidate(candidate);
                        numCandidate++;
                    }

                    // Poll 300 ms
                    Thread.sleep(300);

                } catch (Throwable e) {
                    log.debug("Exiting gather candidates thread");
                    break;
                }
            }
        }
    };
    t1.start();

    // Append WebRTC mode (send/receive and audio/video) to identify test
    addTestName(KurentoTest.getTestClassName() + "." + KurentoTest.getTestMethodName());
    appendStringToTitle(mode.toString());
    appendStringToTitle(channel.toString());

    // Setting custom audio stream (if necessary)
    String audio = browser.getAudio();
    if (audio != null) {
        browser.executeScript("setCustomAudio('" + audio + "');");
    }

    // Create peerConnection for using dataChannels (if necessary)
    if (useDataChannels) {
        browser.executeScript("useDataChannels()");
    }

    // Setting IceServer (if necessary)
    String iceServerJsFunction = candidateType.getJsFunction();
    log.debug("Setting IceServer: {}", iceServerJsFunction);
    if (iceServerJsFunction != null) {
        browser.executeScript(iceServerJsFunction);
    }

    // Setting MediaConstraints (if necessary)
    String channelJsFunction = channel.getJsFunction();
    if (channelJsFunction != null) {
        browser.executeScript(channelJsFunction);
    }

    // Execute JavaScript kurentoUtils.WebRtcPeer
    browser.executeScript(mode.getJsFunction());

    // SDP offer/answer
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t2 = new Thread() {
        @Override
        public void run() {
            // Wait to valid sdpOffer
            String sdpOffer = (String) browser.executeScriptAndWaitOutput("return sdpOffer;");

            log.debug("SDP offer: {}", sdpOffer);
            String sdpAnswer = webRtcConfigurer.processOffer(sdpOffer);
            log.debug("SDP answer: {}", sdpAnswer);

            // Encoding in Base64 to avoid parsing errors in JavaScript
            sdpAnswer = new String(Base64.encodeBase64(sdpAnswer.getBytes()));

            // Process sdpAnswer
            browser.executeScript("processSdpAnswer('" + sdpAnswer + "');");

            latch.countDown();
        }
    };
    t2.start();

    if (!latch.await(browser.getTimeout(), TimeUnit.SECONDS)) {
        t1.interrupt();
        t1.stop();
        t2.interrupt();
        t2.stop();
        throw new KurentoException("ICE negotiation not finished in " + browser.getTimeout() + " seconds");
    }
}

From source file:com.nextep.designer.sqlgen.oracle.debug.ctrl.DebugMethod.java

@Override
public Object invokeMethod(Object... arg) {

    IConnection conn = (IConnection) arg[0];

    CallableStatement stmt = null;
    Thread debuggedThread = null;
    try {/*from   w  w w . j  a  v a 2s .com*/
        // Initializing our target connection
        targetConn = CorePlugin.getConnectionService().connect(conn);
        //
        stmt = targetConn.prepareCall("ALTER SESSION SET PLSQL_DEBUG=TRUE"); //$NON-NLS-1$
        try {
            stmt.execute();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        stmt = targetConn.prepareCall("{ ? = CALL DBMS_DEBUG.INITIALIZE() }"); //$NON-NLS-1$
        try {
            stmt.registerOutParameter(1, Types.VARCHAR);
            stmt.execute();
            debugSessionID = stmt.getString(1);
        } catch (SQLException e) {
            throw new ErrorException(e);
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        // Switching to debug mode
        stmt = targetConn.prepareCall("{ CALL DBMS_DEBUG.DEBUG_ON() }"); //$NON-NLS-1$
        try {
            stmt.execute();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        // Starting our target code
        debuggedThread = new Thread(new TargetRunnable(targetConn));
        debuggedThread.start();

        // Now that we have our ID, we initialize debug connection
        debugConn = CorePlugin.getConnectionService().connect(conn);
        // new Thread(new DebugRunnable(debugConn,debugSessionID)).start();

        stmt = debugConn.prepareCall("{ CALL DBMS_DEBUG.ATTACH_SESSION(?) }"); //$NON-NLS-1$
        try {
            stmt.setString(1, debugSessionID);
            stmt.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        stmt = debugConn.prepareCall("{ ? = CALL DBMS_DEBUG.SYNCHRONIZE(?,0) }"); //$NON-NLS-1$
        try {
            stmt.registerOutParameter(1, Types.INTEGER);
            stmt.registerOutParameter(2, OracleTypes.OTHER, "DBMS_DEBUG.RUNTIME_INFO"); //$NON-NLS-1$
            stmt.execute();
            Object o = stmt.getObject(2);
            if (o != null) {

            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }
        // // Setting breakpoints
        // stmt =
        // debugConn.prepareCall("{ call adp_debug.set_breakpoint(p_line=>?, p_name=>?, p_body=>true) }");
        // try {
        // for(IBreakpoint bp : SQLEditorUIServices.getInstance().getBreakpoints()) {
        // stmt.setInt(1, bp.getLine());
        // stmt.setString(2,bp.getTarget().getName());
        // stmt.execute();
        // }
        // } catch( Exception e) {
        // e.printStackTrace();
        // } finally {
        // stmt.close();
        // }
        stmt = debugConn.prepareCall("{ ? = CALL DBMS_DEBUG.CONTINUE(?,0,46) }"); //$NON-NLS-1$
        stmt.registerOutParameter(1, Types.INTEGER);
        stmt.registerOutParameter(2, OracleTypes.OTHER, "DBMS_DEBUG.RUNTIME_INFO"); //$NON-NLS-1$

        try {
            stmt.execute();
            Struct struct = (Struct) stmt.getObject(2);
            Object[] attrs = struct.getAttributes();
            int line = (Integer) attrs[0];
            int terminated = (Integer) attrs[1];
            int breakpoint = (Integer) attrs[2];
            LOGGER.debug(
                    "Continued to line " + line + ", terminated=" + terminated + ", breakpoint=" + breakpoint);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

    } catch (SQLException e) {
        if (debuggedThread != null) {
            debuggedThread.interrupt();
        }
        throw new ErrorException(e);
    } finally {
        try {
            if (debugConn != null) {
                debugConn.close();
            }
        } catch (SQLException e) {
            throw new ErrorException("Unable to properly close connection: " + e.getMessage(), e);
        }
    }

    return null;
}

From source file:io.fabric8.maven.core.service.PortForwardService.java

/**
 * Forwards a port to the newest pod matching the given selector.
 * If another pod is created, it forwards connections to the new pod once it's ready.
 *///w w w .j  a v  a2s  .c o  m
public Closeable forwardPortAsync(final Logger externalProcessLogger, final LabelSelector podSelector,
        final int remotePort, final int localPort) throws Fabric8ServiceException {

    final Lock monitor = new ReentrantLock(true);
    final Condition podChanged = monitor.newCondition();
    final Pod[] nextForwardedPod = new Pod[1];

    final Thread forwarderThread = new Thread() {
        @Override
        public void run() {

            Pod currentPod = null;
            Closeable currentPortForward = null;

            try {
                monitor.lock();

                while (true) {
                    if (podEquals(currentPod, nextForwardedPod[0])) {
                        podChanged.await();
                    } else {
                        Pod nextPod = nextForwardedPod[0]; // may be null
                        try {
                            monitor.unlock();
                            // out of critical section

                            if (currentPortForward != null) {
                                log.info("Closing port-forward from pod %s",
                                        KubernetesHelper.getName(currentPod));
                                currentPortForward.close();
                                currentPortForward = null;
                            }

                            if (nextPod != null) {
                                log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod));
                                currentPortForward = forwardPortAsync(externalProcessLogger,
                                        KubernetesHelper.getName(nextPod), remotePort, localPort);
                            } else {
                                log.info("Waiting for a pod to become ready before starting port-forward");
                            }
                            currentPod = nextPod;
                        } finally {
                            monitor.lock();
                        }
                    }

                }

            } catch (InterruptedException e) {
                log.debug("Port-forwarding thread interrupted", e);
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                log.warn("Error while port-forwarding to pod", e);
            } finally {
                monitor.unlock();

                if (currentPortForward != null) {
                    try {
                        currentPortForward.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    // Switching forward to the current pod if present
    Pod newPod = getNewestPod(podSelector);
    nextForwardedPod[0] = newPod;

    final Watch watch = KubernetesClientUtil.withSelector(kubernetes.pods(), podSelector, log)
            .watch(new Watcher<Pod>() {

                @Override
                public void eventReceived(Action action, Pod pod) {
                    monitor.lock();
                    try {
                        List<Pod> candidatePods;
                        if (nextForwardedPod[0] != null) {
                            candidatePods = new LinkedList<>();
                            candidatePods.add(nextForwardedPod[0]);
                            candidatePods.add(pod);
                        } else {
                            candidatePods = Collections.singletonList(pod);
                        }
                        Pod newPod = getNewestPod(candidatePods); // may be null
                        if (!podEquals(nextForwardedPod[0], newPod)) {
                            nextForwardedPod[0] = newPod;
                            podChanged.signal();
                        }
                    } finally {
                        monitor.unlock();
                    }
                }

                @Override
                public void onClose(KubernetesClientException e) {
                    // don't care
                }
            });

    forwarderThread.start();

    final Closeable handle = new Closeable() {
        @Override
        public void close() throws IOException {
            try {
                watch.close();
            } catch (Exception e) {
            }
            try {
                forwarderThread.interrupt();
                forwarderThread.join(15000);
            } catch (Exception e) {
            }
        }
    };
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                handle.close();
            } catch (Exception e) {
                // suppress
            }
        }
    });

    return handle;
}

From source file:org.nuxeo.ecm.core.storage.sql.TestSQLBackend.java

@Test
public void testParallelPrepareUserReadAcls() throws Throwable {
    Session session = repository.getConnection();
    Node root = session.getRootNode();
    session.addChildNode(root, "foo", null, "TestDoc", false);
    session.save();/*from  w  w  w .  j a  va2  s .co  m*/
    session.close();

    CyclicBarrier barrier = new CyclicBarrier(2);
    CountDownLatch firstReady = new CountDownLatch(1);
    PrepareUserReadAclsJob r1 = new PrepareUserReadAclsJob(firstReady, barrier);
    PrepareUserReadAclsJob r2 = new PrepareUserReadAclsJob(null, barrier);
    Thread t1 = null;
    Thread t2 = null;
    try {
        t1 = new Thread(r1, "t1");
        t2 = new Thread(r2, "t2");
        t1.start();
        if (firstReady.await(60, TimeUnit.SECONDS)) {
            t2.start();

            t1.join();
            t1 = null;
            t2.join();
            t2 = null;
            if (r1.throwable != null) {
                throw r1.throwable;
            }
            if (r2.throwable != null) {
                throw r2.throwable;
            }
        } // else timed out
    } finally {
        // error condition recovery
        if (t1 != null) {
            t1.interrupt();
        }
        if (t2 != null) {
            t2.interrupt();
        }
    }

    // after both threads have run, check that we don't see
    // duplicate documents
    session = repository.getConnection();
    checkOneDoc(session);
    session.close();

}

From source file:com.screenslicer.core.scrape.Scrape.java

private static String getHelper(final RemoteWebDriver driver, final Node urlNode, final String url,
        final boolean p_cached, final String runGuid, final HtmlNode[] clicks) {
    final String urlHash = CommonUtil.isEmpty(url) ? null : Crypto.fastHash(url);
    final long time = System.currentTimeMillis();
    if (urlHash != null) {
        synchronized (fetchLocalCacheLock) {
            if (fetchLocalCache.containsKey(urlHash)) {
                if (time - fetchLocalCache.get(urlHash) < FETCH_LOCAL_CACHE_EXPIRES) {
                    try {
                        return FileUtils.readFileToString(new File("./fetch_local_cache/" + urlHash), "utf-8");
                    } catch (Throwable t) {
                        Log.exception(t);
                        fetchLocalCache.remove(urlHash);
                    }//from  www.  j a  v  a2  s.  com
                } else {
                    fetchLocalCache.remove(urlHash);
                }
            }
        }
    }
    if (!CommonUtil.isEmpty(url)) {
        final Object resultLock = new Object();
        final String initVal;
        final String[] result;
        synchronized (resultLock) {
            initVal = Random.next();
            result = new String[] { initVal };
        }
        final AtomicBoolean started = new AtomicBoolean();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                started.set(true);
                boolean cached = p_cached;
                String newHandle = null;
                String origHandle = null;
                try {
                    origHandle = driver.getWindowHandle();
                    String content = null;
                    if (!cached) {
                        try {
                            Util.get(driver, url, urlNode, false);
                        } catch (Throwable t) {
                            if (urlNode != null) {
                                Util.newWindow(driver);
                            }
                            Util.get(driver, url, false);
                        }
                        if (urlNode != null) {
                            newHandle = driver.getWindowHandle();
                        }
                        Util.doClicks(driver, clicks, null);
                        content = driver.getPageSource();
                        if (CommonUtil.isEmpty(content)) {
                            cached = true;
                        }
                    }
                    if (cached) {
                        if (ScreenSlicerBatch.isCancelled(runGuid)) {
                            return;
                        }
                        Util.get(driver, toCacheUrl(url), false);
                        content = driver.getPageSource();
                    }
                    content = Util.clean(content, driver.getCurrentUrl()).outerHtml();
                    if (WebApp.DEBUG) {
                        try {
                            FileUtils.writeStringToFile(new File("./" + System.currentTimeMillis()), content);
                        } catch (IOException e) {
                        }
                    }
                    //TODO make iframes work
                    //            if (!CommonUtil.isEmpty(content)) {
                    //              Document doc = Jsoup.parse(content);
                    //              Elements docFrames = doc.getElementsByTag("iframe");
                    //              List<WebElement> iframes = driver.findElementsByTagName("iframe");
                    //              int cur = 0;
                    //              for (WebElement iframe : iframes) {
                    //                try {
                    //                  driver.switchTo().frame(iframe);
                    //                  String frameSrc = driver.getPageSource();
                    //                  if (!CommonUtil.isEmpty(frameSrc) && cur < docFrames.size()) {
                    //                    docFrames.get(cur).html(
                    //                        Util.outerHtml(Jsoup.parse(frameSrc).body().childNodes()));
                    //                  }
                    //                } catch (Throwable t) {
                    //                  Log.exception(t);
                    //                }
                    //                ++cur;
                    //              }
                    //              driver.switchTo().defaultContent();
                    //              content = doc.outerHtml();
                    //            }
                    synchronized (resultLock) {
                        result[0] = content;
                    }
                } catch (Throwable t) {
                    Log.exception(t);
                } finally {
                    synchronized (resultLock) {
                        if (initVal.equals(result[0])) {
                            result[0] = null;
                        }
                    }
                    Util.driverSleepRandLong();
                    if (newHandle != null && origHandle != null) {
                        try {
                            Util.cleanUpNewWindows(driver, origHandle);
                        } catch (Throwable t) {
                            Log.exception(t);
                        }
                    }
                }
            }
        });
        thread.start();
        try {
            while (!started.get()) {
                try {
                    Thread.sleep(WAIT);
                } catch (Throwable t) {
                    Log.exception(t);
                }
            }
            thread.join(HANG_TIME);
            synchronized (resultLock) {
                if (initVal.equals(result[0])) {
                    try {
                        Log.exception(new Exception("Browser is hanging"));
                        forceQuit();
                        thread.interrupt();
                    } catch (Throwable t) {
                        Log.exception(t);
                    }
                    throw new ActionFailed();
                } else if (urlHash != null && !CommonUtil.isEmpty(result[0])
                        && result[0].length() > MIN_FETCH_CACHE_PAGE_LEN) {
                    synchronized (fetchLocalCacheLock) {
                        if (fetchLocalCache.size() > MAX_FETCH_LOCAL_CACHE) {
                            try {
                                FileUtils.deleteQuietly(new File("./fetch_local_cache"));
                                FileUtils.forceMkdir(new File("./fetch_local_cache"));
                            } catch (Throwable t) {
                                Log.exception(t);
                            }
                            fetchLocalCache.clear();
                        }
                        FileUtils.writeStringToFile(new File("./fetch_local_cache/" + urlHash), result[0],
                                "utf-8", false);
                        fetchLocalCache.put(urlHash, time);
                    }
                }
                return result[0];
            }
        } catch (Throwable t) {
            Log.exception(t);
        }
    }
    return null;
}

From source file:org.yccheok.jstock.gui.MainFrame.java

private void initMarketThread() {
    final Thread oldMarketThread = marketThread;
    if (oldMarketThread != null) {
        zombiePool.execute(new Runnable() {
            @Override// w w w.j  a v  a 2 s. c o m
            public void run() {
                log.info("Prepare to shut down market thread " + oldMarketThread + "...");
                oldMarketThread.interrupt();
                try {
                    oldMarketThread.join();
                } catch (InterruptedException ex) {
                    log.error(null, ex);
                }
                log.info("Shut down market thread " + oldMarketThread + " peacefully.");
            }
        });
    }

    this.marketThread = new Thread(new MarketRunnable());
    this.marketThread.start();
}