Example usage for java.io InputStream InputStream

List of usage examples for java.io InputStream InputStream

Introduction

In this page you can find the example usage for java.io InputStream InputStream.

Prototype

InputStream

Source Link

Usage

From source file:it.anyplace.sync.httprelay.client.HttpRelayConnection.java

protected HttpRelayConnection(String httpRelayServerUrl, String deviceId) {
    this.httpRelayServerUrl = httpRelayServerUrl;
    try {/*  w  ww .ja  v a 2  s . c  o  m*/
        HttpRelayProtos.HttpRelayServerMessage serverMessage = sendMessage(HttpRelayProtos.HttpRelayPeerMessage
                .newBuilder().setMessageType(HttpRelayProtos.HttpRelayPeerMessageType.CONNECT)
                .setDeviceId(deviceId));
        checkArgument(equal(serverMessage.getMessageType(),
                HttpRelayProtos.HttpRelayServerMessageType.PEER_CONNECTED));
        checkNotNull(Strings.emptyToNull(serverMessage.getSessionId()));
        sessionId = serverMessage.getSessionId();
        isServerSocket = serverMessage.getIsServerSocket();
        outputStream = new OutputStream() {

            private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            private long lastFlush = System.currentTimeMillis();

            {
                flusherStreamService.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        if (System.currentTimeMillis() - lastFlush > 1000) {
                            try {
                                flush();
                            } catch (IOException ex) {
                            }
                        }
                    }
                }, 1, 1, TimeUnit.SECONDS);
            }

            @Override
            public synchronized void write(int i) throws IOException {
                checkArgument(!HttpRelayConnection.this.isClosed());
                buffer.write(i);
            }

            @Override
            public synchronized void write(byte[] bytes, int offset, int size) throws IOException {
                checkArgument(!HttpRelayConnection.this.isClosed());
                buffer.write(bytes, offset, size);
            }

            @Override
            public synchronized void flush() throws IOException {
                final ByteString data = ByteString.copyFrom(buffer.toByteArray());
                buffer = new ByteArrayOutputStream();
                try {
                    if (!data.isEmpty()) {
                        outgoingExecutorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    sendMessage(HttpRelayProtos.HttpRelayPeerMessage.newBuilder()
                                            .setMessageType(
                                                    HttpRelayProtos.HttpRelayPeerMessageType.PEER_TO_RELAY)
                                            .setSequence(++peerToRelaySequence).setData(data));
                                } catch (Exception ex) {
                                    if (!isClosed()) {
                                        logger.error("error", ex);
                                        closeBg();
                                    }
                                    throw ex;
                                }
                            }

                        }).get();
                    }
                    lastFlush = System.currentTimeMillis();
                } catch (InterruptedException | ExecutionException ex) {
                    logger.error("error", ex);
                    closeBg();
                    throw new IOException(ex);
                }
            }

            @Override
            public synchronized void write(byte[] bytes) throws IOException {
                checkArgument(!HttpRelayConnection.this.isClosed());
                buffer.write(bytes);
            }

        };
        incomingExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                while (!isClosed()) {
                    try {
                        HttpRelayProtos.HttpRelayServerMessage serverMessage = sendMessage(
                                HttpRelayProtos.HttpRelayPeerMessage.newBuilder().setMessageType(
                                        HttpRelayProtos.HttpRelayPeerMessageType.WAIT_FOR_DATA));
                        if (isClosed()) {
                            return;
                        }
                        checkArgument(equal(serverMessage.getMessageType(),
                                HttpRelayProtos.HttpRelayServerMessageType.RELAY_TO_PEER));
                        checkArgument(serverMessage.getSequence() == relayToPeerSequence + 1);
                        if (!serverMessage.getData().isEmpty()) {
                            incomingDataQueue.add(serverMessage.getData().toByteArray());
                        }
                        relayToPeerSequence = serverMessage.getSequence();
                    } catch (Exception ex) {
                        if (!isClosed()) {
                            logger.error("error", ex);
                            closeBg();
                        }
                        return;
                    }
                }
            }
        });
        inputStream = new InputStream() {

            private boolean noMoreData = false;
            private ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(new byte[0]);

            @Override
            public int read() throws IOException {
                checkArgument(!HttpRelayConnection.this.isClosed());
                if (noMoreData) {
                    return -1;
                }
                int bite;
                while ((bite = byteArrayInputStream.read()) == -1) {
                    try {
                        byte[] data = incomingDataQueue.poll(1, TimeUnit.SECONDS);
                        if (data == null) {
                            //continue
                        } else if (data == STREAM_CLOSED) {
                            noMoreData = true;
                            return -1;
                        } else {
                            byteArrayInputStream = new ByteArrayInputStream(data);
                        }
                    } catch (InterruptedException ex) {
                    }
                }
                return bite;
            }

        };
        socket = new Socket() {
            @Override
            public boolean isClosed() {
                return HttpRelayConnection.this.isClosed();
            }

            @Override
            public boolean isConnected() {
                return !isClosed();
            }

            @Override
            public void shutdownOutput() throws IOException {
                logger.debug("shutdownOutput");
                getOutputStream().flush();
            }

            @Override
            public void shutdownInput() throws IOException {
                logger.debug("shutdownInput");
                //do nothing
            }

            @Override
            public synchronized void close() throws IOException {
                logger.debug("received close on socket adapter");
                HttpRelayConnection.this.close();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return outputStream;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return inputStream;
            }

            @Override
            public SocketAddress getRemoteSocketAddress() {
                return new InetSocketAddress(getInetAddress(), getPort());
            }

            @Override
            public int getPort() {
                return 22067;
            }

            @Override
            public InetAddress getInetAddress() {
                try {
                    return InetAddress
                            .getByName(URI.create(HttpRelayConnection.this.httpRelayServerUrl).getHost());
                } catch (UnknownHostException ex) {
                    throw new RuntimeException(ex);
                }
            }

        };
    } catch (Exception ex) {
        close();
        throw ex;
    }
}

