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.openmastery.logging.LoggingFilter.java

private InputStream logInboundEntity(StringBuilder b, InputStream stream, Charset charset) throws IOException {
    if (!stream.markSupported()) {
        stream = new BufferedInputStream(stream);
    }/*w  w w  .  j  a  v  a 2  s  . c  o  m*/
    stream.mark(maxEntitySize + 1);
    byte[] entity = new byte[maxEntitySize + 1];
    int entitySize = stream.read(entity);
    entitySize = entitySize < 0 ? 0 : entitySize;
    b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset));
    if (entitySize > maxEntitySize) {
        b.append("...more...");
    }
    b.append('\n');
    stream.reset();
    return stream;
}

From source file:org.craftercms.studio.impl.v1.web.security.access.StudioPublishingAPIAccessDecisionVoter.java

@Override
public int vote(Authentication authentication, Object o, Collection collection) {
    int toRet = ACCESS_ABSTAIN;
    String requestUri = "";
    if (o instanceof FilterInvocation) {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        HttpServletRequest request = filterInvocation.getRequest();
        requestUri = request.getRequestURI().replace(request.getContextPath(), "");
        String userParam = request.getParameter("username");
        String siteParam = request.getParameter("site_id");
        if (StringUtils.isEmpty(userParam)
                && StringUtils.equalsIgnoreCase(request.getMethod(), HttpMethod.POST.name())
                && !ServletFileUpload.isMultipartContent(request)) {
            try {
                InputStream is = request.getInputStream();
                is.mark(0);//from   w  w w .  j  a v a  2 s. com
                String jsonString = IOUtils.toString(is);
                if (StringUtils.isNoneEmpty(jsonString)) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonString);
                    if (jsonObject.has("username")) {
                        userParam = jsonObject.getString("username");
                    }
                    if (jsonObject.has("site_id")) {
                        siteParam = jsonObject.getString("site_id");
                    }
                }
                is.reset();
            } catch (IOException | JSONException e) {
                // TODO: ??
                logger.debug("Failed to extract username from POST request");
            }
        }
        User currentUser = null;
        try {
            currentUser = (User) authentication.getPrincipal();
        } catch (ClassCastException e) {
            // anonymous user
            if (!authentication.getPrincipal().toString().equals("anonymousUser")) {
                logger.info("Error getting current user", e);
                return ACCESS_ABSTAIN;
            }
        }
        switch (requestUri) {
        case START:
        case STOP:
            if (currentUser != null) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case STATUS:
            if (siteService.exists(siteParam)) {
                if (currentUser != null && isSiteMember(siteParam, currentUser)) {
                    toRet = ACCESS_GRANTED;
                } else {
                    toRet = ACCESS_DENIED;
                }
            } else {
                toRet = ACCESS_ABSTAIN;
            }
            break;
        default:
            toRet = ACCESS_ABSTAIN;
            break;
        }
    }
    logger.debug("Request: " + requestUri + " - Access: " + toRet);
    return toRet;
}

From source file:cn.com.esrichina.gcloud.commons.LicenseContext.java

