protected String check(Blob blob, String targetExt) throws Exception {
   assertNotNull(blob);
   ImageMagickCaller imc =
       new ImageMagickCaller() {
         @Override
         public void callImageMagick() {
           return;
         }
       };
   try {
     imc.makeFiles(blob, targetExt);
     return "src="
         + FilenameUtils.getExtension(imc.sourceFile.getName())
         + " dst="
         + FilenameUtils.getExtension(imc.targetFile.getName())
         + " tmp="
         + FilenameUtils.getExtension(imc.tmpFile == null ? "" : imc.tmpFile.getName());
   } finally {
     if (imc.targetFile != null) {
       imc.targetFile.delete();
     }
     if (imc.tmpFile != null) {
       imc.tmpFile.delete();
     }
   }
 }
Exemple #2
0
 private String getContentType(HttpRequest request, Path resource) {
   String extensionFromUri = FilenameUtils.getExtension(request.getUriWithoutContextPath());
   Optional<String> contentType = MimeMapper.getMimeType(extensionFromUri);
   if (contentType.isPresent()) {
     return contentType.get();
   }
   // Here 'resource' never null, thus 'FilenameUtils.getExtension(...)' never return null.
   String extensionFromPath = FilenameUtils.getExtension(resource.getFileName().toString());
   return MimeMapper.getMimeType(extensionFromPath).orElse(CONTENT_TYPE_WILDCARD);
 }
  public static void copyThumbnail(ForeignPK fromPK, ForeignPK toPK) {
    ThumbnailDetail vignette =
        ThumbnailController.getCompleteThumbnail(
            new ThumbnailDetail(
                fromPK.getInstanceId(),
                Integer.parseInt(fromPK.getId()),
                ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE));
    try {
      if (vignette != null) {
        ThumbnailDetail thumbDetail =
            new ThumbnailDetail(
                toPK.getInstanceId(),
                Integer.valueOf(toPK.getId()),
                ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE);
        if (vignette.getOriginalFileName().startsWith("/")) {
          thumbDetail.setOriginalFileName(vignette.getOriginalFileName());
          thumbDetail.setMimeType(vignette.getMimeType());
        } else {
          String from = getImageDirectory(fromPK.getInstanceId()) + vignette.getOriginalFileName();

          String type = FilenameUtils.getExtension(vignette.getOriginalFileName());
          String newOriginalImage = String.valueOf(System.currentTimeMillis()) + "." + type;

          String to = getImageDirectory(toPK.getInstanceId()) + newOriginalImage;
          FileRepositoryManager.copyFile(from, to);
          thumbDetail.setOriginalFileName(newOriginalImage);

          // then copy thumbnail image if exists
          if (vignette.getCropFileName() != null) {
            from = getImageDirectory(fromPK.getInstanceId()) + vignette.getCropFileName();
            type = FilenameUtils.getExtension(vignette.getCropFileName());
            String newThumbnailImage = String.valueOf(System.currentTimeMillis()) + "." + type;
            to = getImageDirectory(toPK.getInstanceId()) + newThumbnailImage;
            FileRepositoryManager.copyFile(from, to);
            thumbDetail.setCropFileName(newThumbnailImage);
          }
          thumbDetail.setMimeType(vignette.getMimeType());
          thumbDetail.setXLength(vignette.getXLength());
          thumbDetail.setYLength(vignette.getYLength());
          thumbDetail.setXStart(vignette.getXStart());
          thumbDetail.setYStart(vignette.getYStart());
        }
        getThumbnailService().createThumbnail(thumbDetail);
      }
    } catch (Exception e) {
      throw new ThumbnailRuntimeException(
          "ThumbnailController.copyThumbnail()",
          SilverpeasRuntimeException.ERROR,
          "thumbnail_CANT_COPY_THUMBNAIL",
          e);
    }
  }
  /** Launches the associated applications for each selected file in the library if it can. */
  void launch(boolean playAudio) {
    int[] rows = TABLE.getSelectedRows();
    if (rows.length == 0) {
      return;
    }

    File selectedFile = DATA_MODEL.getFile(rows[0]);

    if (OSUtils.isWindows()) {
      if (selectedFile.isDirectory()) {
        GUIMediator.launchExplorer(selectedFile);
        return;
      } else if (!MediaPlayer.isPlayableFile(selectedFile)) {
        String extension = FilenameUtils.getExtension(selectedFile.getName());
        if (extension != null && extension.equals("torrent")) {
          GUIMediator.instance().openTorrentFile(selectedFile, true);
        } else {
          GUIMediator.launchFile(selectedFile);
        }
        return;
      }
    }

    LaunchableProvider[] providers = new LaunchableProvider[rows.length];
    boolean stopAudio = false;
    for (int i = 0; i < rows.length; i++) {
      try {
        MediaType mt =
            MediaType.getMediaTypeForExtension(
                FilenameUtils.getExtension(DATA_MODEL.getFile(rows[i]).getName()));
        if (mt.equals(MediaType.getVideoMediaType())) {
          stopAudio = true;
        }
      } catch (Throwable e) {
        // ignore
      }
      providers[i] = new FileProvider(DATA_MODEL.getFile(rows[i]));
    }
    if (stopAudio || !playAudio) {
      MediaPlayer.instance().stop();
    }

    if (playAudio) {
      GUILauncher.launch(providers);
      UXStats.instance()
          .log(stopAudio ? UXAction.LIBRARY_VIDEO_PLAY : UXAction.LIBRARY_PLAY_AUDIO_FROM_FILE);
    } else {
      GUIMediator.launchFile(selectedFile);
    }
  }
  private static void createCropFile(
      int thumbnailWidth, int thumbnailHeight, ThumbnailDetail thumbDetailComplete)
      throws IOException, ThumbnailException {

    String pathOriginalFile =
        getImageDirectory(thumbDetailComplete.getInstanceId())
            + thumbDetailComplete.getOriginalFileName();

    if (thumbnailWidth == -1 && thumbnailHeight != -1) {
      // crop with fix height
      String[] result =
          ImageUtil.getWidthAndHeightByHeight(new File(pathOriginalFile), thumbnailHeight);
      thumbnailWidth = Integer.valueOf(result[0]);
      thumbnailHeight = Integer.valueOf(result[1]);
    } else if (thumbnailHeight == -1 && thumbnailWidth != -1) {
      // crop with fix width
      String[] result =
          ImageUtil.getWidthAndHeightByWidth(new File(pathOriginalFile), thumbnailWidth);
      thumbnailWidth = Integer.valueOf(result[0]);
      thumbnailHeight = Integer.valueOf(result[1]);
    } else if (thumbnailHeight == -1) {
      // crop full file
      String[] result = ImageUtil.getWidthAndHeight(new File(pathOriginalFile));
      thumbnailWidth = Integer.valueOf(result[0]);
      thumbnailHeight = Integer.valueOf(result[1]);
    }

    String extension = FilenameUtils.getExtension(thumbDetailComplete.getOriginalFileName());
    // add 2 to be sure cropfilename is different from original filename
    String cropFileName = String.valueOf(new Date().getTime() + 2) + '.' + extension;
    thumbDetailComplete.setCropFileName(cropFileName);
    // crop sur l image entiere
    cropFromPath(pathOriginalFile, thumbDetailComplete, thumbnailHeight, thumbnailWidth);
  }
  protected boolean sanitizeFileName(Path filePath) {
    if (OSDetector.isWindows()) {
      return false;
    }

    String fileName = String.valueOf(filePath.getFileName());

    String sanitizedFileName =
        FileUtil.getSanitizedFileName(fileName, FilenameUtils.getExtension(fileName));

    if (!sanitizedFileName.equals(fileName)) {
      String sanitizedFilePathName =
          FileUtil.getFilePathName(String.valueOf(filePath.getParent()), sanitizedFileName);

      sanitizedFilePathName = FileUtil.getNextFilePathName(sanitizedFilePathName);

      FileUtil.checkFilePath(filePath);

      FileUtil.moveFile(filePath, Paths.get(sanitizedFilePathName));

      return true;
    }

    return false;
  }
 public Icon getIcon(File obj) {
   String extension = FilenameUtils.getExtension(obj.getName());
   if (extension != null) {
     return IconManager.instance().getIconForExtension(extension);
   }
   return null;
 }
  String getContent(String identifier) throws Exception {
    logger.trace("Searching for '{}' in cache.", identifier);
    ResourceWrapper wrapper = resources.get(identifier);

    // If not in cache yet, load it
    if (wrapper == null) {
      long start = System.currentTimeMillis();
      logger.debug("'{}' not in cache. Loading and processing...", identifier);
      String extension = FilenameUtils.getExtension(identifier);

      Type type = TypeFactory.getType(extension);
      if (type == null) {
        logger.warn("No type available for the specified resource: {}", extension);
        throw new UnknownTypeException(
            "No type available for the specified resource: " + extension);
      }

      String content = processContent(loader.loadResource(identifier), type);
      wrapper = new ResourceWrapper(identifier, type, content);
      resources.put(identifier, wrapper);
      logger.debug("Resource loaded and processed in {} ms.", System.currentTimeMillis() - start);
    } else {
      // If in cache, check last modified
      if (wrapper.getLastLoaded() < loader.lastModified(identifier)) {
        // If last loaded was before last modified, load it again
        wrapper.setContent(loader.loadResource(identifier));
      }
    }

    return wrapper.getContent();
  }
