Example usage for java.io InputStream markSupported

List of usage examples for java.io InputStream markSupported

Introduction

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

Prototype

public boolean markSupported() 

Source Link

Document

Tests if this input stream supports the mark and reset methods.

Usage

From source file:com.alibaba.simpleimage.CompositeImageProcessor.java

private void errorLog(InputStream is) {
    if (StringUtils.isBlank(errorDir)) {
        errorDir = System.getProperty("java.io.tmpdir") + File.separator + FILE_CONTENT_LOG_BASE_DIR_NAME;
    }//from  w w w.j a  va  2s. co  m

    if (StringUtils.isNotBlank(errorDir)) {
        File errorPath = new File(errorDir);
        if (!errorPath.exists()) {
            errorPath.mkdirs();
        }

        if (!canWriteErrorDir(errorPath)) {
            return;
        }

        //  ????(????)
        if (errorPath.exists() && is.markSupported()) {
            OutputStream os = null;
            try {
                is.reset();
                File temp = new File(errorPath,
                        "errimg-" + UUID.randomUUID().toString().replace("-", "_") + ".jpg");
                os = new FileOutputStream(temp);
                // write error image stream to a temp file
                byte buffer[] = new byte[1024];
                int count = -1;
                while ((count = is.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                }
                os.flush();
            } catch (IOException igonre) {

            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    }
}

From source file:org.jeecgframework.poi.excel.imports.ExcelImportServer.java

/**
 * Excel  field  Integer,Long,Double,Date,String,Boolean
 * /*from ww w  . j  a v  a  2s .  c  o m*/
 * @param inputstream
 * @param pojoClass
 * @param params
 * @return
 * @throws Exception
 */
public ExcelImportResult importExcelByIs(InputStream inputstream, Class<?> pojoClass, ImportParams params)
        throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Excel import start ,class is {}", pojoClass);
    }
    List<T> result = new ArrayList<T>();
    Workbook book = null;
    boolean isXSSFWorkbook = true;
    if (!(inputstream.markSupported())) {
        inputstream = new PushbackInputStream(inputstream, 8);
    }
    if (POIFSFileSystem.hasPOIFSHeader(inputstream)) {
        book = new HSSFWorkbook(inputstream);
        isXSSFWorkbook = false;
    } else if (POIXMLDocument.hasOOXMLHeader(inputstream)) {
        book = new XSSFWorkbook(OPCPackage.open(inputstream));
    }
    createErrorCellStyle(book);
    Map<String, PictureData> pictures;
    for (int i = 0; i < params.getSheetNum(); i++) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" start to read excel by is ,startTime is {}", new Date().getTime());
        }
        if (isXSSFWorkbook) {
            pictures = PoiPublicUtil.getSheetPictrues07((XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book);
        } else {
            pictures = PoiPublicUtil.getSheetPictrues03((HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" end to read excel by is ,endTime is {}", new Date().getTime());
        }
        result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, params, pictures));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" end to read excel list by pos ,endTime is {}", new Date().getTime());
        }
    }
    if (params.isNeedSave()) {
        saveThisExcel(params, pojoClass, isXSSFWorkbook, book);
    }
    return new ExcelImportResult(result, verfiyFail, book);
}

From source file:com.qihang.winter.poi.excel.imports.ExcelImportServer.java

/**
 * Excel  field  Integer,Long,Double,Date,String,Boolean
 *
 * @param inputstream// ww w  .  j  a v a 2  s.c o m
 * @param pojoClass
 * @param params
 * @return
 * @throws Exception
 */
