Search in sources :

Example 46 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project sis by apache.

the class StorageConnectorTest method testGetAsDataInput.

/**
 * Implementation of {@link #testGetAsDataInputFromURL()} and {@link #testGetAsDataInputFromStream()}.
 */
private void testGetAsDataInput(final boolean asStream) throws DataStoreException, IOException {
    final StorageConnector connection = create(asStream);
    final DataInput input = connection.getStorageAs(DataInput.class);
    assertSame("Value shall be cached.", input, connection.getStorageAs(DataInput.class));
    assertInstanceOf("Needs the SIS implementation.", ChannelImageInputStream.class, input);
    assertSame("Instance shall be shared.", input, connection.getStorageAs(ChannelDataInput.class));
    /*
         * Reads a single integer for checking that the stream is at the right position, then close the stream.
         * Since the file is a compiled Java class, the integer that we read shall be the Java magic number.
         */
    final ReadableByteChannel channel = ((ChannelImageInputStream) input).channel;
    assertTrue("channel.isOpen()", channel.isOpen());
    assertEquals("First 4 bytes", MAGIC_NUMBER, input.readInt());
    connection.closeAllExcept(null);
    assertFalse("channel.isOpen()", channel.isOpen());
}
Also used : DataInput(java.io.DataInput) ChannelDataInput(org.apache.sis.internal.storage.io.ChannelDataInput) ReadableByteChannel(java.nio.channels.ReadableByteChannel) ChannelImageInputStream(org.apache.sis.internal.storage.io.ChannelImageInputStream) ChannelDataInput(org.apache.sis.internal.storage.io.ChannelDataInput)

Example 47 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project lwjgl3-demos by LWJGL.

the class DemoUtils method ioResourceToByteBuffer.

/**
 * Reads the specified resource and returns the raw data as a ByteBuffer.
 *
 * @param resource   the resource to read
 * @param bufferSize the initial buffer size
 *
 * @return the resource data
 *
 * @throws IOException if an IO error occurs
 */
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
    ByteBuffer buffer;
    URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
    File file = new File(url.getFile());
    if (file.isFile()) {
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        fc.close();
        fis.close();
    } else {
        buffer = BufferUtils.createByteBuffer(bufferSize);
        InputStream source = url.openStream();
        if (source == null)
            throw new FileNotFoundException(resource);
        try {
            ReadableByteChannel rbc = Channels.newChannel(source);
            try {
                while (true) {
                    int bytes = rbc.read(buffer);
                    if (bytes == -1)
                        break;
                    if (buffer.remaining() == 0)
                        buffer = resizeBuffer(buffer, buffer.capacity() * 2);
                }
                buffer.flip();
            } finally {
                rbc.close();
            }
        } finally {
            source.close();
        }
    }
    return buffer;
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) FileChannel(java.nio.channels.FileChannel) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) ByteBuffer(java.nio.ByteBuffer) File(java.io.File) URL(java.net.URL) FileInputStream(java.io.FileInputStream)

Example 48 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project android_packages_apps_Updater by LineageOS.

the class FileUtils method copyFile.