Exemple #9
0
  public static void createAd(@Valid Ad ad, File photo) throws IOException {

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // get current date time with Date()
    Date date = new Date();
    ad.createDate = dateFormat.format(date);
    ad.student = Student.findById(1l);
    // ad.category=Category.findById(ad.category.id);
    File d = new File(Play.applicationPath.getAbsolutePath() + "/public/img/ads");
    // if(d.exists()){
    String suffix = FilenameUtils.getExtension(photo.getName());
    File o = File.createTempFile("ad-", "." + suffix, d);

    InputStream input = new FileInputStream(photo);
    OutputStream output = new FileOutputStream(o);
    ad.image = o.getName();

    ad.save();
    try {
      IOUtils.copy(input, output);
    } finally {
      IOUtils.closeQuietly(output);
      IOUtils.closeQuietly(input);
    }

    Ads.index(1, ad.category.id.toString());
  }
  @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
  @ResponseStatus(value = HttpStatus.OK)
  public Collection<Route> handleFileUpload(@RequestParam("file") MultipartFile file) {
    Collection<Route> result = Collections.emptyList();
    if (!file.isEmpty()) {
      log.info("{} uploaded", file.getOriginalFilename());
      try {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        byte[] data = null;
        if ("zip".equals(extension)) {
          data = zipUtils.doUnzip(file.getBytes());
        } else if ("js".equals(extension)) {
          data = file.getBytes();
        }

        if (data == null) {
          throw new IllegalArgumentException("Unrecognized file extension");
        }

        List<Route> routes = routeCacheFileUtils.parseRoutes(data);
        log.info("Found {} routes", routes.size());
        result = routes;
      } catch (Exception e) {
        log.error("Unexpected error occured while uploading a file", e);
      }
    }
    return result;
  }
 private void callParserDefault(
     String[] sources,
     String[] encodings,
     String[] classPaths,
     String rootDir,
     String className,
     String renamedMethod,
     Multimap<String, String> invokers)
     throws IOException {
   File directory = new File(rootDir);
   File[] fList = directory.listFiles();
   for (File file : fList) {
     if (file.isDirectory()) {
       callParserDefault(
           sources,
           encodings,
           classPaths,
           file.getAbsolutePath(),
           className,
           renamedMethod,
           invokers);
     } else {
       if (FilenameUtils.getExtension(file.getAbsolutePath()).equalsIgnoreCase("java")) {
         List<String> invocations =
             createParserAndFindMethodReferences(
                 sources, encodings, classPaths, file, className, renamedMethod);
         for (String method : invocations) {
           invokers.put(file.getAbsolutePath(), method);
         }
       }
     }
   }
 }
  //
  // general information about this file
  // =================================================================================================================
  private int internalGetType() {

    Stream videoStream = getStream(CODEC_TYPE_VIDEO);
    if (videoStream == null) return TYPE_NO_GOOD;

    Stream audioStream = getStream(CODEC_TYPE_AUDIO);
    if (audioStream == null) return TYPE_NO_GOOD;

    // good video codec and profile
    if (VIDEO_CODEC.equals(videoStream.getCodec_name())
        && VIDEO_PROFILE.equals(videoStream.getProfile())) {

      // good audio codec
      if (AUDIO_CODEC_1.equals(audioStream.getCodec_name())
          || AUDIO_CODEC_2.equals(audioStream.getCodec_name())) {

        // good container
        String ext =
            FilenameUtils.getExtension(conversionSetting.getOriginalVideoFile().getAbsolutePath());
        if (MP4.equals(ext)
            && conversionSetting.getFfProbe().getFormat().getFormat_name().contains(MP4)) {
          return TYPE_NO_CHANGE;
        }

        return TYPE_JUST_CHANGE_CONTAINER;
      }

      return TYPE_CONVERT_ONLY_AUDIO;
    }

    // same file size uses 2 pass, other qualities uses CRF
    return conversionSetting.getQuality() == Settings.QUALITY_SAME_FILE_SIZE
        ? TYPE_TWO_PASS
        : TYPE_CRF;
  }
  @Override
  public String parseMime(String baseName) {
    String ext = FilenameUtils.getExtension(baseName);
    Optional<String> mime = Optional.ofNullable(extensionRegistry.get(ext));

    return mime.orElse(MIME_FOR_UNKNOWN);
  }
 public static ThumbnailDetail cropThumbnail(
     ThumbnailDetail thumbnail, int thumbnailWidth, int thumbnailHeight) {
   try {
     ThumbnailDetail thumbDetailComplete = getThumbnailService().getCompleteThumbnail(thumbnail);
     if (thumbDetailComplete.getCropFileName() != null) {
       // on garde toujours le meme nom de fichier par contre on le supprime
       // puis le recreer avec les nouvelles coordonnees
       deleteThumbnailFileOnServer(
           thumbnail.getInstanceId(), thumbDetailComplete.getCropFileName());
     } else {
       // case creation
       String extension = FilenameUtils.getExtension(thumbDetailComplete.getOriginalFileName());
       String cropFileName = String.valueOf(new Date().getTime()) + '.' + extension;
       thumbDetailComplete.setCropFileName(cropFileName);
     }
     String pathCropdir = getImageDirectory(thumbnail.getInstanceId());
     String pathOriginalFile = pathCropdir + thumbDetailComplete.getOriginalFileName();
     String pathCropFile = pathCropdir + thumbDetailComplete.getCropFileName();
     createCropThumbnailFileOnServer(
         pathOriginalFile, pathCropdir, pathCropFile, thumbnail, thumbnailWidth, thumbnailHeight);
     thumbDetailComplete.setXStart(thumbnail.getXStart());
     thumbDetailComplete.setXLength(thumbnail.getXLength());
     thumbDetailComplete.setYStart(thumbnail.getYStart());
     thumbDetailComplete.setYLength(thumbnail.getYLength());
     getThumbnailService().updateThumbnail(thumbDetailComplete);
     return thumbDetailComplete;
   } catch (Exception e) {
     throw new ThumbnailRuntimeException(
         "ThumbnailController.cropThumbnail()",
         SilverpeasRuntimeException.ERROR,
         "thumbnail_MSG_GET_IMAGE_KO",
         e);
   }
 }
