Exemplo n.º 1
0
  /**
   * Save fileEntry and return the the path.
   *
   * @param user current user
   * @param path path to which this will forward.
   * @param fileEntry file to be saved
   * @param targetHosts target host parameter
   * @param createLibAndResource true if lib and resources should be created as well.
   * @param validated validated the script or not, 1 is validated, 0 is not.
   * @param model model
   * @return script/scriptList
   */
  @RequestMapping(value = "/save/**", method = RequestMethod.POST)
  public String saveFileEntry(
      User user,
      @RemainedPath String path,
      FileEntry fileEntry,
      @RequestParam String targetHosts,
      @RequestParam(defaultValue = "0") String validated,
      @RequestParam(defaultValue = "false") boolean createLibAndResource,
      ModelMap model) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("validated", validated);
    if (StringUtils.isNotBlank(targetHosts)) {
      map.put("targetHosts", StringUtils.trim(targetHosts));
    }
    fileEntry.setProperties(map);

    fileEntryService.save(user, fileEntry);

    String basePath = FilenameUtils.getPath(fileEntry.getPath());
    if (createLibAndResource) {
      fileEntryService.addFolder(user, basePath, "lib", getMessages("script.commit.libfolder"));
      fileEntryService.addFolder(
          user, basePath, "resources", getMessages("script.commit.resourcefolder"));
    }
    model.clear();
    return "redirect:/script/list/" + basePath;
  }
  private void doConvert(File directory) throws MojoExecutionException {
    if (directory.exists() && directory.isDirectory()) {
      for (File file : directory.listFiles(filter)) {
        if (file.isDirectory()) {
          doConvert(file);
        } else {
          getLog().info("Creating DocBook from " + file.getAbsolutePath());
          Reader reader = null;
          Writer writer = null;
          try {
            String relativePath =
                FilenameUtils.getPath(file.getAbsolutePath().replace(input.getAbsolutePath(), ""));

            File result = new File(output + File.separator + relativePath, file.getName() + ".xml");
            if (!result.getParentFile().exists()) {
              result.getParentFile().mkdirs();
            }

            reader = new FileReader(file);
            writer = new FileWriter(result);

            converter.convert(reader, writer);
          } catch (IOException e) {
            throw new MojoExecutionException("Unable to convert " + file, e);
          } finally {
            if (reader != null) {
              try {
                reader.close();
              } catch (IOException e) {
                // ignore this
              }
            }
            if (writer != null) {
              try {
                writer.close();
              } catch (IOException e) {
                // ignore this
              }
            }
          }
        }
      }
    }
  }
  /**
   * Creates a tool tip for each row of the playlist. Tries to grab any information that was
   * extracted from the Meta-Tag or passed in to the PlaylistItem as a property map
   */
  public String[] getToolTipArray(int col) {
    List<String> list = new ArrayList<String>();
    if (!StringUtils.isNullOrEmpty(initializer.getTrackTitle(), true)) {
      list.add(I18n.tr("Title") + ": " + initializer.getTrackTitle());
    }
    if (!StringUtils.isNullOrEmpty(initializer.getTrackNumber(), true)) {
      list.add(I18n.tr("Track") + ": " + initializer.getTrackNumber());
    }

    list.add(
        I18n.tr("Duration")
            + ": "
            + LibraryUtils.getSecondsInDDHHMMSS((int) initializer.getTrackDurationInSecs()));

    if (!StringUtils.isNullOrEmpty(initializer.getTrackArtist(), true)) {
      list.add(I18n.tr("Artist") + ": " + initializer.getTrackArtist());
    }
    if (!StringUtils.isNullOrEmpty(initializer.getTrackAlbum(), true)) {
      list.add(I18n.tr("Album") + ": " + initializer.getTrackAlbum());
    }
    if (!StringUtils.isNullOrEmpty(initializer.getTrackGenre(), true)) {
      list.add(I18n.tr("Genre") + ": " + initializer.getTrackGenre());
    }
    if (!StringUtils.isNullOrEmpty(initializer.getTrackYear(), true)) {
      list.add(I18n.tr("Year") + ": " + initializer.getTrackYear());
    }
    if (!StringUtils.isNullOrEmpty(initializer.getTrackComment(), true)) {
      list.add(I18n.tr("Comment") + ": " + initializer.getTrackComment());
    }

    if (list.size() == 1) {
      if (!StringUtils.isNullOrEmpty(initializer.getFileName(), true)) {
        list.add(I18n.tr("File") + ": " + initializer.getFileName());
      }
      if (!StringUtils.isNullOrEmpty(initializer.getFilePath(), true)) {
        list.add(I18n.tr("Folder") + ": " + FilenameUtils.getPath(initializer.getFilePath()));
      }
      if (!StringUtils.isNullOrEmpty(initializer.getTrackBitrate(), true)) {
        list.add(I18n.tr("Bitrate") + ": " + initializer.getTrackBitrate());
      }
    }

    return list.toArray(new String[0]);
  }
 private List<VcmFileData> getFiles(File directory, String outputPath)
     throws IOException, ZipException {
   ArrayList<VcmFileData> list = new ArrayList<VcmFileData>();
   for (File file :
       directory.listFiles(
           (FileFilter) FileFilterUtils.suffixFileFilter("vcm", IOCase.INSENSITIVE))) {
     log.debug(String.format("Opening %s", file.getCanonicalPath()));
     File destFile = new File(outputPath, file.getName());
     String relativePath =
         destFile
             .getCanonicalPath()
             .substring(new File(outputRootPath).getCanonicalPath().length() + 1);
     relativePath = StringUtils.replace(FilenameUtils.getPath(relativePath), "\\", "/");
     VcmFileData vcmFile = new VcmFileData(file, relativePath);
     list.add(vcmFile);
     log.debug(String.format("Generating thumbnail for %s", file.getCanonicalPath()));
     createThumbnail(vcmFile.getModel(), new File(outputPath, vcmFile.getThumbnailName()));
     log.debug(String.format("Copying %s", file.getCanonicalPath()));
     FileUtils.copyFile(file, destFile);
   }
   return list;
 }
 public static String getParentPath(String path) {
   String parentPath = FilenameUtils.getPath(path);
   return normalize(parentPath);
 }
