Java Code Examples for org.apache.tomcat.util.http.fileupload.IOUtils

The following examples show how to use org.apache.tomcat.util.http.fileupload.IOUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private SysAttachMediaSizeVO getImageSize(InputStream inputStream) {
    try {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            return null;
        }
        SysAttachMediaSizeVO mediaSizeVO = new SysAttachMediaSizeVO();
        mediaSizeVO.setWidth(image.getWidth());
        mediaSizeVO.setHeight(image.getHeight());
        return mediaSizeVO;
    } catch (IOException e) {
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 2
Source Project: mPaaS   Source File: SysAttachTempUploadOperationService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 上传临时附件,并保存临时附件记录
 * @param uploadFunction 需要具体实现的文件上传逻辑
 * @return 生成的临时附件ID
 */
private String recordTempUpload(SysAttachUploadBaseVO uploadBaseVO, InputStream inputStream,
                                Function<InputStream, SysAttachUploadResultVO> uploadFunction) {
    try {
        // 执行文件上传
        SysAttachUploadResultVO uploadResultVO = uploadFunction.apply(inputStream);
        if (uploadResultVO == null) {
            return null;
        }
        // 保存attachFileTemp
        SysAttachFile attachFile = this.saveAttachFile(uploadBaseVO, uploadResultVO);

        // 保存attachTemp
        SysAttachMain attachTemp = this.saveAttachTemp(uploadBaseVO, attachFile);
        return attachTemp.getFdId();
    } catch (Exception e) {
        throw new KmssServiceException("sys-attach:sys.attach.msg.error.SysAttachWriteFailed", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 3
Source Project: chaos-proxy   Source File: ChaosController.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void copyProxyResponseToServletResponse(HttpServletResponse response, byte[] bodyString, HttpHeaders proxyResponseHeaders, int proxyResponseStatusCode) throws IOException
{
    if (proxyResponseHeaders != null)
    {
        proxyResponseHeaders.forEach((headerName, value) -> {
            if (shouldCopyResponseHeader(headerName))
            {
                response.addHeader(headerName, String.join(",", value));
            }
        });
    }

    response.setStatus(proxyResponseStatusCode);
    if (bodyString != null)
    {
        IOUtils.copy(new ByteArrayInputStream(bodyString), response.getOutputStream());
    }
}
 
Example 4
Source Project: xechat   Source File: SensitiveWordUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 读取敏感词
 */
private static void readSensitiveWords() {
    keyWords = new HashSet<>();
    BufferedReader reader = null;

    try {
        reader = new BufferedReader(new InputStreamReader(SensitiveWordUtils.class
                .getResourceAsStream("/sensitive-word.txt"), "utf-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            keyWords.add(line.trim());
        }
    } catch (Exception e) {
        log.error("读取敏感词库出现异常! error -> {}", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}
 
Example 5
Source Project: jeecg-boot   Source File: MinioController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 下载minio服务的文件
 *
 * @param response
 * @return
 */
@GetMapping("download")
public String download(HttpServletResponse response) {
    try {
        MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
        InputStream fileInputStream = minioClient.getObject(bucketName, "11.jpg");
        response.setHeader("Content-Disposition", "attachment;filename=" + "11.jpg");
        response.setContentType("application/force-download");
        response.setCharacterEncoding("UTF-8");
        IOUtils.copy(fileInputStream, response.getOutputStream());
        return "下载完成";
    } catch (Exception e) {
        e.printStackTrace();
        return "下载失败";
    }
}
 
Example 6
Source Project: onetwo   Source File: TomcatConfig.java    License: Apache License 2.0 6 votes vote down vote up
public static Properties load(String srcpath){
	Properties config = new Properties();
	try {
		config = loadProperties(srcpath);
	} catch (Exception e) {
		InputStream in = null;
		try {
			in = TomcatConfig.class.getResourceAsStream(srcpath);
			if(in==null)
				throw new RuntimeException("can load resource as stream with : " +srcpath );
			config.load(in);
		} catch (Exception e1) {
			throw new RuntimeException("load config error: " + srcpath, e);
		} finally{
			IOUtils.closeQuietly(in);
		}
	}
	return config;
}
 
Example 7
Source Project: Tomcat8-Source-Read   Source File: Streams.java    License: MIT License 5 votes vote down vote up
/**
 * Copies the contents of the given {@link InputStream}
 * to the given {@link OutputStream}.
 *
 * @param inputStream The input stream, which is being read.
 *   It is guaranteed, that {@link InputStream#close()} is called
 *   on the stream.
 * @param outputStream The output stream, to which data should
 *   be written. May be null, in which case the input streams
 *   contents are simply discarded.
 * @param closeOutputStream True guarantees, that {@link OutputStream#close()}
 *   is called on the stream. False indicates, that only
 *   {@link OutputStream#flush()} should be called finally.
 * @param buffer Temporary buffer, which is to be used for
 *   copying data.
 * @return Number of bytes, which have been copied.
 * @throws IOException An I/O error occurred.
 */
public static long copy(InputStream inputStream,
        OutputStream outputStream, boolean closeOutputStream,
        byte[] buffer)
throws IOException {
    OutputStream out = outputStream;
    InputStream in = inputStream;
    try {
        long total = 0;
        for (;;) {
            int res = in.read(buffer);
            if (res == -1) {
                break;
            }
            if (res > 0) {
                total += res;
                if (out != null) {
                    out.write(buffer, 0, res);
                }
            }
        }
        if (out != null) {
            if (closeOutputStream) {
                out.close();
            } else {
                out.flush();
            }
            out = null;
        }
        in.close();
        in = null;
        return total;
    } finally {
        IOUtils.closeQuietly(in);
        if (closeOutputStream) {
            IOUtils.closeQuietly(out);
        }
    }
}
 
Example 8
Source Project: ticket   Source File: CaptchaImageForPy.java    License: GNU General Public License v3.0 5 votes vote down vote up
public String check(String base64String) {
    String filename = UUID.randomUUID() + ".jpg";
    File folder = new File("temp");
    if (!folder.exists()) {
        folder.mkdirs();
    }
    File file = new File(folder, filename);
    try {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] data = decoder.decodeBuffer(base64String);
        IOUtils.copy(new ByteArrayInputStream(data), new FileOutputStream(file));
        Runtime runtime = Runtime.getRuntime();
        String os = System.getProperty("os.name");
        Process process;
        if (os.toLowerCase().startsWith("win")) {
            String[] cmd = new String[]{"cmd", "/c", "cd python  &  set PYTHONIOENCODING=UTF-8 & python main.py " + "..\\temp\\" + filename};
            process = runtime.exec(cmd);
        } else {
            String bash = System.getProperty("user.dir") + "/" + config.getPythonPath() + "/run.sh " + System.getProperty("user.dir") + "/temp/" + filename;
            process = runtime.exec(bash);
        }
        process.waitFor();
        InputStream inputStream = process.getInputStream();
        String r = this.get(inputStream);
        if(StringUtils.isEmpty(r)){
            inputStream = process.getErrorStream();
            r = this.get(inputStream);
        }
        return r;
    } catch (Exception e) {
        log.error("", e);
        return "系统出错,联系QQ:960339491";
    } finally {
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }
}
 
Example 9
Source Project: mPaaS   Source File: FileToBytesService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将文件写入到byte数组
 */
default byte[] writeFileToBytes(File file) {
    try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        IOUtils.copy(bis, bos);
        bos.flush();
        return bos.toByteArray();
    } catch (IOException e) {
        throw new KmssServiceException("errors.fileOperationException", e);
    }
}
 
Example 10
Source Project: mPaaS   Source File: SysAttachServerProxy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeFile(InputStream inputSream, String filePath, Map<String, String> header) {
    // 当服务器上面不存在附件文件时候,分别构建输入,输出流
    File file = new File(filePath);
    File pfile = file.getParentFile();
    if (!pfile.exists()) {
        pfile.mkdirs();
    }
    if (file.exists()) {
        file.delete();
    }
    FileOutputStream fileOutputStream = null;
    InputStream encryptionInputStream = null;
    try {
        file.createNewFile();
        fileOutputStream = new FileOutputStream(file);

        // 进行附件文件写操作
        encryptionInputStream = getEncryService().initEncryInputStream(inputSream);
        IOUtils.copy(encryptionInputStream, fileOutputStream);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 附件写操作完成后,依次关闭输出流和输入流,释放输出,输入流所在内存空间
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(encryptionInputStream);
        IOUtils.closeQuietly(inputSream);
    }
}
 
Example 11
Source Project: mPaaS   Source File: SysAttachServerProxy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void appendFile(InputStream inputSream, String filePath, long position, Map<String, String> header) {
    if (position == 0) {
        this.writeFile(inputSream, filePath, header);
        return;
    }

    // 当服务器上面不存在附件文件时候,抛异常
    File file = new File(filePath);
    if (!file.exists()) {
        throw new KmssRuntimeException("sys-attach:sys.attach.msg.error.SysAttachFileNotFound");
    }
    RandomAccessFile randomFile = null;
    InputStream encryptionInputStream = null;
    try {
        randomFile = new RandomAccessFile(file, "rw");
        randomFile.seek(position);

        // 进行附件文件写操作
        encryptionInputStream = getEncryService().initEncryInputStream(inputSream);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(encryptionInputStream, baos);
        randomFile.write(baos.toByteArray());
    } catch (IOException e) {
        throw new KmssRuntimeException("sys-attach:sys.attach.msg.error.SysAttachFileAppendFailed", e);
    } finally {
        // 附件写操作完成后,依次关闭输出流和输入流,释放输出,输入流所在内存空间
        IOUtils.closeQuietly(randomFile);
        IOUtils.closeQuietly(encryptionInputStream);
        IOUtils.closeQuietly(inputSream);
    }
}
 
Example 12
Source Project: openapi-petstore   Source File: PetApiDelegateImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<ModelApiResponse> uploadFile(Long petId, String additionalMetadata, MultipartFile file) {
    try {
        String uploadedFileLocation = "./" + file.getName();
        System.out.println("uploading to " + uploadedFileLocation);
        IOUtils.copy(file.getInputStream(), new FileOutputStream(uploadedFileLocation));
        String msg = String.format("additionalMetadata: %s\nFile uploaded to %s, %d bytes", additionalMetadata, uploadedFileLocation, (new File(uploadedFileLocation)).length());
        ModelApiResponse output = new ModelApiResponse().code(200).message(msg);
        return ResponseEntity.ok(output);
    }
    catch (Exception e) {
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Couldn't upload file", e);
    }
}
 
Example 13
Source Project: dubbox   Source File: HomePageUI.java    License: Apache License 2.0 5 votes vote down vote up
private FileResource getFileResource(String path,String type){
    InputStream inputStream = null;
    try {
        ClassPathResource resource = new ClassPathResource(path);
        inputStream = resource.getInputStream();
        File tempFile = File.createTempFile("ds_" + System.currentTimeMillis(), type);
        FileUtils.copyInputStreamToFile(inputStream, tempFile);
        return new FileResource(tempFile);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 14
Source Project: tomcatsrc   Source File: Streams.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Copies the contents of the given {@link InputStream}
 * to the given {@link OutputStream}.
 *
 * @param inputStream The input stream, which is being read.
 *   It is guaranteed, that {@link InputStream#close()} is called
 *   on the stream.
 * @param outputStream The output stream, to which data should
 *   be written. May be null, in which case the input streams
 *   contents are simply discarded.
 * @param closeOutputStream True guarantees, that {@link OutputStream#close()}
 *   is called on the stream. False indicates, that only
 *   {@link OutputStream#flush()} should be called finally.
 * @param buffer Temporary buffer, which is to be used for
 *   copying data.
 * @return Number of bytes, which have been copied.
 * @throws IOException An I/O error occurred.
 */
public static long copy(InputStream inputStream,
        OutputStream outputStream, boolean closeOutputStream,
        byte[] buffer)
throws IOException {
    OutputStream out = outputStream;
    InputStream in = inputStream;
    try {
        long total = 0;
        for (;;) {
            int res = in.read(buffer);
            if (res == -1) {
                break;
            }
            if (res > 0) {
                total += res;
                if (out != null) {
                    out.write(buffer, 0, res);
                }
            }
        }
        if (out != null) {
            if (closeOutputStream) {
                out.close();
            } else {
                out.flush();
            }
            out = null;
        }
        in.close();
        in = null;
        return total;
    } finally {
        IOUtils.closeQuietly(in);
        if (closeOutputStream) {
            IOUtils.closeQuietly(out);
        }
    }
}
 
Example 15
Source Project: dubbo-switch   Source File: HomePageUI.java    License: Apache License 2.0 5 votes vote down vote up
private FileResource getFileResource(String path,String type){
    InputStream inputStream = null;
    try {
        ClassPathResource resource = new ClassPathResource(path);
        inputStream = resource.getInputStream();
        File tempFile = File.createTempFile("ds_" + System.currentTimeMillis(), type);
        FileUtils.copyInputStreamToFile(inputStream, tempFile);
        return new FileResource(tempFile);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 16
Source Project: full-teaching   Source File: FileController.java    License: Apache License 2.0 5 votes vote down vote up
private void productionFileDownloader(String fileName, HttpServletResponse response) {
String bucketName = this.bucketAWS + "/files";
      try {
          System.out.println("Downloading an object");
          S3Object s3object = this.amazonS3.getObject(new GetObjectRequest(bucketName, fileName));
          System.out.println("Content-Type: "  + s3object.getObjectMetadata().getContentType());
          
          if (s3object != null) {
  			try {
  				String fileExt = this.getFileExtension(fileName);
  				response.setContentType(MimeTypes.getMimeType(fileExt));
  				InputStream objectData = s3object.getObjectContent();
  				IOUtils.copy(objectData, response.getOutputStream());
  				response.flushBuffer();
  				objectData.close();
  			} catch (IOException ex) {
  				throw new RuntimeException("IOError writing file to output stream");
  			}
  		}
          
      } catch (AmazonServiceException ase) {
          System.out.println("Caught an AmazonServiceException, which" +
          		" means your request made it " +
                  "to Amazon S3, but was rejected with an error response" +
                  " for some reason.");
          System.out.println("Error Message:    " + ase.getMessage());
          System.out.println("HTTP Status Code: " + ase.getStatusCode());
          System.out.println("AWS Error Code:   " + ase.getErrorCode());
          System.out.println("Error Type:       " + ase.getErrorType());
          System.out.println("Request ID:       " + ase.getRequestId());
      } catch (AmazonClientException ace) {
          System.out.println("Caught an AmazonClientException, which means"+
          		" the client encountered " +
                  "an internal error while trying to " +
                  "communicate with S3, " +
                  "such as not being able to access the network.");
          System.out.println("Error Message: " + ace.getMessage());
      }
  }
 
Example 17
Source Project: crate-sample-apps   Source File: ImagesController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/image/{digest}", method = RequestMethod.GET)
public void getImageAsByteArray(HttpServletResponse response, @PathVariable String digest) throws IOException {
    logger.debug("Downloading image with digest " + digest);
    if (dao.imageExists(digest)) {
        InputStream in = dao.getImageAsInputStream(digest);
        response.setContentType(MediaType.IMAGE_GIF_VALUE);
        IOUtils.copy(in, response.getOutputStream());
    } else {
        throw new ImageNotExistsException(digest);
    }
}
 
Example 18
Source Project: spring-microservice-boilerplate   Source File: RequestWrapper.java    License: MIT License 5 votes vote down vote up
private void cacheInputStream() throws IOException {
  /* Cache the inputstream in order to read it multiple times. For
   * convenience, I use apache.commons IOUtils
   */
  cachedBytes = new ByteArrayOutputStream();
  IOUtils.copy(super.getInputStream(), cachedBytes);
}
 
Example 19
Source Project: Tomcat8-Source-Read   Source File: TestVirtualContext.java    License: MIT License 4 votes vote down vote up
@Test
public void testAdditionalWebInfClassesPaths() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-virtual-webapp/src/main/webapp");
    // app dir is relative to server home
    StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test",
        appDir.getAbsolutePath());
    File tempFile = File.createTempFile("virtualWebInfClasses", null);

    File additionWebInfClasses = new File(tempFile.getAbsolutePath() + ".dir");
    Assert.assertTrue(additionWebInfClasses.mkdirs());
    File targetPackageForAnnotatedClass =
        new File(additionWebInfClasses,
            MyAnnotatedServlet.class.getPackage().getName().replace('.', '/'));
    Assert.assertTrue(targetPackageForAnnotatedClass.mkdirs());
    try (InputStream annotatedServletClassInputStream = this.getClass().getResourceAsStream(
            MyAnnotatedServlet.class.getSimpleName() + ".class");
            FileOutputStream annotatedServletClassOutputStream = new FileOutputStream(new File(
                    targetPackageForAnnotatedClass, MyAnnotatedServlet.class.getSimpleName()
                            + ".class"));) {
        IOUtils.copy(annotatedServletClassInputStream, annotatedServletClassOutputStream);
    }

    ctx.setResources(new StandardRoot(ctx));
    File f1 = new File("test/webapp-virtual-webapp/target/classes");
    File f2 = new File("test/webapp-virtual-library/target/WEB-INF/classes");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f1.getAbsolutePath(), null, "/");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f2.getAbsolutePath(), null, "/");

    tomcat.start();
    // first test that without the setting on StandardContext the annotated
    // servlet is not detected
    assertPageContains("/test/annotatedServlet", MyAnnotatedServlet.MESSAGE, 404);

    tomcat.stop();

    // then test that if we configure StandardContext with the additional
    // path, the servlet is detected
    ctx.setResources(new StandardRoot(ctx));
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f1.getAbsolutePath(), null, "/");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            f2.getAbsolutePath(), null, "/");
    ctx.getResources().createWebResourceSet(
            WebResourceRoot.ResourceSetType.POST, "/WEB-INF/classes",
            additionWebInfClasses.getAbsolutePath(), null, "/");

    tomcat.start();
    assertPageContains("/test/annotatedServlet", MyAnnotatedServlet.MESSAGE);
    tomcat.stop();
    FileUtils.deleteDirectory(additionWebInfClasses);
    Assert.assertTrue("Failed to clean up [" + tempFile + "]", tempFile.delete());
}
 
Example 20
Source Project: mPaaS   Source File: SysAttachMainUploadOperationService.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * API上传附件,并保存附件记录
 * @param uploadFunction 需要具体实现的文件上传逻辑
 * @return 生成的附件ID
 */
private String recordBytesUpload(SysAttachUploadBaseVO uploadBaseVO, InputStream inputStream, String entityId, String entityKey,
                                 Function<InputStream, SysAttachUploadResultVO> uploadFunction) {
    try {
        // 从已有文件中查找相同文件
        SysAttachFile sameFile = sysAttachFileService.findExistedSameFile(uploadBaseVO.getFdMd5(),
                uploadBaseVO.getFdFileSize(), uploadBaseVO.getFdFileName(), uploadBaseVO.getFdFileExtName());
        SysAttachFile attachFile;
        if (sameFile != null) {
            // 若有相同文件则使用相同文件
            attachFile = sameFile;
        } else {
            // 没有则上传新文件
            SysAttachUploadResultVO uploadResultVO = uploadFunction.apply(inputStream);
            if (uploadResultVO == null) {
                return null;
            }

            // 保存attachFile
            attachFile = new SysAttachFile();
            attachFile.setFdId(uploadResultVO.getFileId());
            attachFile.setFdFileName(uploadBaseVO.getFdFileName());
            attachFile.setFdFileExtName(uploadBaseVO.getFdFileExtName());
            attachFile.setFdFileSize(uploadBaseVO.getFdFileSize());
            attachFile.setFdMd5(uploadBaseVO.getFdMd5());
            attachFile.setFdFilePath(uploadResultVO.getFilePath());
            attachFile.setFdTenantId(TenantUtil.getTenantId());
            attachFile.setFdCreatorId(uploadBaseVO.getFdCreatorId());
            attachFile.setFdStatus(AttachStatusEnum.VALID);
            attachFile.setFdEncryptMethod(sysAttachConfig.getCurrentEncryMethod());
            attachFile.setFdLocation(sysAttachStoreService.getDefaultStoreLocation());
            attachFile.setFdSysAttachCatalog(uploadResultVO.getSysAttachCatalog());
            attachFile.setFdSysAttachModuleLocation(uploadResultVO.getSysAttachModuleLocation());
            // TODO 如果是媒体,获取媒体宽高帧率
            SysAttachMediaSizeVO mediaSizeVO = this.getMediaSize(uploadBaseVO.getFdFileExtName(), uploadResultVO.getFullPath());
            if (mediaSizeVO != null) {
                attachFile.setFdWidth(mediaSizeVO.getWidth());
                attachFile.setFdHeight(mediaSizeVO.getHeight());
            }
            sysAttachFileService.add(attachFile);
        }

        // 获取临时文件过期时间配置
        SysAttachConfigVO configVO = applicationConfig.get(SysAttachConfigVO.class);
        Integer overdueSeconds = configVO != null ? configVO.getTempOverdueSeconds() : SysAttachConstant.ATTACH_TEMP_OVERDUE_SECONDS_DEFAULT;
        long overdueMillis = overdueSeconds * 1000L;

        // 生成attachMain
        String attachId = IDGenerator.generateID();
        SysAttachMain attachMainTemp = new SysAttachMain();
        // 关联已有文件或新创建的文件
        attachMainTemp.setFdId(attachId);
        attachMainTemp.setFdSysAttachFile(attachFile);
        attachMainTemp.setFdFileName(attachFile.getFdFileName());
        attachMainTemp.setFdFileExtName(attachFile.getFdFileExtName());
        attachMainTemp.setFdFileSize(attachFile.getFdFileSize());
        attachMainTemp.setFdCreatorId(attachFile.getFdCreatorId());
        attachMainTemp.setFdLastModifier(attachFile.getFdLastModifier());
        attachMainTemp.setFdEntityName(uploadBaseVO.getFdEntityName());
        attachMainTemp.setFdTenantId(TenantUtil.getTenantId());
        attachMainTemp.setFdMimeType(MimeTypeUtil.getMimeType(attachFile.getFdFileName() + NamingConstant.DOT + attachFile.getFdFileExtName()));
        attachMainTemp.setFdStatus(AttachStatusEnum.VALID);
        attachMainTemp.setFdEffectType(AttachEffectTypeEnum.TRANSIENT);
        attachMainTemp.setFdExpirationTime(new Timestamp(System.currentTimeMillis() + overdueMillis));
        attachMainTemp.setFdExtendInfo(uploadBaseVO.getFdExtendInfo());
        attachMainTemp.setFdWidth(attachFile.getFdWidth());
        attachMainTemp.setFdHeight(attachFile.getFdHeight());
        attachMainTemp.setFdAnonymous(uploadBaseVO.getFdAnonymous());
        sysAttachService.add(attachMainTemp);
        return attachId;
    } catch (Exception e) {
        throw new KmssServiceException("sys-attach:sys.attach.msg.error.SysAttachWriteFailed", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 21
Source Project: Tomcat7.0.67   Source File: TestVirtualContext.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testAdditionalWebInfClassesPaths() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0-virtual-webapp/src/main/webapp");
    // app dir is relative to server home
    StandardContext ctx = (StandardContext) tomcat.addWebapp(null, "/test",
        appDir.getAbsolutePath());
    File tempFile = File.createTempFile("virtualWebInfClasses", null);

    File additionWebInfClasses = new File(tempFile.getAbsolutePath() + ".dir");
    Assert.assertTrue(additionWebInfClasses.mkdirs());
    File targetPackageForAnnotatedClass =
        new File(additionWebInfClasses,
            MyAnnotatedServlet.class.getPackage().getName().replace('.', '/'));
    Assert.assertTrue(targetPackageForAnnotatedClass.mkdirs());
    InputStream annotatedServletClassInputStream =
        this.getClass().getResourceAsStream(
            MyAnnotatedServlet.class.getSimpleName() + ".class");
    FileOutputStream annotatedServletClassOutputStream =
        new FileOutputStream(new File(targetPackageForAnnotatedClass,
            MyAnnotatedServlet.class.getSimpleName() + ".class"));
    IOUtils.copy(annotatedServletClassInputStream, annotatedServletClassOutputStream);
    annotatedServletClassInputStream.close();
    annotatedServletClassOutputStream.close();

    VirtualWebappLoader loader = new VirtualWebappLoader(ctx.getParentClassLoader());
    loader.setVirtualClasspath("test/webapp-3.0-virtual-webapp/target/classes;" + //
        "test/webapp-3.0-virtual-library/target/classes;" + //
        additionWebInfClasses.getAbsolutePath());
    ctx.setLoader(loader);

    tomcat.start();
    // first test that without the setting on StandardContext the annotated
    // servlet is not detected
    assertPageContains("/test/annotatedServlet", MyAnnotatedServlet.MESSAGE, 404);

    tomcat.stop();

    // then test that if we configure StandardContext with the additional
    // path, the servlet is detected
    // ctx.setAdditionalVirtualWebInfClasses(additionWebInfClasses.getAbsolutePath());
    VirtualDirContext resources = new VirtualDirContext();
    resources.setExtraResourcePaths("/WEB-INF/classes=" + additionWebInfClasses);
    ctx.setResources(resources);

    tomcat.start();
    assertPageContains("/test/annotatedServlet", MyAnnotatedServlet.MESSAGE);
    tomcat.stop();
    FileUtils.deleteDirectory(additionWebInfClasses);
    tempFile.delete();
}
 
Example 22
Source Project: kurento-java   Source File: BaseRepositoryTest.java    License: Apache License 2.0 3 votes vote down vote up
protected void uploadFileWithPOST(String uploadURL, File fileToUpload)
    throws FileNotFoundException, IOException {

  RestTemplate client = getRestTemplate();

  ByteArrayOutputStream fileBytes = new ByteArrayOutputStream();
  IOUtils.copy(new FileInputStream(fileToUpload), fileBytes);

  ResponseEntity<String> entity = postWithRetries(uploadURL, client, fileBytes.toByteArray());

  log.debug("Upload response");

  assertEquals("Returned response: " + entity.getBody(), HttpStatus.OK, entity.getStatusCode());
}