Example usage for java.io SequenceInputStream SequenceInputStream

List of usage examples for java.io SequenceInputStream SequenceInputStream

Introduction

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

Prototype

public SequenceInputStream(InputStream s1, InputStream s2) 

Source Link

Document

Initializes a newly created SequenceInputStream by remembering the two arguments, which will be read in order, first s1 and then s2, to provide the bytes to be read from this SequenceInputStream.

Usage

From source file:rapture.blob.mongodb.GridFSBlobHandler.java

protected GridFSInputFile updateExisting(CallingContext context, String docPath, InputStream newContent,
        GridFS gridFS, GridFSDBFile existing) throws IOException {
    GridFSInputFile file;//from   w  w  w .jav a 2s. c  om
    String lockKey = createLockKey(gridFS, docPath);
    LockHandle lockHandle = grabLock(context, lockKey);
    try {
        File tempFile = File.createTempFile("rapture", "blob");
        existing.writeTo(tempFile);
        FileInputStream tempIn = FileUtils.openInputStream(tempFile);
        SequenceInputStream sequence = new SequenceInputStream(tempIn, newContent);
        try {
            gridFS.remove(docPath);
            file = createNewFile(docPath, sequence);
            if (!tempFile.delete()) {
                log.warn(String.format("Unable to delete temp file created while appending docPath %s, at %s",
                        docPath, tempFile.getAbsolutePath()));
            }
        } finally {
            try {
                sequence.close();
            } catch (IOException e) {
                log.error(
                        String.format("Error closing sequence input stream: %s", ExceptionToString.format(e)));
            }
            try {
                tempIn.close();
            } catch (IOException e) {
                log.error(
                        String.format("Error closing sequence input stream: %s", ExceptionToString.format(e)));
            }
        }
    } finally {
        releaseLock(context, lockKey, lockHandle);
    }
    return file;
}

From source file:it.sardegnaricerche.voiceid.sr.VCluster.java

