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.deegree.portal.owswatch.validator.CSWGetRecordsValidator.java

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

    String contentType = method.getResponseHeader("Content-Type").getValue();
    String lastMessage = null;//  ww  w  .  j a va  2 s  . co  m
    Status status = null;

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

    String xml = null;
    try {
        InputStream stream = method.getResponseBodyAsStream();
        stream.reset();
        xml = parseStream(stream);
    } catch (IOException e) {
        status = Status.RESULT_STATE_BAD_RESPONSE;
        lastMessage = status.getStatusMessage();
        return new ValidatorResponse(lastMessage, status);
    }

    if (xml.length() == 0) {
        status = Status.RESULT_STATE_BAD_RESPONSE;
        lastMessage = "Error: XML Response is empty";
        return new ValidatorResponse(lastMessage, status);
    }

    if (xml.contains("ExceptionReport")) {
        validateXmlServiceException(method);
        return new ValidatorResponse(lastMessage, status);
    }
    // If its an xml, and there's no service exception, then don't really parse the xml,
    // we assume that its well formed, since there might be huge xmls, which would take time to be parsed
    status = Status.RESULT_STATE_AVAILABLE;
    lastMessage = status.getStatusMessage();
    return new ValidatorResponse(lastMessage, status);
}

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.source.reader.XmlSchemaMessageBodyReader.java

@Override
public XmlSchema readFrom(Class<XmlSchema> clazz, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> headers, InputStream inStream)
        throws IOException, WebApplicationException {
    // Determine if this is an XMLSchema
    String input = IOUtils.toString(inStream);
    inStream.reset();
    String count = COUNT_XPATH_BUILDER.evaluate(camelContext, input);
    // See if there exactly one instance of "xsd:schema" in this doc
    if (Integer.parseInt(count) == 1) {
        XmlSchema schema = null;//  w ww .  j ava2s .c o  m
        XmlSchemaCollection schemaCollection = new XmlSchemaCollection();
        schemaCollection.init();
        schemaCollection.setSchemaResolver(wfsUriResolver);
        schema = schemaCollection.read(new InputSource(inStream));
        return schema;
    }
    LOGGER.warn("Did not receive valid XML Schema, instead got: \n{}", input);
    return null;
}

From source file:org.craftercms.studio.impl.repository.mongodb.services.ITGridFSService.java

@Test
public void testSaveFile() throws Exception {
    InputStream testInput = NodeServiceCreateFileTest.class.getResourceAsStream("/files/index.xml");
    testInput.mark(Integer.MAX_VALUE);
    String currentMD5 = getMD5(testInput);
    testInput.reset();
    String fileId = gridFSService.createFile(FILE_NAME, testInput);
    Assert.assertNotNull(fileId);//from w w  w.  j ava 2s.c  om
    InputStream stream = gridFSService.getFile(fileId);
    Assert.assertNotNull(stream);
    Assert.assertEquals(currentMD5, getMD5(stream));
}

From source file:fr.mby.utils.common.io.StreamRepositoryTest.java

