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:com.intuit.karate.http.jersey.LoggingInterceptor.java

@Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
    int id = counter.get();
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" < ").append(response.getStatus()).append('\n');
    logHeaders(sb, id, '<', response.getHeaders());
    if (response.hasEntity() && isPrintable(response.getMediaType())) {
        InputStream is = response.getEntityStream();
        if (!is.markSupported()) {
            is = new BufferedInputStream(is);
        }//from  w  w w  .  j a v a  2s .  c o  m
        is.mark(Integer.MAX_VALUE);
        String buffer = IOUtils.toString(is, UTF8);
        sb.append(buffer).append('\n');
        is.reset();
        response.setEntityStream(is); // in case it was swapped
    }
    logger.debug(sb.toString());
}

From source file:com.epam.wilma.browsermob.transformer.helper.InputStreamConverter.java

/**
 * Converts an inputStream to a String with Apache Commons' IOUtils.
 * @param inputStream InputStream to convert
 * @return converted stream//ww  w . ja  v  a2 s .  co m
 * @throws ApplicationException when IOUtils or mark/reset fails
 */
public String getStringFromStream(final InputStream inputStream) throws ApplicationException {
    String result = "";
    if (inputStream != null) {
        try {
            int extendedReadLimit = inputStream.available() + BUFFER_SIZE;
            inputStream.mark(extendedReadLimit);
            result = IOUtils.toString(inputStream);
            inputStream.reset();
        } catch (IOException e) {
            throw new ApplicationException("Could not transform request input stream into string!", e);
        }
    }
    return result;
}

From source file:com.norconex.importer.parser.impl.quattro.QPWTextExtractor.java

private boolean hasNext(InputStream in) throws IOException {
    try {/* ww  w . j  a v a2  s. co m*/
        in.mark(1);
        return in.read() != -1;
    } finally {
        in.reset();
    }
}

From source file:com.smartitengineering.cms.spi.impl.type.validator.XMLSchemaBasedTypeValidator.java

@Override
public boolean isValid(InputStream documentStream) throws Exception {
    if (!documentStream.markSupported()) {
        throw new IOException("Only markeable input stream expected!");
    }//from  w w  w  .j a v a 2 s  .  c  o m
    documentStream.mark(Integer.MAX_VALUE);
    InputStream cloneStream = new ByteArrayInputStream(IOUtils.toByteArray(documentStream));
    documentStream.reset();
    Document document = getDocumentForSource(cloneStream);
    return isValid(document);
}

From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java

/**
 * Reads inputStream (from request) and detects incoming JSON encoding.
 * /*from   w w  w  .j  ava 2  s  .com*/
 * @param inputStream
 *            Input Stream from request
 * @return String identifier for detected JSON (UTF8, UTF16LE, ...)
 * @throws IOException
 *             Exception while parsing JSON
 */
private String detectJsonEncoding(InputStream inputStream) throws IOException {
    inputStream.mark(4);
    int mask = 0;
    for (int count = 0; count < 4; count++) {
        int r = inputStream.read();
        if (r == -1) {
            break;
        }
        mask = mask << 1;
        mask |= (r == 0) ? 0 : 1;
    }
    inputStream.reset();
    return match(mask);
}

From source file:org.gytheio.messaging.jackson.QpidJsonBodyCleanerObjectMapper.java

public <T> T readValue(InputStream inputStream, Class<T> valueType)
        throws JsonParseException, JsonMappingException, IOException {
    try {/* ww  w.  ja  v  a  2  s .  c o m*/
        // Try to unmarshal normally
        if (inputStream.markSupported()) {
            inputStream.mark(1024 * 512);
        }
        return super.readValue(inputStream, valueType);
    } catch (JsonParseException e) {
        if (!inputStream.markSupported()) {
            // We can't reset this stream, bail out
            throw e;
        }
        // Reset the stream
        inputStream.reset();
    }
    // Clean the message body and try again
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, DEFAULT_ENCODING);
    String content = writer.toString();
    content = content.substring(content.indexOf("{"), content.length());
    return readValue(content, valueType);
}

From source file:com.intuit.karate.LoggingFilter.java

@Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
    int id = counter.get();
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" < ").append(response.getStatus()).append('\n');
    logHeaders(sb, id, '<', response.getHeaders());
    if (response.hasEntity() && isPrintable(response.getMediaType())) {
        InputStream is = response.getEntityStream();
        if (!is.markSupported()) {
            is = new BufferedInputStream(is);
        }//ww w  .j  av  a  2 s  .c  o  m
        is.mark(Integer.MAX_VALUE);
        String buffer = IOUtils.toString(is, getCharset(response.getMediaType()));
        sb.append(buffer).append('\n');
        is.reset();
        response.setEntityStream(is); // in case it was swapped
    }
    logger.debug(sb.toString());
}

