@RequestMapping( value = "/download", method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded; charset=UTF-8") public String download( @RequestParam("path") String path, HttpServletRequest request, HttpServletResponse response) throws MessageException { try { if (path != null && path.endsWith("pdf")) { InputStream content = null; String fileName = path.substring(path.lastIndexOf("/") + 1); content = TestArtifactController.class.getResourceAsStream("/" + path); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); FileCopyUtils.copy(content, response.getOutputStream()); } else if (path != null && path.endsWith("docx")) { InputStream content = null; String fileName = path.substring(path.lastIndexOf("/") + 1); if (!path.startsWith("/")) { content = TestArtifactController.class.getResourceAsStream("/" + path); } else { content = TestArtifactController.class.getResourceAsStream(path); } response.setContentType( "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); FileCopyUtils.copy(content, response.getOutputStream()); } throw new IllegalArgumentException("Invalid Path Provided"); } catch (IOException e) { logger.debug("Failed to download the test package "); throw new TestCaseException("Cannot download the artifact " + e.getMessage()); } }
@Test public void testMoveFromLocalMultiAndDir() throws Exception { String name1 = UUID.randomUUID() + "-1.txt"; String name2 = UUID.randomUUID() + "-2.txt"; String dst = "local/"; File f1 = new File(name1); File f2 = new File(name2); f1.deleteOnExit(); f2.deleteOnExit(); FileCopyUtils.copy(name1, new FileWriter(f1)); FileCopyUtils.copy(name2, new FileWriter(f2)); try { shell.moveFromLocal(name1, dst); shell.moveFromLocal(name2, dst); assertTrue(shell.test(dst + name1)); assertTrue(shell.test(dst + name2)); assertEquals(name1, shell.cat(dst + name1).toString()); assertEquals(name2, shell.cat(dst + name2).toString()); assertFalse(f1.exists()); assertFalse(f2.exists()); } finally { f1.delete(); f2.delete(); } }
@Test public void shouldBeAbleToGetInputStreamTwice() throws Exception { Entry entry = archiveEntries.get("index.html"); ByteArrayOutputStream s1 = new ByteArrayOutputStream(); FileCopyUtils.copy(entry.getInputStream(), s1); ByteArrayOutputStream s2 = new ByteArrayOutputStream(); FileCopyUtils.copy(entry.getInputStream(), s2); assertThat(s1.toByteArray().length, is(93)); assertThat(s2.toByteArray().length, is(93)); assertThat(s1.toByteArray(), is(equalTo(s2.toByteArray()))); }
@Test public void getBody() throws Exception { byte[] content = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(content, response.getBody()); assertArrayEquals("Invalid content written", content, mockResponse.getContentAsByteArray()); }
/** * Uploads the dsl file of a user to an auxiliar folder, if it's not upload returns an error * * @param file * @param idUser */ @RequestMapping(method = RequestMethod.POST, value = "/uploadDSL") public ResponseEntity<String> handleFileUploadDSL( @RequestParam("dsl") MultipartFile file, @RequestParam("idUser") String idUser) { // target DSL name String name = "dsl.yml"; if (!file.isEmpty()) { try { // User folder File userFolder = new File(idUser); if (!userFolder.exists()) Files.createDirectory(userFolder.toPath()); // Auxiliar folder where the temporal configuration files are // copy String folderAux = idUser + "/aux"; File folder = new File(folderAux); if (!folder.exists()) Files.createDirectory(folder.toPath()); // Copy DSL file BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(folderAux + "/" + name))); FileCopyUtils.copy(file.getInputStream(), stream); stream.close(); log.info("DSL copied: " + idUser); } catch (Exception e) { log.warn("DSL not copied:" + e.getMessage()); throw new InternalError("Error copying: " + e.getMessage()); } } else { log.warn("DSL not copied, empty file: " + idUser); throw new BadRequestError("Empty file"); } return new ResponseEntity<>("copied", HttpStatus.OK); }
public String createEmailTemplate(MemberDocumentTempInfo membershipInfo) throws Exception { String html = ""; // configure velocity engine Properties p = new Properties(); p.setProperty("file.resource.loader.path", IMUtil.TEMP_DIR); p.setProperty("file.resource.loader.path", IMUtil.TEMP_DIR); Velocity.init(p); // create temp file tempFile = new File(IMUtil.TEMP_DIR + File.separator + TEMPLATE_FILE_NAME); FileCopyUtils.copy(contentFields.getBytes(), tempFile); // create template and fill it VelocityContext context = new VelocityContext(); context.put("membershipInfo", membershipInfo); context.put("user", receiver); String language = "fa"; if (language == "fa") context.put("language", "fa"); else context.put("language", "en"); Template template = null; template = Velocity.getTemplate(tempFile.getName(), "UTF-8"); StringWriter sw = new StringWriter(); template.merge(context, sw); html = sw.toString(); return html; }
@RequestMapping(value = "addBlogs.action", method = RequestMethod.POST) @ResponseBody public Object addBlogs(Blogs blogs, HttpServletRequest request) throws IOException { User_Ext_Personal user_Ext_Personal = PublicUtil.getUserOfSession(request); if (user_Ext_Personal == null) { return "needLogin"; } blogs.setUserid(user_Ext_Personal.getUserId()); MultipartHttpServletRequest httpServletRequest = (MultipartHttpServletRequest) request; MultipartFile file = httpServletRequest.getFile("image"); String fileName = file.getOriginalFilename(); byte[] b = file.getBytes(); File dirFile = new File(PublicUtil.getRootFileDirectory(request) + "/media_upload/personal_upload"); if (!dirFile.exists()) { dirFile.mkdirs(); } String imagepath = "/media_upload/personal_upload/" + new Hanyu().getStringPinYin(blogs.getTitle()) + fileName; File files = new File(PublicUtil.getRootFileDirectory(request) + imagepath); if (!files.exists()) { dirFile.createNewFile(); } FileCopyUtils.copy(b, files); boolean bool = blogsService.addBlogs(blogs, imagepath, null); return bool + ""; }
@RequestMapping(value = "upload", method = RequestMethod.POST) public void upload(@RequestParam String memberId, MultipartHttpServletRequest request) throws Exception { System.out.println("Member Upload..."); String genId = null; String extName = null; int fileIndex = 0; String filePath = "C:/workspace/Trace/WebContent/traceupload/"; MultipartFile mpf = null; Iterator<String> itr = request.getFileNames(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); genId = UUID.randomUUID().toString(); fileIndex = mpf.getOriginalFilename().lastIndexOf("."); extName = mpf.getOriginalFilename().substring(fileIndex, mpf.getOriginalFilename().length()); Member member = new Member(); member.setMemberId(memberId); member.setStoImgName(genId + extName); updateMember(member); try { FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(filePath + genId + extName)); } catch (IOException e) { e.printStackTrace(); } } }
private void saveFileToLocalDisk(MultipartFile multipartFile) throws IOException, FileNotFoundException { String outputFileName = getOutputFilename(multipartFile); FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName)); }
@Override protected void writeInternal(String t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { MediaType contentType = outputMessage.getHeaders().getContentType(); Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET; FileCopyUtils.copy(t, new OutputStreamWriter(outputMessage.getBody(), charset)); }
public static void save(String fileName, String content) { try { FileCopyUtils.copy(content, new FileWriter(new File(fileDir, fileName))); } catch (IOException e) { logger.error("fail to save file " + fileName); } }
/** * Streams content back to client from a given resource path. * * @param req The request * @param res The response * @param resourcePath The classpath resource path the content is required for. * @param attach Indicates whether the content should be streamed as an attachment or not * @param attachFileName Optional file name to use when attach is <code>true</code> * @throws IOException */ protected void streamContent( WebScriptRequest req, WebScriptResponse res, String resourcePath, boolean attach, String attachFileName, Map<String, Object> model) throws IOException { if (logger.isDebugEnabled()) logger.debug( "Retrieving content from resource path " + resourcePath + " (attach: " + attach + ")"); // get extension of resource String ext = ""; int extIndex = resourcePath.lastIndexOf('.'); if (extIndex != -1) { ext = resourcePath.substring(extIndex); } // We need to retrieve the modification date/time from the resource itself. StringBuilder sb = new StringBuilder("classpath:").append(resourcePath); final String classpathResource = sb.toString(); long resourceLastModified = resourceLoader.getResource(classpathResource).lastModified(); // create temporary file File file = TempFileProvider.createTempFile("streamContent-", ext); InputStream is = resourceLoader.getResource(classpathResource).getInputStream(); OutputStream os = new FileOutputStream(file); FileCopyUtils.copy(is, os); // stream the contents of the file, but using the modifiedDate of the original resource. streamContent(req, res, file, resourceLastModified, attach, attachFileName, model); }
public void addVideo( User user, int channelId, String title, String tags, String description, File videoFile, String fileNameOnClient) throws Exception { if (videoFile != null) { long duration = 0; Encoder encoder = new Encoder(); /*MutimediaInfo*/ /*随机产生一个UUID串,作为视频文件在服务端的名称*/ String fileNameOnServer = UUID.randomUUID().toString(); File fileOnServer = new File(Const.UPLOAD_REAL_PATH, fileNameOnServer); try { FileCopyUtils.copy(videoFile, fileOnServer); } catch (Exception e) { throw new Exception("复制文件时发生错误"); } Video video = new Video(); /*需要在daoimpl中实现findById方法*/ // video.setChannelId(ChannelDao.findById(channelId)); } }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String portalId = request.getParameter("portalId"); if (portalId != null) { long id = Long.parseLong(portalId); ProfilePerson person = service.findProfilePersonByPortalId(id); byte[] images = null; if (person.getRegisterType() == ProfilePerson.REAL) { images = service.findRealProfilePersonByProfilePersonId(person.getId()).getImage(); } else if (person.getRegisterType() == ProfilePerson.LEGAL) { images = service.findLegalProfilePersonByProfilePersonId(person.getId()).getImage(); } if (images != null) { ServletOutputStream ouputStream = null; BufferedInputStream inputStream = null; response.setContentType("application/download"); ouputStream = response.getOutputStream(); ByteArrayInputStream bais = new ByteArrayInputStream(images); inputStream = new BufferedInputStream(bais); if (inputStream != null) { FileCopyUtils.copy(inputStream, ouputStream); } } } return null; }
@MediumTest public void testGetAcceptEncodingGzip() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/gzip"), HttpMethod.GET); assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); request.getHeaders().add("Accept-Encoding", "gzip"); ClientHttpResponse response = request.execute(); try { assertNotNull(response.getStatusText()); assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); assertTrue("Header not found", response.getHeaders().containsKey("Content-Encoding")); assertEquals( "Header value not found", Arrays.asList("gzip"), response.getHeaders().get("Content-Encoding")); byte[] body = "gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip " .getBytes("UTF-8"); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertTrue("Invalid body", Arrays.equals(body, result)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(body.length); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream); FileCopyUtils.copy(body, gzipOutputStream); byte[] compressedBody = byteArrayOutputStream.toByteArray(); assertEquals( "Invalid content-length", response.getHeaders().getContentLength(), compressedBody.length); } finally { response.close(); } }
@RequestMapping(value = "/{id:.+}", method = GET) public void getFile(@PathVariable("id") String id, HttpServletResponse response) throws IOException { FileMeta fileMeta = dataService.findOne(FileMeta.ENTITY_NAME, id, FileMeta.class); if (fileMeta == null) { response.setStatus(HttpStatus.NOT_FOUND.value()); } else { java.io.File fileStoreFile = fileStore.getFile(fileMeta.getFilename()); // if file meta data exists for this file String outputFilename = fileMeta.getFilename(); String contentType = fileMeta.getContentType(); if (contentType != null) { response.setContentType(contentType); } Long size = fileMeta.getSize(); if (size != null) { response.setContentLength(size.intValue()); } response.setHeader( "Content-Disposition", "attachment; filename=" + outputFilename.replace(" ", "_")); InputStream is = new FileInputStream(fileStoreFile); try { FileCopyUtils.copy(is, response.getOutputStream()); } finally { is.close(); } } }
private File loadTestFile(String name) throws IOException { InputStream in = getClass().getResourceAsStream("/" + name); File f = File.createTempFile(name, "." + StringUtils.getFilenameExtension(name)); FileCopyUtils.copy(in, new FileOutputStream(f)); return f; }
/** * Copy the contents of the given byte array to the given output File. * * @param in the byte array to copy from * @param out the file to copy to * @throws IOException in case of I/O errors */ public static void copy(byte[] in, File out) throws IOException { Assert.notNull(in, "No input byte array specified"); Assert.notNull(out, "No output File specified"); ByteArrayInputStream inStream = new ByteArrayInputStream(in); OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out)); copy(inStream, outStream); }
@MediumTest public void testEchoNoContentLength() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod()); String headerName = "MyHeader"; String headerValue1 = "value1"; request.getHeaders().add(headerName, headerValue1); String headerValue2 = "value2"; request.getHeaders().add(headerName, headerValue2); byte[] body = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute(); try { assertNotNull(response.getStatusText()); assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); assertTrue("Header not found", response.getHeaders().containsKey(headerName)); assertEquals( "Header value not found", Arrays.asList(headerValue1, headerValue2), response.getHeaders().get(headerName)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertTrue("Invalid body", Arrays.equals(body, result)); } finally { response.close(); } }
public void copyGrailsResource(Object targetFile, Resource resource, boolean overwrite) throws FileNotFoundException, IOException { File file = new File(targetFile.toString()); if (overwrite || !file.exists()) { FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(file)); } }
@RequestMapping(value = "/ViewReports", method = RequestMethod.POST) public String prs( ModelMap model, HttpServletRequest request, HttpServletResponse response, @Valid CompanyReports CompanyName, BindingResult result) { if (result.hasErrors()) { System.out.println("sa"); model.addAttribute("up", "Please Check the Values Entered"); model.addAttribute("StockSearchHelper", new stocksearchhelper()); model.addAttribute("CompanyName", new CompanyReports()); List<stock> x = stockServiceInterface.liststock("NASDAQ"); List<stock> y = stockServiceInterface.liststock("NASDAQCOMPOSITE"); List<stock> z = stockServiceInterface.liststock("DOWJONES"); List<stock> a = stockServiceInterface.liststock("GOLD"); List<stock> b = stockServiceInterface.liststock("SANDP"); List<stock> c = stockServiceInterface.liststock("OIL"); model.addAttribute("NASDAQ", x.get(0).getPrice()); model.addAttribute("NASDAQCOMPOSITE", y.get(0).getPrice()); model.addAttribute("DOWJONES", z.get(0).getPrice()); model.addAttribute("GOLD", a.get(0).getPrice()); model.addAttribute("SANDP", b.get(0).getPrice()); model.addAttribute("OIL", c.get(0).getPrice()); List<TopPerformers> opds1 = topPerformerServiceInterface.liststock(); model.addAttribute("first", opds1.get(0).getTickerCode()); model.addAttribute("second", opds1.get(1).getTickerCode()); model.addAttribute("third", opds1.get(2).getTickerCode()); model.addAttribute("fourth", opds1.get(3).getTickerCode()); return "ClientHome"; } else { System.out.println("saa"); String cn = CompanyName.getCompanyName(); // String // s="C:"+File.separator+"Users"+File.separator+"nisha"+File.separator+"Desktop"+File.separator+"New folder (6)"+File.separator+".metadata"+File.separator+".plugins"+File.separator+"org.eclipse.wst.server.core"+File.separator+"tmp1"+File.separator+"wtpwebapps"+File.separator+"Project"+File.separator+"images"+File.separator; String s = request.getRealPath("") + File.separator; String e = s + CompanyName.getCompanyName() + ".pdf"; File files = new File(e); response.setContentType("application/pdf"); // in my example this was an xls file response.setContentLength(new Long(files.length()).intValue()); response.setHeader("Content-Disposition", "attachment; filename=MyFile.pdf"); try { FileCopyUtils.copy(new FileInputStream(files), response.getOutputStream()); } catch (IOException es) { es.printStackTrace(); } // return "redirect:/Client/viewmyaccount"; return "redirect:/success"; } }
@MediumTest public void testMultipleWrites() throws Exception { boolean success = false; try { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); byte[] body = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute(); try { FileCopyUtils.copy(body, request.getBody()); } finally { response.close(); } } catch (IllegalStateException e) { success = true; } assertTrue("Expected IllegalStateException", success); }
private void echo(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); for (Enumeration<?> e1 = request.getHeaderNames(); e1.hasMoreElements(); ) { String headerName = (String) e1.nextElement(); for (Enumeration<?> e2 = request.getHeaders(headerName); e2.hasMoreElements(); ) { String headerValue = (String) e2.nextElement(); response.addHeader(headerName, headerValue); } } FileCopyUtils.copy(request.getInputStream(), response.getOutputStream()); }
@RequestMapping(value = "/hello/upload", method = RequestMethod.POST) public String upload(@RequestParam(value = "file") MultipartFile file, RedirectAttributes flash) throws IOException { if (!file.isEmpty()) { FileCopyUtils.copy(file.getBytes(), new File(file.getOriginalFilename() + ".pdf")); } else { flash.addFlashAttribute("error", "Error: the file is empty"); } return "redirect:/hello"; }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { byte[] body = "gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip " .getBytes("UTF-8"); resp.setStatus(HttpServletResponse.SC_OK); if (containsHeader(req, "Accept-Encoding", "gzip")) { resp.addHeader("Content-Encoding", "gzip"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(body.length); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream); FileCopyUtils.copy(body, gzipOutputStream); byte[] compressedBody = byteArrayOutputStream.toByteArray(); FileCopyUtils.copy(compressedBody, resp.getOutputStream()); resp.addHeader("Content-Length", String.valueOf(compressedBody.length)); } else { FileCopyUtils.copy(body, resp.getOutputStream()); resp.addHeader("Content-Length", String.valueOf(body.length)); } }
public File save(byte[] bytes, String targetPath) { File target = new File(globalVars.fileSystemRoot, targetPath); try { Files.createParentDirs(target); FileCopyUtils.copy(bytes, target); return target; } catch (IOException e) { LOG.error(e.getMessage(), e); throw new RuntimeException(e); } }
@Test public void jarFileWithScriptAtTheStart() throws Exception { File file = this.temporaryFolder.newFile(); InputStream sourceJarContent = new FileInputStream(this.rootJarFile); FileOutputStream outputStream = new FileOutputStream(file); StreamUtils.copy("#/bin/bash", Charset.defaultCharset(), outputStream); FileCopyUtils.copy(sourceJarContent, outputStream); this.rootJarFile = file; this.jarFile = new JarFile(file); // Call some other tests to verify getEntries(); getNestedJarFile(); }
/** * ************************************************* URL: /rest/controller/get/{value} get(): get * file as an attachment * * @param response : passed by the server * @param value : value from the URL * @return void ************************************************** */ @RequestMapping(value = "/get/{value}", method = RequestMethod.GET) public void get(HttpServletResponse response, @PathVariable String value) { FileMeta getFile = files.get(Integer.parseInt(value)); try { response.setContentType(getFile.getFileType()); response.setHeader( "Content-disposition", "attachment; filename=\"" + getFile.getFileName() + "\""); FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private ByteArrayOutputStream getAsByteArrayOutputStream(boolean skipBOM) { try { InputStream in = doGetDataAsInputStream(skipBOM); if (in == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); FileCopyUtils.copy(in, out); return out; } catch (IOException e) { return null; } }
private TFile getFile(String extension, String location) { File file = TempFileProvider.createTempFile("moduleManagementToolTest-", extension); InputStream is = this.getClass().getClassLoader().getResourceAsStream(location); assertNotNull(is); OutputStream os; try { os = new FileOutputStream(file); FileCopyUtils.copy(is, os); } catch (IOException error) { error.printStackTrace(); } return new TFile(file); }