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.apache.synapse.commons.json.JsonUtil.java

/**
 * Returns the JSON stream associated with the payload of this message context.
 *
 * @param messageContext Axis2 Message context
 * @param reset          Whether to reset the input stream that contains this JSON payload so that next read will start from the beginning of this stream.
 * @return JSON input stream//from   w ww .j  a v  a 2s  . c o  m
 */
private static InputStream jsonStream(MessageContext messageContext, boolean reset) {
    if (messageContext == null) {
        return null;
    }
    Object o = messageContext.getProperty(ORG_APACHE_SYNAPSE_COMMONS_JSON_JSON_INPUT_STREAM);
    if (o instanceof InputStream) {
        InputStream is = (InputStream) o;
        if (reset) {
            if (is.markSupported()) {
                try {
                    is.reset();
                } catch (IOException e) {
                    logger.error("#jsonStream. Could not reuse JSON Stream. Error>>>\n", e);
                    return null;
                }
            }
        }
        return is;
    }
    return null;
}

From source file:org.apache.synapse.commons.json.JsonUtil.java

private static void writeJsonStream(InputStream json, MessageContext messageContext, OutputStream out)
        throws AxisFault {
    try {//from w  w w .  jav  a2s.c  o  m
        if (json.markSupported()) {
            json.reset();
        }
        IOUtils.copy(json, out); // Write the JSON stream
        if (messageContext.getProperty(PRESERVE_JSON_STREAM) != null) {
            if (json.markSupported()) {
                json.reset();
            }
            messageContext.removeProperty(PRESERVE_JSON_STREAM);
        }
    } catch (IOException e) {
        logger.error("#writeJsonStream. Could not write JSON stream. MessageID: "
                + messageContext.getMessageID() + ". Error>> " + e.getLocalizedMessage());
        throw new AxisFault("Could not write JSON stream.", e);
    }
}

From source file:VASSAL.tools.io.RereadableInputStreamTest.java

@Test(expected = IOException.class)
public void testResetBad() throws IOException {
    final InputStream in = new RereadableInputStream(new NullInputStream(10));
    in.reset();
}

From source file:org.deegree.portal.owswatch.validator.WMSGetMapValidator.java

@Override
public ValidatorResponse validateAnswer(HttpMethodBase method, int statusCode) {

    String contentType = method.getResponseHeader("Content-Type").getValue();
    String lastMessage = null;/*from w  w w  .ja va2s  .com*/
    Status status = null;

    if (!contentType.contains("image")) {
        if (!contentType.contains("xml")) {
            status = Status.RESULT_STATE_UNEXPECTED_CONTENT;
            lastMessage = StringTools.concat(100, "Error: Response Content is ", contentType, " not image");
            return new ValidatorResponse(lastMessage, status);
        } else {
            return validateXmlServiceException(method);
        }
    }

    try {
        InputStream stream = copyStream(method.getResponseBodyAsStream());
        stream.reset();
        ImageIO.read(stream);
        status = Status.RESULT_STATE_AVAILABLE;
        lastMessage = status.getStatusMessage();
        return new ValidatorResponse(lastMessage, status);
    } catch (Exception e) {
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        lastMessage = e.getLocalizedMessage();
        return new ValidatorResponse(lastMessage, status);
    }
}

From source file:org.deegree.portal.owswatch.validator.WCSGetCoverageValidator.java

@Override
public ValidatorResponse validateAnswer(HttpMethodBase method, int statusCode) {

    String lastMessage = null;//w  w w .j  a  v a 2  s.  c o  m
    Status status = null;
    String contentType = method.getResponseHeader("Content-Type").getValue();
    if (contentType.contains("image")) {
        try {
            InputStream stream = copyStream(method.getResponseBodyAsStream());
            stream.reset();
            ImageIO.read(stream);
            status = Status.RESULT_STATE_AVAILABLE;
            lastMessage = status.getStatusMessage();
            return new ValidatorResponse(lastMessage, status);
        } catch (Exception e) {
            status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
            lastMessage = e.getLocalizedMessage();
            return new ValidatorResponse(lastMessage, status);
        }
    } else if (contentType.contains("xml")) {
        return validateXml(method);
    } else {
        StringBuilder builder = new StringBuilder("Response content is: ");
        builder.append(contentType);
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        lastMessage = Messages.getMessage("ERROR_INCORRECT_RESP_CONTENT2", contentType, "image", "xml");
        return new ValidatorResponse(lastMessage, status);
    }
}

From source file:org.codice.ddf.spatial.ogc.wfs.v2_0_0.catalog.source.WfsResponseExceptionMapper.java

