List of usage examples for java.io InputStream markSupported
public boolean markSupported()
mark
and reset
methods. From source file:com.smartitengineering.event.hub.core.ChannelEventsResource.java
public Response get(String placeholderId, boolean isBefore) { if (count == null) { count = 10;//from w w w . j av a 2 s . c o m } ResponseBuilder responseBuilder = Response.ok(); Feed atomFeed = getFeed("Events", new Date()); int thisCount = count; if (isBefore) { thisCount = count * -1; } Collection<Event> events = HubPersistentStorerSPI.getInstance().getStorer().getEvents(placeholderId, channelId, thisCount); if (events != null && !events.isEmpty()) { MultivaluedMap<String, String> queryParams = getUriInfo().getQueryParameters(); List<Event> eventList = new ArrayList<Event>(events); Link nextLink = getAbderaFactory().newLink(); nextLink.setRel(Link.REL_PREVIOUS); Event lastEvent = eventList.get(0); final UriBuilder nextUri = getRelativeURIBuilder().path(ChannelEventsResource.class).path(AFTER_METHOD); final UriBuilder previousUri = getRelativeURIBuilder().path(ChannelEventsResource.class) .path(BEFORE_METHOD); for (String key : queryParams.keySet()) { final Object[] values = queryParams.get(key).toArray(); nextUri.queryParam(key, values); previousUri.queryParam(key, values); } nextLink.setHref(nextUri.build(channelId, lastEvent.getPlaceholderId()).toString()); atomFeed.addLink(nextLink); Link previousLink = getAbderaFactory().newLink(); previousLink.setRel(Link.REL_NEXT); Event firstEvent = eventList.get(events.size() - 1); previousLink.setHref(previousUri.build(channelId, firstEvent.getPlaceholderId()).toString()); atomFeed.addLink(previousLink); for (Event event : events) { Entry eventEntry = getAbderaFactory().newEntry(); eventEntry.setId(event.getPlaceholderId()); eventEntry.setTitle(event.getPlaceholderId().toString()); InputStream contentStream = event.getEventContent().getContent(); String contentAsString = ""; if (contentStream != null) { if (contentCache.containsKey(event)) { contentAsString = contentCache.get(event); } else { try { if (contentStream.markSupported()) { contentStream.mark(Integer.MAX_VALUE); } contentAsString = IOUtils.toString(contentStream); contentCache.put(event, contentAsString); if (contentStream.markSupported()) { contentStream.reset(); } } catch (IOException ex) { } } } eventEntry.setContent(contentAsString); eventEntry.setUpdated(event.getCreationDate()); Link eventLink = getAbderaFactory().newLink(); eventLink.setHref(getRelativeURIBuilder().path(EventResource.class).build(event.getPlaceholderId()) .toString()); eventLink.setRel(Link.REL_ALTERNATE); eventLink.setMimeType(MediaType.APPLICATION_JSON); eventEntry.addLink(eventLink); atomFeed.addEntry(eventEntry); } } responseBuilder.entity(atomFeed); return responseBuilder.build(); }
From source file:com.smartitengineering.event.hub.core.AllEventsResource.java
public Response get(String placeholderId, boolean isBefore) { if (count == null) { count = 10;/*from w ww. j a v a 2 s .c o m*/ } int thisCount = count; if (isBefore) { thisCount = count * -1; } ResponseBuilder responseBuilder = Response.ok(); Feed atomFeed = getFeed("Events", new Date()); Link eventsLink = getAbderaFactory().newLink(); eventsLink.setHref(getRelativeURIBuilder().path(RootResource.class).build().toString()); eventsLink.setRel("root"); atomFeed.addLink(eventsLink); Collection<Event> events = HubPersistentStorerSPI.getInstance().getStorer().getEvents(placeholderId, null, thisCount); if (events != null && !events.isEmpty()) { MultivaluedMap<String, String> queryParams = getUriInfo().getQueryParameters(); List<Event> eventList = new ArrayList<Event>(events); Link nextLink = getAbderaFactory().newLink(); nextLink.setRel(Link.REL_PREVIOUS); Event lastEvent = eventList.get(0); final UriBuilder nextUri = getRelativeURIBuilder().path(AllEventsResource.class).path(AFTER_METHOD); final UriBuilder previousUri = getRelativeURIBuilder().path(AllEventsResource.class) .path(BEFORE_METHOD); for (String key : queryParams.keySet()) { final Object[] values = queryParams.get(key).toArray(); nextUri.queryParam(key, values); previousUri.queryParam(key, values); } nextLink.setHref(nextUri.build(lastEvent.getPlaceholderId()).toString()); atomFeed.addLink(nextLink); Link previousLink = getAbderaFactory().newLink(); previousLink.setRel(Link.REL_NEXT); Event firstEvent = eventList.get(events.size() - 1); previousLink.setHref(previousUri.build(firstEvent.getPlaceholderId()).toString()); atomFeed.addLink(previousLink); for (Event event : events) { Entry eventEntry = getAbderaFactory().newEntry(); eventEntry.setId(event.getPlaceholderId()); eventEntry.setTitle(event.getPlaceholderId().toString()); InputStream contentStream = event.getEventContent().getContent(); String contentAsString = ""; if (contentStream != null) { if (contentCache.containsKey(event)) { contentAsString = contentCache.get(event); } else { try { if (contentStream.markSupported()) { contentStream.mark(Integer.MAX_VALUE); } contentAsString = IOUtils.toString(contentStream); contentCache.put(event, contentAsString); if (contentStream.markSupported()) { contentStream.reset(); } } catch (IOException ex) { } } } eventEntry.setContent(contentAsString); eventEntry.setUpdated(event.getCreationDate()); Link eventLink = getAbderaFactory().newLink(); eventLink.setHref(getRelativeURIBuilder().path(EventResource.class).build(event.getPlaceholderId()) .toString()); eventLink.setRel(Link.REL_ALTERNATE); eventLink.setMimeType(MediaType.APPLICATION_JSON); eventEntry.addLink(eventLink); atomFeed.addEntry(eventEntry); } } responseBuilder.entity(atomFeed); return responseBuilder.build(); }
From source file:cn.bzvs.excel.imports.ExcelImportServer.java
/** * Excel field Integer,Long,Double,Date,String,Boolean * //ww w. j a v a2 s . c o m * @param inputstream * @param pojoClass * @param params * @return * @throws Exception */ public ExcelImportResult importExcelByIs(InputStream inputstream, Class<?> pojoClass, ImportParams params) throws Exception { List<T> result = new ArrayList<T>(); Workbook book = null; boolean isXSSFWorkbook = true; if (!(inputstream.markSupported())) { inputstream = new PushbackInputStream(inputstream, 8); } if (POIFSFileSystem.hasPOIFSHeader(inputstream)) { book = new HSSFWorkbook(inputstream); isXSSFWorkbook = false; } else if (POIXMLDocument.hasOOXMLHeader(inputstream)) { book = new XSSFWorkbook(OPCPackage.open(inputstream)); } createErrorCellStyle(book); Map<String, PictureData> pictures; for (int i = params.getStartSheetIndex(); i < params.getStartSheetIndex() + params.getSheetNum(); i++) { if (isXSSFWorkbook) { pictures = PoiPublicUtil.getSheetPictrues07((XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book); } else { pictures = PoiPublicUtil.getSheetPictrues03((HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book); } result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, params, pictures)); } if (params.isNeedSave()) { saveThisExcel(params, pojoClass, isXSSFWorkbook, book); } return new ExcelImportResult(result, verfiyFail, book); }
From source file:com.smartsheet.api.internal.http.HttpEntitySnapshot.java
/** * this ctor creates a snapshot of the original entity (which requires its stream either support reset or it must be * entirely consumed and replaced with an exact copy) *//* w ww . j a va2 s . com*/ public HttpEntitySnapshot(HttpEntity original) throws IOException { final String contentType = original.getContentType(); final InputStream contentStream = original.getContent(); final long contentLength = original.getContentLength(); super.setContentLength(contentLength); super.setContentType(contentType); if (contentType != null && contentType.startsWith(JSON_MIME_TYPE)) { // we need to read and then reset (if possible) the original entity's content stream (or replace it with an exact copy) // if contentLength > Integer.MAX_VALUE we have MUCH bigger problems than long->int rollover boolean sourceSupportsMark = contentStream.markSupported(); if (sourceSupportsMark) { // here we can read up to a limited contents contentArray = new byte[MAX_SNAPSHOT_SIZE]; contentStream.mark(MAX_SNAPSHOT_SIZE + 1); int bytesRead = contentStream.read(contentArray, 0, MAX_SNAPSHOT_SIZE); contentStream.reset(); // trim content array to actual size if (bytesRead < MAX_SNAPSHOT_SIZE) { contentArray = Arrays.copyOf(contentArray, bytesRead); } } else { // here we must read everything and then repackage the byte[] into an input stream to replace the original byte[] fullContentArray; try { fullContentArray = StreamUtil.readBytesFromStream(contentStream, StreamUtil.ONE_MB); } finally { contentStream.close(); } // having consumed the content into memory we must now replace the original stream (so it can be read by subsequent code) original.setContent(new ByteArrayInputStream(fullContentArray)); // and we need a copy for potential logging purposes contentArray = Arrays.copyOf(fullContentArray, Math.min(MAX_SNAPSHOT_SIZE, fullContentArray.length)); // we see a lot of Content-Length:-1 from certain responses - no point in logging those if (contentLength != -1 && fullContentArray.length != contentLength) { LoggerFactory.getLogger(HttpEntitySnapshot.class).info( "actual content-length {} doesn't match" + " declared content-length {}", fullContentArray.length, contentLength); } } } else { contentArray = String.format("**contentType '%s' not logged**", contentType).getBytes(); } }
From source file:com.aliyun.odps.rest.RestClient.java
private void resetBody(InputStream body) { if (body != null && body.markSupported()) { try {/* w w w . j av a2s . co m*/ body.reset(); } catch (IOException e) { // DO NOTHING FOR SUPPORTED MARK STREAM WILL NOT FAILED } } }
From source file:org.globus.gsi.X509Credential.java
public X509Credential(InputStream certInputStream, InputStream keyInputStream) throws CredentialException { if (certInputStream.markSupported()) { certInputStream.mark(BUFFER_SIZE); }/*w w w .j a v a 2s. c o m*/ loadKey(keyInputStream); loadCertificate(certInputStream); validateCredential(); }
From source file:com.gargoylesoftware.htmlunit.WebResponseData.java
private InputStream getStream(final DownloadedContent downloadedContent, final List<NameValuePair> headers) throws IOException { InputStream stream = downloadedContent_.getInputStream(); if (stream == null) { return null; }/*from w ww. j a v a 2 s .co m*/ if (downloadedContent.isEmpty()) { return stream; } final String encoding = getHeader(headers, "content-encoding"); if (encoding != null) { if (StringUtils.contains(encoding, "gzip")) { stream = new GZIPInputStream(stream); } else if (StringUtils.contains(encoding, "deflate")) { boolean zlibHeader = false; if (stream.markSupported()) { // should be always the case as the content is in a byte[] or in a file stream.mark(2); final byte[] buffer = new byte[2]; stream.read(buffer, 0, 2); zlibHeader = (((buffer[0] & 0xff) << 8) | (buffer[1] & 0xff)) == 0x789c; stream.reset(); } if (zlibHeader) { stream = new InflaterInputStream(stream); } else { stream = new InflaterInputStream(stream, new Inflater(true)); } } } return stream; }
From source file:com.zimbra.cs.mime.Mime.java
/** * Returns a {@link Reader} that decodes the specified {@link InputStream}. * <p>//w w w .jav a 2s .c o m * {@code contentType} must of type "text/*". This method tries to detect a charset in the following order. * <ol> * <li>{@code charset} parameter in {@code Content-Type} * <li>auto-detect using ICU4J * <li>user's default charset preference * <li>platform default charset * </ol> * * @param input The InputStream to decode. * @param contentType The stream's Content-Type, which must be "text/*". * @param defaultCharset The user's default charset preference */ public static Reader getTextReader(InputStream input, String contentType, String defaultCharset) { Charset charset = CharsetUtil.toCharset(getCharset(contentType)); if (charset == null) { if (!input.markSupported()) { input = new BufferedInputStream(input); } charset = detectCharset(input, CharsetUtil.toCharset(defaultCharset)); } return new InputStreamReader(input, CharsetUtil.normalizeCharset(charset)); }
From source file:com.microsoft.azure.storage.core.Utility.java
/** * Encrypts an input stream up to a given length. * Exits early if the encrypted data is longer than the abandon length. * /*from w ww. ja va 2 s . c o m*/ * @param sourceStream * A <code>InputStream</code> object that represents the stream to measure. * @param targetStream * A <code>ByteArrayOutputStream</code> object that represents the stream to write the encrypted data. * @param cipher * The <code>Cipher</code> to use to encrypt the data. * @param writeLength * The number of bytes to read and encrypt from the sourceStream. * @param abandonLength * The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to * force the entire stream to be read. This parameter is provided to support upload thresholds. * @return * The size of the encrypted stream, or -1 if the encrypted stream would be over the abandonLength. * @throws IOException * If an I/O error occurs. */ public static long encryptStreamIfUnderThreshold(final InputStream sourceStream, final ByteArrayOutputStream targetStream, Cipher cipher, long writeLength, long abandonLength) throws IOException { if (abandonLength < 0) { abandonLength = Long.MAX_VALUE; } if (!sourceStream.markSupported()) { throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE); } sourceStream.mark(Constants.MAX_MARK_LENGTH); if (writeLength < 0) { writeLength = Long.MAX_VALUE; } CipherOutputStream encryptStream = new CipherOutputStream(targetStream, cipher); int count = -1; long totalEncryptedLength = targetStream.size(); final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); while (nextCopy > 0 && count != -1) { // Note: We are flushing the CryptoStream on every write here. This way, we don't end up encrypting more data than we intend here, if // we go over the abandonLength. encryptStream.write(retrievedBuff, 0, count); encryptStream.flush(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { // Abandon operation break; } nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); } sourceStream.reset(); sourceStream.mark(Constants.MAX_MARK_LENGTH); encryptStream.close(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { totalEncryptedLength = -1; } return totalEncryptedLength; }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java
/** * Validates configuration XML against XML defined XSD schema. * * @param config// ww w .j av a 2s . co m * {@link InputStream} to get configuration data from * @return map of found validation errors * @throws SAXException * if there was an error parsing the configuration * @throws IOException * if there is an error reading the configuration data */ public static Map<OpLevel, List<SAXParseException>> validate(InputStream config) throws SAXException, IOException { final Map<OpLevel, List<SAXParseException>> validationErrors = new HashMap<>(); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { handleValidationError(OpLevel.WARNING, exception); } @Override public void error(SAXParseException exception) throws SAXException { handleValidationError(OpLevel.ERROR, exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { handleValidationError(OpLevel.FATAL, exception); } private void handleValidationError(OpLevel level, SAXParseException exception) { List<SAXParseException> lErrorsList = validationErrors.get(level); if (lErrorsList == null) { lErrorsList = new ArrayList<>(); validationErrors.put(level, lErrorsList); } lErrorsList.add(exception); } }); validator.validate(new StreamSource(config)); } finally { if (config.markSupported()) { config.reset(); } } return validationErrors; }