public void updateLicence(InputStream is) throws GeneralException {
    try {/*from  w  w  w  . j a  va  2s .c o  m*/

        File tempFile = new File(
                System.getProperty("java.io.tmpdir") + File.separator + LicenseUtil.LICENSE_NAME);

        FileUtils.copyInputStreamToFile(is, tempFile);

        isAuthorized = true;
        loadLicence(System.getProperty("java.io.tmpdir") + File.separator + LicenseUtil.LICENSE_NAME, false);

        // After validate success ,then covered the license file.
        if (isAuthorized) {
            is.reset();
            FileUtils.copyInputStreamToFile(is,
                    new File(ConfigContext.getInstance().getString("license.path")));
            // FileUtils.copyFile(tempFile, new
            // File(ConfigContext.getInstance().getString("license.path")));
        }

    } catch (Exception e) {
        logger.error("?", e);
        throw new GeneralException(Messages.getMessage("license_update_error", e.getMessage()), e);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java

/**
 * Validates configuration XML against XML defined XSD schema.
 *
 * @param config/* w  ww.  jav a 2  s.  co  m*/
 *            {@link InputStream} to get configuration data from
 * @return map of found validation errors
 * @throws SAXException
 *             if there was an error parsing the configuration
 * @throws IOException
 *             if there is an error reading the configuration data
 */
public static Map<OpLevel, List<SAXParseException>> validate(InputStream config)
        throws SAXException, IOException {
    final Map<OpLevel, List<SAXParseException>> validationErrors = new HashMap<>();
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema();
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.WARNING, exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.ERROR, exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.FATAL, exception);
            }

            private void handleValidationError(OpLevel level, SAXParseException exception) {
                List<SAXParseException> lErrorsList = validationErrors.get(level);
                if (lErrorsList == null) {
                    lErrorsList = new ArrayList<>();
                    validationErrors.put(level, lErrorsList);
                }

                lErrorsList.add(exception);
            }
        });
        validator.validate(new StreamSource(config));
    } finally {
        if (config.markSupported()) {
            config.reset();
        }
    }

    return validationErrors;
}

From source file:com.seajas.search.contender.service.storage.StorageService.java

/**
 * Store the given content in GridFS and return the relevant ObjectId.
 *
 * @param content//from  w  ww  . j  a v  a  2  s . c  om
 * @return ObjectId
 */
private ObjectId storeContent(final InputStream content) {
    if (content == null)
        throw new IllegalArgumentException("Content storage was requested but no content was given");

    if (!content.markSupported())
        logger.warn(
                "Marking of the (original) content stream is not supported - will not reset the stream after storage");

    GridFSInputFile inputFile = gridFs.createFile(content, false);

    try {
        inputFile.save();
    } finally {
        if (content.markSupported())
            try {
                content.reset();
            } catch (IOException e) {
                logger.error("Unable to reset the given stream, despite mark() being supported", e);
            }

        return (ObjectId) inputFile.getId();
    }
}

From source file:org.apache.ivory.resource.AbstractEntityManager.java

protected Entity deserializeEntity(HttpServletRequest request, EntityType entityType)
        throws IOException, IvoryException {

    EntityParser<?> entityParser = EntityParserFactory.getParser(entityType);
    InputStream xmlStream = request.getInputStream();
    if (xmlStream.markSupported()) {
        xmlStream.mark(XML_DEBUG_LEN); // mark up to debug len
    }/*from   www.j  a  v  a 2s .c  o  m*/
    try {
        return entityParser.parse(xmlStream);
    } catch (IvoryException e) {
        if (LOG.isDebugEnabled() && xmlStream.markSupported()) {
            try {
                xmlStream.reset();
                String xmlData = getAsString(xmlStream);
                LOG.debug("XML DUMP for (" + entityType + "): " + xmlData, e);
            } catch (IOException ignore) {
            }
        }
        throw e;
    }
}

From source file:org.craftercms.studio.impl.v1.web.security.access.StudioGroupAPIAccessDecisionVoter.java

