Example usage for java.io InputStream mark

List of usage examples for java.io InputStream mark

Introduction

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

Prototype

public synchronized void mark(int readlimit) 

Source Link

Document

Marks the current position in this input stream.

Usage

From source file:org.guvnor.m2repo.backend.server.FileServlet.java

public String uploadFile(FormData uploadItem) throws IOException {
    InputStream fileData = uploadItem.getFile().getInputStream();
    String fileName = uploadItem.getFile().getName();
    GAV gav = uploadItem.getGav();//from   w w  w  .j a  va 2s.  c  o  m

    try {
        if (gav == null) {
            if (!fileData.markSupported()) {
                fileData = new BufferedInputStream(fileData);
            }

            fileData.mark(fileData.available()); // is available() safe?
            String pom = GuvnorM2Repository.loadPOMFromJar(fileData);
            fileData.reset();

            if (pom != null) {
                Model model = new MavenXpp3Reader().read(new StringReader(pom));

                String groupId = model.getGroupId();
                String artifactId = model.getArtifactId();
                String version = model.getVersion();

                if (groupId == null) {
                    groupId = model.getParent().getGroupId();
                }
                if (version == null) {
                    version = model.getParent().getVersion();
                }

                gav = new GAV(groupId, artifactId, version);
            } else {
                return "NO VALID POM";
            }
        }

        m2RepoService.deployJar(fileData, gav);
        uploadItem.getFile().getInputStream().close();

        return "OK";
    } catch (XmlPullParserException e) {
    } catch (IOException ioe) {
    }

    return "INTERNAL ERROR";
}

From source file:com.amazonaws.mobileconnectors.s3.transfermanager.internal.UploadCallable.java

/**
 * Uploads all parts in the request in serial in this thread, then completes
 * the upload and returns the result.//ww w  .j ava2s  . c o m
 */
private UploadResult uploadPartsInSeries(UploadPartRequestFactory requestFactory) {

    final List<PartETag> partETags = new ArrayList<PartETag>();

    while (requestFactory.hasMoreRequests()) {
        if (threadPool.isShutdown())
            throw new CancellationException("TransferManager has been shutdown");
        UploadPartRequest uploadPartRequest = requestFactory.getNextUploadPartRequest();
        // Mark the stream in case we need to reset it
        InputStream inputStream = uploadPartRequest.getInputStream();
        if (inputStream != null && inputStream.markSupported()) {
            if (uploadPartRequest.getPartSize() >= Integer.MAX_VALUE) {
                inputStream.mark(Integer.MAX_VALUE);
            } else {
                inputStream.mark((int) uploadPartRequest.getPartSize());
            }
        }
        partETags.add(s3.uploadPart(uploadPartRequest).getPartETag());
    }

    CompleteMultipartUploadResult completeMultipartUploadResult = s3
            .completeMultipartUpload(new CompleteMultipartUploadRequest(putObjectRequest.getBucketName(),
                    putObjectRequest.getKey(), multipartUploadId, partETags));

    UploadResult uploadResult = new UploadResult();
    uploadResult.setBucketName(completeMultipartUploadResult.getBucketName());
    uploadResult.setKey(completeMultipartUploadResult.getKey());
    uploadResult.setETag(completeMultipartUploadResult.getETag());
    uploadResult.setVersionId(completeMultipartUploadResult.getVersionId());
    return uploadResult;
}

From source file:org.guvnor.m2repo.backend.server.helpers.HttpPostHelper.java

private String uploadJar(final FormData formData) throws IOException {
    GAV gav = formData.getGav();//from  ww  w  . j  a v a  2  s.c  o  m
    InputStream jarStream = null;

    try {
        jarStream = formData.getFile().getInputStream();
        if (gav == null) {
            if (!jarStream.markSupported()) {
                jarStream = new BufferedInputStream(jarStream);
            }

            // is available() safe?
            jarStream.mark(jarStream.available());

            PomModel pomModel = PomModelResolver.resolveFromJar(jarStream);

            //If we were able to get a POM model we can get the GAV
            if (pomModel != null) {
                String groupId = pomModel.getReleaseId().getGroupId();
                String artifactId = pomModel.getReleaseId().getArtifactId();
                String version = pomModel.getReleaseId().getVersion();

                if (isNullOrEmpty(groupId) || isNullOrEmpty(artifactId) || isNullOrEmpty(version)) {
                    return UPLOAD_MISSING_POM;
                } else {
                    gav = new GAV(groupId, artifactId, version);
                }

            } else {
                return UPLOAD_MISSING_POM;
            }
            jarStream.reset();
        }

        m2RepoService.deployJar(jarStream, gav);

        return UPLOAD_OK;

    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw ExceptionUtilities.handleException(ioe);

    } finally {
        if (jarStream != null) {
            jarStream.close();
        }

    }
}

