List of usage examples for org.springframework.core.io InputStreamResource InputStreamResource
public InputStreamResource(InputStream inputStream)
From source file:business.services.ExcerptListService.java
/** * Write the excerpt list as a file.// w w w . j ava2 s . c o m * @param list - the list * @param selectedOnly - writes only selected excerpts if true; all excerpts otherwise. * @return the resource holding selected excerpts or all (depends on the value of {@value selected} * in CSV format. */ public HttpEntity<InputStreamResource> writeExcerptList(ExcerptList list, boolean selectedOnly) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(out, EXCERPT_LIST_CHARACTER_ENCODING); CSVWriter csvwriter = new CSVWriter(writer, ';', '"'); csvwriter.writeNext(list.getCsvColumnNames()); for (ExcerptEntry entry : list.getEntries()) { if (!selectedOnly || entry.isSelected()) { csvwriter.writeNext(entry.getCsvValues()); } } csvwriter.flush(); writer.flush(); out.flush(); InputStream in = new ByteArrayInputStream(out.toByteArray()); csvwriter.close(); writer.close(); out.close(); InputStreamResource resource = new InputStreamResource(in); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.valueOf("text/csv;charset=" + EXCERPT_LIST_CHARACTER_ENCODING)); String filename = (selectedOnly ? "selection" : "excerpts") + "_" + list.getProcessInstanceId() + ".csv"; headers.set("Content-Disposition", "attachment; filename=" + filename); HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers); log.info("Returning reponse."); return response; } catch (IOException e) { log.error(e.getStackTrace()); log.error(e.getMessage()); throw new ExcerptListDownloadError(); } }
From source file:io.syndesis.runtime.ExtensionsITCase.java
private MultiValueMap<String, Object> multipartBody(byte[] data) { LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>(); multipartData.add("file", new InputStreamResource(new ByteArrayInputStream(data))); return multipartData; }
From source file:business.services.FileService.java
public HttpEntity<InputStreamResource> downloadAccessLog(String filename, boolean writeContentDispositionHeader) { try {/*from ww w. jav a2 s . c o m*/ FileSystem fileSystem = FileSystems.getDefault(); Path path = fileSystem.getPath(accessLogsPath).normalize(); filename = filename.replace(fileSystem.getSeparator(), "_"); filename = URLEncoder.encode(filename, "utf-8"); Path f = fileSystem.getPath(accessLogsPath, filename).normalize(); // filter path names that point to places outside the logs path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, f.getParent())) { // Path f is not in the upload path. Maybe 'name' contains '..'? log.error("Invalid filename: " + filename); throw new FileDownloadError("Invalid file name"); } if (!Files.isReadable(f)) { log.error("File does not exist: " + filename); throw new FileDownloadError("File does not exist"); } InputStream input = new FileInputStream(f.toFile()); InputStreamResource resource = new InputStreamResource(input); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); if (writeContentDispositionHeader) { headers.set("Content-Disposition", "attachment; filename=" + filename.replace(" ", "_")); } HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers); return response; } catch (IOException e) { log.error(e); throw new FileDownloadError(); } }
From source file:de.codesourcery.spring.contextrewrite.AnnotationParserTest.java
private static void assertTransform(String xml, RewriteConfig config, String expected) throws Exception { final XMLRewrite rewrite = new XMLRewrite(); final Resource filtered = rewrite .filterResource(new InputStreamResource(new ByteArrayInputStream(xml.getBytes())), config); final String rewritten = XMLRewrite.stripXML(XMLRewrite.readXMLString(filtered)); assertEquals(expected, rewritten);//from w w w. j a v a2s . c o m }
From source file:bjerne.gallery.controller.GalleryController.java
/** * Method used to return the binary of a gallery file ( * {@link GalleryFile#getActualFile()} ). This method handles 304 redirects * (if file has not changed) and range headers if requested by browser. The * range parts is particularly important for videos. The correct response * status is set depending on the circumstances. * <p>//from w ww. ja v a2 s .c o m * NOTE: the range logic should NOT be considered a complete implementation * - it's a bare minimum for making requests for byte ranges work. * * @param request * Request * @param galleryFile * Gallery file * @return The binary of the gallery file, or a 304 redirect, or a part of * the file. * @throws IOException * If there is an issue accessing the binary file. */ private ResponseEntity<InputStreamResource> returnResource(WebRequest request, GalleryFile galleryFile) throws IOException { LOG.debug("Entering returnResource()"); if (request.checkNotModified(galleryFile.getActualFile().lastModified())) { return null; } File file = galleryFile.getActualFile(); String contentType = galleryFile.getContentType(); String rangeHeader = request.getHeader(HttpHeaders.RANGE); long[] ranges = getRangesFromHeader(rangeHeader); long startPosition = ranges[0]; long fileTotalSize = file.length(); long endPosition = ranges[1] != 0 ? ranges[1] : fileTotalSize - 1; long contentLength = endPosition - startPosition + 1; LOG.debug("contentLength: {}, file length: {}", contentLength, fileTotalSize); LOG.debug("Returning resource {} as inputstream. Start position: {}", file.getCanonicalPath(), startPosition); InputStream boundedInputStream = new BoundedInputStream(new FileInputStream(file), endPosition + 1); InputStream is = new BufferedInputStream(boundedInputStream, 65536); InputStreamResource inputStreamResource = new InputStreamResource(is); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentLength(contentLength); responseHeaders.setContentType(MediaType.valueOf(contentType)); responseHeaders.add(HttpHeaders.ACCEPT_RANGES, "bytes"); if (StringUtils.isNotBlank(rangeHeader)) { is.skip(startPosition); String contentRangeResponseHeader = "bytes " + startPosition + "-" + endPosition + "/" + fileTotalSize; responseHeaders.add(HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader); LOG.debug("{} was not null but {}. Adding header {} to response: {}", HttpHeaders.RANGE, rangeHeader, HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader); } HttpStatus status = (startPosition == 0 && contentLength == fileTotalSize) ? HttpStatus.OK : HttpStatus.PARTIAL_CONTENT; LOG.debug("Returning {}. Status: {}, content-type: {}, {}: {}, contentLength: {}", file, status, contentType, HttpHeaders.CONTENT_RANGE, responseHeaders.get(HttpHeaders.CONTENT_RANGE), contentLength); return new ResponseEntity<InputStreamResource>(inputStreamResource, responseHeaders, status); }
From source file:com.wooki.test.unit.ConversionsTest.java
@Test(enabled = true) public void testLatexConversion() { String result = /* * generator .adaptContent( */"<h2>SubTitle</h2><p>Lorem ipsum</p><h3>SubTitle2</h3><p>Lorem ipsum</p>"/* ) */; Resource resource = new ByteArrayResource(result.getBytes()); /** Generate Latex */ InputStream xhtml = toXHTMLConvertor.performTransformation(resource); InputStream improvedXhtml = toImprovedXHTML4LatexConvertor .performTransformation(new InputStreamResource(xhtml)); InputStream latex = toLatexConvertor.performTransformation(new InputStreamResource(improvedXhtml)); logger.debug("xhtml to apt ok"); File latexFile;/*from w ww. jav a 2 s. c o m*/ try { latexFile = File.createTempFile("wooki", ".latex"); FileOutputStream fos = new FileOutputStream(latexFile); logger.debug("latex File is " + latexFile.getAbsolutePath()); byte[] content = null; int available = 0; while ((available = latex.available()) > 0) { content = new byte[available]; latex.read(content); fos.write(content); } fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java
/** * Determine imports for the given bundle. Based on the user settings, this * method will consider only the the test hierarchy until the testing * framework is found or all classes available inside the test bundle. <p/> * Note that split packages are not supported. * /* ww w.jav a 2 s .c o m*/ * @return */ private String[] determineImports() { boolean useTestClassOnly = false; // no jar entry present, bail out. if (jarEntries == null || jarEntries.isEmpty()) { logger.debug("No test jar content detected, generating bundle imports from the test class"); useTestClassOnly = true; } else if (createManifestOnlyFromTestClass()) { logger.info("Using the test class for generating bundle imports"); useTestClassOnly = true; } else logger.info("Using all classes in the jar for the generation of bundle imports"); // className, class resource Map entries; if (useTestClassOnly) { entries = new LinkedHashMap(4); // get current class (test class that bootstraps the OSGi infrastructure) Class<?> clazz = getClass(); String clazzPackage = null; String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName(); do { // consider inner classes as well List classes = new ArrayList(4); classes.add(clazz); CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes); for (Iterator iterator = classes.iterator(); iterator.hasNext();) { Class<?> classToInspect = (Class) iterator.next(); Package pkg = classToInspect.getPackage(); if (pkg != null) { clazzPackage = pkg.getName(); String classFile = ClassUtils.getClassFileName(classToInspect); entries.put(classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX), new InputStreamResource(classToInspect.getResourceAsStream(classFile))); } // handle default package else { logger.warn("Could not find package for class " + classToInspect + "; ignoring..."); } } clazz = clazz.getSuperclass(); } while (!endPackage.equals(clazzPackage)); } else entries = jarEntries; return determineImportsFor(entries); }
From source file:com.viewer.controller.ViewerController.java
@RequestMapping(value = "/GetResourceForHtml") @ResponseBody/*from w ww.j av a 2s . co m*/ public ResponseEntity<InputStreamResource> GetResourceForHtml(@RequestParam String documentPath, int pageNumber, String resourceName) { if (!DotNetToJavaStringHelper.isNullOrEmpty(resourceName) && resourceName.indexOf("/") >= 0) { resourceName = resourceName.replace("/", ""); } HtmlResource resource = new HtmlResource(); resource.setResourceName(resourceName); resource.setResourceType(Utils.GetResourceType(resourceName)); resource.setDocumentPageNumber(pageNumber); InputStream stream = _htmlHandler.getResource(documentPath, resource); return ResponseEntity.ok() .contentType(MediaType.parseMediaType(Utils.GetImageMimeTypeFromFilename(resourceName))) .body(new InputStreamResource(stream)); }
From source file:org.shaf.server.controller.CmdActionController.java
/** * Gets data from the server.//from ww w . jav a 2 s . c om * * @param storage * the resource type. * @param alias * the data alias. * @return the entity for downloading data. * @throws Exception * if an error occurs. */ @RequestMapping(value = "/download/{storage}/{alias}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<InputStreamResource> onDownload(@PathVariable String storage, @PathVariable String alias) throws Exception { LOG.debug("CALL service: /cmd/download/{" + storage + "}/{" + alias + "}"); Firewall firewall = super.getFirewall(); String username = super.getUserName(); StorageDriver driver = OPER.getStorageDriver(firewall, username, StorageType.CONSUMER, storage); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); header.setContentLength(driver.getLength(alias)); header.setContentDispositionFormData("attachment", alias); return new ResponseEntity<InputStreamResource>(new InputStreamResource(driver.getInputStream(alias)), header, HttpStatus.OK); }
From source file:org.cmo.cancerhotspots.controller.HotspotController.java
public InputStreamResource downloadFile(@PathVariable String filename) throws IOException { Resource resource = new ClassPathResource("data/" + filename + ".txt"); return new InputStreamResource(resource.getInputStream()); }