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.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);//from   w ww  .  j a v a 2 s  .  c om
                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 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:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Assume that the InputStream has a SOAP fault message and return a String
 * suitable to present as an exception message
 *  /* ww w .j av  a2 s  .  c om*/
 * @param is InputStream that contains a SOAP message
 * @return String containing a formated error message
 * 
 * @throws IOException
 * @throws SOAPException
 */
private String getSOAPFaultAsString(InputStream is) throws IOException, SOAPException {
    is.reset();
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage(null, is);
    SOAPBody body = message.getSOAPBody();

    if (body.hasFault()) {
        SOAPFault fault = body.getFault();
        String code, string, actor;
        code = fault.getFaultCode();
        string = fault.getFaultString();
        actor = fault.getFaultActor();
        String formatedMessage = "SOAP transaction resulted in a SOAP fault.";

        if (code != null)
            formatedMessage += "  Code=\"" + code + ".\"";

        if (string != null)
            formatedMessage += "  String=\"" + string + ".\"";

        if (actor != null)
            formatedMessage += "  Actor=\"" + actor + ".\"";

        return formatedMessage;
    }
    return null;
}

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.  java 2s . c o 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.apache.synapse.commons.json.JsonUtil.java

/**
 * Builds and returns a new JSON payload for a message context with a stream of JSON content. <br/>
 * This is the recommended way to build a JSON payload into an Axis2 message context.<br/>
 * A JSON payload built into a message context with this method can only be removed by calling
 * {@link #removeJsonPayload(org.apache.axis2.context.MessageContext)} method.
 *
 * @param messageContext     Axis2 Message context to which the new JSON payload must be saved (if instructed with <tt>addAsNewFirstChild</tt>).
 * @param inputStream        JSON content as an input stream.
 * @param removeChildren     Whether to remove existing child nodes of the existing payload of the message context
 * @param addAsNewFirstChild Whether to add the new JSON payload as the first child of this message context *after* removing the existing first child element.<br/>
 *                           Setting this argument to <tt>true</tt> will have no effect if the value of the argument <tt>removeChildren</tt> is already <tt>false</tt>.
 * @return Payload object that stores the input JSON content as a Sourced object (See {@link org.apache.axiom.om.OMSourcedElement}) that can build the XML tree for contained JSON payload on demand.
 *///from  w w w  . j  av  a2  s .  c o m
public static OMElement newJsonPayload(MessageContext messageContext, InputStream inputStream,
        boolean removeChildren, boolean addAsNewFirstChild) {
    if (messageContext == null) {
        logger.error("#newJsonPayload. Could not save JSON stream. Message context is null.");
        return null;
    }
    boolean isObject = false;
    boolean isArray = false;
    if (inputStream != null) {
        InputStream json = toReadOnlyStream(inputStream);
        messageContext.setProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_JSON_INPUT_STREAM, json);
        // read ahead few characters to see if the stream is valid...
        try {
            // check for empty/all-whitespace streams
            int c = json.read();
            boolean valid = false;
            while (c != -1 && c != '{' && c != '[') {
                c = json.read();
            }
            if (c != -1) {
                valid = true;
            }
            if (c == '{') {
                isObject = true;
                isArray = false;
            } else if (c == '[') {
                isArray = true;
                isObject = false;
            }
            json.reset();
            if (!valid) {
                logger.error(
                        "#newJsonPayload. Could not save JSON payload. Invalid input stream found. MessageID: "
                                + messageContext.getMessageID());
                return null;
            }
        } catch (IOException e) {
            logger.error(
                    "#newJsonPayload. Could not determine availability of the JSON input stream. MessageID: "
                            + messageContext.getMessageID() + ". Error>>> " + e.getLocalizedMessage());
            return null;
        }
        QName jsonElement = null;
        if (isObject) {
            jsonElement = JSON_OBJECT;
            messageContext.setProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_IS_JSON_OBJECT, true);
        }
        if (isArray) {
            jsonElement = JSON_ARRAY;
            messageContext.setProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_IS_JSON_OBJECT, false);
        }
        OMElement elem = new OMSourcedElementImpl(jsonElement, OMAbstractFactory.getOMFactory(),
                new JsonDataSource((InputStream) messageContext
                        .getProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_JSON_INPUT_STREAM)));
        if (!removeChildren) {
            if (logger.isTraceEnabled()) {
                logger.trace(
                        "#newJsonPayload. Not removing child elements from exiting message. Returning result. MessageID: "
                                + messageContext.getMessageID());
            }
            return elem;
        }
        SOAPEnvelope e = messageContext.getEnvelope();
        if (e != null) {
            SOAPBody b = e.getBody();
            if (b != null) {
                removeIndentations(b);
                Iterator children = b.getChildren();
                while (children.hasNext()) {
                    Object o = children.next();
                    if (o instanceof OMNode) {
                        //((OMNode) o).detach();
                        children.remove();
                    }
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("#newJsonPayload. Removed child elements from exiting message. MessageID: "
                            + messageContext.getMessageID());
                }
                if (addAsNewFirstChild) {
                    b.addChild(elem);
                    if (logger.isTraceEnabled()) {
                        logger.trace(
                                "#newJsonPayload. Added the new JSON sourced element as the first child. MessageID: "
                                        + messageContext.getMessageID());
                    }
                }
            }
        }
        return elem;
    }
    return null;
}