From source file:eu.medsea.mimeutil.TextMimeDetector.java

/**
 * @see MimeDetector.getMimeTypesInputStream(InputStream in)
 *//*from  w  ww. ja  v a2s  .co  m*/
public Collection getMimeTypesInputStream(InputStream in) throws UnsupportedOperationException {

    int offset = 0;
    int len = TextMimeDetector.BUFFER_SIZE;
    byte[] data = new byte[len];
    byte[] copy = null;
    // Mark the input stream
    in.mark(len);

    try {
        // Since an InputStream might return only some data (not all
        // requested), we have to read in a loop until
        // either EOF is reached or the desired number of bytes have been
        // read.
        int restBytesToRead = len;
        while (restBytesToRead > 0) {
            int bytesRead = in.read(data, offset, restBytesToRead);
            if (bytesRead < 0)
                break; // EOF

            offset += bytesRead;
            restBytesToRead -= bytesRead;
        }
        if (offset < len) {
            copy = new byte[offset];
            System.arraycopy(data, 0, copy, 0, offset);
        } else {
            copy = data;
        }
    } catch (IOException ioe) {
        throw new MimeException(ioe);
    } finally {
        try {
            // Reset the input stream to where it was marked.
            in.reset();
        } catch (Exception e) {
            throw new MimeException(e);
        }
    }
    return getMimeTypesByteArray(copy);
}

From source file:org.apache.fop.fonts.type1.PFMFile.java

/**
 * Parses a PFM file//from ww  w. j  a  v  a2s.  c  o m
 *
 * @param  inStream The stream from which to read the PFM file.
 * @throws IOException In case of an I/O problem
 */
public void load(InputStream inStream) throws IOException {
    byte[] pfmBytes = IOUtils.toByteArray(inStream);
    InputStream bufin = inStream;
    bufin = new ByteArrayInputStream(pfmBytes);
    PFMInputStream in = new PFMInputStream(bufin);
    bufin.mark(512);
    short sh1 = in.readByte();
    short sh2 = in.readByte();
    if (sh1 == 128 && sh2 == 1) {
        //Found the first section header of a PFB file!
        throw new IOException("Cannot parse PFM file. You probably specified the PFB file"
                + " of a Type 1 font as parameter instead of the PFM.");
    }
    bufin.reset();
    byte[] b = new byte[16];
    bufin.read(b);
    if (new String(b, "US-ASCII").equalsIgnoreCase("StartFontMetrics")) {
        //Found the header of a AFM file!
        throw new IOException("Cannot parse PFM file. You probably specified the AFM file"
                + " of a Type 1 font as parameter instead of the PFM.");
    }
    bufin.reset();
    final int version = in.readShort();
    if (version != 256) {
        log.warn("PFM version expected to be '256' but got '" + version + "'."
                + " Please make sure you specify the PFM as parameter" + " and not the PFB or the AFM.");
    }
    //final long filesize = in.readInt();
    bufin.reset();

    loadHeader(in);
    loadExtension(in);
}

From source file:dk.dr.radio.data.JsonIndlaesning.java

    sInputStreamSomStreng(InputStream is) throws IOException, UnsupportedEncodingException {

  // Det kan vre ndvendigt at hoppe over BOM mark - se http://android.forums.wordpress.org/topic/xml-pull-error?replies=2
  //is.read(); is.read(); is.read(); // - dette virker kun hvis der ALTID er en BOM
  // Hop over BOM - hvis den er der!
  is = new BufferedInputStream(is);  // bl.a. FileInputStream understtter ikke mark, s brug BufferedInputStream
  is.mark(1); // vi har faktisk kun brug for at sge n byte tilbage
  if (is.read() == 0xef) {
    is.read();//w w w. j ava  2 s.c o  m
    is.read();
  } // Der var en BOM! Ls de sidste 2 byte
  else is.reset(); // Der var ingen BOM - hop tilbage til start


  final char[] buffer = new char[0x3000];
  StringBuilder out = new StringBuilder();
  Reader in = new InputStreamReader(is, "UTF-8");
  int read;
  do {
    read = in.read(buffer, 0, buffer.length);
    if (read > 0) {
      out.append(buffer, 0, read);
    }
  } while (read >= 0);
  in.close();
  return out.toString();
}

From source file:org.apache.nifi.processors.standard.util.crypto.OpenSSLPKCS5CipherProvider.java

