Search in sources :

Example 11 with Source

use of okio.Source in project wire by square.

the class WireCompilerTest method assertFilesMatch.

private void assertFilesMatch(File expectedFile, File actualFile) throws IOException {
    String expected;
    try (Source source = Okio.source(expectedFile)) {
        expected = Okio.buffer(source).readUtf8();
    }
    String actual;
    try (Source source = Okio.source(actualFile)) {
        actual = Okio.buffer(source).readUtf8();
    }
    // Normalize CRLF -> LF
    expected = expected.replace("\r\n", "\n");
    actual = actual.replace("\r\n", "\n");
    assertThat(actual).isEqualTo(expected);
}
Also used : Source(okio.Source)

Example 12 with Source

use of okio.Source in project grpc-java by grpc.

the class OkHttpClientTransport method start.

@Override
public Runnable start(Listener listener) {
    this.listener = Preconditions.checkNotNull(listener, "listener");
    if (enableKeepAlive) {
        scheduler = SharedResourceHolder.get(TIMER_SERVICE);
        keepAliveManager = new KeepAliveManager(this, scheduler, keepAliveDelayNanos, keepAliveTimeoutNanos, false);
        keepAliveManager.onTransportStarted();
    }
    frameWriter = new AsyncFrameWriter(this, serializingExecutor);
    outboundFlow = new OutboundFlowController(this, frameWriter);
    // Connecting in the serializingExecutor, so that some stream operations like synStream
    // will be executed after connected.
    serializingExecutor.execute(new Runnable() {

        @Override
        public void run() {
            if (isForTest()) {
                if (connectingCallback != null) {
                    connectingCallback.run();
                }
                clientFrameHandler = new ClientFrameHandler(testFrameReader);
                executor.execute(clientFrameHandler);
                synchronized (lock) {
                    maxConcurrentStreams = Integer.MAX_VALUE;
                    startPendingStreams();
                }
                frameWriter.becomeConnected(testFrameWriter, socket);
                connectedFuture.set(null);
                return;
            }
            // Use closed source on failure so that the reader immediately shuts down.
            BufferedSource source = Okio.buffer(new Source() {

                @Override
                public long read(Buffer sink, long byteCount) {
                    return -1;
                }

                @Override
                public Timeout timeout() {
                    return Timeout.NONE;
                }

                @Override
                public void close() {
                }
            });
            Variant variant = new Http2();
            BufferedSink sink;
            Socket sock;
            try {
                if (proxyAddress == null) {
                    sock = new Socket(address.getAddress(), address.getPort());
                } else {
                    sock = createHttpProxySocket(address, proxyAddress, proxyUsername, proxyPassword);
                }
                if (sslSocketFactory != null) {
                    sock = OkHttpTlsUpgrader.upgrade(sslSocketFactory, sock, getOverridenHost(), getOverridenPort(), connectionSpec);
                }
                sock.setTcpNoDelay(true);
                source = Okio.buffer(Okio.source(sock));
                sink = Okio.buffer(Okio.sink(sock));
            } catch (StatusException e) {
                startGoAway(0, ErrorCode.INTERNAL_ERROR, e.getStatus());
                return;
            } catch (Exception e) {
                onException(e);
                return;
            } finally {
                clientFrameHandler = new ClientFrameHandler(variant.newReader(source, true));
                executor.execute(clientFrameHandler);
            }
            FrameWriter rawFrameWriter;
            synchronized (lock) {
                socket = sock;
                maxConcurrentStreams = Integer.MAX_VALUE;
                startPendingStreams();
            }
            rawFrameWriter = variant.newWriter(sink, true);
            frameWriter.becomeConnected(rawFrameWriter, socket);
            try {
                // Do these with the raw FrameWriter, so that they will be done in this thread,
                // and before any possible pending stream operations.
                rawFrameWriter.connectionPreface();
                Settings settings = new Settings();
                rawFrameWriter.settings(settings);
            } catch (Exception e) {
                onException(e);
                return;
            }
        }
    });
    return null;
}
Also used : Buffer(okio.Buffer) Http2(io.grpc.okhttp.internal.framed.Http2) BufferedSink(okio.BufferedSink) BufferedSource(okio.BufferedSource) Source(okio.Source) EOFException(java.io.EOFException) StatusException(io.grpc.StatusException) IOException(java.io.IOException) FrameWriter(io.grpc.okhttp.internal.framed.FrameWriter) Variant(io.grpc.okhttp.internal.framed.Variant) StatusException(io.grpc.StatusException) KeepAliveManager(io.grpc.internal.KeepAliveManager) Socket(java.net.Socket) Settings(io.grpc.okhttp.internal.framed.Settings) BufferedSource(okio.BufferedSource)