From source file:org.duracloud.chunk.writer.FilesystemContentWriterTest.java

@Test
public void testWriteSingle() throws NotFoundException, IOException {
    long contentSize = 1500;
    InputStream contentStream = createContentStream(contentSize);

    String spaceId = new File(destDir, "spaceId-1").getPath();
    String contentId = "a/b/c/contentId";

    boolean preserveMD5 = true;
    ChunkInputStream chunk = new ChunkInputStream(contentId, contentStream, contentSize, preserveMD5);
    IOUtils.closeQuietly(contentStream);

    String md5 = writer.writeSingle(spaceId, null, chunk);
    Assert.assertNotNull(md5);//from  w w w  .  j a v a  2 s  .c  o m

    // check files
    File file = new File(spaceId, contentId);
    Assert.assertTrue(file.exists());

    String md5Real = calculateMD5(file);
    Assert.assertEquals(md5Real, md5);

    file.delete();
    contentStream.reset();
    chunk = new ChunkInputStream(contentId, contentStream, contentSize, preserveMD5);
    md5 = writer.writeSingle(spaceId, md5Real, chunk);
    Assert.assertNotNull(md5);
    Assert.assertEquals(md5, md5Real);
}

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.
 * /*  w w  w.  j  a va2s . com*/
 * @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:com.aliyun.oss.common.comm.ServiceClient.java

private ResponseMessage sendRequestImpl(RequestMessage request, ExecutionContext context)
        throws ClientException, ServiceException {

    RetryStrategy retryStrategy = context.getRetryStrategy() != null ? context.getRetryStrategy()
            : this.getDefaultRetryStrategy();

    // Sign the request if a signer provided.
    if (context.getSigner() != null && !request.isUseUrlSignature()) {
        context.getSigner().sign(request);
    }//from ww w.ja v  a 2s .  c  o  m

    InputStream requestContent = request.getContent();
    if (requestContent != null && requestContent.markSupported()) {
        requestContent.mark(OSSConstants.DEFAULT_STREAM_BUFFER_SIZE);
    }

    int retries = 0;
    ResponseMessage response = null;

    while (true) {
        try {
            if (retries > 0) {
                pause(retries, retryStrategy);
                if (requestContent != null && requestContent.markSupported()) {
                    try {
                        requestContent.reset();
                    } catch (IOException ex) {
                        logException("Failed to reset the request input stream: ", ex);
                        throw new ClientException("Failed to reset the request input stream: ", ex);
                    }
                }
            }

            /* The key four steps to send HTTP requests and receive HTTP responses. */

            // Step1. Build HTTP request with specified request parameters and context.
            Request httpRequest = buildRequest(request, context);

            // Step 2. Postprocess HTTP request.
            handleRequest(httpRequest, context.getResquestHandlers());

            // Step 3. Send HTTP request to OSS.
            response = sendRequestCore(httpRequest, context);

            // Step 4. Preprocess HTTP response.
            handleResponse(response, context.getResponseHandlers());

            return response;
        } catch (ServiceException sex) {
            logException("[Server]Unable to execute HTTP request: ", sex);

            // Notice that the response should not be closed in the
            // finally block because if the request is successful,
            // the response should be returned to the callers.
            closeResponseSilently(response);

            if (!shouldRetry(sex, request, response, retries, retryStrategy)) {
                throw sex;
            }
        } catch (ClientException cex) {
            logException("[Client]Unable to execute HTTP request: ", cex);

            closeResponseSilently(response);

            if (!shouldRetry(cex, request, response, retries, retryStrategy)) {
                throw cex;
            }
        } catch (Exception ex) {
            logException("[Unknown]Unable to execute HTTP request: ", ex);

            closeResponseSilently(response);

            throw new ClientException(
                    COMMON_RESOURCE_MANAGER.getFormattedString("ConnectionError", ex.getMessage()), ex);
        } finally {
            retries++;
        }
    }
}

