Search in sources :

Example 46 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project MVPFrames by RockyQu.

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);
    }
    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;
    if (hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    log(requestStartMessage);
    // Content-Type
    if (hasRequestBody) {
        if (requestBody.contentType() != null) {
            log("Content-Type: " + requestBody.contentType());
        }
        if (requestBody.contentLength() != -1) {
            log("Content-Length: " + requestBody.contentLength());
        }
    }
    // 拼装请求参数
    Headers headers = request.headers();
    for (int i = 0, count = headers.size(); i < count; i++) {
        String name = headers.name(i);
        if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
            log(name + ": " + headers.value(i));
        }
    }
    // Request结束
    if (!hasRequestBody) {
        log("--> END " + request.method());
    } else if (bodyEncoded(request.headers())) {
        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);
        }
        if (isPlaintext(buffer)) {
            log(buffer.readString(charset));
            log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        } else {
            log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
        }
    }
    // Response开始
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (", " + bodySize + " body") + ')');
    headers = response.headers();
    for (int i = 0, count = headers.size(); i < count; i++) {
        log(headers.name(i) + ": " + headers.value(i));
    }
    if (!HttpHeaders.hasBody(response)) {
        log("<-- END HTTP");
    } else if (bodyEncoded(response.headers())) {
        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) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                log("Couldn't decode the response body; charset is likely malformed.");
                log("<-- END HTTP");
                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
            return response;
        }
        if (contentLength != 0) {
            log(buffer.clone().readString(charset));
        }
        log("<-- END HTTP (" + buffer.size() + "-byte body)");
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 47 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project okHttp-Util-gson by xwdz.

the class HttpLoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    HttpLoggingInterceptor.Level level = this.level;
    Request request = chain.request();
    if (level == HttpLoggingInterceptor.Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == HttpLoggingInterceptor.Level.BODY;
    boolean logHeaders = logBody || level == HttpLoggingInterceptor.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;
    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("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
            }
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    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 || !HttpHeaders.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) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    logger.log("");
                    logger.log("Couldn't decode the response body; charset is likely malformed.");
                    logger.log("<-- END HTTP");
                    return response;
                }
            }
            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
            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) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 48 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project wildfly-core by wildfly.

the class JConsoleCLIPlugin method connectUsingRemoting.

private boolean connectUsingRemoting(CommandContext cmdCtx, RemotingMBeanServerConnection rmtMBeanSvrConn) throws IOException, CliInitializationException {
    Connection conn = rmtMBeanSvrConn.getConnection();
    Channel channel;
    final IoFuture<Channel> futureChannel = conn.openChannel("management", OptionMap.EMPTY);
    IoFuture.Status result = futureChannel.await(5, TimeUnit.SECONDS);
    if (result == IoFuture.Status.DONE) {
        channel = futureChannel.get();
    } else {
        futureChannel.cancel();
        return false;
    }
    ModelControllerClient modelCtlrClient = ExistingChannelModelControllerClient.createReceiving(channel, createExecutor());
    cmdCtx.bindClient(modelCtlrClient);
    return true;
}
Also used : ExistingChannelModelControllerClient(org.jboss.as.controller.client.impl.ExistingChannelModelControllerClient) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) Channel(org.jboss.remoting3.Channel) Connection(org.jboss.remoting3.Connection) MBeanServerConnection(javax.management.MBeanServerConnection) RemotingMBeanServerConnection(org.jboss.remotingjmx.RemotingMBeanServerConnection) IoFuture(org.xnio.IoFuture)

Example 49 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project wildfly-core by wildfly.

the class RemoteDomainConnection method openConnection.

/**
 * Connect and register at the remote domain controller.
 *
 * @return connection the established connection
 * @throws IOException
 */
protected Connection openConnection() throws IOException {
    // Perhaps this can just be done once?
    CallbackHandler callbackHandler = null;
    SSLContext sslContext = null;
    final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);
    // TODO this needs cleaning up.
    config.setCallbackHandler(callbackHandler);
    config.setSslContext(sslContext);
    config.setUri(uri);
    AuthenticationContext authenticationContext = this.authenticationContext != null ? this.authenticationContext : AuthenticationContext.captureCurrent();
    // Connect
    try {
        return authenticationContext.run((PrivilegedExceptionAction<Connection>) () -> ProtocolConnectionUtils.connectSync(config));
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        }
        throw new IOException(e);
    }
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) AuthenticationContext(org.wildfly.security.auth.client.AuthenticationContext) PrivilegedActionException(java.security.PrivilegedActionException) ProtocolConnectionConfiguration(org.jboss.as.protocol.ProtocolConnectionConfiguration) Connection(org.jboss.remoting3.Connection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException)

Example 50 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project wildfly-core by wildfly.

the class HostControllerConnection method doReConnect.

/**
 * Reconnect to the HC.
 *
 * @return whether the server is still in sync
 * @throws IOException
 */
synchronized boolean doReConnect() throws IOException {
    // In case we are still connected, test the connection and see if we can reuse it
    if (connectionManager.isConnected()) {
        try {
            final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();
            // Hmm, perhaps 15 is already too much
            result.get(15, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            ServerLogger.AS_ROOT_LOGGER.debugf(e, "failed to ping the host-controller, going to reconnect");
        }
        // Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect
        final Connection connection = connectionManager.getConnection();
        StreamUtils.safeClose(connection);
        if (connection != null) {
            try {
                // Wait for the connection to be closed
                connection.awaitClosed();
            } catch (InterruptedException e) {
                throw new InterruptedIOException();
            }
        }
    }
    boolean ok = false;
    final Connection connection = connectionManager.connect();
    try {
        // Reconnect to the host-controller
        final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);
        try {
            boolean inSync = result.getResult().get();
            ok = true;
            reconnectRunner = null;
            return inSync;
        } catch (ExecutionException e) {
            throw new IOException(e);
        } catch (InterruptedException e) {
            throw new InterruptedIOException();
        }
    } finally {
        if (!ok) {
            StreamUtils.safeClose(connection);
        }
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) Connection(org.jboss.remoting3.Connection) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

IOException (java.io.IOException)68 Connection (org.ovirt.engine.sdk4.Connection)64 Connection (com.trilead.ssh2.Connection)61 Connection (org.osate.aadl2.Connection)57 Session (com.trilead.ssh2.Session)33 Connection (org.jboss.remoting3.Connection)33 Connection (com.google.cloud.bigquery.connection.v1.Connection)31 Test (org.junit.Test)30 VmsService (org.ovirt.engine.sdk4.services.VmsService)30 Vm (org.ovirt.engine.sdk4.types.Vm)30 InputStream (java.io.InputStream)29 Connection (okhttp3.Connection)28 Connection (ch.ethz.ssh2.Connection)24 Request (okhttp3.Request)20 Subcomponent (org.osate.aadl2.Subcomponent)19 FeatureGroupConnection (org.osate.aadl2.FeatureGroupConnection)18 PortConnection (org.osate.aadl2.PortConnection)18 VmService (org.ovirt.engine.sdk4.services.VmService)18 ArrayList (java.util.ArrayList)17 Response (okhttp3.Response)17