Example 13 with Source

use of okio.Source in project android-rest-client by darko1002001.

the class RequestBodyUtils method create.

public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public long contentLength() {
            try {
                return inputStream.available();
            } catch (IOException e) {
                return 0;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = null;
            try {
                source = Okio.source(inputStream);
                sink.writeAll(source);
            } finally {
                Util.closeQuietly(source);
            }
        }
    };
}
Also used : BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Source(okio.Source) RequestBody(com.squareup.okhttp.RequestBody)

Example 14 with Source

use of okio.Source in project grpc-java by grpc.

the class OkHttpClientTransport method createHttpProxySocket.

private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddress proxyAddress, String proxyUsername, String proxyPassword) throws IOException, StatusException {
    try {
        Socket sock = new Socket(proxyAddress.getAddress(), proxyAddress.getPort());
        sock.setTcpNoDelay(true);
        Source source = Okio.source(sock);
        BufferedSink sink = Okio.buffer(Okio.sink(sock));
        // Prepare headers and request method line
        Request proxyRequest = createHttpProxyRequest(address, proxyUsername, proxyPassword);
        HttpUrl url = proxyRequest.httpUrl();
        String requestLine = String.format("CONNECT %s:%d HTTP/1.1", url.host(), url.port());
        // Write request to socket
        sink.writeUtf8(requestLine).writeUtf8("\r\n");
        for (int i = 0, size = proxyRequest.headers().size(); i < size; i++) {
            sink.writeUtf8(proxyRequest.headers().name(i)).writeUtf8(": ").writeUtf8(proxyRequest.headers().value(i)).writeUtf8("\r\n");
        }
        sink.writeUtf8("\r\n");
        // Flush buffer (flushes socket and sends request)
        sink.flush();
        // Read status line, check if 2xx was returned
        StatusLine statusLine = StatusLine.parse(readUtf8LineStrictUnbuffered(source));
        // Drain rest of headers
        while (!readUtf8LineStrictUnbuffered(source).equals("")) {
        }
        if (statusLine.code < 200 || statusLine.code >= 300) {
            Buffer body = new Buffer();
            try {
                sock.shutdownOutput();
                source.read(body, 1024);
            } catch (IOException ex) {
                body.writeUtf8("Unable to read body: " + ex.toString());
            }
            try {
                sock.close();
            } catch (IOException ignored) {
            // ignored
            }
            String message = String.format("Response returned from proxy was not successful (expected 2xx, got %d %s). " + "Response body:\n%s", statusLine.code, statusLine.message, body.readUtf8());
            throw Status.UNAVAILABLE.withDescription(message).asException();
        }
        return sock;
    } catch (IOException e) {
        throw Status.UNAVAILABLE.withDescription("Failed trying to connect with proxy").withCause(e).asException();
    }
}
Also used : StatusLine(com.squareup.okhttp.internal.http.StatusLine) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) BufferedSink(okio.BufferedSink) ByteString(okio.ByteString) IOException(java.io.IOException) Socket(java.net.Socket) BufferedSource(okio.BufferedSource) Source(okio.Source) HttpUrl(com.squareup.okhttp.HttpUrl)

Example 15 with Source

use of okio.Source in project FileDownloader by lingochamp.

the class PerformanceTestActivity method onClickWriteTest.