Exemple #15
0
  public static String getNextFilePathName(String filePathName) {
    Path filePath = Paths.get(filePathName);

    Path parentFilePath = filePath.getParent();

    for (int i = 0; ; i++) {
      StringBuilder sb = new StringBuilder();

      sb.append(FilenameUtils.getBaseName(filePathName));

      if (i > 0) {
        sb.append(" (");
        sb.append(i);
        sb.append(")");
      }

      String extension = FilenameUtils.getExtension(filePathName);

      if (extension.length() > 0) {
        sb.append(".");
        sb.append(extension);
      }

      String tempFilePathName = FileUtil.getFilePathName(parentFilePath.toString(), sb.toString());

      if (SyncFileService.fetchSyncFile(tempFilePathName) == null) {
        Path tempFilePath = Paths.get(tempFilePathName);

        if (!Files.exists(tempFilePath)) {
          return tempFilePathName;
        }
      }
    }
  }
Exemple #16
0
 /**
  * Create a tmp file with the uploaded file
  *
  * @param fio
  * @return
  */
 private File createTmpFile() {
   try {
     return File.createTempFile("upload", "." + FilenameUtils.getExtension(title));
   } catch (Exception e) {
     throw new RuntimeException("Error creating a temp file", e);
   }
 }
 private void innerGet(String path, HttpServletResponse response) throws IOException {
   path = path.replace("/static/", "");
   if (FilenameUtils.isExtension(path, "js")) {
     path = "js/" + path;
     response.setContentType("text/javascript; charset=UTF-8");
   } else if (FilenameUtils.isExtension(path, "css") || FilenameUtils.isExtension(path, "less")) {
     path = "css/" + path;
     response.setContentType("text/css; charset=UTF-8");
   } else if (FilenameUtils.isExtension(path, IMG_EXTENSION)) {
     path = "img/" + path;
     response.setContentType("image/" + FilenameUtils.getExtension(path));
   }
   path = "view/" + path;
   if (path.endsWith(".handlebars.js")) {
     // handlebars
     response.setContentType("text/javascript; charset=UTF-8");
     path = path.substring(0, path.length() - 3);
     File file = new File(getWebInf(), path);
     String content = FileUtils.readFileToString(file, "UTF-8");
     try {
       content = HandlebarsObj.toJavaScript(content);
       IOUtils.write(content.getBytes("UTF-8"), response.getOutputStream());
     } catch (Exception e) {
       throw new ServerError(e);
     }
   } else {
     sendFile(response, path);
   }
 }