public void trimSegments(File inputFile) throws IOException {
    String base = Utils.getBasename(inputFile);
    File mydir = new File(base);
    mydir.mkdirs();//from ww  w.ja v a2  s  .c o m
    String mywav = mydir.getAbsolutePath() + "/" + this.getLabel() + ".wav";
    AudioFileFormat fileFormat = null;
    AudioInputStream inputStream = null;
    AudioInputStream shortenedStream = null;
    AudioInputStream current = null;
    int bytesPerSecond = 0;
    long framesOfAudioToCopy = 0;
    wavFile = new File(mywav);
    try {
        fileFormat = AudioSystem.getAudioFileFormat(inputFile);
        AudioFormat format = fileFormat.getFormat();
        boolean firstTime = true;

        for (VSegment s : this.getSegments()) {
            bytesPerSecond = format.getFrameSize() * (int) format.getFrameRate();
            inputStream = AudioSystem.getAudioInputStream(inputFile);
            inputStream.skip(0);
            inputStream.skip((int) (s.getStart() * 100) * bytesPerSecond / 100);
            framesOfAudioToCopy = (int) (s.getDuration() * 100) * (int) format.getFrameRate() / 100;

            if (firstTime) {
                shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
            } else {
                current = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
                shortenedStream = new AudioInputStream(new SequenceInputStream(shortenedStream, current),
                        format, shortenedStream.getFrameLength() + framesOfAudioToCopy);
            }
            firstTime = false;
        }
        AudioSystem.write(shortenedStream, fileFormat.getType(), wavFile);
    } catch (Exception e) {
        logger.severe(e.getMessage());
        e.printStackTrace();
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
        if (shortenedStream != null)
            try {
                shortenedStream.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
        if (current != null)
            try {
                current.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
    }
    logger.fine("filename: " + wavFile.getAbsolutePath());
}

From source file:cz.jirutka.spring.http.client.cache.internal.SizeLimitedHttpResponseReader.java

private CombinedClientHttpResponse createCombinedResponse(ClientHttpResponse originalResponse,
        ByteArrayOutputStream consumedBody, InputStream originalBody) {

    InputStream combinedBody = new SequenceInputStream(new ByteArrayInputStream(consumedBody.toByteArray()),
            originalBody);/*  w  ww .ja  va2 s  .  c om*/

    return new CombinedClientHttpResponse(originalResponse, combinedBody);
}

From source file:com.streamsets.pipeline.lib.parser.TestCompressionInputBuilder.java

private void testConcatenatedCompressedFile(String compressionType) throws Exception {
    ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
    ByteArrayOutputStream bytes2 = new ByteArrayOutputStream();
    CompressorOutputStream compressed1 = new CompressorStreamFactory()
            .createCompressorOutputStream(compressionType, bytes1);

    CompressorOutputStream compressed2 = new CompressorStreamFactory()
            .createCompressorOutputStream(compressionType, bytes2);

    compressed1.write("line1\n".getBytes());
    compressed1.close();//from   ww  w .j  a  v  a 2 s .  c o  m

    compressed2.write("line2".getBytes());
    compressed2.close();

    CompressionDataParser.CompressionInputBuilder compressionInputBuilder = new CompressionDataParser.CompressionInputBuilder(
            Compression.COMPRESSED_FILE, null,
            new SequenceInputStream(new ByteArrayInputStream(bytes1.toByteArray()),
                    new ByteArrayInputStream(bytes2.toByteArray())),
            "0");
    CompressionDataParser.CompressionInput input = compressionInputBuilder.build();

    //verify
    Assert.assertNotNull(input);
    Assert.assertEquals("myFile::4567", input.wrapOffset("myFile::4567"));
    Assert.assertEquals("myFile::4567", input.wrapRecordId("myFile::4567"));
    InputStream myFile = input.getNextInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(myFile));
    Assert.assertEquals("line1", reader.readLine());
    Assert.assertEquals("line2", reader.readLine());
}

From source file:nya.miku.wishmaster.chans.nullchan.NullchanclubModule.java

@Override
protected WakabaReader getKusabaReader(InputStream stream, UrlPageModel urlModel) {
    if ((urlModel != null) && (urlModel.chanName != null) && urlModel.chanName.equals("expand")) {
        stream = new SequenceInputStream(new ByteArrayInputStream("<form id=\"delform\">".getBytes()), stream);
    }//  w  w  w  .j  a va  2s.c  o  m
    return new NullclubReader(stream, canCloudflare());
}

From source file:org.openhab.voice.marytts.internal.MaryTTSAudioStream.java

@Override
public synchronized void reset() throws IOException {
    IOUtils.closeQuietly(inputStream);//w ww  .  j  a v a  2s  . c  om
    this.inputStream = new SequenceInputStream(getWavHeaderInputStream(length),
            new ByteArrayInputStream(rawAudio));
}

From source file:org.openhab.voice.marytts.internal.MaryTTSAudioStream.java

@Override
public InputStream getClonedStream() throws AudioException {
    try {//from w  ww.  j  a v a 2s.c  o  m
        return new SequenceInputStream(getWavHeaderInputStream(length), new ByteArrayInputStream(rawAudio));
    } catch (IOException e) {
        throw new AudioException(e);
    }
}

From source file:org.fcrepo.utilities.io.TestByteRangeInputStream.java

@SuppressWarnings("resource")
@Test/*  w  w  w  .  j  a v  a 2 s .c om*/
public void testSkippedBytes() throws IndexOutOfBoundsException, IOException {
    String data = "1234567890";
    String input = "bytes=3-12";
    InputStream bytes = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8")));
    ByteRangeInputStream test = new ByteRangeInputStream(bytes, 10, input);
    assertEquals("bad offset of " + test.offset + " for " + input, 3, test.offset);
    assertEquals("bad length of " + test.length + " for " + input, 7, test.length);
    assertEquals("bytes 3-9/10", test.contentRange);
    bytes.reset();
    test = new ByteRangeInputStream(bytes, 10, "bytes=0-8");
    assertEquals("123456789", IOUtils.toString(test));
    bytes.reset();
    InputStream bytes2 = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8")));
    test = new ByteRangeInputStream(bytes, 10, "bytes=0-2");
    ByteRangeInputStream test2 = new ByteRangeInputStream(bytes2, 10, "bytes=-7");
    SequenceInputStream test3 = new SequenceInputStream(test, test2);
    String actual = IOUtils.toString(test3);
    assertEquals(data, actual);
}

From source file:org.codehaus.plexus.archiver.zip.OffloadingOutputStream.java

public InputStream getInputStream() throws IOException {

    InputStream memoryAsInput = memoryOutputStream.toInputStream();
    if (outputFile == null) {
        return memoryAsInput;
    }//from  w  w  w . ja  v  a  2  s .  c  o m
    return new SequenceInputStream(memoryAsInput, new FileInputStream(outputFile));
}

From source file:com.github.pockethub.android.accounts.LoginWebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WebView webView = new WebView(this);

    // Needs the be activated to allow GitHub to perform their requests.
    webView.getSettings().setJavaScriptEnabled(true);

    String userAgent = webView.getSettings().getUserAgentString();
    // Remove chrome from the user agent since GitHub checks it incorrectly
    userAgent = userAgent.replaceAll("Chrome/\\d{2}\\.\\d\\.\\d\\.\\d", "");
    webView.getSettings().setUserAgentString(userAgent);

    String url = getIntent().getStringExtra(LoginActivity.INTENT_EXTRA_URL);
    webView.loadUrl(url);//  w  w  w. j a  va 2 s.  c  o m

    webView.setWebViewClient(new WebViewClient() {
        MaterialDialog dialog = new MaterialDialog.Builder(LoginWebViewActivity.this).content(R.string.loading)
                .progress(true, 0).build();

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            dialog.show();
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            dialog.dismiss();
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(android.webkit.WebView view,
                WebResourceRequest request) {
            return shouldIntercept(request.getUrl().toString());
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(android.webkit.WebView view, String url) {
            return shouldIntercept(url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            Uri uri = Uri.parse(url);
            return overrideOAuth(uri) || super.shouldOverrideUrlLoading(view, url);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {

            return overrideOAuth(request.getUrl()) || super.shouldOverrideUrlLoading(view, request);
        }

        /**
         * This method will inject polyfills to the auth javascript if the version is
         * below Lollipop. After Lollipop WebView is updated via the Play Store so the polyfills
         * are not needed.
         *
         * @param url The requests url
         * @return null if there request should not be altered or a new response
         *     instance with polyfills.
         */
        private WebResourceResponse shouldIntercept(String url) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                return null;
            }

            if (url.matches(".*frameworks.*.js")) {
                InputStream in1 = null;
                InputStream in2 = null;
                Response response = null;
                try {
                    response = new OkHttpClient.Builder().build()
                            .newCall(new Request.Builder().get().url(url).build()).execute();

                    if (response.body() != null) {
                        in1 = response.body().byteStream();
                    }

                    in2 = getAssets().open("polyfills.js");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (response == null) {
                    return null;
                }

                SequenceInputStream inputStream = new SequenceInputStream(in2, in1);
                return new WebResourceResponse("text/javascript", "utf-8", inputStream);
            } else {
                return null;
            }
        }

        private boolean overrideOAuth(Uri uri) {
            if (uri.getScheme().equals(getString(R.string.github_oauth_scheme))) {
                Intent data = new Intent();
                data.setData(uri);
                setResult(RESULT_OK, data);
                finish();
                return true;
            }

            return false;
        }
    });

    setContentView(webView);
}