Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:com.pszh.ablibrary.util.AbFileUtil.java

/**
 * ??byte[].//from  w ww  .  j  ava 2s  . c o  m
 * @param imgByte byte[]
 * @param fileName ?????.jpg
 * @param type ???AbConstant
 * @param desiredWidth 
 * @param desiredHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth,
        int desiredHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap bitmap = null;
    File file = null;
    try {
        if (imgByte != null) {

            file = new File(imageDownloadDir, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int readLength = 0;
            bis = new ByteArrayInputStream(imgByte);
            dis = new DataInputStream(bis);
            byte[] buffer = new byte[1024];

            while ((readLength = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            fos.flush();

            bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
    return bitmap;
}

From source file:cn.org.eshow.framwork.util.AbFileUtil.java

/**
 * ??byte[]./*from ww  w  .j a v  a 2 s  .c  om*/
 * @param imgByte byte[]
 * @param fileName ?????.jpg
 * @param type ???AbConstant
 * @param desiredWidth 
 * @param desiredHeight 
 * @return Bitmap 
 */
public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth,
        int desiredHeight) {
    FileOutputStream fos = null;
    DataInputStream dis = null;
    ByteArrayInputStream bis = null;
    Bitmap bitmap = null;
    File file = null;
    try {
        if (imgByte != null) {

            file = new File(imageDownloadDir + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int readLength = 0;
            bis = new ByteArrayInputStream(imgByte);
            dis = new DataInputStream(bis);
            byte[] buffer = new byte[1024];

            while ((readLength = dis.read(buffer)) != -1) {
                fos.write(buffer, 0, readLength);
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            fos.flush();

            bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }
    return bitmap;
}

From source file:com.espringtran.compressor4j.processor.LzmaProcessor.java

/**
 * Read from compressed file//from   www  .  j  av a2 s.c om
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    LZMACompressorInputStream cis = new LZMACompressorInputStream(bais);
    ZipInputStream zis = new ZipInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = zis.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = zis.read(buffer);
            }
            zis.closeEntry();
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = zis.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        zis.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Analyzes and creates passed message data
 *//*from   w  ww .ja  v  a  2s.com*/
public AS2Message createMessageFromRequest(byte[] rawMessageData, Properties header, String contentType)
        throws AS2Exception {
    AS2Message message = new AS2Message(new AS2MessageInfo());
    if (this.configConnection == null) {
        throw new AS2Exception(AS2Exception.PROCESSING_ERROR,
                "AS2MessageParser: Pass a DB connection before calling createMessageFromRequest()", message);
    }
    try {
        //decode the content transfer encoding if set
        rawMessageData = this.processContentTransferEncoding(rawMessageData, header);
        //check if this is a MDN
        MDNParser mdnParser = new MDNParser();
        AS2MDNInfo mdnInfo = mdnParser.parseMDNData(rawMessageData, contentType);
        //its a MDN
        if (mdnInfo != null) {
            message.setAS2Info(mdnInfo);
            mdnInfo.initializeByRequestHeader(header);
            return (this.createFromMDNRequest(rawMessageData, header, contentType, mdnInfo, mdnParser));
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            messageInfo.initializeByRequestHeader(header);
            //inbound AS2 message, no MDN
            //no futher processing if the message does not contain a message id
            if (messageInfo.getMessageId() == null) {
                return (message);
            }
            //figure out if the MDN should be signed NOW. If an error occurs beyond this point
            //the info has to know if the returned MDN should be signed
            messageInfo.getDispositionNotificationOptions()
                    .setHeaderValue(header.getProperty("disposition-notification-options"));
            //check for existing partners
            PartnerAccessDB partnerAccess = new PartnerAccessDB(this.configConnection, this.runtimeConnection);
            Partner sender = partnerAccess.getPartner(messageInfo.getSenderId());
            Partner receiver = partnerAccess.getPartner(messageInfo.getReceiverId());
            if (sender == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Sender AS2 id " + messageInfo.getSenderId() + " is unknown.", message);
            }
            if (receiver == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Receiver AS2 id " + messageInfo.getReceiverId() + " is unknown.", message);
            }
            if (!receiver.isLocalStation()) {
                throw new AS2Exception(
                        AS2Exception.PROCESSING_ERROR, "The receiver of the message ("
                                + receiver.getAS2Identification() + ") is not defined as a local station.",
                        message);
            }
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            //check if the message already exists
            AS2MessageInfo alreadyExistingInfo = this.messageAlreadyExists(messageAccess,
                    messageInfo.getMessageId());
            if (alreadyExistingInfo != null) {
                //perform notification: Resend detected, manual interaction might be required
                Notification notification = new Notification(this.configConnection, this.runtimeConnection);
                notification.sendResendDetected(messageInfo, alreadyExistingInfo, sender, receiver);
                throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "An AS2 message with the message id "
                        + messageInfo.getMessageId()
                        + " has been already processed successfully by the system or is pending ("
                        + alreadyExistingInfo.getInitDate() + "). Please "
                        + " resubmit the message with a new message id instead or resending it if it should be processed again.",
                        new AS2Message(messageInfo));
            }
            messageAccess.initializeOrUpdateMessage(messageInfo);
            if (this.logger != null) {
                //do not log before because the logging process is related to an already created message in the transaction log
                this.logger.log(
                        Level.FINE, this.rb
                                .getResourceString("msg.incoming",
                                        new Object[] { messageInfo.getMessageId(),
                                                AS2Tools.getDataSizeDisplay(rawMessageData.length) }),
                        messageInfo);
            }
            //indicates if a sync or async mdn is requested
            messageInfo.setAsyncMDNURL(header.getProperty("receipt-delivery-option"));
            messageInfo.setRequestsSyncMDN(header.getProperty("receipt-delivery-option") == null
                    || header.getProperty("receipt-delivery-option").trim().length() == 0);
            message.setRawData(rawMessageData);
            byte[] decryptedData = this.decryptMessage(message, rawMessageData, contentType, sender, receiver);
            //may be already compressed here. Decompress first before going further
            if (this.contentTypeIndicatesCompression(contentType)) {
                byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(), decryptedData,
                        contentType);
                message.setDecryptedRawData(decompressed);
                //content type has changed now, get it from the decompressed data
                ByteArrayInputStream memIn = new ByteArrayInputStream(decompressed);
                MimeBodyPart tempPart = new MimeBodyPart(memIn);
                memIn.close();
                contentType = tempPart.getContentType();
            } else {
                //check the MIME structure that is embedded in decryptedData for its content type
                ByteArrayInputStream memIn = new ByteArrayInputStream(decryptedData);
                MimeMessage possibleCompressedPart = new MimeMessage(
                        Session.getInstance(System.getProperties()), memIn);
                memIn.close();
                if (this.contentTypeIndicatesCompression(possibleCompressedPart.getContentType())) {
                    long compressedSize = possibleCompressedPart.getSize();
                    byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(),
                            new SMIMECompressed(possibleCompressedPart), compressedSize);
                    message.setDecryptedRawData(decompressed);
                } else {
                    message.setDecryptedRawData(decryptedData);
                }
            }
            decryptedData = null;
            Part payloadPart = this.verifySignature(message, sender, contentType);
            //decompress the data if it has been sent compressed, only possible for signed data
            if (message.getAS2Info().getSignType() != AS2Message.SIGNATURE_NONE) {
                //signed message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.1 MIC Calculation For Signed Message
                //For any signed message, the MIC to be returned is calculated over
                //the same data that was signed in the original message as per [AS1].
                //The signed content will be a mime bodypart that contains either
                //compressed or uncompressed data.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
                payloadPart = this.decompressData(payloadPart, message);
                this.writePayloadsToMessage(payloadPart, message, header);
            } else {
                //this is an unsigned message
                this.writePayloadsToMessage(message.getDecryptedRawData(), message, header);
                //unsigned message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.2 MIC Calculation For Encrypted, Unsigned Message
                //For encrypted, unsigned messages, the MIC to be returned is
                //calculated over the uncompressed data content including all
                //MIME header fields and any applied Content-Transfer-Encoding.

                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.3 MIC Calculation For Unencrypted, Unsigned Message
                //For unsigned, unencrypted messages, the MIC is calculated
                //over the uncompressed data content including all MIME header
                //fields and any applied Content-Transfer-Encoding.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
            }
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("found.attachments",
                        new Object[] { messageInfo.getMessageId(), String.valueOf(message.getPayloadCount()) }),
                        messageInfo);
            }
            return (message);
        }
    } catch (Exception e) {
        if (e instanceof AS2Exception) {
            throw (AS2Exception) e;
        } else {
            throw new AS2Exception(AS2Exception.PROCESSING_ERROR, e.getMessage(), message);
        }
    }
}

