Example usage for java.lang InterruptedException toString

List of usage examples for java.lang InterruptedException toString

Introduction

In this page you can find the example usage for java.lang InterruptedException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.apache.synapse.samples.framework.clients.EventSampleClient.java

public SampleClientResult subscribe(String addUrl, String address, String expires, String topic) {
    OMElement subscribeOm = factory.createOMElement("Subscribe", eventingNamespace);
    OMElement deliveryOm = factory.createOMElement("Delivery", eventingNamespace);
    deliveryOm.addAttribute(factory.createOMAttribute("Mode", null,
            "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push"));
    OMElement notifyToOm = factory.createOMElement("NotifyTo", eventingNamespace);
    OMElement addressOm = factory.createOMElement("Address", addressingNamespace);
    factory.createOMText(addressOm, address);
    OMElement expiresOm = factory.createOMElement("Expires", eventingNamespace);
    factory.createOMText(expiresOm, expires);
    OMElement filterOm = factory.createOMElement("Filter", eventingNamespace);
    filterOm.addAttribute(factory.createOMAttribute("Dialect", null,
            "http://synapse.apache.org/eventing/dialect/topicFilter"));
    factory.createOMText(filterOm, topic);

    notifyToOm.addChild(addressOm);/*from w w  w  . j  a  v a 2 s  .c om*/
    deliveryOm.addChild(notifyToOm);
    subscribeOm.addChild(deliveryOm);
    if (!(expires.equals("*"))) {
        subscribeOm.addChild(expiresOm); // Add only if the value provided
    }
    subscribeOm.addChild(filterOm);

    log.info("Subscribing: " + subscribeOm.toString());
    SampleClientResult clientResult = new SampleClientResult();
    try {
        initializeClient(addUrl);
        options.setAction("http://schemas.xmlsoap.org/ws/2004/08/eventing/Subscribe");

        OMElement response = serviceClient.sendReceive(subscribeOm);
        log.info("Subscribed to topic " + topic);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {

        }
        log.info("Response Received: " + response.toString());
        String subId = response
                .getFirstChildWithName(new QName(eventingNamespace.getNamespaceURI(), "SubscriptionManager"))
                .getFirstChildWithName(new QName(addressingNamespace.getNamespaceURI(), "ReferenceParameters"))
                .getFirstChildWithName(new QName(eventingNamespace.getNamespaceURI(), "Identifier")).getText();
        log.info("Subscription identifier: " + subId);
        clientResult.addProperty("subId", subId);
        clientResult.incrementResponseCount();
    } catch (Exception e) {
        log.error("Fault Received : " + e.toString(), e);
        clientResult.setException(e);
    }
    deInitializeClient();
    return clientResult;

}

From source file:org.tio.examples.im.client.ui.JFrameMain.java

private void sendBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendBtnActionPerformed
    sendBtn.setEnabled(false);/* w w  w  . j av a2  s .c o  m*/

    ClientGroupContext<ImSessionContext, ImPacket, Object> clientGroupContext = imClientStarter.getAioClient()
            .getClientGroupContext();
    setStartRecievedBytes(clientGroupContext.getGroupStat().getReceivedBytes().get());
    setStartSentBytes(clientGroupContext.getGroupStat().getSentBytes().get());

    JFrameMain.getInstance().getMsgTextArea().setText("");
    receivedPackets.set(0);
    sentPackets.set(0);

    String msg = msgField.getText();
    int loopcount = Integer.parseInt(loopcountField.getText());
    String toGroup = groupField.getText();
    ChatReqBody.Builder builder = ChatReqBody.newBuilder();
    builder.setTime(SystemTimer.currentTimeMillis());
    builder.setGroup(toGroup);
    builder.setType(ChatType.CHAT_TYPE_PUBLIC);
    builder.setText(msg);

    ChatReqBody chatReqBody = builder.build();
    setSendStartTime(SystemTimer.currentTimeMillis());

    byte[] body = chatReqBody.toByteArray();
    ImPacket packet = new ImPacket(body, Command.COMMAND_CHAT_REQ);

    if (listModel.size() == 0) {
        return;
    }
    ClientChannelContext<ImSessionContext, ImPacket, Object> channelContext = listModel.getElementAt(0);
    for (int i = 0; i < loopcount; i++) {
        Aio.send(channelContext, packet);
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.error(e.toString(), e);
            }
            sendBtn.setEnabled(true);
        }
    }).start();

}

