use of java.nio.channels.WritableByteChannel in project linuxtools by eclipse.
the class DockerConnection method attachCommand.
public void attachCommand(final String id, final InputStream in, @SuppressWarnings("unused") final DockerConsoleOutputStream out) throws DockerException {
final byte[] prevCmd = new byte[1024];
try {
final LogStream pty_stream = client.attachContainer(id, AttachParameter.STDIN, AttachParameter.STDOUT, AttachParameter.STDERR, AttachParameter.STREAM, AttachParameter.LOGS);
final IDockerContainerInfo info = getContainerInfo(id);
final boolean isTtyEnabled = info.config().tty();
final boolean isOpenStdin = info.config().openStdin();
if (isTtyEnabled) {
openTerminal(pty_stream, info.name(), out);
}
// Data from the given input stream
// Written to container's STDIN
Thread t_in = new Thread(() -> {
byte[] buff = new byte[1024];
int n;
try {
WritableByteChannel pty_out = HttpHijackWorkaround.getOutputStream(pty_stream, getUri());
while ((n = in.read(buff)) != -1 && getContainerInfo(id).state().running()) {
synchronized (prevCmd) {
pty_out.write(ByteBuffer.wrap(buff, 0, n));
for (int i = 0; i < prevCmd.length; i++) {
prevCmd[i] = buff[i];
}
}
buff = new byte[1024];
}
} catch (Exception e) {
}
});
if (!isTtyEnabled && isOpenStdin) {
t_in.start();
}
} catch (Exception e) {
throw new DockerException(e.getMessage(), e.getCause());
}
}
use of java.nio.channels.WritableByteChannel in project linuxtools by eclipse.
the class HttpHijackWorkaround method getOutputStream.
public static WritableByteChannel getOutputStream(LogStream stream, String uri) throws Exception {
final String[] fields = new String[] { // $NON-NLS-1$
"reader", // $NON-NLS-1$
"stream", // $NON-NLS-1$
"original", // $NON-NLS-1$
"input", // $NON-NLS-1$
"in", // $NON-NLS-1$
"in", // $NON-NLS-1$
"wrappedStream", // $NON-NLS-1$
"in", // $NON-NLS-1$
"instream" };
final String[] declared = new String[] { "com.spotify.docker.client.DefaultLogStream", LogReader.class.getName(), // $NON-NLS-1$
"org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream", // $NON-NLS-1$
"org.glassfish.jersey.message.internal.EntityInputStream", FilterInputStream.class.getName(), FilterInputStream.class.getName(), // $NON-NLS-1$
"org.apache.http.conn.EofSensorInputStream", // $NON-NLS-1$
"org.apache.http.impl.io.IdentityInputStream", // $NON-NLS-1$
"org.apache.http.impl.io.SessionInputBufferImpl" };
final String[] bundles = new String[] { // $NON-NLS-1$
"org.glassfish.jersey.core.jersey-common", // $NON-NLS-1$
"org.apache.httpcomponents.httpcore", // $NON-NLS-1$
"org.apache.httpcomponents.httpclient" };
List<String[]> list = new LinkedList<>();
for (int i = 0; i < fields.length; i++) {
list.add(new String[] { declared[i], fields[i] });
}
try {
// See org.apache.http.impl.conn.LoggingManagedHttpClientConnection#getSocketInputStream()
// We need to perform : LogFactory.getLogger("org.apache.http.wire").isDebugEnabled()
Class<?> cLogFactory = null;
Class<?> cLog = null;
// $NON-NLS-1$
final String[] commonsLogging = new String[] { "org.apache.commons.logging" };
// $NON-NLS-1$
cLogFactory = loadClass("org.apache.commons.logging.LogFactory", commonsLogging);
// $NON-NLS-1$
cLog = loadClass("org.apache.commons.logging.Log", commonsLogging);
if (cLogFactory != null && cLog != null) {
// $NON-NLS-1$
Method mGetLog = cLogFactory.getMethod("getLog", String.class);
// $NON-NLS-1$
Object log = mGetLog.invoke(null, "org.apache.http.wire");
// $NON-NLS-1$
Method mIsDebug = cLog.getMethod("isDebugEnabled");
Boolean isDebug = (Boolean) mIsDebug.invoke(log);
if (isDebug.booleanValue()) {
// $NON-NLS-1$ //$NON-NLS-2$
list.add(new String[] { "org.apache.http.impl.conn.LoggingInputStream", "in" });
}
}
} catch (Exception e) {
}
if (uri.startsWith("unix:")) {
// $NON-NLS-1$
// $NON-NLS-1$ //$NON-NLS-2$
list.add(new String[] { "sun.nio.ch.ChannelInputStream", "ch" });
} else if (uri.startsWith("https:")) {
// $NON-NLS-1$
// $NON-NLS-1$
float jvmVersion = Float.parseFloat(System.getProperty("java.specification.version"));
String fName;
if (jvmVersion < 1.9f) {
// $NON-NLS-1$
fName = "c";
} else {
// $NON-NLS-1$
fName = "socket";
}
// $NON-NLS-1$
list.add(new String[] { "sun.security.ssl.AppInputStream", fName });
} else {
// $NON-NLS-1$ //$NON-NLS-2$
list.add(new String[] { "java.net.SocketInputStream", "socket" });
}
Object res = getInternalField(stream, list, bundles);
if (res instanceof WritableByteChannel) {
return (WritableByteChannel) res;
} else if (res instanceof Socket) {
return Channels.newChannel(((Socket) res).getOutputStream());
} else {
// TODO: throw an exception and let callers handle it.
return null;
}
}
use of java.nio.channels.WritableByteChannel in project opentheso by miledrousset.
the class FileUtilities method copyToStream.
/**
* Buffered copy of file to given output stream. Must be fast&furious... Omg
* it's not!
*/
public static void copyToStream(String from, OutputStream out) throws IOException {
WritableByteChannel outCh;
outCh = Channels.newChannel(out);
try {
FileInputStream inStream = new FileInputStream(from);
try {
FileChannel in = inStream.getChannel();
in.transferTo(0, in.size(), outCh);
} finally {
inStream.close();
}
} finally {
// so close out
outCh.close();
}
}
use of java.nio.channels.WritableByteChannel in project Payara by payara.
the class ModuleExtractor method copy.
/**
* Copies input to output. To avoid unnecessary allocation of byte buffers,
* this method takes a byte buffer as argument. It clears the byte buffer
* at the end of the operation.
*
* @param in
* @param out
* @param byteBuffer
*/
private static void copy(InputStream in, OutputStream out, ByteBuffer byteBuffer) throws IOException {
try {
ReadableByteChannel inChannel = Channels.newChannel(in);
WritableByteChannel outChannel = Channels.newChannel(out);
int read;
do {
read = inChannel.read(byteBuffer);
if (read > 0) {
byteBuffer.limit(byteBuffer.position());
byteBuffer.rewind();
int written = 0;
while ((written += outChannel.write(byteBuffer)) < read) {
// sometimes channel.write may write partial data,
// so ensure that the data is written fully.
}
if (logger.isLoggable(Level.FINER)) {
if (logger.isLoggable(Level.FINER)) {
logger.logp(Level.FINE, "JarHelper", "write", "Copied {0} bytes", new Object[] { read });
}
}
byteBuffer.clear();
}
} while (read != -1);
} finally {
byteBuffer.clear();
}
}
use of java.nio.channels.WritableByteChannel in project druid by druid-io.
the class CompressedIntsIndexedWriterTest method checkSerializedSizeAndData.
private void checkSerializedSizeAndData(int chunkFactor) throws Exception {
FileSmoosher smoosher = new FileSmoosher(FileUtils.getTempDirectory());
CompressedIntsIndexedWriter writer = new CompressedIntsIndexedWriter(ioPeon, "test", chunkFactor, byteOrder, compressionStrategy);
CompressedIntsIndexedSupplier supplierFromList = CompressedIntsIndexedSupplier.fromList(Ints.asList(vals), chunkFactor, byteOrder, compressionStrategy);
writer.open();
for (int val : vals) {
writer.add(val);
}
writer.close();
long writtenLength = writer.getSerializedSize();
final WritableByteChannel outputChannel = Channels.newChannel(ioPeon.makeOutputStream("output"));
writer.writeToChannel(outputChannel, smoosher);
outputChannel.close();
smoosher.close();
assertEquals(writtenLength, supplierFromList.getSerializedSize());
// read from ByteBuffer and check values
CompressedIntsIndexedSupplier supplierFromByteBuffer = CompressedIntsIndexedSupplier.fromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(ioPeon.makeInputStream("output"))), byteOrder, null);
IndexedInts indexedInts = supplierFromByteBuffer.get();
assertEquals(vals.length, indexedInts.size());
for (int i = 0; i < vals.length; ++i) {
assertEquals(vals[i], indexedInts.get(i));
}
CloseQuietly.close(indexedInts);
}
Aggregations