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:org.lockss.remote.RemoteApi.java

/** Open an InputStream on the local AU config file, for backup purposes */
public InputStream getAuConfigBackupStreamV1(String machineName) throws FileNotFoundException {
    InputStream fileStream = openCacheConfigFile(ConfigManager.CONFIG_FILE_AU_CONFIG);
    String line1 = AU_BACKUP_FILE_COMMENT + new Date() + " from " + machineName + "\n";
    return new SequenceInputStream(new ByteArrayInputStream(line1.getBytes()), fileStream);
}

From source file:org.sipfoundry.voicemail.VmMessage.java

/**
 * Combine two wav files into one bigger one
 * /*  ww  w .j a va2  s. c o  m*/
 * @param newFile
 * @param orig1
 * @param orig2
 * @throws Exception
 */
static void concatAudio(File newFile, File orig1, File orig2) throws Exception {
    String operation = "dunno";
    try {
        operation = "getting AudioInputStream from " + orig1.getPath();
        AudioInputStream clip1 = AudioSystem.getAudioInputStream(orig1);
        operation = "getting AudioInputStream from " + orig2.getPath();
        AudioInputStream clip2 = AudioSystem.getAudioInputStream(orig2);

        operation = "building SequnceInputStream";
        AudioInputStream concatStream = new AudioInputStream(new SequenceInputStream(clip1, clip2),
                clip1.getFormat(), clip1.getFrameLength() + clip2.getFrameLength());

        operation = "writing SequnceInputStream to " + newFile.getPath();
        AudioSystem.write(concatStream, AudioFileFormat.Type.WAVE, newFile);
        LOG.info("VmMessage::concatAudio created combined file " + newFile.getPath());
    } catch (Exception e) {
        String trouble = "VmMessage::concatAudio Problem while " + operation;
        //           LOG.error(trouble, e);
        throw new Exception(trouble, e);
    }
}

From source file:org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreBlobStore.java

/**
 * Create a BLOB value from in input stream. Small objects will create an in-memory object,
 * while large objects are stored in the data store
 *
 * @param in the input stream//from  w  w w .  j  a  va 2 s .  c o  m
 * @return the value
 */
private DataRecord writeStream(InputStream in) throws IOException, DataStoreException {
    int maxMemorySize = Math.max(0, delegate.getMinRecordLength() + 1);
    byte[] buffer = new byte[maxMemorySize];
    int pos = 0, len = maxMemorySize;
    while (pos < maxMemorySize) {
        int l = in.read(buffer, pos, len);
        if (l < 0) {
            break;
        }
        pos += l;
        len -= l;
    }
    DataRecord record;
    if (pos < maxMemorySize) {
        // shrink the buffer
        byte[] data = new byte[pos];
        System.arraycopy(buffer, 0, data, 0, pos);
        record = InMemoryDataRecord.getInstance(data);
    } else {
        // a few bytes are already read, need to re-build the input stream
        in = new SequenceInputStream(new ByteArrayInputStream(buffer, 0, pos), in);
        record = delegate.addRecord(in);
    }
    return record;
}

From source file:org.apache.james.James.java

/**
 * Place a mail on the spool for processing
 *
 * @param sender the sender of the mail//from w  w  w .  ja v  a2s.c om
 * @param recipients the recipients of the mail
 * @param msg an <code>InputStream</code> containing the message
 *
 * @throws MessagingException if an exception is caught while placing the mail
 *                            on the spool
 */
public void sendMail(MailAddress sender, Collection recipients, InputStream msg) throws MessagingException {
    // parse headers
    MailHeaders headers = new MailHeaders(msg);

    // if headers do not contains minimum REQUIRED headers fields throw Exception
    if (!headers.isValid()) {
        throw new MessagingException("Some REQURED header field is missing. Invalid Message");
    }
    ByteArrayInputStream headersIn = new ByteArrayInputStream(headers.toByteArray());
    sendMail(new MailImpl(getId(), sender, recipients, new SequenceInputStream(headersIn, msg)));
}

From source file:org.apache.pig.impl.util.Utils.java

public static InputStream getCompositeStream(InputStream in, Properties properties) {
    //Load default ~/.pigbootup if not specified by user
    final String bootupFile = properties.getProperty("pig.load.default.statements",
            System.getProperty("user.home") + "/.pigbootup");
    try {//from  w  w w  .j a  v a  2 s.c o  m
        final InputStream inputSteam = new FileInputStream(new File(bootupFile));
        return new SequenceInputStream(inputSteam, in);
    } catch (FileNotFoundException fe) {
        log.info("Default bootup file " + bootupFile + " not found");
        return in;
    }
}

