Search in sources :

Example 11 with SequenceInputStream

use of java.io.SequenceInputStream in project jdk8u_jdk by JetBrains.

the class WaveFileWriter method getFileStream.

private InputStream getFileStream(WaveFileFormat waveFileFormat, InputStream audioStream) throws IOException {
    // private method ... assumes audioFileFormat is a supported file type
    // WAVE header fields
    AudioFormat audioFormat = waveFileFormat.getFormat();
    int headerLength = waveFileFormat.getHeaderSize();
    int riffMagic = WaveFileFormat.RIFF_MAGIC;
    int waveMagic = WaveFileFormat.WAVE_MAGIC;
    int fmtMagic = WaveFileFormat.FMT_MAGIC;
    int fmtLength = WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType());
    short wav_type = (short) waveFileFormat.getWaveType();
    short channels = (short) audioFormat.getChannels();
    short sampleSizeInBits = (short) audioFormat.getSampleSizeInBits();
    int sampleRate = (int) audioFormat.getSampleRate();
    int frameSizeInBytes = (int) audioFormat.getFrameSize();
    int frameRate = (int) audioFormat.getFrameRate();
    int avgBytesPerSec = channels * sampleSizeInBits * sampleRate / 8;
    ;
    short blockAlign = (short) ((sampleSizeInBits / 8) * channels);
    int dataMagic = WaveFileFormat.DATA_MAGIC;
    int dataLength = waveFileFormat.getFrameLength() * frameSizeInBytes;
    int length = waveFileFormat.getByteLength();
    int riffLength = dataLength + headerLength - 8;
    byte[] header = null;
    ByteArrayInputStream headerStream = null;
    ByteArrayOutputStream baos = null;
    DataOutputStream dos = null;
    SequenceInputStream waveStream = null;
    AudioFormat audioStreamFormat = null;
    AudioFormat.Encoding encoding = null;
    InputStream codedAudioStream = audioStream;
    // if audioStream is an AudioInputStream and we need to convert, do it here...
    if (audioStream instanceof AudioInputStream) {
        audioStreamFormat = ((AudioInputStream) audioStream).getFormat();
        encoding = audioStreamFormat.getEncoding();
        if (AudioFormat.Encoding.PCM_SIGNED.equals(encoding)) {
            if (sampleSizeInBits == 8) {
                wav_type = WaveFileFormat.WAVE_FORMAT_PCM;
                // plug in the transcoder to convert from PCM_SIGNED to PCM_UNSIGNED
                codedAudioStream = AudioSystem.getAudioInputStream(new AudioFormat(AudioFormat.Encoding.PCM_UNSIGNED, audioStreamFormat.getSampleRate(), audioStreamFormat.getSampleSizeInBits(), audioStreamFormat.getChannels(), audioStreamFormat.getFrameSize(), audioStreamFormat.getFrameRate(), false), (AudioInputStream) audioStream);
            }
        }
        if ((AudioFormat.Encoding.PCM_SIGNED.equals(encoding) && audioStreamFormat.isBigEndian()) || (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding) && !audioStreamFormat.isBigEndian()) || (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding) && audioStreamFormat.isBigEndian())) {
            if (sampleSizeInBits != 8) {
                wav_type = WaveFileFormat.WAVE_FORMAT_PCM;
                // plug in the transcoder to convert to PCM_SIGNED_LITTLE_ENDIAN
                codedAudioStream = AudioSystem.getAudioInputStream(new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioStreamFormat.getSampleRate(), audioStreamFormat.getSampleSizeInBits(), audioStreamFormat.getChannels(), audioStreamFormat.getFrameSize(), audioStreamFormat.getFrameRate(), false), (AudioInputStream) audioStream);
            }
        }
    }
    // Now push the header into a stream, concat, and return the new SequenceInputStream
    baos = new ByteArrayOutputStream();
    dos = new DataOutputStream(baos);
    // we write in littleendian...
    dos.writeInt(riffMagic);
    dos.writeInt(big2little(riffLength));
    dos.writeInt(waveMagic);
    dos.writeInt(fmtMagic);
    dos.writeInt(big2little(fmtLength));
    dos.writeShort(big2littleShort(wav_type));
    dos.writeShort(big2littleShort(channels));
    dos.writeInt(big2little(sampleRate));
    dos.writeInt(big2little(avgBytesPerSec));
    dos.writeShort(big2littleShort(blockAlign));
    dos.writeShort(big2littleShort(sampleSizeInBits));
    //$$fb 2002-04-16: Fix for 4636355: RIFF audio headers could be _more_ spec compliant
    if (wav_type != WaveFileFormat.WAVE_FORMAT_PCM) {
        // add length 0 for "codec specific data length"
        dos.writeShort(0);
    }
    dos.writeInt(dataMagic);
    dos.writeInt(big2little(dataLength));
    dos.close();
    header = baos.toByteArray();
    headerStream = new ByteArrayInputStream(header);
    waveStream = new SequenceInputStream(headerStream, new NoCloseInputStream(codedAudioStream));
    return (InputStream) waveStream;
}
Also used : AudioInputStream(javax.sound.sampled.AudioInputStream) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DataOutputStream(java.io.DataOutputStream) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AudioInputStream(javax.sound.sampled.AudioInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AudioFormat(javax.sound.sampled.AudioFormat)

Example 12 with SequenceInputStream

use of java.io.SequenceInputStream in project sling by apache.

the class DistributionPackageUtils method createStreamWithHeader.

public static InputStream createStreamWithHeader(DistributionPackage distributionPackage) throws IOException {
    DistributionPackageInfo packageInfo = distributionPackage.getInfo();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Map<String, Object> headerInfo = new HashMap<String, Object>();
    headerInfo.put(DistributionPackageInfo.PROPERTY_REQUEST_TYPE, packageInfo.getRequestType());
    headerInfo.put(DistributionPackageInfo.PROPERTY_REQUEST_PATHS, packageInfo.getPaths());
    headerInfo.put(PROPERTY_REMOTE_PACKAGE_ID, distributionPackage.getId());
    if (packageInfo.containsKey("reference-required")) {
        headerInfo.put("reference-required", packageInfo.get("reference-required"));
        log.info("setting reference-required to {}", packageInfo.get("reference-required"));
    }
    writeInfo(outputStream, headerInfo);
    InputStream headerStream = new ByteArrayInputStream(outputStream.toByteArray());
    InputStream bodyStream = distributionPackage.createInputStream();
    return new SequenceInputStream(headerStream, bodyStream);
}
Also used : DistributionPackageInfo(org.apache.sling.distribution.packaging.DistributionPackageInfo) SequenceInputStream(java.io.SequenceInputStream) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 13 with SequenceInputStream

use of java.io.SequenceInputStream in project eclipse.platform.text by eclipse.

the class FileDocumentProvider method doSaveDocument.

@Override
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
    if (element instanceof IFileEditorInput) {
        IFileEditorInput input = (IFileEditorInput) element;
        String encoding = null;
        FileInfo info = (FileInfo) getElementInfo(element);
        IFile file = input.getFile();
        encoding = getCharsetForNewFile(file, document, info);
        if (info != null && info.fBOM == IContentDescription.BOM_UTF_16LE && CHARSET_UTF_16.equals(encoding))
            encoding = CHARSET_UTF_16LE;
        Charset charset;
        try {
            charset = Charset.forName(encoding);
        } catch (UnsupportedCharsetException ex) {
            String message = NLSUtility.format(TextEditorMessages.DocumentProvider_error_unsupported_encoding_message_arg, encoding);
            IStatus s = new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, IStatus.OK, message, ex);
            throw new CoreException(s);
        } catch (IllegalCharsetNameException ex) {
            String message = NLSUtility.format(TextEditorMessages.DocumentProvider_error_illegal_encoding_message_arg, encoding);
            IStatus s = new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, IStatus.OK, message, ex);
            throw new CoreException(s);
        }
        CharsetEncoder encoder = charset.newEncoder();
        encoder.onMalformedInput(CodingErrorAction.REPLACE);
        encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
        InputStream stream;
        try {
            byte[] bytes;
            ByteBuffer byteBuffer = encoder.encode(CharBuffer.wrap(document.get()));
            if (byteBuffer.hasArray())
                bytes = byteBuffer.array();
            else {
                bytes = new byte[byteBuffer.limit()];
                byteBuffer.get(bytes);
            }
            stream = new ByteArrayInputStream(bytes, 0, byteBuffer.limit());
        } catch (CharacterCodingException ex) {
            Assert.isTrue(ex instanceof UnmappableCharacterException);
            String message = NLSUtility.format(TextEditorMessages.DocumentProvider_error_charset_mapping_failed_message_arg, encoding);
            IStatus s = new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, EditorsUI.CHARSET_MAPPING_FAILED, message, null);
            throw new CoreException(s);
        }
        /*
			 * XXX:
			 * This is a workaround for a corresponding bug in Java readers and writer,
			 * see http://developer.java.sun.com/developer/bugParade/bugs/4508058.html
			 */
        if (info != null && info.fBOM == IContentDescription.BOM_UTF_8 && CHARSET_UTF_8.equals(encoding))
            stream = new SequenceInputStream(new ByteArrayInputStream(IContentDescription.BOM_UTF_8), stream);
        if (info != null && info.fBOM == IContentDescription.BOM_UTF_16LE && CHARSET_UTF_16LE.equals(encoding))
            stream = new SequenceInputStream(new ByteArrayInputStream(IContentDescription.BOM_UTF_16LE), stream);
        if (file.exists()) {
            if (info != null && !overwrite)
                checkSynchronizationState(info.fModificationStamp, file);
            // inform about the upcoming content change
            fireElementStateChanging(element);
            try {
                file.setContents(stream, overwrite, true, monitor);
            } catch (CoreException x) {
                // inform about failure
                fireElementStateChangeFailed(element);
                throw x;
            } catch (RuntimeException x) {
                // inform about failure
                fireElementStateChangeFailed(element);
                throw x;
            }
            if (info != null) {
                ResourceMarkerAnnotationModel model = (ResourceMarkerAnnotationModel) info.fModel;
                if (model != null)
                    model.updateMarkers(info.fDocument);
                info.fModificationStamp = computeModificationStamp(file);
            }
        } else {
            SubMonitor subMonitor = SubMonitor.convert(monitor, TextEditorMessages.FileDocumentProvider_task_saving, 2);
            ContainerCreator creator = new ContainerCreator(file.getWorkspace(), file.getParent().getFullPath());
            creator.createContainer(subMonitor.split(1));
            file.create(stream, false, subMonitor.split(1));
        }
    } else {
        super.doSaveDocument(monitor, element, document, overwrite);
    }
}
Also used : MultiStatus(org.eclipse.core.runtime.MultiStatus) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IResourceStatus(org.eclipse.core.resources.IResourceStatus) ResourceMarkerAnnotationModel(org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel) IStatus(org.eclipse.core.runtime.IStatus) IFile(org.eclipse.core.resources.IFile) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) InputStream(java.io.InputStream) SubMonitor(org.eclipse.core.runtime.SubMonitor) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) CoreException(org.eclipse.core.runtime.CoreException) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) IFileEditorInput(org.eclipse.ui.IFileEditorInput) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnmappableCharacterException(java.nio.charset.UnmappableCharacterException) ContainerCreator(org.eclipse.core.filebuffers.manipulation.ContainerCreator)