From source file:io.mycat.util.ByteBufferUtil.java

public static InputStream inputStream(ByteBuffer bytes) {
    final ByteBuffer copy = bytes.duplicate();

    return new InputStream() {
        public int read() {
            if (!copy.hasRemaining()) {
                return -1;
            }/*from w  ww .  j  a  va  2  s.c o  m*/

            return copy.get() & 0xFF;
        }

        @Override
        public int read(byte[] bytes, int off, int len) {
            if (!copy.hasRemaining()) {
                return -1;
            }

            len = Math.min(len, copy.remaining());
            copy.get(bytes, off, len);
            return len;
        }

        @Override
        public int available() {
            return copy.remaining();
        }
    };
}

From source file:org.apache.maven.plugin.jar.JarSignMojo.java

void signJar() throws MojoExecutionException {
    List arguments = new ArrayList();

    Commandline commandLine = new Commandline();

    commandLine.setExecutable(getJarsignerPath());

    addArgIf(arguments, verbose, "-verbose");

    // I believe Commandline to add quotes where appropriate, although I haven't tested it enough.
    // FIXME addArgIfNotEmpty will break those parameters containing a space.
    // Look at webapp:gen-keystore for a way to fix that
    addArgIfNotEmpty(arguments, "-keystore", this.keystore);
    addArgIfNotEmpty(arguments, "-storepass", this.storepass);
    addArgIfNotEmpty(arguments, "-keypass", this.keypass);
    addArgIfNotEmpty(arguments, "-signedjar", this.signedjar);
    addArgIfNotEmpty(arguments, "-storetype", this.type);
    addArgIfNotEmpty(arguments, "-sigfile", this.sigfile);

    arguments.add(getJarFile());//from   w  w  w . j  av  a  2s.  co  m

    addArgIf(arguments, alias != null, this.alias);

    for (Iterator it = arguments.iterator(); it.hasNext();) {
        commandLine.createArgument().setValue(it.next().toString());
    }

    commandLine.setWorkingDirectory(workingDirectory.getAbsolutePath());

    createParentDirIfNecessary(signedjar);

    if (signedjar == null) {
        getLog().debug("Signing JAR in-place (overwritting original JAR).");
    }

    if (getLog().isDebugEnabled()) {
        getLog().debug("Executing: " + purgePassword(commandLine));
    }

    // jarsigner may ask for some input if the parameters are missing or incorrect.
    // This should take care of it and make it fail gracefully
    final InputStream inputStream = new InputStream() {
        public int read() {
            return -1;
        }
    };
    StreamConsumer outConsumer = new StreamConsumer() {
        public void consumeLine(String line) {
            getLog().info(line);
        }
    };
    final StringBuffer errBuffer = new StringBuffer();
    StreamConsumer errConsumer = new StreamConsumer() {
        public void consumeLine(String line) {
            errBuffer.append(line);
            getLog().warn(line);
        }
    };

    try {
        int result = executeCommandLine(commandLine, inputStream, outConsumer, errConsumer);

        if (result != 0) {
            throw new MojoExecutionException(
                    "Result of " + purgePassword(commandLine) + " execution is: \'" + result + "\'.");
        }
    } catch (CommandLineException e) {
        throw new MojoExecutionException("command execution failed", e);
    }

    // signed in place, no need to attach
    if (signedjar == null || skipAttachSignedArtifact) {
        return;
    }

    if (classifier != null) {
        projectHelper.attachArtifact(project, "jar", classifier, signedjar);
    } else {
        project.getArtifact().setFile(signedjar);
    }
}