From source file:org.apache.tika.parser.iwork.IWorkPackageParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    ZipArchiveInputStream zip = new ZipArchiveInputStream(stream);
    ZipArchiveEntry entry = zip.getNextZipEntry();

    while (entry != null) {
        if (!IWORK_CONTENT_ENTRIES.contains(entry.getName())) {
            entry = zip.getNextZipEntry();
            continue;
        }//from  ww w  . j  ava2  s . c  om

        InputStream entryStream = new BufferedInputStream(zip, 4096);
        entryStream.mark(4096);
        IWORKDocumentType type = IWORKDocumentType.detectType(entryStream);
        entryStream.reset();

        if (type != null) {
            XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
            ContentHandler contentHandler;

            switch (type) {
            case KEYNOTE:
                contentHandler = new KeynoteContentHandler(xhtml, metadata);
                break;
            case NUMBERS:
                contentHandler = new NumbersContentHandler(xhtml, metadata);
                break;
            case PAGES:
                contentHandler = new PagesContentHandler(xhtml, metadata);
                break;
            case ENCRYPTED:
                // We can't do anything for the file right now
                contentHandler = null;
                break;
            default:
                throw new TikaException("Unhandled iWorks file " + type);
            }

            metadata.add(Metadata.CONTENT_TYPE, type.getType().toString());
            xhtml.startDocument();
            if (contentHandler != null) {
                context.getSAXParser().parse(new CloseShieldInputStream(entryStream),
                        new OfflineContentHandler(contentHandler));
            }
            xhtml.endDocument();
        }

        entry = zip.getNextZipEntry();
    }
    // Don't close the zip InputStream (TIKA-1117).
}

From source file:org.craftercms.studio.impl.v1.web.security.access.StudioUserAPIAccessDecisionVoter.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);
                String jsonString = IOUtils.toString(is);
                if (StringUtils.isNoneEmpty(jsonString)) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonString);
                    if (jsonObject.has("username")) {
                        userParam = jsonObject.getString("username");
                    }//  www  .  java  2  s. c  om
                    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 FORGOT_PASSWORD:
        case LOGIN:
        case LOGOUT:
        case SET_PASSWORD:
        case VALIDATE_TOKEN:
            toRet = ACCESS_GRANTED;
            break;
        case CHANGE_PASSWORD:
            if (currentUser != null && isSelf(currentUser, userParam)) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case CREATE:
        case DELETE:
        case DISABLE:
        case ENABLE:
        case RESET_PASSWORD:
        case STATUS:
            if (currentUser != null && isAdmin(currentUser)) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case GET_ALL:
            if (currentUser != null) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case GET:
            if (currentUser != null && (isAdmin(currentUser) || isSelf(currentUser, userParam)
                    || isSiteMember(currentUser, userParam))) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case GET_PER_SITE:
            if (currentUser != null && (isAdmin(currentUser) || isSiteMember(currentUser, userParam))) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        case UPDATE:
            if (currentUser != null && (isAdmin(currentUser) || isSelf(currentUser, userParam))) {
                toRet = ACCESS_GRANTED;
            } else {
                toRet = ACCESS_DENIED;
            }
            break;
        default:
            toRet = ACCESS_ABSTAIN;
            break;
        }
    }
    logger.debug("Request: " + requestUri + " - Access: " + toRet);
    return toRet;
}

From source file:edu.umd.cfar.lamp.viper.util.StringHelp.java

/** 
 * Checks to see if the stream begins with an xml processing directive, eg
 * <code>&lt;?xml?&gt;</code>. This method does not check to see that the 
 * stream is well-formed, or even if the processing directive is good, just that
 * the first non-whitespace characters are "&lt;?xml".
 *
 * @param f The file to check for xml processing directive
 * @throws IOException if there is an error while reading the file, eg FileNotFoundException
 * @return <code>true</code> if the directive was found. 
 *//*from w  ww.j a v  a 2s.c  om*/
public static boolean isXMLFormat(InputStream f) throws IOException {
    final int LIMIT = 4024;
    f.mark(LIMIT);
    InputStreamReader isr = new InputStreamReader(f);
    char n;
    do {
        n = (char) isr.read();
    } while (Character.isWhitespace(n));
    boolean xml = (n == '<' && isr.read() == '?' && (char) isr.read() == 'x' && (char) isr.read() == 'm'
            && (char) isr.read() == 'l');
    f.reset();
    return xml;
}