Exemple #18
0
 public static String getFileContent(File file) throws FileNotFoundException, IOException {
   String ext = FilenameUtils.getExtension(file.getName());
   String outContent = "";
   try {
     if (ext.toLowerCase().equals("doc")) {
       if (file != null) {
         WordExtractor we = new WordExtractor(new FileInputStream(file));
         outContent = we.getText();
       } else {
         logger.warning("file not found : " + file);
       }
     } else if (ext.toLowerCase().equals("pdf")) {
       PDDocument doc = PDDocument.load(file);
       PDFTextStripper text = new PDFTextStripper();
       outContent = text.getText(doc);
       doc.close();
     } else if (StringHelper.isHTML(file.getName())) {
       return loadStringFromFile(file);
     }
   } catch (Throwable t) {
     logger.warning("error when read : " + file + "+ [" + t.getMessage() + "]");
     t.printStackTrace();
   }
   return outContent;
 }
Exemple #19
0
 private WebErrors validateUpload(MultipartFile file, HttpServletRequest request) {
   int fileSize = (int) (file.getSize() / 1024);
   WebErrors errors = WebErrors.create(request);
   if (errors.ifNull(file, "file")) {
     return errors;
   }
   CmsUser user = CmsUtils.getUser(request);
   String origName = file.getOriginalFilename();
   String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
   if (!Constants.LIBRARY_SUFFIX.contains(ext)) {
     errors.addErrorCode("error.uploadValidFile", ext);
   }
   // 非允许的后缀
   if (!user.isAllowSuffix(ext)) {
     errors.addErrorCode("upload.error.invalidsuffix", ext);
     return errors;
   }
   // 超过附件大小限制
   if (!user.isAllowMaxFile((int) (file.getSize() / 1024))) {
     errors.addErrorCode("upload.error.toolarge", origName, user.getGroup().getAllowMaxFile());
     return errors;
   }
   // 超过每日上传限制
   if (!user.isAllowPerDay(fileSize)) {
     long laveSize = user.getGroup().getAllowPerDay() - user.getUploadSize();
     if (laveSize < 0) {
       laveSize = 0;
     }
     errors.addErrorCode("upload.error.dailylimit", laveSize);
   }
   return errors;
 }
 public static String getFilenameExtension(String filename) {
   String fileNameExt = "";
   if (FilenameUtils.indexOfExtension(filename) != -1) {
     fileNameExt = FilenameUtils.getExtension(filename);
   }
   return fileNameExt;
 }
  private String getMediafilename(FeedMedia media) {
    String filename;
    String titleBaseFilename = "";

    // Try to generate the filename by the item title
    if (media.getItem() != null && media.getItem().getTitle() != null) {
      String title = media.getItem().getTitle();
      // Delete reserved characters
      titleBaseFilename = title.replaceAll("[\\\\/%\\?\\*:|<>\"\\p{Cntrl}]", "");
      titleBaseFilename = titleBaseFilename.trim();
    }

    String URLBaseFilename =
        URLUtil.guessFileName(media.getDownload_url(), null, media.getMime_type());

    if (!titleBaseFilename.equals("")) {
      // Append extension
      final int FILENAME_MAX_LENGTH = 220;
      if (titleBaseFilename.length() > FILENAME_MAX_LENGTH) {
        titleBaseFilename = titleBaseFilename.substring(0, FILENAME_MAX_LENGTH);
      }
      filename =
          titleBaseFilename
              + FilenameUtils.EXTENSION_SEPARATOR
              + FilenameUtils.getExtension(URLBaseFilename);
    } else {
      // Fall back on URL file name
      filename = URLBaseFilename;
    }
    return filename;
  }