From source file:com.panet.imeta.job.entries.shell.JobEntryShell.java

private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) {
    LogWriter log = LogWriter.getInstance();
    FileObject fileObject = null;
    String realScript = null;//w  w w  .j  a  v a  2 s  .c  o m
    FileObject tempFile = null;

    try {
        // What's the exact command?
        String base[] = null;
        List<String> cmds = new ArrayList<String>();

        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.RunningOn", Const.getOS()));

        if (insertScript) {
            realScript = environmentSubstitute(script);
        } else {
            String realFilename = environmentSubstitute(getFilename());
            fileObject = KettleVFS.getFileObject(realFilename);
        }

        if (Const.getOS().equals("Windows 95")) {
            base = new String[] { "command.com", "/C" };
        } else if (Const.getOS().startsWith("Windows")) {
            base = new String[] { "cmd.exe", "/C" };
        } else {
            if (!insertScript) {
                // Just set the command to the script we need to execute...
                //
                base = new String[] { KettleVFS.getFilename(fileObject) };
            } else {
                // Create a unique new temporary filename in the working directory, put the script in there
                // Set the permissions to execute and then run it...
                //
                try {
                    tempFile = KettleVFS.createTempFile("kettle", "shell", workDirectory);
                    tempFile.createFile();
                    OutputStream outputStream = tempFile.getContent().getOutputStream();
                    outputStream.write(realScript.getBytes());
                    outputStream.close();
                    String tempFilename = KettleVFS.getFilename(tempFile);
                    // Now we have to make this file executable...
                    // On Unix-like systems this is done using the command "/bin/chmod +x filename"
                    //
                    ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename);
                    Process proc = procBuilder.start();
                    // Eat/log stderr/stdout all messages in a different thread...
                    StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(),
                            toString() + " (stderr)");
                    StreamLogger outputLogger = new StreamLogger(proc.getInputStream(),
                            toString() + " (stdout)");
                    new Thread(errorLogger).start();
                    new Thread(outputLogger).start();
                    proc.waitFor();

                    // Now set this filename as the base command...
                    //
                    base = new String[] { tempFilename };
                } catch (Exception e) {
                    throw new Exception("Unable to create temporary file to execute script", e);
                }
            }
        }

        // Construct the arguments...
        if (argFromPrevious && cmdRows != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmdline.append(' ');
                        cmdline.append(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmds.add(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
            }
        } else if (args != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));

                for (int i = 0; i < args.length; i++) {
                    cmdline.append(' ');
                    cmdline.append(optionallyQuoteField(args[i], "\""));
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                for (int i = 0; i < args.length; i++) {
                    cmds.add(args[i]);
                }
            }
        }

        StringBuffer command = new StringBuffer();

        Iterator<String> it = cmds.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first)
                command.append(' ');
            else
                first = false;
            command.append((String) it.next());
        }
        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.ExecCommand", command.toString()));

        // Build the environment variable list...
        ProcessBuilder procBuilder = new ProcessBuilder(cmds);
        Map<String, String> env = procBuilder.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) {
            String vfsFilename = environmentSubstitute(getWorkDirectory());
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename)));
            procBuilder.directory(file);
        }
        Process proc = procBuilder.start();

        // any error message?
        StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(), toString() + " (stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(proc.getInputStream(), toString() + " (stdout)");

        // kick them off
        new Thread(errorLogger).start();
        new Thread(outputLogger).start();

        proc.waitFor();
        if (log.isDetailed())
            log.logDetailed(toString(), Messages.getString("JobShell.CommandFinished", command.toString()));

        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobShell.ExitStatus",
                        environmentSubstitute(getFilename()), "" + result.getExitStatus()));

            result.setNrErrors(1);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (IOException ioe) {
        log.logError(toString(), Messages.getString("JobShell.ErrorRunningShell",
                environmentSubstitute(getFilename()), ioe.toString()));
        result.setNrErrors(1);
    } catch (InterruptedException ie) {
        log.logError(toString(), Messages.getString("JobShell.Shellinterupted",
                environmentSubstitute(getFilename()), ie.toString()));
        result.setNrErrors(1);
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobShell.UnexpectedError",
                environmentSubstitute(getFilename()), e.toString()));
        result.setNrErrors(1);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                Messages.getString("JobShell.UnexpectedError", tempFile.toString(), e.toString());
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
}