@Test
public void testRepository() throws Exception {

    final StreamRepository repo = new StreamRepository();

    final InputStream inputStream = repo.getInputStream();
    final OutputStream outputStream = repo.getOutputStream();

    inputStream.reset();
    Assert.assertEquals("Input stream should be empty !", "", IOUtils.toString(inputStream));

    outputStream.write(StreamRepositoryTest.BYTE_WORD_1);

    Assert.assertEquals("Input stream should be empty !", "", IOUtils.toString(inputStream));

    outputStream.flush();// ww w  .  j av a 2 s .  c o m

    Assert.assertEquals("Input stream should contain Word 1 !", new String(StreamRepositoryTest.BYTE_WORD_1),
            IOUtils.toString(inputStream));

    outputStream.write(StreamRepositoryTest.BYTE_WORD_2);

    Assert.assertEquals("Input stream should be empty !", "", IOUtils.toString(inputStream));

    outputStream.flush();

    final byte[] expected = ArrayUtils.addAll(StreamRepositoryTest.BYTE_WORD_1,
            StreamRepositoryTest.BYTE_WORD_2);
    Assert.assertEquals("Input stream should contain Word 1 & Word 2 !", new String(expected),
            IOUtils.toString(inputStream));

    inputStream.reset();

    Assert.assertEquals("Input stream should be empty !", "", IOUtils.toString(inputStream));

    outputStream.flush();

    Assert.assertEquals("Input stream should be empty !", "", IOUtils.toString(inputStream));

    outputStream.write(StreamRepositoryTest.BYTE_WORD_3);
    outputStream.write(StreamRepositoryTest.BYTE_WORD_1);
    outputStream.write(StreamRepositoryTest.BYTE_WORD_2);
    outputStream.flush();

    byte[] expected2 = ArrayUtils.addAll(StreamRepositoryTest.BYTE_WORD_3, StreamRepositoryTest.BYTE_WORD_1);
    expected2 = ArrayUtils.addAll(expected2, StreamRepositoryTest.BYTE_WORD_2);

    Assert.assertEquals("Input stream should contain Word 3 & Word 1 & Word 2 !", new String(expected2),
            IOUtils.toString(inputStream));
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.source.CswResponseExceptionMapper.java

@Override
public CswException fromResponse(Response response) {
    CswException cswException = null;//from ww  w .  j  a  v  a 2  s  . c  o m

    if (response != null) {
        if (response.getEntity() instanceof InputStream) {
            String msg = null;
            try {
                InputStream is = (InputStream) response.getEntity();
                if (is.markSupported()) {
                    is.reset();
                }
                msg = IOUtils.toString(is);
            } catch (IOException e) {
                cswException = new CswException(
                        "Error received from remote Csw server" + (msg != null ? ": " + msg : ""));
                LOGGER.warn("Unable to parse exception report: {}", 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));
                    cswException = convertToCswException(report);
                } catch (JAXBException e) {
                    cswException = new CswException("Error received from remote Csw server: " + msg, e);
                    LOGGER.warn("Error parsing the exception report: {}", e);
                }
            }
        } else {
            cswException = new CswException("Error reading response, entity type not understood: "
                    + response.getEntity().getClass().getName());
        }
        cswException.setHttpStatus(response.getStatus());
    } else {
        cswException = new CswException("Error handling response, response is null");
    }

    return cswException;
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.CswResponseExceptionMapper.java

@Override
public CswException fromResponse(Response response) {
    CswException cswException = null;//w  w w . j  av a2 s  . c o  m

    if (response != null) {
        if (response.getEntity() instanceof InputStream) {
            String msg = null;
            try {
                InputStream is = (InputStream) response.getEntity();
                if (is.markSupported()) {
                    is.reset();
                }
                msg = IOUtils.toString(is);
            } catch (IOException e) {
                cswException = new CswException(
                        "Error received from remote Csw server" + (msg != null ? ": " + msg : ""));
                LOGGER.warn("Unable to parse exception report: {}", e.getMessage());
                LOGGER.debug("Unable to parse exception report: {}", 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));
                    cswException = convertToCswException(report);
                } catch (JAXBException e) {
                    cswException = new CswException("Error received from remote Csw server: " + msg, e);
                    LOGGER.warn("Error parsing the exception report: {}", e.getMessage());
                    LOGGER.debug("Error parsing the exception report", e);
                }
            }
        } else {
            cswException = new CswException("Error reading response, entity type not understood: "
                    + response.getEntity().getClass().getName());
        }
        cswException.setHttpStatus(response.getStatus());
    } else {
        cswException = new CswException("Error handling response, response is null");
    }

    return cswException;
}

From source file:org.codice.ddf.attachment.impl.AttachmentParserImpl.java