From source file:org.pentaho.reporting.platform.plugin.async.WriteToJcrTaskTest.java

@Test
public void testConcurrentSave() throws Exception {

    final UUID uuid = UUID.randomUUID();
    final RepositoryFile file = mock(RepositoryFile.class);
    when(file.getId()).thenReturn(uuid.toString());
    when(PentahoSystem.get(IUnifiedRepository.class).getFile(startsWith("/test"))).thenReturn(file);

    final CountDownLatch latch1 = new CountDownLatch(1);

    final FakeLocation fakeLocation = new FakeLocation(latch1);

    final IAsyncReportExecution reportExecution = mock(IAsyncReportExecution.class);
    final IAsyncReportState state = mock(IAsyncReportState.class);
    when(state.getMimeType()).thenReturn("application/pdf");
    when(state.getPath()).thenReturn("report.prpt");
    when(reportExecution.getState()).thenReturn(state);

    final ReportContentRepository contentRepository = mock(ReportContentRepository.class);

    when(contentRepository.getRoot()).thenReturn(fakeLocation);

    final WriteToJcrTask toJcrTask = new WriteToJcrTask(reportExecution, new InputStream() {
        @Override/*from   w ww. ja  v  a2s.c  om*/
        public int read() throws IOException {
            try {
                Thread.sleep(100);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
            return -1;
        }
    }) {
        @Override
        protected ReportContentRepository getReportContentRepository(final RepositoryFile outputFolder) {
            return contentRepository;
        }
    };

    final ExecutorService executorService = Executors.newFixedThreadPool(10);

    final List<Future<Serializable>> results = new ArrayList<>();

    for (int i = 0; i < 10; i++) {
        results.add(executorService.submit(toJcrTask));
    }

    latch1.countDown();

    for (final Future<Serializable> res : results) {
        assertNotNull(res.get());
    }

}

From source file:com.github.sardine.FunctionalSardineTest.java

@Test
public void testPutExpectContinue() throws Exception {
    // Anonymous PUT to restricted resource
    Sardine sardine = SardineFactory.begin();
    final String url = "http://sudo.ch/dav/basic/sardine/" + UUID.randomUUID().toString();
    try {//from  ww  w  .  j a va 2s.  com
        sardine.put(url, new InputStream() {
            @Override
            public int read() throws IOException {
                fail("Expected authentication to fail without sending any body");
                return -1;
            }
        });
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Required
        assertEquals(401, e.getStatusCode());
    }
}

From source file:kx.c.java

/** Initializes a new {@link c} instance for the purposes of serialization only.  */
public c() {/*from  w  w  w  .java2s.c  o  m*/
    vt = '\3';
    l = false;
    i = new DataInputStream(new InputStream() {
        @Override
        public int read() throws IOException {
            throw new UnsupportedOperationException("nyi");
        }
    });
    o = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            throw new UnsupportedOperationException("nyi");
        }
    };
}