From source file:com.talent.aio.examples.im.client.ui.JFrameMain.java

private void sendBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendBtnActionPerformed
    sendBtn.setEnabled(false);//from   w w w. j  a v a 2  s .  c om

    ClientGroupContext<Object, ImPacket, Object> clientGroupContext = imClientStarter.getAioClient()
            .getClientGroupContext();
    setStartRecievedBytes(clientGroupContext.getGroupStat().getReceivedBytes().get());
    setStartSentBytes(clientGroupContext.getGroupStat().getSentBytes().get());

    JFrameMain.getInstance().getMsgTextArea().setText("");
    receivedPackets.set(0);
    sentPackets.set(0);

    String msg = msgField.getText();
    int loopcount = Integer.parseInt(loopcountField.getText());
    String toGroup = groupField.getText();
    ChatReqBody.Builder builder = ChatReqBody.newBuilder();
    builder.setTime(SystemTimer.currentTimeMillis());
    builder.setGroup(toGroup);
    builder.setType(ChatType.pub);
    builder.setText(msg);

    ChatReqBody chatReqBody = builder.build();
    setSendStartTime(SystemTimer.currentTimeMillis());

    byte[] body = chatReqBody.toByteArray();
    ImPacket packet = new ImPacket(body, Command.CHAT_REQ);

    if (listModel.size() == 0) {
        return;
    }
    ClientChannelContext<Object, ImPacket, Object> channelContext = listModel.getElementAt(0);
    for (int i = 0; i < loopcount; i++) {
        Aio.send(channelContext, packet);
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.error(e.toString(), e);
            }
            sendBtn.setEnabled(true);
        }
    }).start();

}

From source file:byps.test.TestRemoteServerR.java

/**
 * Call a server function which in turn calls a client function many times simultaneously.
 * @throws BException/*from www  . j a  v  a2s  .c o m*/
 * @throws InterruptedException
 */
@Test
public void testCallClientFromServerParallel() throws RemoteException {
    log.info("testCallClientFromServerParallel(");

    int nbOfReverseRequests = 10;

    // (1) Provide implementation for interface ClientIF
    BClient_Testser client = TestUtilsHttp.createClient(nbOfReverseRequests);
    client.addRemote(new BSkeleton_ClientIF() {
        @Override
        public int incrementInt(int a) throws RemoteException {
            log.info("incrementInt(");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new BException(BExceptionC.CANCELLED, e.toString(), e);
            }
            log.info(")incrementInt");
            return 1;
        }
    });

    // (2) Call server method. 
    // On the server, this method calls the client-side interface 
    // from step (1)
    log.info("callClientIncrementInt...");
    int r = client.getServerIF().callClientParallel(nbOfReverseRequests);
    log.info("callClientIncrementInt OK");

    TestUtils.assertEquals(log, "callClientParallel", 10, r);

    log.info(")testCallClientFromServer");
}

From source file:se.lu.nateko.edca.svc.GeoHelper.java

/**
 * Pauses or resumes this AsyncTask if the external storage
 * becomes unavailable or is available again.
 *//*from   ww w .j a  va 2  s .  c  om*/
