private File createSampleJarFile() throws IOException {
   File file = this.temp.newFile("sample.jar");
   JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(file));
   jarOutputStream.putNextEntry(new ZipEntry(PACKAGE_PATH + "/Sample.class"));
   StreamUtils.copy(getClass().getResourceAsStream("Sample.class"), jarOutputStream);
   jarOutputStream.closeEntry();
   jarOutputStream.putNextEntry(new ZipEntry(PACKAGE_PATH + "/Sample.txt"));
   StreamUtils.copy("fromchild", UTF_8, jarOutputStream);
   jarOutputStream.closeEntry();
   jarOutputStream.close();
   return file;
 }
Ejemplo n.º 2
0
  @Test
  public void testDoFilterGzipResponseCompression() throws Exception {
    MockHttpServletRequest request =
        new MockHttpServletRequest(HttpMethod.POST.name(), "http://localhost:8080/gzip");
    request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");

    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain =
        new MockFilterChain(
            servlet,
            new GzipServletFilter(),
            new OncePerRequestFilter() {
              @Override
              protected void doFilterInternal(
                  HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                  throws ServletException, IOException {
                response.getOutputStream().write("Should be compressed".getBytes());
              }
            });
    filterChain.doFilter(request, response);

    ByteArrayOutputStream unzippedStream = new ByteArrayOutputStream();
    StreamUtils.copy(
        new GZIPInputStream(new ByteArrayInputStream(response.getContentAsByteArray())),
        unzippedStream);
    String unzipped = new String(unzippedStream.toByteArray());

    Assert.assertEquals(unzipped, "Should be compressed");
  }
Ejemplo n.º 3
0
 public String saveResource(InputStream data, String orginalName, int customerId, String folder)
     throws IOException {
   if (serverUri == null || resourceHome == null)
     throw new IllegalStateException("请设置micromall.resourcesUri和micromall.resourcesHome属性");
   FileOutputStream outputStream = null;
   String prefix = orginalName.substring(orginalName.lastIndexOf(".") + 1);
   Date now = new Date();
   String fileFolder = folder + customerId + "/" + StringUtil.DateFormat(now, "yyyyMMdd");
   String fileName = StringUtil.DateFormat(now, "yyyyMMddHHmmSS") + "." + prefix;
   try {
     File targetFile = new File(resourceHome + fileFolder, fileName);
     if (!targetFile.getParentFile().exists()) {
       targetFile.getParentFile().mkdirs();
     }
     outputStream = new FileOutputStream(targetFile);
     StreamUtils.copy(data, outputStream);
   } finally {
     try {
       data.close();
       outputStream.close();
     } catch (IOException e) {
     }
   }
   return fileFolder + "/" + fileName;
 }
 public void assertContent(String url, int port, Object expected) throws Exception {
   SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
   ClientHttpRequest request =
       clientHttpRequestFactory.createRequest(
           new URI("http://localhost:" + port + url), HttpMethod.GET);
   try {
     ClientHttpResponse response = request.execute();
     try {
       String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
       if (expected instanceof Matcher) {
         assertThat(actual).is(Matched.by((Matcher<?>) expected));
       } else {
         assertThat(actual).isEqualTo(expected);
       }
     } finally {
       response.close();
     }
   } catch (Exception ex) {
     if (expected == null) {
       if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) {
         return;
       }
     }
     throw ex;
   }
 }
 protected String getResponse(String url, String... headers)
     throws IOException, URISyntaxException {
   ClientHttpResponse response = getClientResponse(url, headers);
   try {
     return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
   } finally {
     response.close();
   }
 }
 @Test
 public void content() throws IOException {
   byte[] bytes = "body".getBytes(Charset.defaultCharset());
   request.setContent(bytes);
   assertEquals(bytes.length, request.getContentLength());
   assertNotNull(request.getInputStream());
   assertEquals(
       "body", StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset()));
 }
Ejemplo n.º 7
0
 @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();
 }
