Example usage for java.lang IllegalThreadStateException IllegalThreadStateException

List of usage examples for java.lang IllegalThreadStateException IllegalThreadStateException

Introduction

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

Prototype

public IllegalThreadStateException(String s) 

Source Link

Document

Constructs an IllegalThreadStateException with the specified detail message.

Usage

From source file:com.hellblazer.process.impl.AbstractManagedProcess.java

@Override
public InputStream getStdOut() {
    try {/*  w  w  w .  j  a  va 2s .c o  m*/
        return new FileInputStream(getStdOutFile());
    } catch (FileNotFoundException e) {
        throw new IllegalThreadStateException("Process has not been started");
    }
}

From source file:com.hellblazer.process.impl.AbstractManagedProcess.java

@Override
public String getStdOutTail(int numLines) throws IOException {
    if (!getStdOutFile().exists()) {
        throw new IllegalThreadStateException("Process has not been started or has already exited");
    }/*w  w  w . jav a2 s  .  c om*/
    List<String> lines = new ArrayList<>();
    try (ReversedLinesFileReader reader = new ReversedLinesFileReader(getStdOutFile())) {
        int linesRead = 0;
        String line;
        while (((line = reader.readLine()) != null) && (linesRead++ < numLines)) {
            lines.add(line);
        }
    }
    Collections.reverse(lines);
    StringBuilder builder = new StringBuilder();
    for (String line : lines) {
        builder.append(line);
        builder.append('\n');
    }
    return builder.toString();
}

From source file:com.xebialabs.overthere.cifs.telnet.CifsTelnetConnection.java