synchronized private void handleStorageChange() {
    //      Log.d(TAG, "handleStorageChange() called.");
    /* The external storage has become unavailable, pause the thread. */
    if (!mExternalStorageAvailable) {
        Log.w(TAG, "External storage made unavailable. Thread put on hold.");
        try {
            this.wait();
        } catch (InterruptedException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
    }
    /* The external storage cannot be written to and the mode requires this, pause the thread. */
    else if (!mExternalStorageWriteable && (mRwMode == RWMODE_WRITE || mRwMode == RWMODE_OVERWRITE)) {
        Log.w(TAG, "External storage made unavailable. Thread put on hold.");
        try {
            this.wait();
        } catch (InterruptedException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
    }
    /* The external storage can now be written to, resume the thread. */
    else if (mExternalStorageWriteable) {
        this.notify();
        Log.w(TAG, "External storage made available. Thread resumed.");
    }
    /* The external storage has become available and the mode only requires reading, resume the thread. */
    else if (mExternalStorageAvailable && mRwMode == RWMODE_READ) {
        this.notify();
        Log.w(TAG, "External storage made available. Thread resumed.");
    }
}

From source file:com.tencent.gaia.portal.util.Shell.java

/**
 * Run a command/* www  .  j  a  v  a2s  . c om*/
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        try {
            if (!completed.get()) {
                errThread.interrupt();
                errThread.join();
            }
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while joining errThread");
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:com.bringcommunications.etherpay.Payment_Processor.java

public void run() {
    while (true) {
        long wait_sec;
        do {//from w  w  w . ja  v a  2 s . c  o m
            wait_sec = Long.MAX_VALUE;
            synchronized (monitor) {
                long now_sec = System.currentTimeMillis() / 1000;
                if ((current_send_message != null && !current_send_message.is_suspended)
                        || (current_balance_message != null && !current_balance_message.is_suspended)) {
                    System.out.println("payment_processor::run - have active message"); //we have an active process... wait max time
                } else {
                    if (wait_sec > 0 && current_send_message != null) {
                        if ((wait_sec = Math.min(wait_sec,
                                Math.max(0, current_send_message.wait_until_sec - now_sec))) == 0) {
                            System.out.println("payment_processor::run - suspended send message is ready");
                            current_send_message.wait_until_sec = 0;
                        } else
                            System.out.println("payment_processor::run - have suspended send message ("
                                    + wait_sec + " more secs)");
                    }
                    if (wait_sec > 0 && current_balance_message != null) {
                        if ((wait_sec = Math.min(wait_sec,
                                Math.max(0, current_balance_message.wait_until_sec - now_sec))) == 0) {
                            System.out.println("payment_processor::run - suspended balance message is ready");
                            current_balance_message.wait_until_sec = 0;
                        } else
                            System.out.println("payment_processor::run - have suspended balance message ("
                                    + wait_sec + " more secs)");
                    }
                    if (wait_sec > 0 && current_send_message == null && !send_message_list.isEmpty()) {
                        System.out.println("payment_processor::run - got new send message");
                        current_send_message = send_message_list.remove(0);
                        wait_sec = 0;
                    }
                    if (wait_sec > 0 && current_balance_message == null && !balance_message_list.isEmpty()) {
                        System.out.println("payment_processor::run - got new balance message");
                        current_balance_message = balance_message_list.remove(0);
                        wait_sec = 0;
                    }
                }
                if (wait_sec > 0) {
                    wait_sec = Math.min(wait_sec, 15);
                    System.out.println("Payment_Processor waiting " + wait_sec + " seconds");
                    try {
                        monitor.wait(wait_sec * 1000);
                    } catch (InterruptedException e) {
                        System.out.println("Payment_Processor wait interrupted " + e.toString());
                    }
                }
            }
        } while (wait_sec > 0);
        if (current_send_message != null && current_send_message.wait_until_sec == 0) {
            System.out.println("Payment_Processor process send message");
            current_send_message.is_suspended = false;
            send_guts();
        } else if (current_balance_message != null && current_balance_message.wait_until_sec == 0) {
            System.out.println("Payment_Processor process balance message");
            current_balance_message.is_suspended = false;
            refresh_balance_guts();
        }
    }
}

From source file:org.apache.bookkeeper.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;//from  w ww .ja  v a  2 s . c  o m
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charsets.UTF_8));
    BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charsets.UTF_8));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = MathUtils.now();
    }
}

From source file:id.ac.idu.webui.order.OrderDialogCtrl.java

private void doPrintOrderReport(Event event) throws InterruptedException {

    Order anOrder = getOrder();/*from w  w w . j  av  a  2s  . co m*/

    Window win = (Window) Path.getComponent("/outerIndexWindow");

    try {
        new OrderDJReport(win, anOrder);
    } catch (final InterruptedException e) {
        ZksampleMessageUtils.showErrorMessage(e.toString());
    }

}