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:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testMarkResetAfterReadWithBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, true));
    assertTrue(in.markSupported());//from   ww w  .ja v  a2  s .  co m

    in.read();
    in.mark(10);

    in.read();
    in.read();
    in.reset();
    assertEquals('B', in.read());
}

From source file:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testMarkResetAfterReadWithoutBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, false));
    assertTrue(in.markSupported());//  ww w.j  a v  a  2 s.c o m

    in.read();
    in.mark(10);

    in.read();
    in.read();
    in.reset();
    assertEquals('B', in.read());
}

From source file:org.apache.sling.distribution.packaging.impl.AbstractDistributionPackageBuilder.java

@Nonnull
public DistributionPackage readPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull InputStream stream)
        throws DistributionException {

    if (!stream.markSupported()) {
        stream = new BufferedInputStream(stream);
    }/*www .  j  av a  2 s . c o m*/
    Map<String, Object> headerInfo = new HashMap<String, Object>();
    DistributionPackageUtils.readInfo(stream, headerInfo);

    try {
        stream.reset();
    } catch (IOException e) {
        // do nothing
    }

    DistributionPackage distributionPackage = SimpleDistributionPackage.fromStream(stream, type);

    try {
        stream.reset();
    } catch (IOException e) {
        // do nothing
    }

    // not a simple package
    if (distributionPackage == null) {
        distributionPackage = readPackageInternal(resourceResolver, stream);
    }

    distributionPackage.getInfo().putAll(headerInfo);
    return distributionPackage;
}

From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java

private void connectAndSend(String xml) throws ServerException {

    HttpURLConnection conn = null;
    OutputStreamWriter wr = null;

    try {//from   w  w w.j av a 2s. com
        LOGGER.debug("{} - Url: {}", instanceName, urlstr);
        String payload = cmd + xml;
        conn = createHTTPConnection(payload);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(payload);
        wr.flush();

        /*
         * Look for status != 0 by building a DOM to parse
         * <status>0</status> <message>OK</message>
         */

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGGER.error("{} - Could not get a doc builder", instanceName, e);
            return;
        }

        /*
         * Getting the value for status and message tags
         */
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));) {

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("NRDP return string - {}", convertStreamToString(is));
                is.reset();
            }

            Document doc = null;

            doc = dBuilder.parse(is);

            doc.getDocumentElement().normalize();
            String rootNode = doc.getDocumentElement().getNodeName();
            NodeList responselist = doc.getElementsByTagName(rootNode);
            String result = (String) ((Element) responselist.item(0)).getElementsByTagName("status").item(0)
                    .getChildNodes().item(0).getNodeValue().trim();

            LOGGER.debug("NRDP return status is: {}", result);

            if (!"0".equals(result)) {
                String message = (String) ((Element) responselist.item(0)).getElementsByTagName("message")
                        .item(0).getChildNodes().item(0).getNodeValue().trim();
                LOGGER.error("{} - nrdp returned message \"{}\" for xml: {}", instanceName, message, xml);
            }
        } catch (SAXException e) {
            LOGGER.error("{} - Could not parse response xml", instanceName, e);
        }

    } catch (IOException e) {
        LOGGER.error("{} - Network error - check nrdp server and that service is started", instanceName, e);
        throw new ServerException(e);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException ignore) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.redhat.rhn.domain.config.ConfigurationFactory.java

/**
 * Convert input stream to byte array/*from   www  .ja  v a  2s  . c  om*/
 * @param stream input stream
 * @param size stream size
 * @return byte array
 */
public static byte[] bytesFromStream(InputStream stream, Long size) {
    byte[] foo = new byte[size.intValue()];
    try {
        //this silly bit of logic is to ensure that we read as much from the file
        //as we possibly can.  Most likely, stream.read(foo) would do the exact same
        //thing, but according to the javadoc, that may not always be the case.

        int offset = 0;
        int read = 0;
        // mark and reset stream, so that stream can be re-read later
        stream.mark(size.intValue());
        do {
            read = stream.read(foo, offset, (foo.length - offset));
            offset += read;
        } while (read > 0 && offset < foo.length);
        stream.reset();
    } catch (IOException e) {
        log.error("IOException while reading config content from input stream!", e);
        throw new RuntimeException("IOException while reading config content from" + " input stream!");
    }
    return foo;
}