@Override
public OverthereProcess startProcess(final CmdLine cmd) {
    checkNotNull(cmd, "Cannot execute null command line");
    checkArgument(cmd.getArguments().size() > 0, "Cannot execute empty command line");

    final String obfuscatedCmd = cmd.toCommandLine(os, true);
    logger.info("Starting command [{}] on [{}]", obfuscatedCmd, this);

    try {/*w  w  w.j a v a 2  s  . c om*/
        final TelnetClient tc = new TelnetClient();
        tc.setConnectTimeout(connectionTimeoutMillis);
        tc.addOptionHandler(new WindowSizeOptionHandler(299, 25, true, false, true, false));
        logger.info("Connecting to telnet://{}@{}", username, address);
        tc.connect(address, port);
        final InputStream stdout = tc.getInputStream();
        final OutputStream stdin = tc.getOutputStream();
        final PipedInputStream callersStdout = new PipedInputStream();
        final PipedOutputStream toCallersStdout = new PipedOutputStream(callersStdout);
        final ByteArrayOutputStream outputBuf = new ByteArrayOutputStream();
        final int[] exitValue = new int[1];
        exitValue[0] = -1;

        final Thread outputReaderThread = new Thread("Telnet output reader") {
            @Override
            public void run() {
                try {
                    receive(stdout, outputBuf, toCallersStdout, "ogin:");
                    send(stdin, username);

                    receive(stdout, outputBuf, toCallersStdout, "assword:");
                    send(stdin, password);

                    receive(stdout, outputBuf, toCallersStdout, ">", "ogon failure");
                    send(stdin, "PROMPT " + DETECTABLE_WINDOWS_PROMPT);
                    // We must wait for the prompt twice; the first time is an echo of the PROMPT command,
                    // the second is the actual prompt
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    if (workingDirectory != null) {
                        send(stdin, "CD /D " + workingDirectory.getPath());
                        receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    }

                    send(stdin, cmd.toCommandLine(getHostOperatingSystem(), false));

                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    send(stdin, "ECHO \"" + ERRORLEVEL_PREAMBLE + "%errorlevel%" + ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    String outputBufStr = outputBuf.toString();
                    int preamblePos = outputBufStr.indexOf(ERRORLEVEL_PREAMBLE);
                    int postamblePos = outputBufStr.indexOf(ERRORLEVEL_POSTAMBLE);
                    if (preamblePos >= 0 && postamblePos >= 0) {
                        String errorlevelString = outputBufStr
                                .substring(preamblePos + ERRORLEVEL_PREAMBLE.length(), postamblePos);
                        logger.debug("Errorlevel string found: {}", errorlevelString);

                        try {
                            synchronized (exitValue) {
                                exitValue[0] = Integer.parseInt(errorlevelString);
                            }
                        } catch (NumberFormatException exc) {
                            logger.error("Cannot parse errorlevel in Windows output: " + outputBuf);
                        }
                    } else {
                        logger.error("Cannot find errorlevel in Windows output: " + outputBuf);
                    }
                } catch (IOException exc) {
                    throw new RuntimeIOException(format("Cannot start command [%s] on [%s]", obfuscatedCmd,
                            CifsTelnetConnection.this), exc);
                } finally {
                    closeQuietly(toCallersStdout);
                }
            }
        };
        outputReaderThread.setDaemon(true);
        outputReaderThread.start();

        return new OverthereProcess() {
            @Override
            public synchronized OutputStream getStdin() {
                return stdin;
            }

            @Override
            public synchronized InputStream getStdout() {
                return callersStdout;
            }

            @Override
            public synchronized InputStream getStderr() {
                return new ByteArrayInputStream(new byte[0]);
            }

            @Override
            public synchronized int waitFor() {
                if (!tc.isConnected()) {
                    return exitValue[0];
                }

                try {
                    try {
                        outputReaderThread.join();
                    } finally {
                        disconnect();
                    }
                    return exitValue[0];
                } catch (InterruptedException exc) {
                    throw new RuntimeIOException(format("Cannot start command [%s] on [%s]", obfuscatedCmd,
                            CifsTelnetConnection.this), exc);
                }
            }

            @Override
            public synchronized void destroy() {
                if (!tc.isConnected()) {
                    return;
                }

                disconnect();
            }

            private synchronized void disconnect() {
                try {
                    tc.disconnect();
                    logger.info("Disconnected from {}", CifsTelnetConnection.this);

                    closeQuietly(toCallersStdout);
                } catch (IOException exc) {
                    throw new RuntimeIOException(format("Cannot disconnect from %s", CifsTelnetConnection.this),
                            exc);
                }
            }

            @Override
            public synchronized int exitValue() {
                if (tc.isConnected()) {
                    throw new IllegalThreadStateException(
                            format("Process for command [%s] on %s is still running", obfuscatedCmd,
                                    CifsTelnetConnection.this));
                }

                synchronized (exitValue) {
                    return exitValue[0];
                }
            }
        };
    } catch (InvalidTelnetOptionException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    } catch (IOException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    }
}

From source file:com.xebialabs.overthere.telnet.TelnetConnection.java

@Override
public OverthereProcess startProcess(final CmdLine cmd) {
    checkNotNull(cmd, "Cannot execute null command line");
    checkArgument(cmd.getArguments().size() > 0, "Cannot execute empty command line");

    final String obfuscatedCmd = cmd.toCommandLine(os, true);
    logger.info("Starting command [{}] on [{}]", obfuscatedCmd, this);

    try {/*from w  w w. j av a  2s. c  o  m*/
        final TelnetClient tc = new TelnetClient();
        tc.setSocketFactory(mapper.socketFactory());
        tc.setConnectTimeout(connectionTimeoutMillis);
        tc.addOptionHandler(new WindowSizeOptionHandler(299, 25, true, false, true, false));
        logger.info("Connecting to telnet://{}@{}", username, address);
        tc.connect(address, port);
        tc.setSoTimeout(socketTimeoutMillis);
        final InputStream stdout = tc.getInputStream();
        final OutputStream stdin = tc.getOutputStream();
        final PipedInputStream callersStdout = new PipedInputStream();
        final PipedOutputStream toCallersStdout = new PipedOutputStream(callersStdout);
        final ByteArrayOutputStream outputBuf = new ByteArrayOutputStream();
        final int[] exitValue = new int[1];
        exitValue[0] = -1;

        final Thread outputReaderThread = new Thread("Telnet output reader") {
            @Override
            public void run() {
                try {
                    receive(stdout, outputBuf, toCallersStdout, "ogin:");
                    send(stdin, username);

                    receive(stdout, outputBuf, toCallersStdout, "assword:");
                    send(stdin, password);

                    receive(stdout, outputBuf, toCallersStdout, ">", "ogon failure");
                    send(stdin, "PROMPT " + DETECTABLE_WINDOWS_PROMPT);
                    // We must wait for the prompt twice; the first time is an echo of the PROMPT command,
                    // the second is the actual prompt
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    if (workingDirectory != null) {
                        send(stdin, "CD /D " + workingDirectory.getPath());
                        receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);
                    }

                    send(stdin, cmd.toCommandLine(os, false));

                    receive(stdout, outputBuf, toCallersStdout, DETECTABLE_WINDOWS_PROMPT);

                    send(stdin, "ECHO \"" + ERRORLEVEL_PREAMBLE + "%errorlevel%" + ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    receive(stdout, outputBuf, toCallersStdout, ERRORLEVEL_POSTAMBLE);
                    String outputBufStr = outputBuf.toString();
                    int preamblePos = outputBufStr.indexOf(ERRORLEVEL_PREAMBLE);
                    int postamblePos = outputBufStr.indexOf(ERRORLEVEL_POSTAMBLE);
                    if (preamblePos >= 0 && postamblePos >= 0) {
                        String errorlevelString = outputBufStr
                                .substring(preamblePos + ERRORLEVEL_PREAMBLE.length(), postamblePos);
                        logger.debug("Errorlevel string found: {}", errorlevelString);

                        try {
                            synchronized (exitValue) {
                                exitValue[0] = Integer.parseInt(errorlevelString);
                            }
                        } catch (NumberFormatException exc) {
                            logger.error("Cannot parse errorlevel in Windows output: " + outputBuf);
                        }
                    } else {
                        logger.error("Cannot find errorlevel in Windows output: " + outputBuf);
                    }
                } catch (IOException exc) {
                    throw new RuntimeIOException(
                            format("Cannot start command [%s] on [%s]", obfuscatedCmd, TelnetConnection.this),
                            exc);
                } finally {
                    closeQuietly(toCallersStdout);
                }
            }
        };
        outputReaderThread.setDaemon(true);
        outputReaderThread.start();

        return new OverthereProcess() {
            @Override
            public synchronized OutputStream getStdin() {
                return stdin;
            }

            @Override
            public synchronized InputStream getStdout() {
                return callersStdout;
            }

            @Override
            public synchronized InputStream getStderr() {
                return new ByteArrayInputStream(new byte[0]);
            }

            @Override
            public synchronized int waitFor() {
                if (!tc.isConnected()) {
                    return exitValue[0];
                }

                try {
                    try {
                        outputReaderThread.join();
                    } finally {
                        disconnect();
                    }
                    return exitValue[0];
                } catch (InterruptedException exc) {
                    throw new RuntimeIOException(
                            format("Cannot start command [%s] on [%s]", obfuscatedCmd, TelnetConnection.this),
                            exc);
                }
            }

            @Override
            public synchronized void destroy() {
                if (!tc.isConnected()) {
                    return;
                }

                disconnect();
            }

            private synchronized void disconnect() {
                try {
                    tc.disconnect();
                    logger.info("Disconnected from {}", TelnetConnection.this);

                    closeQuietly(toCallersStdout);
                } catch (IOException exc) {
                    throw new RuntimeIOException(format("Cannot disconnect from %s", TelnetConnection.this),
                            exc);
                }
            }

            @Override
            public synchronized int exitValue() {
                if (tc.isConnected()) {
                    throw new IllegalThreadStateException(
                            format("Process for command [%s] on %s is still running", obfuscatedCmd,
                                    TelnetConnection.this));
                }

                synchronized (exitValue) {
                    return exitValue[0];
                }
            }
        };
    } catch (InvalidTelnetOptionException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    } catch (IOException exc) {
        throw new RuntimeIOException(
                "Cannot execute command " + cmd + " at telnet://" + username + "@" + address, exc);
    }
}

From source file:org.psikeds.common.services.AbstractBaseService.java

private Object invokeSynchronous(final String reqId, final Executable reqExec, final Object reqData) {
    Object respData = null;//from w  w  w  .j a va  2 s  . c o m
    try {
        getLogger().trace("--> invokeSynchronous({}, {}, {})", reqId, reqExec, reqData);
        final Callback cb = new CallbackImpl(reqId, reqData);
        reqExec.setCallback(cb);
        this.executionStrategy.execute(reqExec);
        if (!cb.isFinished()) {
            final StringBuilder sb = new StringBuilder("This must never happen! Synchronous Execution of ");
            sb.append(reqId);
            sb.append(" ended without being finished!? Check implementation of Executable ");
            sb.append(reqExec);
            sb.append(" and Strategy ");
            sb.append(this.executionStrategy);
            final String msg = sb.toString();
            getLogger().error(msg);
            throw new IllegalThreadStateException(sb.toString());
        }
        respData = cb.getPayload();
        return respData;
    } finally {
        getLogger().trace("<-- invokeSynchronous({}, {}, {}); respData = {}", reqId, reqExec, reqData,
                respData);
    }
}

From source file:com.thinkbiganalytics.metadata.rest.client.MetadataClient.java

/**
 * gets a list of feeds matching the criteria given
 *
 * @param criteria the criteria of the feeds to return
 * @return a list of feeds// w  w  w.j a  v a  2s  . c  om
 */
public List<Feed> getFeeds(FeedCriteria criteria) {
    try {
        return get(path("feed"), (TargetFeedCriteria) criteria, FEED_LIST);
    } catch (ClassCastException e) {
        throw new IllegalThreadStateException("Unknown criteria type: " + criteria.getClass());
    }
}

From source file:com.thinkbiganalytics.metadata.rest.client.MetadataClient.java

/**
 * get the data sources available in the system, that match the criteria given
 *
 * @return the list of datasources/*from  w w  w  . ja va2 s . com*/
 */
public List<Datasource> getDatasources(DatasourceCriteria criteria) {
    try {
        return get(path("datasource"), (TargetDatasourceCriteria) criteria, DATASOURCE_LIST);
    } catch (ClassCastException e) {
        throw new IllegalThreadStateException("Unknown criteria type: " + criteria.getClass());
    }
}

From source file:com.microsoft.tfs.core.httpclient.MultiThreadedHttpConnectionManager.java

private HttpConnection doGetConnection(HostConfiguration hostConfiguration, final long timeout)
        throws ConnectionPoolTimeoutException {

    HttpConnection connection = null;/*  w  w w . ja  v  a2  s  .  c o  m*/

    final int maxHostConnections = params.getMaxConnectionsPerHost(hostConfiguration);
    final int maxTotalConnections = params.getMaxTotalConnections();

    synchronized (connectionPool) {

        // we clone the hostConfiguration
        // so that it cannot be changed once the connection has been
        // retrieved
        hostConfiguration = new HostConfiguration(hostConfiguration);
        final HostConnectionPool hostPool = connectionPool.getHostPool(hostConfiguration, true);
        WaitingThread waitingThread = null;

        final boolean useTimeout = (timeout > 0);
        long timeToWait = timeout;
        long startWait = 0;
        long endWait = 0;

        while (connection == null) {

            if (shutdown) {
                throw new IllegalStateException("Connection factory has been shutdown.");
            }

            // happen to have a free connection with the right specs
            //
            if (hostPool.freeConnections.size() > 0) {
                connection = connectionPool.getFreeConnection(hostConfiguration);

                // have room to make more
                //
            } else if ((hostPool.numConnections < maxHostConnections)
                    && (connectionPool.numConnections < maxTotalConnections)) {

                connection = connectionPool.createConnection(hostConfiguration);

                // have room to add host connection, and there is at least
                // one free
                // connection that can be liberated to make overall room
                //
            } else if ((hostPool.numConnections < maxHostConnections)
                    && (connectionPool.freeConnections.size() > 0)) {

                connectionPool.deleteLeastUsedConnection();
                connection = connectionPool.createConnection(hostConfiguration);

                // otherwise, we have to wait for one of the above
                // conditions to
                // become true
                //
            } else {
                // TODO: keep track of which hostConfigurations have waiting
                // threads, so they avoid being sacrificed before necessary

                try {

                    if (useTimeout && timeToWait <= 0) {
                        throw new ConnectionPoolTimeoutException("Timeout waiting for connection");
                    }

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Unable to get a connection, waiting..., hostConfig=" + hostConfiguration);
                    }

                    if (waitingThread == null) {
                        waitingThread = new WaitingThread();
                        waitingThread.hostConnectionPool = hostPool;
                        waitingThread.thread = Thread.currentThread();
                    } else {
                        waitingThread.interruptedByConnectionPool = false;
                    }

                    if (useTimeout) {
                        startWait = System.currentTimeMillis();
                    }

                    hostPool.waitingThreads.addLast(waitingThread);
                    connectionPool.waitingThreads.addLast(waitingThread);
                    connectionPool.wait(timeToWait);
                } catch (final InterruptedException e) {
                    if (!waitingThread.interruptedByConnectionPool) {
                        LOG.debug("Interrupted while waiting for connection", e);
                        throw new IllegalThreadStateException(
                                "Interrupted while waiting in MultiThreadedHttpConnectionManager");
                    }
                    // Else, do nothing, we were interrupted by the
                    // connection pool
                    // and should now have a connection waiting for us,
                    // continue
                    // in the loop and let's get it.
                } finally {
                    if (!waitingThread.interruptedByConnectionPool) {
                        // Either we timed out, experienced a
                        // "spurious wakeup", or were
                        // interrupted by an external thread. Regardless we
                        // need to
                        // cleanup for ourselves in the wait queue.
                        hostPool.waitingThreads.remove(waitingThread);
                        connectionPool.waitingThreads.remove(waitingThread);
                    }

                    if (useTimeout) {
                        endWait = System.currentTimeMillis();
                        timeToWait -= (endWait - startWait);
                    }
                }
            }
        }
    }

    LOG.debug("Using connection from the pool. ID = " + connection.getID());
    return connection;
}