Example usage for java.io InputStream reset

List of usage examples for java.io InputStream reset

Introduction

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

Prototype

public synchronized void reset() throws IOException 

Source Link

Document

Repositions this stream to the position at the time the mark method was last called on this input stream.

Usage

From source file:org.craftercms.studio.impl.v1.repository.cached.CachedContentRepository.java

@Override
public InputStream getContent(String path) throws ContentNotFoundException {
    InputStream value = null;

    try {/* w ww . j  a  v a 2 s  . c o  m*/
        BytesContainer cachedBytesContainer = (BytesContainer) getCachedObject("getContent-" + path);

        if (path.startsWith("/cstudio")) {
            if (cachedBytesContainer == null) {
                value = wrappedRepo.getContent(path);

                if (value != null) {
                    byte[] bytes = IOUtils.toByteArray(value);
                    value.reset();
                    BytesContainer container = new BytesContainer(bytes);
                    cacheObject("getContent-" + path, bytes);
                }
            } else {
                byte[] cachedBytes = cachedBytesContainer.getBytes();
                value = new ByteArrayInputStream(cachedBytes);
            }
        } else {
            // web content
            value = wrappedRepo.getContent(path);
        }
    } catch (Exception err) {
        value = wrappedRepo.getContent(path);
    }

    return value;
}

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  ww  .  j a  v  a2s.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:org.infoscoop.web.MultiRssServlet.java

private int getStreamLength(InputStream is) throws IOException {
    is.mark(1);//from  w ww  . ja va 2  s . com
    byte[] b = new byte[1024];
    int i = 0;
    int length = 0;
    while ((i = is.read(b)) != -1) {
        length += i;
    }

    is.reset();

    return length;
}

From source file:com.myapps.upesse.upes_spefest.ui.activity.NewPostUploadTaskFragment.java

public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight) throws IOException {
    InputStream stream = new BufferedInputStream(
            mApplicationContext.getContentResolver().openInputStream(fileUri));
    stream.mark(stream.available());//from   www . jav a  2 s  . c  o m
    BitmapFactory.Options options = new BitmapFactory.Options();
    //options.
    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, null, options);
    stream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    BitmapFactory.decodeStream(stream, null, options);
    // Decode bitmap with inSampleSize set
    stream.reset();
    return BitmapFactory.decodeStream(stream, null, options);
}