@Override
public AttachmentInfo generateAttachmentInfo(InputStream inputStream, String contentType,
        String submittedFilename) {

    try {/*from   w  w w .j av  a 2 s .  c  o m*/
        if (inputStream != null && inputStream.available() == 0) {
            inputStream.reset();
        }
    } catch (IOException e) {
        LOGGER.debug("IOException reading stream from file attachment in multipart body", e);
    }

    String filename = submittedFilename;

    if (StringUtils.isEmpty(filename)) {
        LOGGER.debug("No filename parameter provided - generating default filename: fileExtension={}",
                DEFAULT_FILE_EXTENSION);
        String fileExtension = DEFAULT_FILE_EXTENSION;
        try {
            fileExtension = mimeTypeMapper.getFileExtensionForMimeType(contentType);
            if (StringUtils.isEmpty(fileExtension)) {
                fileExtension = DEFAULT_FILE_EXTENSION;
            }
        } catch (MimeTypeResolutionException e) {
            LOGGER.debug("Exception getting file extension for contentType = {}", contentType);
        }
        filename = DEFAULT_FILE_NAME + "." + fileExtension;
        LOGGER.debug("No filename parameter provided - default to {}", filename);
    } else {
        filename = FilenameUtils.getName(filename);

        if (StringUtils.isEmpty(contentType) || REFINEABLE_MIME_TYPES.contains(contentType)) {
            contentType = contentTypeFromFilename(filename);
        }
    }

    return new AttachmentInfoImpl(inputStream, filename, contentType);
}

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

/**
 * Parses a given InputStream to a String
 *
 * @param stream//  w w w.  ja  v a2  s  . co  m
 * @return String
 * @throws IOException
 */
protected String parseStream(InputStream stream) throws IOException {
    stream.reset();
    InputStreamReader reader = new InputStreamReader(stream);
    BufferedReader bufReader = new BufferedReader(reader);
    StringBuilder builder = new StringBuilder();
    String line = null;

    line = bufReader.readLine();
    while (line != null) {
        builder.append(line);
        line = bufReader.readLine();
    }

    String answer = builder.toString();
    return answer;
}

From source file:edu.cornell.mannlib.vitro.webapp.rdfservice.impl.ModelChangeImpl.java

private String streamToString(InputStream stream) {
    if (!stream.markSupported()) {
        return String.valueOf(stream);
    }//from   w w w  .j ava  2  s.  c o  m
    try {
        stream.mark(Integer.MAX_VALUE);
        List<String> lines = IOUtils.readLines(stream);
        stream.reset();
        return String.valueOf(lines);
    } catch (IOException e) {
        return "Failed to read input stream: " + e;
    }
}

From source file:org.apache.any23.extractor.csv.CSVReaderBuilder.java

/**
 * make sure the reader has correct delimiter and quotation set.
 * Check first lines and make sure they have the same amount of columns and at least 2
 *
 * @param is input stream to be checked/* w  w  w .  j av a  2 s.com*/
 * @param strategy strategy to be verified.
 * @return
 * @throws IOException
 * @param is
 */
private static boolean testStrategy(InputStream is, CSVStrategy strategy) throws IOException {
    final int MIN_COLUMNS = 2;

    is.mark(Integer.MAX_VALUE);
    try {
        final CSVParser parser = new CSVParser(new InputStreamReader(is), strategy);
        int linesToCheck = 5;
        int headerColumnCount = -1;
        while (linesToCheck > 0) {
            String[] row;
            row = parser.getLine();
            if (row == null) {
                break;
            }
            if (row.length < MIN_COLUMNS) {
                return false;
            }
            if (headerColumnCount == -1) { // first row
                headerColumnCount = row.length;
            } else { // make sure rows have the same number of columns or one more than the header
                if (row.length < headerColumnCount) {
                    return false;
                } else if (row.length - 1 > headerColumnCount) {
                    return false;
                }
            }
            linesToCheck--;
        }
        return true;
    } finally {
        is.reset();
    }
}