Example 14 with SequenceInputStream

use of java.io.SequenceInputStream in project linuxtools by eclipse.

the class Utils method watchProcess.

/**
 * Watches the streams of the given running process. Note that the process can
 * be terminated at any time by interrupting the thread this method runs in.
 *
 * @param outStream
 *            The stream to write the output to.
 * @param child
 *            The process to watch the output of.
 * @return An IStatus indicating the result of the command.
 * @since 2.2
 */
public static IStatus watchProcess(final OutputStream outStream, Process child) {
    final BufferedInputStream in = new BufferedInputStream(new SequenceInputStream(child.getInputStream(), child.getErrorStream()));
    Thread readinJob = new Thread(() -> {
        try {
            int i;
            while ((i = in.read()) != -1) {
                outStream.write(i);
            }
            outStream.flush();
            outStream.close();
            in.close();
        } catch (IOException e) {
        }
        return;
    });
    readinJob.start();
    boolean canceled = false;
    try {
        // Catch interrupt attempts made before the wait
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException();
        }
        child.waitFor();
    } catch (InterruptedException e) {
        child.destroy();
        canceled = true;
    }
    while (readinJob.isAlive()) {
        try {
            readinJob.join();
        } catch (InterruptedException e) {
        }
    }
    if (canceled) {
        return Status.CANCEL_STATUS;
    }
    if (child.exitValue() != 0) {
        return new Status(IStatus.ERROR, FrameworkUtil.getBundle(Utils.class).getSymbolicName(), NLS.bind(Messages.Utils_NON_ZERO_RETURN_CODE, child.exitValue()), null);
    }
    return Status.OK_STATUS;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) SequenceInputStream(java.io.SequenceInputStream) BufferedInputStream(java.io.BufferedInputStream) IOException(java.io.IOException)