From source file:dk.dr.radio.net.Diverse.java

    sStreng(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();//from   ww w. j ava2  s  .com
    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.openhab.binding.neato.internal.VendorVorwerk.java

@Override
public String executeRequest(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout) throws IOException {

    URL requestUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();
    applyNucleoSslConfiguration(connection);
    connection.setRequestMethod(httpMethod);
    for (String propName : httpHeaders.stringPropertyNames()) {
        connection.addRequestProperty(propName, httpHeaders.getProperty(propName));
    }/*w  ww . j av a2  s.  com*/
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    content.reset();
    IOUtils.copy(content, connection.getOutputStream());

    java.io.InputStream is = connection.getInputStream();
    return IOUtils.toString(is);
}

From source file:org.apache.xml.security.signature.XMLSignatureInput.java

/**
 * Returns the byte array from input which was specified as the parameter of 
 * {@link XMLSignatureInput} constructor
 *
 * @return the byte[] from input which was specified as the parameter of 
 * {@link XMLSignatureInput} constructor
 *
 * @throws CanonicalizationException//w w w  .  j  a  va  2 s . c o m
 * @throws IOException
 */
public byte[] getBytes() throws IOException, CanonicalizationException {
    if (bytes != null) {
        return bytes;
    }
    InputStream is = getResetableInputStream();
    if (is != null) {
        //resetable can read again bytes. 
        if (bytes == null) {
            is.reset();
            bytes = JavaUtils.getBytesFromStream(is);
        }
        return bytes;
    }
    Canonicalizer20010315OmitComments c14nizer = new Canonicalizer20010315OmitComments();
    bytes = c14nizer.engineCanonicalize(this);
    return bytes;
}

From source file:com.aliyun.odps.rest.RestClient.java

private void resetBody(InputStream body) {
    if (body != null && body.markSupported()) {
        try {/*  w w  w. ja v  a2s. c o m*/
            body.reset();
        } catch (IOException e) {
            // DO NOTHING FOR SUPPORTED MARK STREAM WILL NOT FAILED
        }
    }
}

From source file:com.smartitengineering.event.hub.common.EventJsonProvider.java

public String getJsonString(Event event) {
    if (event == null) {
        return "";
    }// w ww . j  a  va2  s.c o m
    Map<String, String> jsonMap = new LinkedHashMap<String, String>();
    if (StringUtils.isNotBlank(event.getPlaceholderId())) {
        jsonMap.put(PLACEHOLDER_ID, event.getPlaceholderId());
    }
    if (StringUtils.isNotBlank(event.getUniversallyUniqueID())) {
        jsonMap.put(UNIVERSAL_UNIQUE_ID, event.getUniversallyUniqueID());
    }
    if (StringUtils.isNotBlank(event.getEventContent().getContentType())) {
        jsonMap.put(CONTENT_TYPE, event.getEventContent().getContentType());
    }
    InputStream contentStream = event.getEventContent().getContent();
    if (contentStream != null) {
        String contentAsString = "";
        if (contentCache.containsKey(event)) {
            contentAsString = contentCache.get(event);
        } else {
            try {
                if (contentStream.markSupported()) {
                    contentStream.mark(Integer.MAX_VALUE);
                }
                contentAsString = IOUtils.toString(contentStream);
                contentCache.put(event, contentAsString);
                if (contentStream.markSupported()) {
                    contentStream.reset();
                }
            } catch (IOException ex) {
            }
        }
        jsonMap.put(CONTENT_AS_STRING, contentAsString);
    }
    Date creationDate = event.getCreationDate();
    if (creationDate != null) {
        jsonMap.put(CREATION_DATE, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(creationDate));
    }
    try {
        return mapper.writeValueAsString(jsonMap);
    } catch (Exception ex) {
        return "";
    }
}

From source file:com.adguard.filter.proxy.ProtocolDetector.java

/**
 * Peeks first N non-empty bytes from a peeking stream.
 *
 * @param inputStream Input stream//from w w w  .  j  ava 2  s  . c  o  m
 * @param length      Length of the non-empty fragment we need
 * @return First non-empty bytes read or null if there is no fragment of the specified length
 */
private static byte[] peekFirstNotEmptyBytes(InputStream inputStream, int length) throws IOException {

    final int markLength = 32 * 1024;
    int bytesRead = 0;
    int bytesFound = 0;
    byte[] firstBytes = new byte[length];
    byte[] buffer = new byte[512];

    inputStream.mark(markLength);
    try {
        while (bytesRead < markLength) {
            int bytesMarked = IOUtils.read(inputStream, buffer);

            // if stream is finished and we still didn't read the array of length we need
            if (bytesMarked <= 0)
                return null;
            bytesRead += bytesMarked;

            for (int i = 0; i < bytesMarked; i++) {
                byte b = buffer[i];
                boolean empty = IoUtils.isEmptyOrWhitespace(b) || IoUtils.isBomByte(b);
                // bytesFound > 0 means that we have already found first non-empty character
                // we also ignore zero byte to handle UTF-16
                if ((!empty || bytesFound > 0) && b != 0) {
                    firstBytes[bytesFound] = b;
                    bytesFound++;
                }

                if (bytesFound == firstBytes.length) {
                    // Found enough bytes
                    return firstBytes;
                }
            }

            // End of stream and we have not found enough bytes
            if (bytesMarked < buffer.length) {
                return null;
            }
        }
    } finally {
        inputStream.reset();
    }

    return null;
}