public com.qihang.winter.poi.excel.entity.result.ExcelImportResult importExcelByIs(InputStream inputstream,
        Class<?> pojoClass, com.qihang.winter.poi.excel.entity.ImportParams params) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Excel import start ,class is {}", pojoClass);
    }
    List<T> result = new ArrayList<T>();
    Workbook book = null;
    boolean isXSSFWorkbook = true;
    if (!(inputstream.markSupported())) {
        inputstream = new PushbackInputStream(inputstream, 8);
    }
    if (POIFSFileSystem.hasPOIFSHeader(inputstream)) {
        book = new HSSFWorkbook(inputstream);
        isXSSFWorkbook = false;
    } else if (POIXMLDocument.hasOOXMLHeader(inputstream)) {
        book = new XSSFWorkbook(OPCPackage.open(inputstream));
    }
    createErrorCellStyle(book);
    Map<String, PictureData> pictures;
    for (int i = 0; i < params.getSheetNum(); i++) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" start to read excel by is ,startTime is {}", new Date().getTime());
        }
        if (isXSSFWorkbook) {
            pictures = com.qihang.winter.poi.util.PoiPublicUtil
                    .getSheetPictrues07((XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book);
        } else {
            pictures = com.qihang.winter.poi.util.PoiPublicUtil
                    .getSheetPictrues03((HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" end to read excel by is ,endTime is {}", new Date().getTime());
        }
        result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, params, pictures));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(" end to read excel list by pos ,endTime is {}", new Date().getTime());
        }
    }
    String excelName = "";
    if (params.isNeedSave()) {
        excelName = saveThisExcel(params, pojoClass, isXSSFWorkbook, book);
    }
    return new com.qihang.winter.poi.excel.entity.result.ExcelImportResult(result, verfiyFail, book, excelName);
}

From source file:com.microsoft.azure.storage.core.Utility.java

/**
 * //from  ww  w .  ja  va2 s. c  o  m
 * Determines the size of an input stream, and optionally calculates the MD5 hash for the stream.
 * 
 * @param sourceStream
 *            A <code>InputStream</code> object that represents the stream to measure.
 * @param writeLength
 *            The number of bytes to read from the stream.
 * @param abandonLength
 *            The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to
 *            force the entire stream to be read. This parameter is provided to support upload thresholds.
 * @param rewindSourceStream
 *            <code>true</code> if the stream should be rewound after it is read; otherwise, <code>false</code>.
 * @param calculateMD5
 *            <code>true</code> if an MD5 hash will be calculated; otherwise, <code>false</code>.
 * 
 * @return A {@link StreamMd5AndLength} object that contains the stream length, and optionally the MD5 hash.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 * @throws StorageException
 *             If a storage service error occurred.
 */
public static StreamMd5AndLength analyzeStream(final InputStream sourceStream, long writeLength,
        long abandonLength, final boolean rewindSourceStream, final boolean calculateMD5)
        throws IOException, StorageException {
    if (abandonLength < 0) {
        abandonLength = Long.MAX_VALUE;
    }

    if (rewindSourceStream) {
        if (!sourceStream.markSupported()) {
            throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE);
        }

        sourceStream.mark(Constants.MAX_MARK_LENGTH);
    }

    MessageDigest digest = null;
    if (calculateMD5) {
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    if (writeLength < 0) {
        writeLength = Long.MAX_VALUE;
    }

    final StreamMd5AndLength retVal = new StreamMd5AndLength();
    int count = -1;
    final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH];

    int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength());
    count = sourceStream.read(retrievedBuff, 0, nextCopy);

    while (nextCopy > 0 && count != -1) {
        if (calculateMD5) {
            digest.update(retrievedBuff, 0, count);
        }
        retVal.setLength(retVal.getLength() + count);

        if (retVal.getLength() > abandonLength) {
            // Abandon operation
            retVal.setLength(-1);
            retVal.setMd5(null);
            break;
        }

        nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength());
        count = sourceStream.read(retrievedBuff, 0, nextCopy);
    }

    if (retVal.getLength() != -1 && calculateMD5) {
        retVal.setMd5(Base64.encode(digest.digest()));
    }

    if (retVal.getLength() != -1 && writeLength > 0) {
        retVal.setLength(Math.min(retVal.getLength(), writeLength));
    }

    if (rewindSourceStream) {
        sourceStream.reset();
        sourceStream.mark(Constants.MAX_MARK_LENGTH);
    }

    return retVal;
}

From source file:org.xwiki.webjars.internal.WebJarsResourceReferenceHandler.java

/**
 * Sends back the specified resource./*from w  w  w .  j  a va 2  s .c om*/
 *
 * @param resourceReference the reference to the WebJar resource to get
 * @param rawResourceStream the resource stream used to read the resource from the WebJar
 * @throws ResourceReferenceHandlerException if it fails to read the resource
 */