public WfsException fromResponse(Response response) {

    WfsException wfsEx = null;//from ww w.ja  v a2s .c  o m

    if (response != null) {
        if (response.getEntity() instanceof InputStream) {
            String msg = null;
            try {
                InputStream is = (InputStream) response.getEntity();
                is.reset();
                msg = IOUtils.toString(is);
            } catch (IOException e) {
                wfsEx = new WfsException("Error reading Response" + (msg != null ? ": " + msg : ""), e);
            }
            if (msg != null) {
                try {
                    JAXBElementProvider<ExceptionReport> provider = new JAXBElementProvider<ExceptionReport>();
                    Unmarshaller um = provider.getJAXBContext(ExceptionReport.class, ExceptionReport.class)
                            .createUnmarshaller();
                    ExceptionReport report = (ExceptionReport) um.unmarshal(new StringReader(msg));
                    wfsEx = convertToWfsException(report);
                } catch (JAXBException e) {
                    wfsEx = new WfsException("Error parsing Response: " + msg, e);
                }
            }
        } else {
            wfsEx = new WfsException("Error reading response, entity type not understood: "
                    + response.getEntity().getClass().getName());
        }
        wfsEx.setHttpStatus(response.getStatus());
    } else {
        wfsEx = new WfsException("Error handling response, response is null");
    }
    return wfsEx;
}

From source file:com.couchbase.cbadmin.client.RestApiException.java

@Override
public String getMessage() {
    List<String> msgList = new ArrayList<String>();
    String existing = super.getMessage();

    if (existing != null) {
        msgList.add(existing);//from w  w w.  j  a v  a 2s.c o m
    }

    if (status.getStatusCode() != 408) {
        msgList.add(String.format("<Status=%d, Reason=%s>", status.getStatusCode(), status.getReasonPhrase()));
    }

    if (json != null) {
        msgList.add("<JSON=" + json + ">");
    }

    if (request != null) {
        msgList.add("Request=" + request + ">");

        if (request instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) request;
            HttpEntity entity = eReq.getEntity();
            try {
                if (entity != null && entity.getContent() != null) {
                    InputStream strm = entity.getContent();
                    strm.reset();
                    msgList.add("<Request Body=" + IOUtils.toString(strm) + ">");
                }
            } catch (IOException ex) {
                // In exception. What do we do here?
                msgList.add("<IOException for reading request>");
            } catch (IllegalStateException ex) {
                msgList.add("<IllegalStateException while reading request>");
            }
        }
    }

    return StringUtils.join(msgList, ",");
}

From source file:it.unimi.di.big.mg4j.query.InputStreamItem.java

protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    try {/*from  w w w  .jav  a2  s . co m*/
        if (request.getParameter("m") != null && request.getParameter("doc") != null) {
            DocumentCollection collection = (DocumentCollection) getServletContext().getAttribute("collection");
            if (collection == null)
                LOGGER.error("The servlet context does not contain a document collection.");
            response.setContentType(request.getParameter("m"));
            response.setCharacterEncoding("UTF-8");
            InputStream rawContent = collection.stream(Long.parseLong(request.getParameter("doc")));
            for (int i = skip; i-- != 0;)
                rawContent.reset();
            IOUtils.copy(rawContent, response.getOutputStream());
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
        LOGGER.error(e.toString());
        throw e;
    }
}

From source file:org.craftercms.cstudio.alfresco.dm.util.DmUtils.java

public static String getMd5ForFile(InputStream input) {
    //PushbackInputStream helper = null;
    String result = null;//www. j  ava  2s . co  m
    MessageDigest md = null;
    try {
        //helper = new PushbackInputStream(input);
        //InputStreamReader reader = new InputStreamReader(input);
        md = MessageDigest.getInstance("MD5");

        md.reset();
        byte[] bytes = new byte[1024];
        int numBytes;
        //input.mark(input.available());
        input.mark(Integer.MAX_VALUE);
        while ((numBytes = input.read(bytes)) != -1) {
            md.update(bytes, 0, numBytes);
        }
        byte[] digest = md.digest();
        result = new String(Hex.encodeHex(digest));
        input.reset();
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error while creating MD5 digest", e);
    } catch (IOException e) {
        logger.error("Error while reading input stream", e);
    } finally {

    }
    return result;
}

From source file:org.deegree.portal.owswatch.validator.CSWGetRecordsValidator.java

@Override
protected ValidatorResponse validateXmlServiceException(HttpMethodBase method) {

    Document doc = null;/*  www .jav a 2s  . c o m*/
    String lastMessage = null;
    Status status = null;

    try {
        InputStream stream = method.getResponseBodyAsStream();
        stream.reset();
        doc = instantiateParser().parse(stream);
    } catch (Exception e) {
        status = Status.RESULT_STATE_INVALID_XML;
        lastMessage = "Error: MalFormed XML Response";
        return new ValidatorResponse(lastMessage, status);
    }
    try {
        NamespaceContext cnxt = CommonNamespaces.getNamespaceContext();
        URI owsns = CommonNamespaces.OWSNS;
        String prefix = doc.lookupPrefix(owsns.toASCIIString());
        StringBuilder builder = new StringBuilder(100);
        builder.append("./");
        if (prefix != null && prefix.length() > 0) {
            builder.append(prefix).append(":");
            cnxt.addNamespace(prefix, owsns);
        }

        builder.append("Exception");
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        lastMessage = XMLTools.getNodeAsString(doc.getDocumentElement(), builder.toString(), cnxt,
                "Service Unavailable. Unknown error");
        return new ValidatorResponse(lastMessage, status);
    } catch (XMLParsingException e) {
        lastMessage = "Service Unavailable";
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        return new ValidatorResponse(lastMessage, status);
    }
}