From source file:org.lealone.cluster.utils.ByteBufferUtil.java

public static InputStream inputStream(ByteBuffer bytes) {
    final ByteBuffer copy = bytes.duplicate();

    return new InputStream() {
        @Override/*from  w  w  w. ja v  a 2s.co m*/
        public int read() {
            if (!copy.hasRemaining())
                return -1;

            return copy.get() & 0xFF;
        }

        @Override
        public int read(byte[] bytes, int off, int len) {
            if (!copy.hasRemaining())
                return -1;

            len = Math.min(len, copy.remaining());
            copy.get(bytes, off, len);
            return len;
        }

        @Override
        public int available() {
            return copy.remaining();
        }
    };
}

From source file:org.duracloud.client.ContentStoreImplTest.java

@Test
public void testGetContentWithMidstreamNetworkFailureAndRecovery() throws Exception {
    String streamContent = "content";
    byte[] bytes = streamContent.getBytes();
    InputStream stream = EasyMock.createMock(InputStream.class);
    EasyMock.expect(stream.available()).andReturn(0).anyTimes();
    EasyMock.expect(stream.read((byte[]) EasyMock.anyObject(), anyInt(), anyInt()))
            .andDelegateTo(new InputStream() {
                @Override//from  ww w.ja v a2  s  .  c o m
                public int read() throws IOException {
                    return bytes[0];
                }

                @Override
                public int read(byte[] bytes1, int offset, int length) throws IOException {
                    bytes1[0] = bytes[0];
                    return 1;
                }

                @Override
                public int available() {
                    return 0;
                }
            });

    EasyMock.expect(stream.read((byte[]) EasyMock.anyObject(), anyInt(), anyInt())).andThrow(new IOException());

    String fullURL = baseURL + "/" + spaceId + "/" + contentId + "?storeID=" + storeId;
    EasyMock.expect(response.getStatusCode()).andReturn(200);
    EasyMock.expect(response.getResponseHeaders()).andReturn(new Header[0]).times(2);
    EasyMock.expect(response.getResponseStream()).andReturn(stream);
    EasyMock.expect(restHelper.get(fullURL)).andReturn(response);

    EasyMock.expect(response.getStatusCode()).andReturn(206);
    Capture<Map<String, String>> captureHeaders = Capture.newInstance();
    EasyMock.expect(restHelper.get(eq(fullURL), capture(captureHeaders))).andReturn(response);
    EasyMock.expect(response.getResponseStream())
            .andReturn(new ByteArrayInputStream(Arrays.copyOfRange(bytes, 1, bytes.length)));

    replayMocks();
    EasyMock.replay(stream);

    Content content = contentStore.getContent(spaceId, contentId);
    Assert.assertNotNull(content);
    Assert.assertEquals(contentId, content.getId());
    Assert.assertEquals(streamContent, IOUtils.toString(content.getStream()));

    Map<String, String> headers = captureHeaders.getValue();
    Assert.assertEquals("Range header value is incorrect.", "bytes=1-", headers.get("Range"));
    EasyMock.verify(stream);
}

From source file:org.apache.marmotta.loader.core.MarmottaLoader.java