public static void copyFile(File sourceFile, File destFile, ProgressCallBack progressCallBack) throws IOException {
    try (FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
        FileChannel destChannel = new FileOutputStream(destFile).getChannel()) {
        if (progressCallBack != null) {
            ReadableByteChannel readableByteChannel = new CallbackByteChannel(sourceChannel, sourceFile.length(), progressCallBack);
            destChannel.transferFrom(readableByteChannel, 0, sourceChannel.size());
        } else {
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        }
    } catch (IOException e) {
        Log.e(TAG, "Could not copy file", e);
        if (destFile.exists()) {
            destFile.delete();
        }
        throw e;
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) FileChannel(java.nio.channels.FileChannel) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 49 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project i2p.i2p by i2p.

the class SAMv3StreamSession method connect.

/**
 * Connect the SAM STREAM session to the specified Destination
 * for a single connection, using the socket stolen from the handler.
 *
 * @param handler The handler that communicates with the requesting client
 * @param dest Base64-encoded Destination to connect to
 * @param props Options to be used for connection
 *
 * @throws DataFormatException if the destination is not valid
 * @throws ConnectException if the destination refuses connections
 * @throws NoRouteToHostException if the destination can't be reached
 * @throws InterruptedIOException if the connection timeouts
 * @throws I2PException if there's another I2P-related error
 * @throws IOException
 */
public void connect(SAMv3Handler handler, String dest, Properties props) throws I2PException, ConnectException, NoRouteToHostException, DataFormatException, InterruptedIOException, IOException {
    boolean verbose = !Boolean.parseBoolean(props.getProperty("SILENT"));
    Destination d = SAMUtils.getDest(dest);
    I2PSocketOptions opts = socketMgr.buildOptions(props);
    if (props.getProperty(I2PSocketOptions.PROP_CONNECT_TIMEOUT) == null)
        opts.setConnectTimeout(60 * 1000);
    String fromPort = props.getProperty("FROM_PORT");
    if (fromPort != null) {
        try {
            opts.setLocalPort(Integer.parseInt(fromPort));
        } catch (NumberFormatException nfe) {
            throw new I2PException("Bad port " + fromPort);
        }
    }
    String toPort = props.getProperty("TO_PORT");
    if (toPort != null) {
        try {
            opts.setPort(Integer.parseInt(toPort));
        } catch (NumberFormatException nfe) {
            throw new I2PException("Bad port " + toPort);
        }
    }
    if (_log.shouldLog(Log.DEBUG))
        _log.debug("Connecting new I2PSocket...");
    // blocking connection (SAMv3)
    I2PSocket i2ps = socketMgr.connect(d, opts);
    SessionRecord rec = SAMv3Handler.sSessionsHash.get(nick);
    if (rec == null)
        throw new InterruptedIOException();
    handler.notifyStreamResult(verbose, "OK", null);
    handler.stealSocket();
    ReadableByteChannel fromClient = handler.getClientSocket();
    ReadableByteChannel fromI2P = Channels.newChannel(i2ps.getInputStream());
    WritableByteChannel toClient = handler.getClientSocket();
    WritableByteChannel toI2P = Channels.newChannel(i2ps.getOutputStream());
    SAMBridge bridge = handler.getBridge();
    (new I2PAppThread(rec.getThreadGroup(), new Pipe(fromClient, toI2P, bridge), "ConnectV3 SAMPipeClientToI2P")).start();
    (new I2PAppThread(rec.getThreadGroup(), new Pipe(fromI2P, toClient, bridge), "ConnectV3 SAMPipeI2PToClient")).start();
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) InterruptedIOException(java.io.InterruptedIOException) ReadableByteChannel(java.nio.channels.ReadableByteChannel) I2PSocket(net.i2p.client.streaming.I2PSocket) WritableByteChannel(java.nio.channels.WritableByteChannel) I2PSocketOptions(net.i2p.client.streaming.I2PSocketOptions) I2PAppThread(net.i2p.util.I2PAppThread)

Example 50 with ReadableByteChannel

use of java.nio.channels.ReadableByteChannel in project UnityModManager by xausky.

the class FileUtils method writeToFile.

public static void writeToFile(byte[] data, File target) throws IOException {
    FileOutputStream fo = null;
    ReadableByteChannel src = null;
    FileChannel out = null;
    try {
        src = Channels.newChannel(new ByteArrayInputStream(data));
        fo = new FileOutputStream(target);
        out = fo.getChannel();
        out.transferFrom(src, 0, data.length);
    } finally {
        if (fo != null) {
            fo.close();
        }
        if (src != null) {
            src.close();
        }
        if (out != null) {
            out.close();
        }
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) ByteArrayInputStream(java.io.ByteArrayInputStream) FileChannel(java.nio.channels.FileChannel) FileOutputStream(java.io.FileOutputStream)

Aggregations

ReadableByteChannel (java.nio.channels.ReadableByteChannel)307 ByteBuffer (java.nio.ByteBuffer)111 IOException (java.io.IOException)84 FileOutputStream (java.io.FileOutputStream)62 WritableByteChannel (java.nio.channels.WritableByteChannel)62 Test (org.junit.Test)52 File (java.io.File)50 FileChannel (java.nio.channels.FileChannel)49 FileInputStream (java.io.FileInputStream)43 ByteArrayInputStream (java.io.ByteArrayInputStream)38 InputStream (java.io.InputStream)36 URL (java.net.URL)35 ByteArrayOutputStream (java.io.ByteArrayOutputStream)21 Path (java.nio.file.Path)18 Test (org.testng.annotations.Test)14 FileNotFoundException (java.io.FileNotFoundException)13 ArrayList (java.util.ArrayList)12 DbusEventGenerator (com.linkedin.databus.core.test.DbusEventGenerator)11 MalformedURLException (java.net.MalformedURLException)11 Vector (java.util.Vector)11