Ejemplo n.º 8
0
 private String getEmptyWebXml() {
   InputStream stream =
       TomcatEmbeddedServletContainerFactory.class.getResourceAsStream("empty-web.xml");
   Assert.state(stream != null, "Unable to read empty web.xml");
   try {
     try {
       return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
     } finally {
       stream.close();
     }
   } catch (IOException ex) {
     throw new IllegalStateException(ex);
   }
 }
 @RequestMapping(value = "/read/{oid}/downloadkeystore")
 public void processReadToDownloadKeystore(
     @PathVariable("oid") DomainKeyStore domainKeyStore, HttpServletResponse response) {
   InputStream is = domainKeyStore.getKeyStoreFile().getStream();
   response.setContentType("application/octet-stream");
   response.setHeader(
       "Content-disposition", "attachment; filename=" + domainKeyStore.getName() + ".jks");
   try {
     StreamUtils.copy(is, response.getOutputStream());
     response.flushBuffer();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 10
0
  @Autowired
  public HtmlController(Environment environment, ServletContext servletContext) throws IOException {
    this.environment = environment;

    ClassPathResource cp = new ClassPathResource("loader.css");
    String loadercss;
    try (InputStream is = cp.getInputStream()) {
      loadercss = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
    }

    cp = new ClassPathResource("index.template");
    String htmlTemplate;
    try (InputStream is = cp.getInputStream()) {
      htmlTemplate = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
    }

    this.indexHtml =
        htmlTemplate
            .replace("application.loader_css", loadercss)
            .replace("application.app_css", (String) servletContext.getAttribute("app_css"));

    this.appJs = (String) servletContext.getAttribute("app_js");
    this.loginJs = (String) servletContext.getAttribute("login_js");
  }
Ejemplo n.º 11
0
  public void createMappings() {
    try {

      File mappingsDir = new ClassPathResource("/elasticsearch/mappings", getClass()).getFile();
      for (final File fileEntry : mappingsDir.listFiles()) {
        String filenameBase = fileEntry.getName().replaceAll("\\.json$", "");
        String mappingJson =
            StreamUtils.copyToString(new FileInputStream(fileEntry), Charset.forName("UTF-8"));
        PutMapping.Builder mapping = new PutMapping.Builder(index, filenameBase, mappingJson);
        execute(mapping.build());
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 12
0
 @Test
 public void testHasAccess() throws Exception {
   String response =
       StreamUtils.copyToString(
           new ClassPathResource("voot/groups.json").getInputStream(), Charset.forName("UTF-8"));
   stubFor(
       get(urlEqualTo("/internal/groups/id1"))
           .willReturn(
               aResponse()
                   .withStatus(200)
                   .withHeader("Content-Type", "application/json")
                   .withBody(response)));
   List<String> groups = subject.groups("id1");
   assertEquals(14, groups.size());
   assertTrue(groups.stream().allMatch(group -> StringUtils.hasText(group)));
 }
 @Test
 public void testCompression() throws Exception {
   HttpHeaders requestHeaders = new HttpHeaders();
   requestHeaders.set("Accept-Encoding", "gzip");
   HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
   RestTemplate restTemplate = new TestRestTemplate();
   ResponseEntity<byte[]> entity =
       restTemplate.exchange(
           "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class);
   assertEquals(HttpStatus.OK, entity.getStatusCode());
   GZIPInputStream inflater = new GZIPInputStream(new ByteArrayInputStream(entity.getBody()));
   try {
     assertEquals("Hello World", StreamUtils.copyToString(inflater, Charset.forName("UTF-8")));
   } finally {
     inflater.close();
   }
 }
 private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, String resourcePath)
     throws Exception {
   SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
   ClientHttpRequest request =
       clientHttpRequestFactory.createRequest(
           new URI(
               "http://localhost:"
                   + context.getEmbeddedServletContainer().getPort()
                   + resourcePath),
           HttpMethod.GET);
   ClientHttpResponse response = request.execute();
   try {
     String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
     assertThat(actual).isEqualTo("Hello World");
   } finally {
     response.close();
   }
 }
Ejemplo n.º 15
0
  /**
   * Filters the given {@link Resource} by replacing values within.
   *
   * @param source must not be {@literal null}.
   * @param replacements
   * @return {@link Resource} with replaced values.
   * @throws IOException
   */
  public static Resource filterResource(Resource source, Map<String, ?> replacements)
      throws IOException {

    Assert.notNull(source, "Cannot filter 'null' resource");
    if (CollectionUtils.isEmpty(replacements)) {
      return source;
    }

    String temp = StreamUtils.copyToString(source.getInputStream(), UTF8);

    for (Map.Entry<String, ?> entry : replacements.entrySet()) {
      temp =
          StringUtils.replace(
              temp, entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : "");
    }

    return new ByteArrayResource(temp.getBytes(UTF8));
  }
 @Override
 public Object resolveEntity(String publicID, String systemID, String base, String ns) {
   return StreamUtils.emptyInput();
 }