From source file:org.apache.jackrabbit.core.value.InternalValue.java

/**
 * Create a BLOB value from in input stream. Small objects will create an in-memory object,
 * while large objects are stored in the data store or in a temp file (if the store parameter is not set).
 *
 * @param store the data store (optional)
 * @param in the input stream/*from ww  w  .j a  va2s .  c om*/
 * @param temporary if the file should be deleted when discard is called (ignored if a data store is used)
 * @return the value
 */
private static BLOBFileValue getBLOBFileValue(DataStore store, InputStream in, boolean temporary)
        throws RepositoryException {
    int maxMemorySize;
    if (store != null) {
        maxMemorySize = store.getMinRecordLength() - 1;
    } else {
        maxMemorySize = MIN_BLOB_FILE_SIZE;
    }
    maxMemorySize = Math.max(0, maxMemorySize);
    byte[] buffer = new byte[maxMemorySize];
    int pos = 0, len = maxMemorySize;
    try {
        while (pos < maxMemorySize) {
            int l = in.read(buffer, pos, len);
            if (l < 0) {
                break;
            }
            pos += l;
            len -= l;
        }
    } catch (IOException e) {
        throw new RepositoryException("Could not read from stream", e);
    }
    if (pos < maxMemorySize) {
        // shrink the buffer
        byte[] data = new byte[pos];
        System.arraycopy(buffer, 0, data, 0, pos);
        return BLOBInMemory.getInstance(data);
    } else {
        // a few bytes are already read, need to re-build the input stream
        in = new SequenceInputStream(new ByteArrayInputStream(buffer, 0, pos), in);
        if (store != null) {
            return BLOBInDataStore.getInstance(store, in);
        } else {
            return BLOBInTempFile.getInstance(in, temporary);
        }
    }
}

From source file:org.apache.james.core.MimeMessageWrapper.java

/**
 * Return an {@link InputStream} which holds the full content of the
 * message. This method tries to optimize this call as far as possible. This
 * stream contains the updated {@link MimeMessage} content if something was
 * changed//  www  .  j av  a 2 s  .c o  m
 * 
 * @return messageInputStream
 * @throws MessagingException
 */

public synchronized InputStream getMessageInputStream() throws MessagingException {
    if (!messageParsed && !isModified() && source != null) {
        try {
            return source.getInputStream();
        } catch (IOException e) {
            throw new MessagingException("Unable to get inputstream", e);
        }
    } else {
        try {

            // Try to optimize if possible to prevent OOM on big mails.
            // See JAMES-1252 for an example
            if (!bodyModified && source != null) {
                // ok only the headers were modified so we don't need to
                // copy the whole message content into memory
                InputStream in = source.getInputStream();

                // skip over headers from original stream we want to use the
                // in memory ones
                new MailHeaders(in);

                // now construct the new stream using the in memory headers
                // and the body from the original source
                return new SequenceInputStream(new InternetHeadersInputStream(getAllHeaderLines()), in);
            } else {
                // the body was changed so we have no other solution to copy
                // it into memory first :(
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                writeTo(out);
                return new ByteArrayInputStream(out.toByteArray());
            }
        } catch (IOException e) {
            throw new MessagingException("Unable to get inputstream", e);
        }
    }
}

From source file:org.apache.pdfbox.pdfwriter.COSWriter.java