Example 15 with SequenceInputStream

use of java.io.SequenceInputStream in project javacore by wang125631.

the class demo03 method merge03.

// �������ļ��ϲ���һ���ļ�
@SuppressWarnings("all")
public static void merge03() throws IOException {
    // �ҵ�(�򴴽�)Ŀ���ļ�
    File inFile1 = new File("D:/demo01.java");
    File inFile2 = new File("D:/demo02.java");
    File inFile3 = new File("D:/demo03.java");
    File outFile = new File("D:/demo04.java");
    // ������Ӧ ���������������
    FileInputStream fileInputStream1 = new FileInputStream(inFile1);
    FileInputStream fileInputStream2 = new FileInputStream(inFile2);
    FileInputStream fileInputStream3 = new FileInputStream(inFile3);
    FileOutputStream fileOutputStream = new FileOutputStream(outFile);
    // ��������������
    Vector<FileInputStream> vector = new Vector<FileInputStream>();
    vector.add(fileInputStream1);
    vector.add(fileInputStream2);
    vector.add(fileInputStream3);
    Enumeration<FileInputStream> e = vector.elements();
    SequenceInputStream sequenceInputStream = new SequenceInputStream(e);
    // ��ȡ�ļ�����
    byte[] buf = new byte[1024];
    int length = 0;
    while ((length = sequenceInputStream.read()) != -1) {
        fileOutputStream.write(buf, 0, length);
    }
    sequenceInputStream.close();
    fileOutputStream.close();
}
Also used : SequenceInputStream(java.io.SequenceInputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Vector(java.util.Vector) FileInputStream(java.io.FileInputStream)

Aggregations

SequenceInputStream (java.io.SequenceInputStream)119 InputStream (java.io.InputStream)76 ByteArrayInputStream (java.io.ByteArrayInputStream)65 IOException (java.io.IOException)46 ArrayList (java.util.ArrayList)31 FileInputStream (java.io.FileInputStream)22 BufferedInputStream (java.io.BufferedInputStream)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 Test (org.junit.Test)10 Vector (java.util.Vector)9 lombok.val (lombok.val)9 OutputStream (java.io.OutputStream)8 List (java.util.List)8 FileOutputStream (java.io.FileOutputStream)7 InputStreamReader (java.io.InputStreamReader)7 HashMap (java.util.HashMap)7 File (java.io.File)6 ByteBuffer (java.nio.ByteBuffer)6 Support_ASimpleInputStream (tests.support.Support_ASimpleInputStream)6 Reader (java.io.Reader)5