From source file:org.liveSense.misc.configloader.ConfigurationLoader.java

/**
 * Set the configuration based on the config file.
 *
 * @param f//w  w w . jav  a 2s.  c  o m
 *            Configuration file
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
boolean setConfig(URL f) throws Exception {
    Properties p = new Properties();

    @SuppressWarnings("rawtypes")
    Dictionary ht = new Hashtable();

    InputStream in = new BufferedInputStream(f.openStream());
    try {
        // If the file name ends with .config, we using the Felix configuration format
        if (f.getFile().endsWith(".config")) {
            ht = ConfigurationHandler.read(in);
        } else {
            in.mark(1);
            boolean isXml = in.read() == '<';
            in.reset();
            if (isXml) {
                p.loadFromXML(in);
            } else {
                p.load(in);
            }
            ((Hashtable) ht).putAll(p);
        }
    } finally {
        in.close();
    }

    // Searching for templated config entry.
    // If we found one we get Java System properties
    // named as the macros. The config became activated if that
    // system proprty is set.

    Pattern macros = Pattern.compile("\\$\\{(.*?)\\}");
    boolean valid = true;

    Enumeration enumr = ht.keys();
    while (enumr.hasMoreElements()) {
        Object key = enumr.nextElement();
        if (ht.get(key) instanceof String) {
            String str = (String) ht.get(key);
            if (str != null) {
                Matcher matcher = macros.matcher(str);

                HashSet<String> propNames = new HashSet<String>();
                while (matcher.find()) {
                    propNames.add(matcher.group(1));
                }

                for (String prop : propNames) {
                    String sysProp = System.getProperty(prop);
                    if (sysProp == null) {
                        valid = false;
                    }
                    if (valid) {
                        str = StringUtils.replace(str, "${" + prop + "}", sysProp);
                        //str = str.replaceAll("\\$\\{"+prop+"\\}", sysProp);
                    }
                }
                if (valid) {
                    ht.put(key, str);
                }
            }
        }
    }

    if (valid) {
        Util.performSubstitution(p);
        String pid[] = parsePid(getName(f.getFile()));
        ht.put(CONFIGURATION_PROPERTY_NAME, getPidName(pid[0], pid[1]));

        Configuration config = getConfiguration(pid[0], pid[1]);

        /*
        // Backuping parameters for restore
        String persistanceName = pid[0]+(pid[1] == null ? "" : "-" + pid[1]);
        if (config.getProperties() != null && config.getProperties().get(CONFIGURATION_PROPERTY_NAME) == null) {
           if (persistence.load(persistanceName).isEmpty()) {
              persistence.store(persistanceName, config.getProperties());
           }
        }
         */
        if (config.getBundleLocation() != null) {
            config.setBundleLocation(null);
        }

        // If the configuration does not created by configuration loader we update it
        // In other cases (for example the user modified the loaded config) there is no configuration overwrite
        if (config.getProperties() == null || config.getProperties().get(CONFIGURATION_PROPERTY_NAME) == null
                || !config.getProperties().get(CONFIGURATION_PROPERTY_NAME).equals(getName(f.getFile()))) {
            config.update(ht);
        }
    }
    return true;
}

From source file:om.sstvencoder.CropView.java

public void setBitmapStream(InputStream stream) throws IOException {
    mImageOK = false;/*from  w w w.  ja va2  s.c o  m*/
    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:com.effektif.adapter.helpers.RequestLogger.java

private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset)
        throws IOException {
    if (!stream.markSupported()) {
        stream = new BufferedInputStream(stream);
    }//from ww  w  .  ja  v a  2  s.  c o  m
    stream.mark(maxEntitySize + 1);
    final byte[] entity = new byte[maxEntitySize + 1];
    final int entitySize = stream.read(entity);
    b.append(REQUEST_PREFIX);
    String entityString = new String(entity, 0, Math.min(entitySize, maxEntitySize), charset);
    if (logEntityJsonPretty && (entitySize <= maxEntitySize)) {
        entityString = getJsonPrettyString(entityString);
    }
    b.append(entityString);
    if (entitySize > maxEntitySize) {
        b.append("...more...");
    }
    stream.reset();
    return stream;
}