From source file:org.craftercms.studio.impl.v1.web.security.access.StudioSiteAPIAccessDecisionVoter.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");
        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  . ja  va  2  s.  co m*/
                String jsonString = IOUtils.toString(is);
                if (StringUtils.isNoneEmpty(jsonString)) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonString);
                    if (jsonObject.has("username")) {
                        userParam = jsonObject.getString("username");
                    }
                }
                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 CREATE:
        case DELETE:
            if (currentUser != null && isAdmin(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:org.xmlactions.email.EMailParser.java

private void addContent(InputStream inputStream) throws DocumentException, IOException {

    if (inputStream.markSupported()) {
        inputStream.mark(inputStream.available());
    }/*  w ww .  j  av a  2s .c om*/

    String bodyContent = IOUtils.toString(inputStream);

    if (this.firstMessageProcessed == false) {
    }
    if (inputStream.markSupported()) {
        inputStream.reset();
    }
}

From source file:com.btoddb.chronicle.catchers.RestCatcherImpl.java

public boolean isJsonArray(InputStream inStream) {
    if (null == inStream) {
        return false;
    }//from   w ww . j  a v a  2 s.  co m

    int count = 100;
    inStream.mark(count);
    int ch;
    try {
        do {
            ch = inStream.read();
        } while ('[' != ch && '{' != ch && Character.isWhitespace((char) ch) && -1 != ch && --count > 0);

        inStream.reset();
        if (0 == count) {
            Utils.logAndThrow(logger, "unrecognizable JSON, or too much whitespace before JSON doc starts");
        }
        return '[' == ch;
    } catch (IOException e) {
        Utils.logAndThrow(logger, "exception while looking for JSON in InputStream", e);
    }

    return false;
}

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

public <T> T readValue(InputStream inputStream, Class<T> valueType)
        throws JsonParseException, JsonMappingException, IOException {
    try {//from  w  w  w. j  a va 2 s.co 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:org.phoenix.jmeter.core.SaveService.java

/**
 * //from www  .  j  ava2s  .c o  m
 * @param reader {@link InputStream} 
 * @param file the JMX file used only for debug, can be null
 * @return the loaded tree
 * @throws IOException if there is a problem reading the file or processing it
 */
private static final HashTree readTree(InputStream reader, File file) throws IOException {
    if (!reader.markSupported()) {
        reader = new BufferedInputStream(reader);
    }
    reader.mark(Integer.MAX_VALUE);
    ScriptWrapper wrapper = null;
    try {
        // Get the InputReader to use
        InputStreamReader inputStreamReader = getInputStreamReader(reader);
        wrapper = (ScriptWrapper) JMXSAVER.fromXML(inputStreamReader);
        inputStreamReader.close();
        if (wrapper == null) {
            log.error("Problem loading XML: see above.");
            return null;
        }
        return wrapper.testPlan;
    } catch (CannotResolveClassException e) {
        // FIXME We switching to JAVA7, use Multi-Catch Exceptions
        if (e.getMessage().startsWith("node")) {
            log.info("Problem loading XML, trying Avalon format");
            reader.reset();
            return OldSaveService.loadSubTree(reader);
        }
        if (file != null) {
            throw new IllegalArgumentException("Problem loading XML from:'" + file.getAbsolutePath()
                    + "', cannot determine class for element: " + e, e);
        } else {
            throw new IllegalArgumentException("Problem loading XML, cannot determine class for element: " + e,
                    e);
        }
    } catch (NoClassDefFoundError e) {
        if (file != null) {
            throw new IllegalArgumentException(
                    "Problem loading XML from:'" + file.getAbsolutePath() + "', missing class " + e, e);
        } else {
            throw new IllegalArgumentException("Problem loading XML, missing class " + e, e);
        }
    } catch (ConversionException e) {
        if (file != null) {
            throw new IllegalArgumentException(
                    "Problem loading XML from:'" + file.getAbsolutePath() + "', conversion error " + e, e);
        } else {
            throw new IllegalArgumentException("Problem loading XML, conversion error " + e, e);
        }
    }

}