@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(); } }
@Test public void testCopyToLocalMulti() throws Exception { String fName1 = UUID.randomUUID() + ".txt"; String name1 = "local/" + fName1; String fName2 = UUID.randomUUID() + ".txt"; String name2 = "local/" + fName2; File dir = new File("local"); dir.mkdir(); Resource res1 = TestUtils.writeToFS(cfg, name1); Resource res2 = TestUtils.writeToFS(cfg, name2); shell.copyToLocal(name1, "local"); shell.copyToLocal(false, true, name2, "local"); File fl1 = new File(name1); File fl2 = new File(name2); try { assertTrue(fl1.exists()); assertTrue(fl2.exists()); assertArrayEquals( FileCopyUtils.copyToByteArray(res1.getInputStream()), FileCopyUtils.copyToByteArray(fl1)); assertArrayEquals( FileCopyUtils.copyToByteArray(res2.getInputStream()), FileCopyUtils.copyToByteArray(fl2)); } finally { FileSystemUtils.deleteRecursively(dir); } }
@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(); } }
@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(); } }
@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 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 testCopyToLocal() throws Exception { String fName = UUID.randomUUID() + ".txt"; String name = "local/" + fName; Resource res = TestUtils.writeToFS(cfg, name); shell.copyToLocal(name, "."); File fl = new File(fName); try { assertTrue(fl.exists()); assertArrayEquals( FileCopyUtils.copyToByteArray(res.getInputStream()), FileCopyUtils.copyToByteArray(fl)); } finally { fl.delete(); } }
public int doEndTag() throws JspException { try { List<ValidationMetaData> rules = new ArrayList<ValidationMetaData>(); if (commandName != null) { rules.addAll(getValidationMetaDataForCommand()); } String bodyString = null; if (bodyContent != null) { // body can be a JSON object, specifying date formats, or other extra configuration info bodyString = FileCopyUtils.copyToString(bodyContent.getReader()); bodyString = bodyString.trim().replaceAll("\\s{2,}", " "); } JspWriter out = pageContext.getOut(); out.write("<script type=\"text/javascript\" id=\""); out.write(commandName + "JSR303JSValidator"); out.write("\">"); generator.generateJavaScript( out, commandName, true, bodyString, rules, new MessageSourceAccessor( getRequestContext().getWebApplicationContext(), getRequestContext().getLocale())); out.write("</script>"); return EVAL_PAGE; } catch (IOException e) { throw new JspException("Could not write validation rules", e); } }
@Override protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { MediaType contentType = inputMessage.getHeaders().getContentType(); Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET; return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset)); }
@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)); }
/** * 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 String getResourceString(String str) { try { return FileCopyUtils.copyToString(new InputStreamReader(getClass().getResourceAsStream(str))); } catch (IOException e) { } return null; }
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; }
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 = "/{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; }
@RequestMapping(value = "/handle44/{imageId}") public ResponseEntity<byte[]> handle44(@PathVariable("imageId") String imageId) throws Throwable { Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(fileData, HttpStatus.OK); return responseEntity; }
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; }
@Override protected void doPost(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, "Content-Encoding", "gzip")) { GZIPInputStream gzipInputStream = new GZIPInputStream(req.getInputStream()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int byteCount = 0; byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = gzipInputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); byteCount += bytesRead; } byteArrayOutputStream.flush(); gzipInputStream.close(); assertEquals("Content length does not match", body.length, byteCount); assertTrue("Invalid body", Arrays.equals(byteArrayOutputStream.toByteArray(), body)); } else { byte[] decompressedBody = FileCopyUtils.copyToByteArray(req.getInputStream()); assertTrue("Invalid body", Arrays.equals(decompressedBody, body)); } }
@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()); }
@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(); } } }
/** * 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); }
protected XmlModel assertRoutes(File file, int expected, String ns) throws Exception { if (ns == null || ns.trim().length() == 0) { ns = CamelNamespaces.springNS; } XmlModel x = assertLoadModel(file, expected); // now lets add a route and write it back again... DefaultCamelContext tmpContext = new DefaultCamelContext(); tmpContext.addRoutes( new RouteBuilder() { @Override public void configure() throws Exception { from("seda:newFrom").to("seda:newTo"); } }); x.getContextElement().getRoutes().addAll(tmpContext.getRouteDefinitions()); List<RouteDefinition> routes = x.getRouteDefinitionList(); assertEquals("routes: " + routes, expected + 1, routes.size()); // now lets write to XML model outDir.mkdirs(); File outFile = new File(outDir, file.getName()); System.out.println("Generating file: " + outFile); tool.marshal(outFile, x); assertFileExists(outFile); // lets check the file has the correct namespace inside it String text = FileCopyUtils.copyToString(new FileReader(outFile)); assertTrue("Namespace " + ns + " not present in output file\n" + text, text.contains(ns)); return x; }
@Test public void testGetMergeWithNewLine() throws Exception { String fName1 = UUID.randomUUID() + ".txt"; String name1 = "local/merge/" + fName1; TestUtils.writeToFS(cfg, name1); String fName2 = UUID.randomUUID() + ".txt"; String name2 = "local/merge/" + fName2; TestUtils.writeToFS(cfg, name2); File dir = new File("local"); dir.mkdir(); String localName = "local/merge.txt"; File fl1 = new File(localName); try { shell.getmerge("local/merge/", localName, true); assertTrue(fl1.exists()); String content = FileCopyUtils.copyToString(new FileReader(fl1)); assertTrue(content.contains(name1 + "\n")); assertTrue(content.contains(name2)); assertEquals(content.length(), name1.length() + name2.length() + 2); } finally { FileSystemUtils.deleteRecursively(dir); } }
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); } }
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)); } }
@Test public void createPidFile() throws Exception { File file = this.temporaryFolder.newFile(); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); listener.onApplicationEvent(EVENT); assertThat(FileCopyUtils.copyToString(new FileReader(file)), not(isEmptyString())); }
@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 + ""; }
private void saveFileToLocalDisk(MultipartFile multipartFile) throws IOException, FileNotFoundException { String outputFileName = getOutputFilename(multipartFile); FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName)); }
@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"; } }