/**
 * Returns the salt provided as part of the cipher stream, or throws an exception if one cannot be detected.
 *
 * @param in the cipher InputStream/*w  ww .ja  v  a2s .c  o m*/
 * @return the salt
 */
@Override
public byte[] readSalt(InputStream in) throws IOException {
    if (in == null) {
        throw new IllegalArgumentException("Cannot read salt from null InputStream");
    }

    // The header and salt format is "Salted__salt x8b" in ASCII
    byte[] salt = new byte[DEFAULT_SALT_LENGTH];

    // Try to read the header and salt from the input
    byte[] header = new byte[OPENSSL_EVP_HEADER_SIZE];

    // Mark the stream in case there is no salt
    in.mark(OPENSSL_EVP_HEADER_SIZE + 1);
    StreamUtils.fillBuffer(in, header);

    final byte[] headerMarkerBytes = OPENSSL_EVP_HEADER_MARKER.getBytes(StandardCharsets.US_ASCII);

    if (!Arrays.equals(headerMarkerBytes, header)) {
        // No salt present
        salt = new byte[0];
        // Reset the stream because we skipped 8 bytes of cipher text
        in.reset();
    }

    StreamUtils.fillBuffer(in, salt);
    return salt;
}

From source file:om.sstvencoder.CropView.java

public void setBitmapStream(InputStream stream) throws IOException {
    mImageOK = false;//ww  w .j  ava  2 s.c om
    mOrientation = 0;
    recycle();

    // app6 + exif
    int bufferBytes = 1048576;
    if (!stream.markSupported())
        stream = new BufferedInputStream(stream, bufferBytes);
    stream.mark(bufferBytes);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(new BufferedInputStream(stream), null, options);
    stream.reset();
    mImageWidth = options.outWidth;
    mImageHeight = options.outHeight;

    if (mImageWidth * mImageHeight < 1024 * 1024) {
        mCacheBitmap = BitmapFactory.decodeStream(stream);
        mSmallImage = true;
    } else {
        mRegionDecoder = BitmapRegionDecoder.newInstance(stream, true);
        mCacheRect.setEmpty();
        mSmallImage = false;
    }

    if (mCacheBitmap == null && mRegionDecoder == null) {
        String size = options.outWidth + "x" + options.outHeight;
        throw new IOException("Stream could not be decoded. Image size: " + size);
    }

    mImageOK = true;
    resetInputRect();
    invalidate();
}

From source file:android.net.http.Request.java

/**
 * Supply an InputStream that provides the body of a request.  It's
 * not great that the caller must also provide the length of the data
 * returned by that InputStream, but the client needs to know up
 * front, and I'm not sure how to get this out of the InputStream
 * itself without a costly readthrough.  I'm not sure skip() would
 * do what we want.  If you know a better way, please let me know.
 *//*www.j a v  a2s  .  c om*/
private void setBodyProvider(InputStream bodyProvider, int bodyLength) {
    if (!bodyProvider.markSupported()) {
        throw new IllegalArgumentException("bodyProvider must support mark()");
    }
    // Mark beginning of stream
    bodyProvider.mark(Integer.MAX_VALUE);

    ((BasicHttpEntityEnclosingRequest) mHttpRequest).setEntity(new InputStreamEntity(bodyProvider, bodyLength));
}

From source file:org.alfresco.encoding.AbstractCharactersetFinder.java

/**
 * {@inheritDoc}//from w w w .j ava2 s  .c  o  m
 * <p>
 * The input stream is checked to ensure that it supports marks, after which
 * a buffer is extracted, leaving the stream in its original state.
 */
public final Charset detectCharset(InputStream is) {
    // Only support marking streams
    if (!is.markSupported()) {
        throw new IllegalArgumentException(
                "The InputStream must support marks.  Wrap the stream in a BufferedInputStream.");
    }
    try {
        int bufferSize = getBufferSize();
        if (bufferSize < 0) {
            throw new RuntimeException("The required buffer size may not be negative: " + bufferSize);
        }
        // Mark the stream for just a few more than we actually will need
        is.mark(bufferSize);
        // Create a buffer to hold the data
        byte[] buffer = new byte[bufferSize];
        // Fill it
        int read = is.read(buffer);
        // Create an appropriately sized buffer
        if (read > -1 && read < buffer.length) {
            byte[] copyBuffer = new byte[read];
            System.arraycopy(buffer, 0, copyBuffer, 0, read);
            buffer = copyBuffer;
        }
        // Detect
        return detectCharset(buffer);
    } catch (IOException e) {
        // Attempt a reset
        throw new AlfrescoRuntimeException("IOException while attempting to detect charset encoding.", e);
    } finally {
        try {
            is.reset();
        } catch (Throwable ee) {
        }
    }
}