public void loadArchive(File archive, LoaderHandler handler, RDFFormat format)
        throws RDFParseException, IOException, ArchiveException {
    log.info("loading files in archive {} ...", archive);

    if (archive.exists() && archive.canRead()) {

        if (archive.getName().endsWith("7z")) {
            log.info("auto-detected archive format: 7Z");

            final SevenZFile sevenZFile = new SevenZFile(archive);

            try {
                SevenZArchiveEntry entry;
                while ((entry = sevenZFile.getNextEntry()) != null) {

                    if (!entry.isDirectory()) {
                        log.info("loading entry {} ...", entry.getName());

                        // detect the file format
                        RDFFormat detectedFormat = Rio.getParserFormatForFileName(entry.getName());
                        if (format == null) {
                            if (detectedFormat != null) {
                                log.info("auto-detected entry format: {}", detectedFormat.getName());
                                format = detectedFormat;
                            } else {
                                throw new RDFParseException(
                                        "could not detect input format of entry " + entry.getName());
                            }//from  ww w.  j a v  a  2  s .c om
                        } else {
                            if (detectedFormat != null && !format.equals(detectedFormat)) {
                                log.warn("user-specified entry format ({}) overrides auto-detected format ({})",
                                        format.getName(), detectedFormat.getName());
                            } else {
                                log.info("user-specified entry format: {}", format.getName());
                            }
                        }

                        load(new InputStream() {
                            @Override
                            public int read() throws IOException {
                                return sevenZFile.read();
                            }

                            @Override
                            public int read(byte[] b) throws IOException {
                                return sevenZFile.read(b);
                            }

                            @Override
                            public int read(byte[] b, int off, int len) throws IOException {
                                return sevenZFile.read(b, off, len);
                            }
                        }, handler, format);
                    }
                }
            } finally {
                sevenZFile.close();
            }

        } else {
            InputStream in;

            String archiveCompression = detectCompression(archive);
            InputStream fin = new BufferedInputStream(new FileInputStream(archive));
            if (archiveCompression != null) {
                if (CompressorStreamFactory.GZIP.equalsIgnoreCase(archiveCompression)) {
                    log.info("auto-detected archive compression: GZIP");
                    in = new GzipCompressorInputStream(fin, true);
                } else if (CompressorStreamFactory.BZIP2.equalsIgnoreCase(archiveCompression)) {
                    log.info("auto-detected archive compression: BZIP2");
                    in = new BZip2CompressorInputStream(fin, true);
                } else if (CompressorStreamFactory.XZ.equalsIgnoreCase(archiveCompression)) {
                    log.info("auto-detected archive compression: XZ");
                    in = new XZCompressorInputStream(fin, true);
                } else {
                    in = fin;
                }
            } else {
                in = fin;
            }

            ArchiveInputStream zipStream = new ArchiveStreamFactory()
                    .createArchiveInputStream(new BufferedInputStream(in));
            logArchiveType(zipStream);

            ArchiveEntry entry;
            while ((entry = zipStream.getNextEntry()) != null) {

                if (!entry.isDirectory()) {
                    log.info("loading entry {} ...", entry.getName());

                    // detect the file format
                    RDFFormat detectedFormat = Rio.getParserFormatForFileName(entry.getName());
                    if (format == null) {
                        if (detectedFormat != null) {
                            log.info("auto-detected entry format: {}", detectedFormat.getName());
                            format = detectedFormat;
                        } else {
                            throw new RDFParseException(
                                    "could not detect input format of entry " + entry.getName());
                        }
                    } else {
                        if (detectedFormat != null && !format.equals(detectedFormat)) {
                            log.warn("user-specified entry format ({}) overrides auto-detected format ({})",
                                    format.getName(), detectedFormat.getName());
                        } else {
                            log.info("user-specified entry format: {}", format.getName());
                        }
                    }

                    load(zipStream, handler, format);
                }
            }
        }

    } else {
        throw new RDFParseException(
                "could not load files from archive " + archive + ": it does not exist or is not readable");
    }

}

From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java

public InputStream getInputStream() throws IOException {
    if (!connected)
        connect();/*from  ww  w.j  av a 2s  .c  o  m*/
    final HttpEntity entity = httpResponse.getEntity();
    if (entity != null)
        return entity.getContent();
    else
        return new InputStream() {
            @Override
            public int read() throws IOException {
                return -1;
            }
        };
}