From source file:org.apache.hadoop.io.TestIOUtils.java

@Test
public void testSkipFully() throws IOException {
    byte inArray[] = new byte[] { 0, 1, 2, 3, 4 };
    ByteArrayInputStream in = new ByteArrayInputStream(inArray);
    try {//from w w w . jav a2s. c o m
        in.mark(inArray.length);
        IOUtils.skipFully(in, 2);
        IOUtils.skipFully(in, 2);
        try {
            IOUtils.skipFully(in, 2);
            fail("expected to get a PrematureEOFException");
        } catch (EOFException e) {
            assertEquals("Premature EOF from inputStream " + "after skipping 1 byte(s).", e.getMessage());
        }
        in.reset();
        try {
            IOUtils.skipFully(in, 20);
            fail("expected to get a PrematureEOFException");
        } catch (EOFException e) {
            assertEquals("Premature EOF from inputStream " + "after skipping 5 byte(s).", e.getMessage());
        }
        in.reset();
        IOUtils.skipFully(in, 5);
        try {
            IOUtils.skipFully(in, 10);
            fail("expected to get a PrematureEOFException");
        } catch (EOFException e) {
            assertEquals("Premature EOF from inputStream " + "after skipping 0 byte(s).", e.getMessage());
        }
    } finally {
        in.close();
    }
}