private void serveResource(WebJarsResourceReference resourceReference, InputStream rawResourceStream)
        throws ResourceReferenceHandlerException {
    InputStream resourceStream = rawResourceStream;
    String resourceName = getResourceName(resourceReference);

    if (shouldEvaluateResource(resourceReference)) {
        resourceStream = evaluate(resourceName, resourceStream);
    }

    // Make sure the resource stream supports mark & reset which is needed in order be able to detect the
    // content type without affecting the stream (Tika may need to read a few bytes from the start of the
    // stream, in which case it will mark & reset the stream).
    if (!resourceStream.markSupported()) {
        resourceStream = new BufferedInputStream(resourceStream);
    }

    try {
        Response response = this.container.getResponse();
        setResponseHeaders(response, resourceReference);
        response.setContentType(this.tika.detect(resourceStream, resourceName));
        IOUtils.copy(resourceStream, response.getOutputStream());
    } catch (Exception e) {
        throw new ResourceReferenceHandlerException(String.format("Failed to read resource [%s]", resourceName),
                e);
    } finally {
        IOUtils.closeQuietly(resourceStream);
    }
}

From source file:com.microsoft.azure.storage.core.Utility.java

/**
 * Reads data from an input stream and writes it to an output stream, calculates the length of the data written, and
 * optionally calculates the MD5 hash for the data.
 * //from www .  ja  v  a 2 s .c  om
 * @param sourceStream
 *            An <code>InputStream</code> object that represents the input stream to use as the source.
 * @param outStream
 *            An <code>OutputStream</code> object that represents the output stream to use as the destination.
 * @param writeLength
 *            The number of bytes to read from the stream.
 * @param rewindSourceStream
 *            <code>true</code> if the input stream should be rewound <strong>before</strong> it is read; otherwise,
 *            <code>false</code>
 * @param calculateMD5
 *            <code>true</code> if an MD5 hash will be calculated; otherwise, <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object that represents the context for the current operation. This object
 *            is used to track requests to the storage service, and to provide additional runtime information about
 *            the operation.
 * @param options
 *            A {@link RequestOptions} object that specifies any additional options for the request. Namely, the
 *            maximum execution time.
 * @param request
 *            Used by download resume to set currentRequestByteCount on the request. Otherwise, null is always used.
 * @return A {@link StreamMd5AndLength} object that contains the output stream length, and optionally the MD5 hash.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 * @throws StorageException
 *             If a storage service error occurred.
 */
public static StreamMd5AndLength writeToOutputStream(final InputStream sourceStream,
        final OutputStream outStream, long writeLength, final boolean rewindSourceStream,
        final boolean calculateMD5, OperationContext opContext, final RequestOptions options,
        final Boolean shouldFlush, StorageRequest<?, ?, Integer> request) throws IOException, StorageException {
    if (rewindSourceStream && sourceStream.markSupported()) {
        sourceStream.reset();
        sourceStream.mark(Constants.MAX_MARK_LENGTH);
    }

    final StreamMd5AndLength retVal = new StreamMd5AndLength();

    if (calculateMD5) {
        try {
            retVal.setDigest(MessageDigest.getInstance("MD5"));
        } catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    if (writeLength < 0) {
        writeLength = Long.MAX_VALUE;
    }

    final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH];
    int nextCopy = (int) Math.min(retrievedBuff.length, writeLength);
    int count = sourceStream.read(retrievedBuff, 0, nextCopy);

    while (nextCopy > 0 && count != -1) {

        // if maximum execution time would be exceeded
        if (Utility.validateMaxExecutionTimeout(options.getOperationExpiryTimeInMs())) {
            // throw an exception
            TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);
            throw Utility.initIOException(timeoutException);
        }

        if (outStream != null) {
            outStream.write(retrievedBuff, 0, count);
        }

        if (calculateMD5) {
            retVal.getDigest().update(retrievedBuff, 0, count);
        }

        retVal.setLength(retVal.getLength() + count);
        retVal.setCurrentOperationByteCount(retVal.getCurrentOperationByteCount() + count);

        if (request != null) {
            request.setCurrentRequestByteCount(request.getCurrentRequestByteCount() + count);
        }

        nextCopy = (int) Math.min(retrievedBuff.length, writeLength - retVal.getLength());
        count = sourceStream.read(retrievedBuff, 0, nextCopy);
    }

    if (outStream != null && shouldFlush) {
        outStream.flush();
    }

    return retVal;
}

From source file:org.gudy.azureus2.pluginsimpl.local.utils.xml.simpleparser.SimpleXMLParserDocumentImpl.java