private void doWriteSignature() throws IOException {
    if (signatureOffset == 0 || byteRangeOffset == 0) {
        return;//from   ww w  . j  a va 2  s .  co m
    }

    // calculate the ByteRange values
    long inLength = incrementalInput.available();
    long beforeLength = signatureOffset;
    long afterOffset = signatureOffset + signatureLength;
    long afterLength = getStandardOutput().getPos() - (inLength + signatureLength)
            - (signatureOffset - inLength);

    String byteRange = "0 " + beforeLength + " " + afterOffset + " " + afterLength + "]";
    if (byteRangeLength - byteRange.length() < 0) {
        throw new IOException("Can't write new ByteRange, not enough space");
    }

    // copy the new incremental data into a buffer (e.g. signature dict, trailer)
    ByteArrayOutputStream byteOut = (ByteArrayOutputStream) output;
    byteOut.flush();
    byte[] buffer = byteOut.toByteArray();

    // overwrite the ByteRange in the buffer
    byte[] byteRangeBytes = byteRange.getBytes(Charsets.ISO_8859_1);
    for (int i = 0; i < byteRangeLength; i++) {
        if (i >= byteRangeBytes.length) {
            buffer[(int) (byteRangeOffset + i - inLength)] = 0x20; // SPACE
        } else {
            buffer[(int) (byteRangeOffset + i - inLength)] = byteRangeBytes[i];
        }
    }

    // get the input PDF bytes
    byte[] inputBytes = IOUtils.toByteArray(incrementalInput);

    // get only the incremental bytes to be signed (includes /ByteRange but not /Contents)
    byte[] signBuffer = new byte[buffer.length - (int) signatureLength];
    int bufSignatureOffset = (int) (signatureOffset - inLength);
    System.arraycopy(buffer, 0, signBuffer, 0, bufSignatureOffset);
    System.arraycopy(buffer, bufSignatureOffset + (int) signatureLength, signBuffer, bufSignatureOffset,
            buffer.length - bufSignatureOffset - (int) signatureLength);

    SequenceInputStream signStream = new SequenceInputStream(new ByteArrayInputStream(inputBytes),
            new ByteArrayInputStream(signBuffer));

    // sign the bytes
    byte[] sign = signatureInterface.sign(signStream);
    String signature = new COSString(sign).toHexString();
    // substract 2 bytes because of the enclosing "<>"
    if (signature.length() > signatureLength - 2) {
        throw new IOException("Can't write signature, not enough space");
    }

    // overwrite the signature Contents in the buffer
    byte[] signatureBytes = signature.getBytes(Charsets.ISO_8859_1);
    System.arraycopy(signatureBytes, 0, buffer, bufSignatureOffset + 1, signatureBytes.length);

    // write the data to the incremental output stream
    incrementalOutput.write(inputBytes);
    incrementalOutput.write(buffer);
}

From source file:org.apache.hadoop.hbase.HRegionInfo.java

/**
 * Parses an HRegionInfo instance from the passed in stream.  Presumes the HRegionInfo was
 * serialized to the stream with {@link #toDelimitedByteArray()}
 * @param in/*  www  . j  av  a  2  s .c  o  m*/
 * @return An instance of HRegionInfo.
 * @throws IOException
 */
public static HRegionInfo parseFrom(final DataInputStream in) throws IOException {
    // I need to be able to move back in the stream if this is not a pb serialization so I can
    // do the Writable decoding instead.
    int pblen = ProtobufUtil.lengthOfPBMagic();
    byte[] pbuf = new byte[pblen];
    if (in.markSupported()) { //read it with mark()
        in.mark(pblen);
    }
    int read = in.read(pbuf); //assumption: if Writable serialization, it should be longer than pblen.
    if (read != pblen)
        throw new IOException("read=" + read + ", wanted=" + pblen);
    if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
        return convert(HBaseProtos.RegionInfo.parseDelimitedFrom(in));
    } else {
        // Presume Writables.  Need to reset the stream since it didn't start w/ pb.
        if (in.markSupported()) {
            in.reset();
            HRegionInfo hri = new HRegionInfo();
            hri.readFields(in);
            return hri;
        } else {
            //we cannot use BufferedInputStream, it consumes more than we read from the underlying IS
            ByteArrayInputStream bais = new ByteArrayInputStream(pbuf);
            SequenceInputStream sis = new SequenceInputStream(bais, in); //concatenate input streams
            HRegionInfo hri = new HRegionInfo();
            hri.readFields(new DataInputStream(sis));
            return hri;
        }
    }
}

From source file:org.apache.hive.beeline.BeeLine.java

public ConsoleReader initializeConsoleReader(InputStream inputStream) throws IOException {
    if (inputStream != null) {
        // ### NOTE: fix for sf.net bug 879425.
        // Working around an issue in jline-2.1.2, see https://github.com/jline/jline/issues/10
        // by appending a newline to the end of inputstream
        InputStream inputStreamAppendedNewline = new SequenceInputStream(inputStream,
                new ByteArrayInputStream((new String("\n")).getBytes()));
        consoleReader = new ConsoleReader(inputStreamAppendedNewline, getErrorStream());
        consoleReader.setCopyPasteDetection(true); // jline will detect if <tab> is regular character
    } else {/*from   w w  w.  jav a2 s.  com*/
        consoleReader = new ConsoleReader(getInputStream(), getErrorStream());
    }

    //disable the expandEvents for the purpose of backward compatibility
    consoleReader.setExpandEvents(false);

    try {
        // now set the output for the history
        consoleReader.setHistory(this.history);
    } catch (Exception e) {
        handleException(e);
    }

    if (inputStream instanceof FileInputStream || inputStream instanceof FSDataInputStream) {
        // from script.. no need to load history and no need of completer, either
        return consoleReader;
    }

    consoleReader.addCompleter(new BeeLineCompleter(this));
    return consoleReader;
}