use of org.openmuc.j60870.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;
}
use of org.openmuc.j60870.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;
}
use of org.openmuc.j60870.Connection in project cosmic by MissionCriticalCloud.
the class SshHelper method scpTo.
public static void scpTo(final String host, final int port, final String user, final File pemKeyFile, final String password, final String remoteTargetDirectory, final byte[] data, final String remoteFileName, final String fileMode, final int connectTimeoutInMs, final int kexTimeoutInMs) throws Exception {
com.trilead.ssh2.Connection conn = null;
com.trilead.ssh2.SCPClient scpClient = null;
try {
conn = new com.trilead.ssh2.Connection(host, port);
conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
if (pemKeyFile == null) {
if (!conn.authenticateWithPassword(user, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
} else {
if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
}
scpClient = conn.createSCPClient();
if (fileMode != null) {
scpClient.put(data, remoteFileName, remoteTargetDirectory, fileMode);
} else {
scpClient.put(data, remoteFileName, remoteTargetDirectory);
}
} finally {
if (conn != null) {
conn.close();
}
}
}
use of org.openmuc.j60870.Connection in project cosmic by MissionCriticalCloud.
the class SshHelper method scpTo.
public static void scpTo(final String host, final int port, final String user, final File pemKeyFile, final String password, final String remoteTargetDirectory, final String localFile, final String fileMode, final int connectTimeoutInMs, final int kexTimeoutInMs) throws Exception {
com.trilead.ssh2.Connection conn = null;
com.trilead.ssh2.SCPClient scpClient = null;
try {
conn = new com.trilead.ssh2.Connection(host, port);
conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
if (pemKeyFile == null) {
if (!conn.authenticateWithPassword(user, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
} else {
if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
}
scpClient = conn.createSCPClient();
if (fileMode != null) {
scpClient.put(localFile, remoteTargetDirectory, fileMode);
} else {
scpClient.put(localFile, remoteTargetDirectory);
}
} finally {
if (conn != null) {
conn.close();
}
}
}
use of org.openmuc.j60870.Connection in project cosmic by MissionCriticalCloud.
the class SshHelper method sshExecute.
public static Pair<Boolean, String> sshExecute(final String host, final int port, final String user, final File pemKeyFile, final String password, final String command, final int connectTimeoutInMs, final int kexTimeoutInMs, final int waitResultTimeoutInMs) throws Exception {
com.trilead.ssh2.Connection conn = null;
com.trilead.ssh2.Session sess = null;
try {
conn = new com.trilead.ssh2.Connection(host, port);
conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
if (pemKeyFile == null) {
if (!conn.authenticateWithPassword(user, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
} else {
if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
final String msg = "Failed to authentication SSH user " + user + " on host " + host;
s_logger.error(msg);
throw new Exception(msg);
}
}
sess = openConnectionSession(conn);
sess.execCommand(command);
final InputStream stdout = sess.getStdout();
final InputStream stderr = sess.getStderr();
final byte[] buffer = new byte[8192];
final StringBuffer sbResult = new StringBuffer();
int currentReadBytes = 0;
while (true) {
throwSshExceptionIfStdoutOrStdeerIsNull(stdout, stderr);
if ((stdout.available() == 0) && (stderr.available() == 0)) {
final int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, waitResultTimeoutInMs);
throwSshExceptionIfConditionsTimeout(conditions);
if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
break;
}
if (canEndTheSshConnection(waitResultTimeoutInMs, sess, conditions)) {
break;
}
}
while (stdout.available() > 0) {
currentReadBytes = stdout.read(buffer);
sbResult.append(new String(buffer, 0, currentReadBytes));
}
while (stderr.available() > 0) {
currentReadBytes = stderr.read(buffer);
sbResult.append(new String(buffer, 0, currentReadBytes));
}
}
final String result = sbResult.toString();
if (sess.getExitStatus() == null) {
// Exit status is NOT available. Returning failure result.
s_logger.error(String.format("SSH execution of command %s has no exit status set. Result output: %s", command, result));
return new Pair<>(false, result);
}
if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
s_logger.error(String.format("SSH execution of command %s has an error status code in return. Result output: %s", command, result));
return new Pair<>(false, result);
}
return new Pair<>(true, result);
} finally {
if (sess != null) {
sess.close();
}
if (conn != null) {
conn.close();
}
}
}
Aggregations