private void create(InputStream _input_stream)

        throws SimpleXMLParserDocumentException {
    // make sure we can mark the stream to permit later recovery if needed

    if (!_input_stream.markSupported()) {

        _input_stream = new BufferedInputStream(_input_stream);
    }//from  w  w  w .j a  v  a 2  s. co m

    _input_stream.mark(100 * 1024);

    // prevent the parser from screwing with our stream by closing it

    UncloseableInputStream uc_is = new UncloseableInputStream(_input_stream);

    try {
        createSupport(uc_is);

    } catch (SimpleXMLParserDocumentException e) {

        String msg = Debug.getNestedExceptionMessage(e);

        if ((msg.contains("entity") && msg.contains("was referenced")) || msg.contains("entity reference")) {

            try {
                // nasty hack to try and handle HTML entities that some annoying feeds include :(

                _input_stream.reset();

                createSupport(new EntityFudger(_input_stream));

                return;

            } catch (Throwable f) {
            }
        }

        //Debug.out( e );

        throw (e);

    } finally {

        try {
            _input_stream.close();

        } catch (Throwable e) {
        }
    }
}

From source file:org.apache.axis.attachments.DimeBodyPart.java

protected long getDataSize(DataHandler dh) {
    long dataSize = -1L;

    try {//  w  w w .j  a v a2s .  co  m
        DataSource ds = dh.getDataSource();

        //Do files our selfs since this is costly to read in. Ask the file system.
        // This is 90% of the use of attachments.
        if (ds instanceof javax.activation.FileDataSource) {
            javax.activation.FileDataSource fdh = (javax.activation.FileDataSource) ds;
            java.io.File df = fdh.getFile();

            if (!df.exists()) {
                throw new RuntimeException(Messages.getMessage("noFile", df.getAbsolutePath()));
            }
            dataSize = df.length();
        } else {
            dataSize = 0;
            java.io.InputStream in = ds.getInputStream();
            byte[] readbuf = new byte[64 * 1024];
            int bytesread;

            do {
                bytesread = in.read(readbuf);
                if (bytesread > 0)
                    dataSize += bytesread;
            } while (bytesread > -1);

            if (in.markSupported()) {
                //Leave the stream open for future reading
                // and reset the stream pointer to the first byte
                in.reset();
            } else {
                //FIXME: bug http://nagoya.apache.org/jira/secure/ViewIssue.jspa?key=AXIS-1126
                //if we close this then how can we read the file? eh?
                in.close();
            }
        }
    } catch (Exception e) {
        //TODO: why are exceptions swallowed here?
        log.error(Messages.getMessage("exception00"), e);
    }
    return dataSize;
}

From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializer.java

boolean isArchiveStream(InputStream in) {
    if (in == null) {
        throw new IllegalArgumentException("Stream must not be null.");
    }/*from w w  w.  ja v a  2s  .  c o m*/

    if (!in.markSupported()) {
        throw new IllegalArgumentException("Mark is not supported.");
    }

    final byte[] signature = new byte[12];
    in.mark(signature.length);
    int signatureLength;
    try {
        signatureLength = IOUtils.readFully(in, signature);
        in.reset();
    } catch (IOException e) {
        throw new RuntimeException(String.format(ERR_UNMARSHALLING_STREAM, "<unknown>", e.getMessage()), e);
    }
    return ZipArchiveInputStream.matches(signature, signatureLength);
}

From source file:com.temenos.interaction.media.odata.xml.atom.AtomXMLProvider.java

/**
 * Method to verify if receieved stream has content or its empty
 * @param stream Stream to check/*w ww .j  a  v  a 2  s . com*/
 * @return verified stream
 * @throws IOException
 */
private InputStream verifyContentReceieved(InputStream stream) throws IOException {

    if (stream == null) { // Check if its null
        LOGGER.debug("Request stream received as null");
        return null;
    } else if (stream.markSupported()) { // Check stream supports mark/reset
        // mark() and read the first byte just to check
        stream.mark(1);
        final int bytesRead = stream.read(new byte[1]);
        if (bytesRead != -1) {
            //stream not empty
            stream.reset(); // reset the stream as if untouched
            return stream;
        } else {
            //stream empty
            LOGGER.debug("Request received with empty body");
            return null;
        }
    } else {
        // Panic! this stream does not support mark/reset, try with PushbackInputStream as a last resort
        int bytesRead;
        PushbackInputStream pbs = new PushbackInputStream(stream);
        if ((bytesRead = pbs.read()) != -1) {
            // Contents detected, unread and return
            pbs.unread(bytesRead);
            return pbs;
        } else {
            // Empty stream detected
            LOGGER.debug("Request received with empty body!");
            return null;
        }
    }
}