List of usage examples for java.io InputStream mark
public synchronized void mark(int readlimit)
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();//from ww w. jav a 2 s .c om String fileId = gridFSService.createFile(FILE_NAME, testInput); Assert.assertNotNull(fileId); InputStream stream = gridFSService.getFile(fileId); Assert.assertNotNull(stream); Assert.assertEquals(currentMD5, getMD5(stream)); }
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); String jsonString = IOUtils.toString(is); if (StringUtils.isNoneEmpty(jsonString)) { JSONObject jsonObject = JSONObject.fromObject(jsonString); if (jsonObject.has("username")) { userParam = jsonObject.getString("username"); }/*from w w w. j av a 2 s . c om*/ } 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.apache.tika.parser.html.charsetdetector.StandardHtmlEncodingDetector.java
@Override public Charset detect(InputStream input, Metadata metadata) throws IOException { int limit = getMarkLimit(); input.mark(limit); // Never read more than the first META_TAG_BUFFER_SIZE bytes InputStream limitedStream = new BoundedInputStream(input, limit); PreScanner preScanner = new PreScanner(limitedStream); // The order of priority for detection is: // 1. Byte Order Mark Charset detectedCharset = preScanner.detectBOM(); // 2. Transport-level information (Content-Type HTTP header) if (detectedCharset == null) detectedCharset = charsetFromContentType(metadata); // 3. HTML <meta> tag if (detectedCharset == null) detectedCharset = preScanner.scan(); input.reset();/*from w w w.j a v a 2 s .c o m*/ return detectedCharset; }
From source file:VASSAL.tools.io.RereadableInputStreamTest.java
@Test public void testMarkAndReset() throws IOException { final byte[] expected = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }; final InputStream in = new RereadableInputStream(new ByteArrayInputStream(expected)); in.mark(4); int count;/*from w ww . j av a2s .co m*/ final byte[] buf = new byte[4]; count = in.read(buf, 0, 4); assertEquals(4, count); in.reset(); final byte[] actual = new byte[expected.length]; count = IOUtils.read(in, actual); assertEquals(expected.length, count); assertEquals(-1, in.read()); assertArrayEquals(expected, actual); }
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 a v a 2 s . c om 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.craftercms.studio.impl.v1.web.security.access.StudioPublishingAPIAccessDecisionVoter.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); String jsonString = IOUtils.toString(is); if (StringUtils.isNoneEmpty(jsonString)) { JSONObject jsonObject = JSONObject.fromObject(jsonString); if (jsonObject.has("username")) { userParam = jsonObject.getString("username"); }// w w w. java2 s. c o m 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 START: case STOP: if (currentUser != null) { toRet = ACCESS_GRANTED; } else { toRet = ACCESS_DENIED; } break; case STATUS: if (siteService.exists(siteParam)) { if (currentUser != null && isSiteMember(siteParam, currentUser)) { toRet = ACCESS_GRANTED; } else { toRet = ACCESS_DENIED; } } else { toRet = ACCESS_ABSTAIN; } break; default: toRet = ACCESS_ABSTAIN; break; } } logger.debug("Request: " + requestUri + " - Access: " + toRet); return toRet; }
From source file:org.craftercms.studio.impl.v1.web.security.access.StudioGroupAPIAccessDecisionVoter.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 siteParam = request.getParameter("site_id"); String userParam = request.getParameter("username"); User currentUser = null;// w w w .j a v a2 s . c o m try { currentUser = (User) authentication.getPrincipal(); } catch (ClassCastException e) { // anonymous user if (!authentication.getPrincipal().toString().equals("anonymousUser")) { logger.error("Error getting current user", e); return ACCESS_ABSTAIN; } } if (StringUtils.isEmpty(userParam) && StringUtils.equalsIgnoreCase(request.getMethod(), HttpMethod.POST.name()) && !ServletFileUpload.isMultipartContent(request)) { try { InputStream is = request.getInputStream(); is.mark(0); 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"); } } switch (requestUri) { case ADD_USER: case CREATE: case DELETE: case GET_ALL: case REMOVE_USER: case UPDATE: if (currentUser != null && (isSiteAdmin( studioConfiguration.getProperty(StudioConfiguration.CONFIGURATION_GLOBAL_SYSTEM_SITE), currentUser) || isSiteAdmin(siteParam, currentUser))) { toRet = ACCESS_GRANTED; } else { toRet = ACCESS_DENIED; } break; case GET: case GET_PER_SITE: case USERS: if (currentUser != null && (isSiteAdmin(siteParam, currentUser) || isSiteMember(siteParam, 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:com.lion328.xenonlauncher.proxy.HttpDataHandler.java
@Override public boolean process(Socket client, Socket server) throws Exception { InputStream clientIn = client.getInputStream(); clientIn.mark(65536); try {/*from w w w . j a va2 s . c o m*/ DefaultBHttpServerConnection httpClient = new DefaultBHttpServerConnection(8192); httpClient.bind(client); httpClient.setSocketTimeout(timeout); DefaultBHttpClientConnection httpServer = new DefaultBHttpClientConnection(8192); httpServer.bind(server); HttpCoreContext context = HttpCoreContext.create(); context.setAttribute("client.socket", client); context.setAttribute("server.socket", server); HttpEntityEnclosingRequest request; do { HttpRequest rawRequest = httpClient.receiveRequestHeader(); if (rawRequest instanceof HttpEntityEnclosingRequest) { request = (HttpEntityEnclosingRequest) rawRequest; } else { request = new BasicHttpEntityEnclosingRequest(rawRequest.getRequestLine()); request.setHeaders(rawRequest.getAllHeaders()); } httpClient.receiveRequestEntity(request); HttpResponse response = new BasicHttpResponse( new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")); boolean sent = false; for (Map.Entry<Integer, HttpRequestHandler> entry : handlers.entrySet()) { entry.getValue().handle(request, response, context); if (context.getAttribute("response.set") instanceof HttpResponse) { response = (HttpResponse) context.getAttribute("response.set"); } if (context.getAttribute("pipeline.end") == Boolean.TRUE) { break; } if (context.getAttribute("response.need-original") == Boolean.TRUE && !sent) { httpServer.sendRequestHeader(request); httpServer.sendRequestEntity(request); response = httpServer.receiveResponseHeader(); httpServer.receiveResponseEntity(response); entry.getValue().handle(request, response, context); context.removeAttribute("response.need-original"); context.setAttribute("request.sent", true); sent = true; } } if (context.getAttribute("response.sent") != Boolean.TRUE) { httpClient.sendResponseHeader(response); if (response.getEntity() != null) { httpClient.sendResponseEntity(response); } } } while (request.getFirstHeader("Connection").getValue().equals("keep-alive")); return true; } catch (ProtocolException e) { clientIn.reset(); return false; } catch (ConnectionClosedException e) { return true; } }
From source file:com.vmware.photon.controller.api.frontend.lib.image.ImageLoader.java
/** * Peak into the stream for the OVA signature. * * @param inputStream/*from ww w. ja v a2 s .c o m*/ * @return * @throws IOException */ private boolean isTarFile(InputStream inputStream) throws IOException { inputStream.mark(TarFileStreamReader.TAR_FILE_GRANULARITY); TarFileStreamReader tar = new TarFileStreamReader(inputStream); boolean isTar = tar.iterator().hasNext(); inputStream.reset(); return isTar; }
From source file:com.jaromin.alfresco.extractor.AbstractBitmapExtractor.java
/** * Check if the next series of bytes from the stream matches the sequence. * The int 'b' is the most recently-read byte and the input stream is positioned * to read the byte immediately following 'b'. * If the match fails, the stream is reset. If it matches, the stream is NOT reset. * @param seq/* www. ja v a 2 s . c o m*/ * @param in * @param b * @return * @throws IOException */ protected boolean matches(byte[] seq, InputStream in, int b) throws IOException { if (((byte) b) == seq[0]) { // potential match, read next 7 bytes byte[] buf = new byte[seq.length - 1]; in.mark(buf.length); if (in.read(buf) == -1) { in.reset(); return false; } else { if (ArrayUtils.isEquals(buf, ArrayUtils.subarray(seq, 1, seq.length))) { // last 7 bytes return true; } in.reset(); // rewind } } return false; }