From source file:com.espringtran.compressor4j.processor.GzipProcessor.java

/**
 * Read from compressed file/*from   w w  w . j a v  a 2 s .c om*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    GzipCompressorInputStream cis = new GzipCompressorInputStream(bais);
    ZipInputStream zis = new ZipInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = zis.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = zis.read(buffer);
            }
            zis.closeEntry();
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = zis.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        zis.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}

From source file:org.power.commons.redis.RedisClient.java

/**
 * Get the object represented by the given serialized bytes.
 *//*from   ww  w .  jav  a 2s. c  o m*/
protected Object deserialize(byte[] in) {
    Object rv = null;
    try {
        if (in != null) {
            ByteArrayInputStream bis = new ByteArrayInputStream(in);
            ObjectInputStream is = new ObjectInputStream(bis);
            rv = is.readObject();
            is.close();
            bis.close();
        }
    } catch (IOException e) {
        logger.warn("Caught IOException decoding %d bytes of data", e);
    } catch (ClassNotFoundException e) {
        logger.warn("Caught CNFE decoding %d bytes of data", e);
    }
    return rv;
}

From source file:com.espringtran.compressor4j.processor.Bzip2Processor.java

/**
 * Read from compressed file/*from w w  w .j ava 2 s . c o m*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    BZip2CompressorInputStream cis = new BZip2CompressorInputStream(bais);
    ZipInputStream zis = new ZipInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = zis.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = zis.read(buffer);
            }
            zis.closeEntry();
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = zis.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        zis.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public PublicKey convertByteArrayPublicKey(byte[] rawKey) throws CryptoException {
    ByteArrayInputStream inputStream = null;
    ObjectInputStream objectInputStream = null;
    PublicKey key;//from  ww  w  .  j  a  v a 2  s . c o m

    try {
        inputStream = new ByteArrayInputStream(rawKey);
        objectInputStream = new ObjectInputStream(inputStream);
        key = (PublicKey) objectInputStream.readObject();

        return key;
    } catch (IOException e) {
        throw new CryptoException("Exception when attempting to unserialize PublicKey", e);
    } catch (ClassNotFoundException e) {
        throw new CryptoException("Exception when attempting to unserialize PublicKey", e);
    } finally {
        try {
            if (objectInputStream != null)
                objectInputStream.close();

            if (inputStream != null)
                inputStream.close();
        } catch (IOException e) {
            throw new CryptoException(
                    "Exception when attempting to unserialize PublicKey (stream close failed)", e);
        }
    }
}

From source file:com.espringtran.compressor4j.processor.XzProcessor.java

/**
 * Read from compressed file/*from w  ww .j  a  va 2 s.  c  o m*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    XZCompressorInputStream cis = new XZCompressorInputStream(bais);
    TarArchiveInputStream ais = new TarArchiveInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        TarArchiveEntry entry = ais.getNextTarEntry();
        while (entry != null && entry.getSize() > 0) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = ais.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = ais.read(buffer);
            }
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = ais.getNextTarEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        ais.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}