Exemple #22
0
 private void initMapper(ModuleData inputs) {
   Date updateTime =
       SkFile.dao
           .findFirst("select update_date from sk_file where name=? limit 1", excelFile)
           .getDate("update_time");
   if (mapUpdateTime.get(excelFile) == null || updateTime.after(mapUpdateTime.get(excelFile))) {
     byte[] content =
         SkFile.dao
             .findFirst("select content from sk_file where name=? limit 1", excelFile)
             .getBytes("content");
     ByteArrayInputStream bais = new ByteArrayInputStream(content);
     try {
       excelMaps.put(
           excelFile, Excel.exportFromExcel(bais, FilenameUtils.getExtension(excelFile), inputs));
       mapUpdateTime.put(excelFile, updateTime);
     } catch (IOException e) {
       throw new RuntimeException(e);
     } finally {
       try {
         if (bais != null) bais.close();
       } catch (IOException e) {
         throw new RuntimeException(e);
       }
     }
   }
 }
 /**
  * A method to set the output file name to a series of numbered files, using a pattern like:
  *
  * <p>fileName = String.format("%s_%03d.%s", fName, fNumber, ext);
  *
  * <p>When fName includes an extension, it is first removed and saved into ext.
  *
  * @param fName a file path + name (with or without an extension).
  */
 private static void createOutputStream(String fName) throws Exception {
   fName = FilenameUtils.normalize(fName);
   String name = FilenameUtils.removeExtension(fName);
   String ext = FilenameUtils.getExtension(fName);
   if (oSerializeFormat.equals("turtle")) {
     ext = "ttl";
   } else if (oSerializeFormat.equals("Ntriples")) {
     ext = "nt";
   } else if (ext.equals("")) {
     ext = "txt";
   }
   fName = String.format("%s_%03d.%s", name, ++oFileNumber, ext);
   oFile = new File(fName);
   try {
     oStream.close();
     oStream = new PrintStream(new FileOutputStream(oFile));
     if (oSerializeFormat.equals("turtle")) {
       oStream.println(SparqlPrefixes.ttlMappingPrefix());
       oStream.println();
       if (oFileNumber == 1) {
         oStream.println(loomInfo.ttlSignature());
         oStream.println();
       }
     }
   } catch (Exception e) {
     log.fatal("Cannot create output file stream: {}", oFile.getAbsolutePath());
     throw e;
   }
 }
  public void saveAppDiff(AppDiff entity) {

    if (StringUtils.isEmpty(entity.getId())) {
      initEntity(entity);
    }

    // save apk
    if (entity.getDiffAttachment() != null
        && StringUtils.isNotEmpty(entity.getDiffAttachment().getFileName())) {
      try {
        String distPath =
            "/attachment/content/" + new SimpleDateFormat("yyyy/MM").format(new Date());
        File distFile = new File(explodedPath + distPath);
        if (!distFile.exists()) {
          FileUtils.forceMkdir(distFile);
        }
        entity.setDiff(
            distPath
                + "/"
                + entity.getDiffAttachment().getTempFileName()
                + "."
                + FilenameUtils.getExtension(entity.getDiffAttachment().getFileName()));
        entity.setDiffFilename(entity.getDiffAttachment().getFileName());
        FileUtils.copyFile(
            new File(tempPath + "/" + entity.getDiffAttachment().getTempFileName()),
            new File(explodedPath + entity.getDiff()));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    appDiffDao.save(entity);
  }
  /**
   * 其他格式文档转pdf服务
   *
   * @param inputFile 输入的文件(原始文档)
   * @param outputFile 输出的文件(转化后的pdf文件)
   */
  public void doc2Pdf(File inputFile, File outputFile) throws IOException {
    String canonicalPath = inputFile.getCanonicalPath();
    // 文件类型
    String fileType = FilenameUtils.getExtension(canonicalPath);

    // 判断是不是文本类型
    boolean isTxt = FileTypeUtil.isTextPlain(fileType);
    boolean isHtml = FileTypeUtil.isHtml(fileType);
    // 如果是html,进行编码转换(转成utf-8无BOM格式),然后采用jodconverter转化
    if (isHtml) {
      Charset charset = FileTypeUtil.detectFileEncoding(inputFile);
      if (!charset.equals(charsetUTF8)) {
        // 需要转码到临时文件
        File tmpFile = new File(TMP_DIR + "tmp" + inputFile.getName());
        tmpFile.createNewFile();
        FileTypeUtil.convert2Utf8(inputFile, tmpFile, charset.name());
        commonOfficeDoc2Pdf(tmpFile, outputFile);
      } else {
        commonOfficeDoc2Pdf(inputFile, outputFile);
      }
    } else if (isTxt) { // 类型为txt
      // 将txt转化为pdf,pdf直接打印
      Charset charset = FileTypeUtil.detectFileEncoding(inputFile);
      txt2Pdf(inputFile, outputFile, charset);
      // commonOfficeDoc2Pdf(inputFile, outputFile);
    } else if (isSupportByExtension(fileType)) {
      // 执行office转化为pdf
      commonOfficeDoc2Pdf(inputFile, outputFile);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.template.service.common.workflow.IWorkFlowService#deploy(java.lang
   * .String)
   */
  @Override
  public Deployment deploy(String fileName) {
    Deployment deployment = null;
    try {
      File f = new File(fileName);
      InputStream fileInputStream = new FileInputStream(f);

      String extension = FilenameUtils.getExtension(fileName);

      if (extension.equals("zip") || extension.equals("bar")) {
        ZipInputStream zip = new ZipInputStream(fileInputStream);
        deployment = repositoryService.createDeployment().addZipInputStream(zip).deploy();
      } else if (extension.equals("bpmn")) {
        deployment =
            repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy();
      } else {
        System.out.println("请上传 zip bar 或者 bpmn文件");
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return deployment;
  }
 public PreprocessorHandlerContext(
     RetailerSite retailerSite,
     DataFile dataFile,
     File fullDataFilePath,
     TableDefinition tableDefinition,
     String encoding,
     String separator,
     String quoteChar)
     throws IOException, CSVReaderException {
   this.dataFile = dataFile;
   this.srcFile = dataFile.getSrcFile();
   this.dataFilePath = dataFile.getFilePath();
   this.fullDataFilePath = fullDataFilePath;
   this.base = FilenameUtils.getBaseName(this.fullDataFilePath.getName());
   int pos = this.base.indexOf('-');
   if (pos == -1) {
     throw new RuntimeException("Protocol error, invalid feed file name: " + this.base);
   }
   this.type = this.base.substring(0, pos);
   this.base = this.base.substring(pos + 1);
   this.ext = FilenameUtils.getExtension(this.fullDataFilePath.getName());
   this.path = this.fullDataFilePath.getParentFile().getPath();
   this.encoding = encoding;
   this.separator = separator;
   this.quoteChar = quoteChar;
   this.reader =
       new CVSTranslatorReader(this.fullDataFilePath, this.encoding, this.separator, quoteChar);
 }
  /*
   * (non-Javadoc)
   *
   * @see com.template.service.common.workflow.IProcessDefinitionService#
   * exportProcessPic(org.activiti.engine.repository.ProcessDefinition,
   * java.lang.String)
   */
  @Override
  public boolean exportProcessPic(String deploymentId) {

    boolean flag = true;
    ProcessDefinition processDefinition =
        repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();

    String diagramResourceName = processDefinition.getDiagramResourceName();
    try {
      diagramResourceName = processDefinition.getDiagramResourceName();
      InputStream imageStream =
          repositoryService.getResourceAsStream(
              processDefinition.getDeploymentId(), diagramResourceName);

      byte[] b = new byte[imageStream.available()];
      imageStream.read(b, 0, b.length);

      File file =
          new File(
              workFlowPicPath
                  + File.separator
                  + processDefinition.getKey()
                  + "."
                  + FilenameUtils.getExtension(diagramResourceName));
      FileUtils.writeByteArrayToFile(file, b);
    } catch (IOException e) {
      flag = false;
    }
    return flag;
  }
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public @ResponseBody String handleFileUpload(
      @RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

    System.out.println(name + " " + file.getOriginalFilename());
    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream =
            new BufferedOutputStream(
                new FileOutputStream(
                    new File(
                        path
                            + name
                            + "."
                            + FilenameUtils.getExtension(file.getOriginalFilename()))));

        stream.write(bytes);
        stream.close();
        return "You successfully uploaded " + name + "!";
      } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    } else {
      return "You failed to upload " + name + " because the file was empty.";
    }
  }
  @Override
  public void addOrUpdatePerson(
      TSysPerson person, MultipartFile photo, String savePath, String urlPath) throws IOException {
    if (photo != null && !photo.isEmpty()) {
      long currentTimeMillis = System.currentTimeMillis();
      String fileType = FilenameUtils.getExtension(photo.getOriginalFilename());
      String thumbnailName = person.getUserId() + "_" + currentTimeMillis + fileType;
      String photoName = person.getUserId() + "_" + currentTimeMillis + "_original" + fileType;

      File dir = new File(savePath);
      if (!dir.exists() || !dir.isDirectory()) {
        dir.delete();
        dir.mkdirs();
      }
      FileUtils.copyInputStreamToFile(photo.getInputStream(), new File(dir, photoName));
      ImageUtils.process(
          savePath + photoName, 256, 256, true, 0, null, null, 0, savePath + thumbnailName);
      person.setPhoto(urlPath + thumbnailName);
    }

    person.setSpell(
        PinyinUtils.getPinyin(person.getNickname())
            + " "
            + PinyinUtils.getPinyinHead(person.getNickname()));
    this.baseDao.saveOrUpdate(person);
  }