@Override
public int vote(Authentication authentication, Object o, Collection collection) {
    int toRet = ACCESS_ABSTAIN;
    String requestUri = "";
    if (o instanceof FilterInvocation) {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        HttpServletRequest request = filterInvocation.getRequest();
        requestUri = request.getRequestURI().replace(request.getContextPath(), "");
        String siteParam = request.getParameter("site_id");
        String userParam = request.getParameter("username");
        User currentUser = null;//from   w  w w  . j a v  a 2  s .  c  o  m
        try {
            currentUser = (User) authentication.getPrincipal();
        } catch (ClassCastException e) {
            // anonymous user
            if (!authentication.getPrincipal().toString().equals("anonymousUser")) {
                logger.error("Error getting current user", e);
                return ACCESS_ABSTAIN;
            }
        }
        if (StringUtils.isEmpty(userParam)
                && StringUtils.equalsIgnoreCase(request.getMethod(), HttpMethod.POST.name())
                && !ServletFileUpload.isMultipartContent(request)) {
            try {
                InputStream is = request.getInputStream();
                is.mark(0);
                String jsonString = IOUtils.toString(is);
                if (StringUtils.isNoneEmpty(jsonString)) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonString);
                    if (jsonObject.has("username")) {
                        userParam = jsonObject.getString("username");
                    }
                    if (jsonObject.has("site_id")) {
                        siteParam = jsonObject.getString("site_id");
                    }
                }
                is.reset();
            } catch (IOException | JSONException e) {
                // TODO: ??
                logger.debug("Failed to extract username from POST request");
            }
        }
        switch (requestUri) {
        case ADD_USER:
        case CREATE:
        case DELETE:
        case GET_ALL:
        case REMOVE_USER:
        case UPDATE:
            if (currentUser != null && (isSiteAdmin(
                    studioConfiguration.getProperty(StudioConfiguration.CONFIGURATION_GLOBAL_SYSTEM_SITE),
                    currentUser) || isSiteAdmin(siteParam, currentUser))) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case GET:
        case GET_PER_SITE:
        case USERS:
            if (currentUser != null
                    && (isSiteAdmin(siteParam, currentUser) || isSiteMember(siteParam, currentUser))) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        default:
            toRet = ACCESS_ABSTAIN;
            break;
        }
    }
    logger.debug("Request: " + requestUri + " - Access: " + toRet);
    return toRet;
}

From source file:util.epub.util.commons.io.XmlStreamReader.java

/**
 * Returns the encoding declared in the <?xml encoding=...?>, NULL if none.
 *
 * @param is InputStream to create the reader from.
 * @param guessedEnc guessed encoding/*w ww  . jav a 2s . co  m*/
 * @return the encoding declared in the <?xml encoding=...?>
 * @throws IOException thrown if there is a problem reading the stream.
 */
private static String getXmlProlog(InputStream is, String guessedEnc) throws IOException {
    String encoding = null;
    if (guessedEnc != null) {
        byte[] bytes = new byte[BUFFER_SIZE];
        is.mark(BUFFER_SIZE);
        int offset = 0;
        int max = BUFFER_SIZE;
        int c = is.read(bytes, offset, max);
        int firstGT = -1;
        String xmlProlog = null;
        while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) {
            offset += c;
            max -= c;
            c = is.read(bytes, offset, max);
            xmlProlog = new String(bytes, 0, offset, guessedEnc);
            firstGT = xmlProlog.indexOf('>');
        }
        if (firstGT == -1) {
            if (c == -1) {
                throw new IOException("Unexpected end of XML stream");
            } else {
                throw new IOException("XML prolog or ROOT element not found on first " + offset + " bytes");
            }
        }
        int bytesRead = offset;
        if (bytesRead > 0) {
            is.reset();
            BufferedReader bReader = new BufferedReader(new StringReader(xmlProlog.substring(0, firstGT + 1)));
            StringBuilder prolog = new StringBuilder();
            String line = bReader.readLine();
            while (line != null) {
                prolog.append(line);
                line = bReader.readLine();
            }
            Matcher m = ENCODING_PATTERN.matcher(prolog);
            if (m.find()) {
                encoding = m.group(1).toUpperCase();
                encoding = encoding.substring(1, encoding.length() - 1);
            }
        }
    }
    return encoding;
}

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();/*from w  ww  .  j  a va  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.archive.io.arc.ARCWriterTest.java

public void testArchiveRecordMarkSupport() throws Exception {
    ARCReader r = getSingleRecordReader("testArchiveRecordMarkSupport");
    ARCRecord record = getSingleRecord(r);
    record.setStrict(true);//from  w  ww.  j a va  2s . co  m
    // ensure mark support
    InputStream stream = new BufferedInputStream(record);
    if (stream.markSupported()) {
        for (int i = 0; i < 3; i++) {
            this.readToEOS(stream);
            stream.mark(stream.available());
            stream.reset();
        }
        stream.close();
    }
    r.close();
}