Search in sources :

Example 61 with WritableByteChannel

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());
    }
}
Also used : DockerException(org.eclipse.linuxtools.docker.core.DockerException) WritableByteChannel(java.nio.channels.WritableByteChannel) LogStream(com.spotify.docker.client.LogStream) IDockerContainerInfo(org.eclipse.linuxtools.docker.core.IDockerContainerInfo) DockerPingConnectionException(org.eclipse.linuxtools.docker.core.DockerPingConnectionException) DockerTimeoutException(com.spotify.docker.client.exceptions.DockerTimeoutException) ProcessingException(javax.ws.rs.ProcessingException) ContainerNotFoundException(com.spotify.docker.client.exceptions.ContainerNotFoundException) DockerCertificateException(com.spotify.docker.client.exceptions.DockerCertificateException) SocketException(java.net.SocketException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) StorageException(org.eclipse.equinox.security.storage.StorageException) DockerContainerNotFoundException(org.eclipse.linuxtools.docker.core.DockerContainerNotFoundException) DockerException(org.eclipse.linuxtools.docker.core.DockerException) DockerOpenConnectionException(org.eclipse.linuxtools.docker.core.DockerOpenConnectionException)

Example 62 with WritableByteChannel

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;
    }
}
Also used : WritableByteChannel(java.nio.channels.WritableByteChannel) Method(java.lang.reflect.Method) LinkedList(java.util.LinkedList) Socket(java.net.Socket)

Example 63 with WritableByteChannel

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();
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) WritableByteChannel(java.nio.channels.WritableByteChannel) FileInputStream(java.io.FileInputStream)

Example 64 with WritableByteChannel

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();
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) WritableByteChannel(java.nio.channels.WritableByteChannel)

Example 65 with WritableByteChannel

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);
}
Also used : FileSmoosher(io.druid.java.util.common.io.smoosh.FileSmoosher) WritableByteChannel(java.nio.channels.WritableByteChannel)

Aggregations

WritableByteChannel (java.nio.channels.WritableByteChannel)118 ByteBuffer (java.nio.ByteBuffer)35 ReadableByteChannel (java.nio.channels.ReadableByteChannel)30 ByteArrayOutputStream (java.io.ByteArrayOutputStream)28 FileOutputStream (java.io.FileOutputStream)24 Test (org.testng.annotations.Test)19 ByteArrayInputStream (java.io.ByteArrayInputStream)16 IOException (java.io.IOException)16 Test (org.junit.Test)15 File (java.io.File)13 OutputStream (java.io.OutputStream)12 DbusEventGenerator (com.linkedin.databus.core.test.DbusEventGenerator)10 Vector (java.util.Vector)10 FileInputStream (java.io.FileInputStream)7 Writer (java.io.Writer)6 FileChannel (java.nio.channels.FileChannel)6 DbusEventIterator (com.linkedin.databus.core.DbusEventBuffer.DbusEventIterator)4 PhysicalPartition (com.linkedin.databus.core.data_model.PhysicalPartition)4 DbusEventsStatisticsCollector (com.linkedin.databus.core.monitoring.mbean.DbusEventsStatisticsCollector)4 ClosedChannelException (java.nio.channels.ClosedChannelException)4