public void onClickWriteTest(final View view) {
    FileOutputStream fos = null;
    InputStream inputStream = initPerformanceTest();
    byte[] buff = new byte[BUFFER_SIZE];
    long start = System.currentTimeMillis();
    int tenthMilliSec = ioPerformanceSb.getProgress();
    int sleepMilliSec = tenthMilliSec / 10;
    int sleepNanoSec = (tenthMilliSec - (tenthMilliSec / 10) * 10) * TENTH_MILLI_TO_NANO;
    infoTv.append(String.format("Output test with %.1f ms extra operate\n", tenthMilliSec / 10.0f));
    // ---------------------- FileOutputStream
    try {
        fos = new FileOutputStream(writePerformanceTestPath, true);
        do {
            int byteCount = inputStream.read(buff);
            if (byteCount == -1) {
                break;
            }
            fos.write(buff, 0, byteCount);
            if (sleepMilliSec > 0 || sleepNanoSec > 0) {
                try {
                    Thread.sleep(sleepMilliSec, sleepNanoSec);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (true);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.getFD().sync();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    infoAppend("FileOutputStream", start);
    BufferedOutputStream bos = null;
    inputStream = initPerformanceTest();
    start = System.currentTimeMillis();
    // ---------------------- BufferedOutputStream
    try {
        bos = new BufferedOutputStream(new FileOutputStream(writePerformanceTestPath, true));
        do {
            int byteCount = inputStream.read(buff);
            if (byteCount == -1) {
                break;
            }
            bos.write(buff, 0, byteCount);
            if (sleepMilliSec > 0 || sleepNanoSec > 0) {
                try {
                    Thread.sleep(sleepMilliSec, sleepNanoSec);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (true);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    infoAppend("BufferOutputStream", start);
    RandomAccessFile raf = null;
    inputStream = initPerformanceTest();
    start = System.currentTimeMillis();
    // ---------------------- RandomAccessFile
    try {
        raf = new RandomAccessFile(writePerformanceTestPath, "rw");
        do {
            int byteCount = inputStream.read(buff);
            if (byteCount == -1) {
                break;
            }
            raf.write(buff, 0, byteCount);
            if (sleepMilliSec > 0 || sleepNanoSec > 0) {
                try {
                    Thread.sleep(sleepMilliSec, sleepNanoSec);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (true);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    infoAppend("RandomAccessFile", start);
    Sink sink = null;
    inputStream = initPerformanceTest();
    Source source = Okio.source(inputStream);
    Buffer buffer = new Buffer();
    start = System.currentTimeMillis();
    try {
        sink = Okio.sink(new File(writePerformanceTestPath));
        sink = Okio.buffer(sink);
        do {
            long byteCount = source.read(buffer, BUFFER_SIZE);
            if (byteCount == -1) {
                break;
            }
            sink.write(buffer, byteCount);
            if (sleepMilliSec > 0 || sleepNanoSec > 0) {
                try {
                    Thread.sleep(sleepMilliSec, sleepNanoSec);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (true);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (sink != null) {
            try {
                sink.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    infoAppend("okio", start);
}
Also used : Buffer(okio.Buffer) ByteBuffer(java.nio.ByteBuffer) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Source(okio.Source) RandomAccessFile(java.io.RandomAccessFile) Sink(okio.Sink) FileOutputStream(java.io.FileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

Source (okio.Source)29 BufferedSource (okio.BufferedSource)17 IOException (java.io.IOException)15 Buffer (okio.Buffer)15 BufferedSink (okio.BufferedSink)11 Test (org.junit.Test)10 InFrame (okhttp3.internal.http2.MockHttp2Peer.InFrame)5 InterruptedIOException (java.io.InterruptedIOException)4 FileNotFoundException (java.io.FileNotFoundException)3 InputStream (java.io.InputStream)3 Bitmap (android.graphics.Bitmap)2 Socket (java.net.Socket)2 Response (okhttp3.Response)2 ContentResolver (android.content.ContentResolver)1 Context (android.content.Context)1 BitmapFactory (android.graphics.BitmapFactory)1 Uri (android.net.Uri)1 Task (bolts.Task)1 FileUploadingHelper (chat.rocket.android.api.FileUploadingHelper)1 LogIfError (chat.rocket.android.helper.LogIfError)1