Search in sources :

Example 16 with Connection

use of org.openmuc.j62056.Connection in project intellij-community by JetBrains.

the class SingleThreadStdoutStderr method main.

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "joe";
    String password = "joespass";
    try {
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* Now connect */
        conn.connect();
        /* Authenticate */
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* Create a session */
        Session sess = conn.openSession();
        sess.execCommand("echo \"Huge amounts of text on STDOUT\"; echo \"Huge amounts of text on STDERR\" >&2");
        /*
			 * Advanced:
			 * The following is a demo on how one can read from stdout and
			 * stderr without having to use two parallel worker threads (i.e.,
			 * we don't use the Streamgobblers here) and at the same time not
			 * risking a deadlock (due to a filled SSH2 channel window, caused
			 * by the stream which you are currently NOT reading from =).
			 */
        /* Don't wrap these streams and don't let other threads work on
			 * these streams while you work with Session.waitForCondition()!!!
			 */
        InputStream stdout = sess.getStdout();
        InputStream stderr = sess.getStderr();
        byte[] buffer = new byte[8192];
        while (true) {
            if ((stdout.available() == 0) && (stderr.available() == 0)) {
                /* Even though currently there is no data available, it may be that new data arrives
					 * and the session's underlying channel is closed before we call waitForCondition().
					 * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may
					 * be set together.
					 */
                int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 2000);
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                    /* A timeout occured. */
                    throw new IOException("Timeout while waiting for data from peer.");
                }
                if ((conditions & ChannelCondition.EOF) != 0) {
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        /* ... and we have consumed all data in the local arrival window. */
                        break;
                    }
                }
            /* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */
            // You can be paranoid and check that the library is not going nuts:
            // if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)
            //	throw new IllegalStateException("Unexpected condition result (" + conditions + ")");
            }
            while (stdout.available() > 0) {
                int len = stdout.read(buffer);
                if (// this check is somewhat paranoid
                len > 0)
                    System.out.write(buffer, 0, len);
            }
            while (stderr.available() > 0) {
                int len = stderr.read(buffer);
                if (// this check is somewhat paranoid
                len > 0)
                    System.err.write(buffer, 0, len);
            }
        }
        /* Close this session */
        sess.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) Session(com.trilead.ssh2.Session)

Example 17 with Connection

use of org.openmuc.j62056.Connection in project intellij-community by JetBrains.

the class StdoutAndStderr method main.

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "joe";
    String password = "joespass";
    try {
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* Now connect */
        conn.connect();
        /* Authenticate */
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* Create a session */
        Session sess = conn.openSession();
        sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2");
        InputStream stdout = new StreamGobbler(sess.getStdout());
        InputStream stderr = new StreamGobbler(sess.getStderr());
        BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
        BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
        System.out.println("Here is the output from stdout:");
        while (true) {
            String line = stdoutReader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        System.out.println("Here is the output from stderr:");
        while (true) {
            String line = stderrReader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        /* Close this session */
        sess.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : StreamGobbler(com.trilead.ssh2.StreamGobbler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Session(com.trilead.ssh2.Session)

Example 18 with Connection

use of org.openmuc.j62056.Connection in project BookReader by JustWayward.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            logger.log("");
            logger.log(buffer.readString(charset));
            logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        }
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 19 with Connection

use of org.openmuc.j62056.Connection in project zm-mailbox by Zimbra.

the class RemoteManager method getSession.

private Session getSession() throws ServiceException {
    try {
        mConnection = new Connection(mHost, mPort);
        mConnection.connect();
        if (!mConnection.authenticateWithPublicKey(mUser, mPrivateKey, null)) {
            throw new IOException("auth failed");
        }
        return mConnection.openSession();
    } catch (IOException ioe) {
        if (mConnection != null) {
            mConnection.close();
        }
        throw ServiceException.FAILURE("exception during auth " + this, ioe);
    }
}
Also used : Connection(ch.ethz.ssh2.Connection) IOException(java.io.IOException)

Example 20 with Connection

use of org.openmuc.j62056.Connection in project wildfly by wildfly.

the class ConnectionSecurityContext method getConnectionPrincipals.

/**
     * Obtain a {@link Collection} containing the {@link Principal} instances for the user associated with the connection.
     *
     * Note: This method should be called from within a {@link PrivilegedAction}.
     *
     * @return The Collection of Principals for the user authenticated with the connection. An empty Collection will be returned
     *         of no user is associated with the connection, {@code null} will be returned if no connection is associated with
     *         the {@link Thread}
     */
public static Collection<Principal> getConnectionPrincipals() {
    Connection con = RemotingContext.getConnection();
    if (con != null) {
        Collection<Principal> principals = new HashSet<>();
        SecurityIdentity localIdentity = con.getLocalIdentity();
        if (localIdentity != null) {
            principals.add(new RealmUser(localIdentity.getPrincipal().getName()));
            StreamSupport.stream(localIdentity.getRoles().spliterator(), true).forEach((String role) -> {
                principals.add(new RealmGroup(role));
                principals.add(new RealmRole(role));
            });
            return principals;
        } else {
            return Collections.emptySet();
        }
    }
    return null;
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) RealmRole(org.jboss.as.core.security.RealmRole) RealmGroup(org.jboss.as.core.security.RealmGroup) Connection(org.jboss.remoting3.Connection) RealmUser(org.jboss.as.core.security.RealmUser) Principal(java.security.Principal) HashSet(java.util.HashSet)

Aggregations

Connection (com.trilead.ssh2.Connection)40 Session (com.trilead.ssh2.Session)31 IOException (java.io.IOException)28 InputStream (java.io.InputStream)21 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 SCPClient (com.trilead.ssh2.SCPClient)7 Connection (org.jboss.remoting3.Connection)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 Connection (okhttp3.Connection)5 Request (okhttp3.Request)5 Connection (ch.ethz.ssh2.Connection)4 File (java.io.File)4 Principal (java.security.Principal)4 MediaType (okhttp3.MediaType)4 RequestBody (okhttp3.RequestBody)4 Response (okhttp3.Response)4 ResponseBody (okhttp3.ResponseBody)4 SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)4