Exemplo n.º 6
0
  /** 执行压缩 */
  private boolean doPack(
      final File targetArchiveFile,
      List<FileData> fileDatas,
      final ArchiveRetriverCallback<FileData> callback) {
    // 首先判断下对应的目标文件是否存在,如存在则执行删除
    if (true == targetArchiveFile.exists() && false == NioUtils.delete(targetArchiveFile, 3)) {
      throw new ArchiveException(
          String.format("[%s] exist and delete failed", targetArchiveFile.getAbsolutePath()));
    }

    boolean exist = false;
    ZipOutputStream zipOut = null;
    Set<String> entryNames = new HashSet<String>();
    BlockingQueue<Future<ArchiveEntry>> queue =
        new LinkedBlockingQueue<Future<ArchiveEntry>>(); // 下载成功的任务列表
    ExecutorCompletionService completionService = new ExecutorCompletionService(executor, queue);

    final File targetDir =
        new File(
            targetArchiveFile.getParentFile(),
            FilenameUtils.getBaseName(targetArchiveFile.getPath()));
    try {
      // 创建一个临时目录
      FileUtils.forceMkdir(targetDir);

      zipOut =
          new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetArchiveFile)));
      zipOut.setLevel(Deflater.BEST_SPEED);
      // 进行并发压缩处理
      for (final FileData fileData : fileDatas) {
        if (fileData.getEventType().isDelete()) {
          continue; // 忽略delete类型的数据打包,因为只需直接在目标进行删除
        }

        String namespace = fileData.getNameSpace();
        String path = fileData.getPath();
        boolean isLocal = StringUtils.isBlank(namespace);
        String entryName = null;
        if (true == isLocal) {
          entryName = FilenameUtils.getPath(path) + FilenameUtils.getName(path);
        } else {
          entryName = namespace + File.separator + path;
        }

        // 过滤一些重复的文件数据同步
        if (entryNames.contains(entryName) == false) {
          entryNames.add(entryName);
        } else {
          continue;
        }

        final String name = entryName;
        if (true == isLocal && !useLocalFileMutliThread) {
          // 采用串行处理,不走临时文件
          queue.add(new DummyFuture(new ArchiveEntry(name, callback.retrive(fileData))));
        } else {
          completionService.submit(
              new Callable<ArchiveEntry>() {

                public ArchiveEntry call() throws Exception {
                  // 处理下异常,可能失败
                  InputStream input = null;
                  OutputStream output = null;
                  try {
                    input = callback.retrive(fileData);

                    if (input instanceof LazyFileInputStream) {
                      input = ((LazyFileInputStream) input).getInputSteam(); // 获取原始的stream
                    }

                    if (input != null) {
                      File tmp = new File(targetDir, name);
                      NioUtils.create(tmp.getParentFile(), false, 3); // 尝试创建父路径
                      output = new FileOutputStream(tmp);
                      NioUtils.copy(input, output); // 拷贝到文件
                      return new ArchiveEntry(name, new File(targetDir, name));
                    } else {
                      return new ArchiveEntry(name);
                    }
                  } finally {
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(output);
                  }
                }
              });
        }
      }

      for (int i = 0; i < entryNames.size(); i++) {
        // 读入流
        ArchiveEntry input = null;
        InputStream stream = null;
        try {
          input = queue.take().get();
          if (input == null) {
            continue;
          }

          stream = input.getStream();
          if (stream == null) {
            continue;
          }

          if (stream instanceof LazyFileInputStream) {
            stream = ((LazyFileInputStream) stream).getInputSteam(); // 获取原始的stream
          }

          exist = true;
          zipOut.putNextEntry(new ZipEntry(input.getName()));
          NioUtils.copy(stream, zipOut); // 输出到压缩流中
          zipOut.closeEntry();
        } finally {
          IOUtils.closeQuietly(stream);
        }
      }

      if (exist) {
        zipOut.finish();
      }
    } catch (Exception e) {
      throw new ArchiveException(e);
    } finally {
      IOUtils.closeQuietly(zipOut);
      try {
        FileUtils.deleteDirectory(targetDir); // 删除临时目录
      } catch (IOException e) {
        // ignore
      }
    }

    return exist;
  }
  /**
   * Create the xml file for the set of collections.
   *
   * @param xmlFile - file to write the xml to
   * @param contributor types - set of contributor types to export
   * @throws IOException - if writing to the file fails.
   */
  public void createXmlFile(File xmlFile, Collection<ContributorType> contributorTypes)
      throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    String path = FilenameUtils.getPath(xmlFile.getCanonicalPath());
    if (!path.equals("")) {
      File pathOnly = new File(FilenameUtils.getFullPath(xmlFile.getCanonicalPath()));
      FileUtils.forceMkdir(pathOnly);
    }

    if (!xmlFile.exists()) {
      if (!xmlFile.createNewFile()) {
        throw new IllegalStateException("could not create file");
      }
    }

    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "contributor_types", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
      fos = new FileOutputStream(xmlFile);

      try {
        outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
      } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
      }
      writer = new BufferedWriter(outputStreamWriter);
      lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
      throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (ContributorType ct : contributorTypes) {
      Element contributorType = doc.createElement("contributor_type");

      this.addIdElement(contributorType, ct.getId().toString(), doc);
      this.addNameElement(contributorType, ct.getName(), doc);
      this.addDescription(contributorType, ct.getDescription(), doc);
      this.addSystemCode(contributorType, ct.getUniqueSystemCode(), doc);
    }
    serializer.write(root, lsOut);

    try {
      fos.close();
      writer.close();
      outputStreamWriter.close();
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }
  @Override
  public boolean uninstallComponent(Component component) throws ApsSystemException {
    ServletContext servletContext =
        ((ConfigurableWebApplicationContext) _applicationContext).getServletContext();
    ClassLoader cl = (ClassLoader) servletContext.getAttribute("componentInstallerClassLoader");
    List<ClassPathXmlApplicationContext> ctxList =
        (List<ClassPathXmlApplicationContext>) servletContext.getAttribute("pluginsContextsList");
    ClassPathXmlApplicationContext appCtx = null;
    if (ctxList != null) {
      for (ClassPathXmlApplicationContext ctx : ctxList) {
        if (component.getCode().equals(ctx.getDisplayName())) {
          appCtx = ctx;
        }
      }
    }
    String appRootPath = servletContext.getRealPath("/");
    String backupDirPath =
        appRootPath + "componentinstaller" + File.separator + component.getArtifactId() + "-backup";
    Map<File, File> resourcesMap = new HashMap<File, File>();
    try {
      ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
      try {
        if (cl != null) {
          Thread.currentThread().setContextClassLoader(cl);
        }
        if (null == component || null == component.getUninstallerInfo()) {
          return false;
        }
        this.getDatabaseManager().createBackup(); // backup database
        SystemInstallationReport report = super.extractReport();
        ComponentUninstallerInfo ui = component.getUninstallerInfo();
        // remove records from db
        String[] dataSourceNames = this.extractBeanNames(DataSource.class);
        for (int j = 0; j < dataSourceNames.length; j++) {
          String dataSourceName = dataSourceNames[j];
          Resource resource = (null != ui) ? ui.getSqlResources(dataSourceName) : null;
          String script = (null != resource) ? this.readFile(resource) : null;
          if (null != script && script.trim().length() > 0) {
            DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
            String[] queries = QueryExtractor.extractDeleteQueries(script);
            TableDataUtils.executeQueries(dataSource, queries, true);
          }
        }
        this.executePostProcesses(ui.getPostProcesses());

        // drop tables
        Map<String, List<String>> tableMapping = component.getTableMapping();
        if (tableMapping != null) {
          for (int j = 0; j < dataSourceNames.length; j++) {
            String dataSourceName = dataSourceNames[j];
            List<String> tableClasses = tableMapping.get(dataSourceName);
            if (null != tableClasses && tableClasses.size() > 0) {
              List<String> newList = new ArrayList<String>();
              newList.addAll(tableClasses);
              Collections.reverse(newList);
              DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
              IDatabaseManager.DatabaseType type =
                  this.getDatabaseManager().getDatabaseType(dataSource);
              TableFactory tableFactory = new TableFactory(dataSourceName, dataSource, type);
              tableFactory.dropTables(newList);
            }
          }
        }

        // move resources (jar, files and folders) on temp folder
        List<String> resourcesPaths = ui.getResourcesPaths();
        if (resourcesPaths != null) {
          for (String resourcePath : resourcesPaths) {
            try {
              String fullResourcePath = servletContext.getRealPath(resourcePath);
              File resFile = new File(fullResourcePath);
              String relResPath = FilenameUtils.getPath(resFile.getAbsolutePath());
              File newResFile =
                  new File(backupDirPath + File.separator + relResPath + resFile.getName());
              if (resFile.isDirectory()) {
                FileUtils.copyDirectory(resFile, newResFile);
                resourcesMap.put(resFile, newResFile);
                FileUtils.deleteDirectory(resFile);
              } else {
                FileUtils.copyFile(resFile, newResFile);
                resourcesMap.put(resFile, newResFile);
                FileUtils.forceDelete(resFile);
              }
            } catch (Exception e) {
            }
          }
        }

        // upgrade report
        ComponentInstallationReport cir = report.getComponentReport(component.getCode(), true);
        cir.getDataSourceReport()
            .upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
        cir.getDataReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
        this.saveReport(report);

        // remove plugin's xmlapplicationcontext if present
        if (appCtx != null) {
          appCtx.close();
          ctxList.remove(appCtx);
        }
        InitializerManager initializerManager =
            (InitializerManager) _applicationContext.getBean("InitializerManager");
        initializerManager.reloadCurrentReport();
        ComponentManager componentManager =
            (ComponentManager) _applicationContext.getBean("ComponentManager");
        componentManager.refresh();
      } catch (Exception e) {
        _logger.error("Unexpected error in component uninstallation process", e);
        throw new ApsSystemException("Unexpected error in component uninstallation process.", e);
      } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
        ApsWebApplicationUtils.executeSystemRefresh(servletContext);
      }
    } catch (Throwable t) {
      // restore files on temp folder
      try {
        for (Object object : resourcesMap.entrySet()) {
          File resFile = ((Map.Entry<File, File>) object).getKey();
          File newResFile = ((Map.Entry<File, File>) object).getValue();
          if (newResFile.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(newResFile, resFile.getParentFile());
          } else {
            FileUtils.copyFile(newResFile, resFile.getParentFile());
          }
        }
      } catch (Exception e) {
      }
      _logger.error("Unexpected error in component uninstallation process", t);
      throw new ApsSystemException("Unexpected error in component uninstallation process.", t);
    } finally {
      // clean temp folder
    }
    return true;
  }