示例#1
1
  protected void initExtensions(ClassLoader extensionClassLoader) {
    /* We break the general rule that you shouldn't catch Throwable, because we don't want extensions to crash SoapUI. */
    try {
      String extDir = System.getProperty("soapui.ext.listeners");
      addExternalListeners(
          FilenameUtils.normalize(
              extDir != null
                  ? extDir
                  : root == null ? "listeners" : root + File.separatorChar + "listeners"),
          extensionClassLoader);
    } catch (Throwable e) {
      SoapUI.logError(e, "Couldn't load external listeners");
    }

    try {
      String factoriesDir = System.getProperty("soapui.ext.factories");
      addExternalFactories(
          FilenameUtils.normalize(
              factoriesDir != null
                  ? factoriesDir
                  : root == null ? "factories" : root + File.separatorChar + "factories"),
          extensionClassLoader);
    } catch (Throwable e) {
      SoapUI.logError(e, "Couldn't load external factories");
    }
  }
  public static void startDownload(
      Context context, Magazine magazine, boolean isTemp, String tempUrlKey) {
    String fileUrl = magazine.getItemUrl();
    String filePath = magazine.getItemPath();
    if (magazine.isSample()) {
      fileUrl = magazine.getSamplePdfUrl();
      filePath = magazine.getSamplePdfPath();
    } else if (isTemp) {
      fileUrl = tempUrlKey;
    }
    Log.d(
        TAG,
        "isSample: " + magazine.isSample() + "\nfileUrl: " + fileUrl + "\nfilePath: " + filePath);
    EasyTracker.getTracker().sendView("Downloading/" + FilenameUtils.getBaseName(filePath));
    DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl));
    request
        .setVisibleInDownloadsUi(false)
        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
        .setDescription(magazine.getSubtitle())
        .setTitle(magazine.getTitle() + (magazine.isSample() ? " Sample" : ""))
        .setDestinationInExternalFilesDir(context, null, FilenameUtils.getName(filePath));
    // TODO should use cache directory?
    magazine.setDownloadManagerId(dm.enqueue(request));

    MagazineManager magazineManager = new MagazineManager(context);
    magazineManager.removeDownloadedMagazine(context, magazine);
    magazineManager.addMagazine(magazine, Magazine.TABLE_DOWNLOADED_MAGAZINES, true);
    magazine.clearMagazineDir();
    EventBus.getDefault().post(new LoadPlistEvent());
  }
 public static String getFilenameExtension(String filename) {
   String fileNameExt = "";
   if (FilenameUtils.indexOfExtension(filename) != -1) {
     fileNameExt = FilenameUtils.getExtension(filename);
   }
   return fileNameExt;
 }
示例#4
0
 private void createWindowsScript(
     String jarPath, File scriptDestinationDir, String wrapperPropertiesPath) throws IOException {
   String windowsWrapperScriptHead =
       IOUtils.toString(getClass().getResourceAsStream("windowsWrapperScriptHead.txt"));
   String windowsWrapperScriptTail =
       IOUtils.toString(getClass().getResourceAsStream("windowsWrapperScriptTail.txt"));
   String fillingWindows =
       ""
           + WINDOWS_NL
           + "set STARTER_MAIN_CLASS="
           + FULLY_QUALIFIED_WRAPPER_NAME
           + WINDOWS_NL
           + "set CLASSPATH="
           + CURRENT_DIR_WINDOWS
           + "\\"
           + FilenameUtils.separatorsToWindows(jarPath)
           + WINDOWS_NL
           + "set WRAPPER_PROPERTIES="
           + CURRENT_DIR_WINDOWS
           + "\\"
           + FilenameUtils.separatorsToWindows(wrapperPropertiesPath)
           + WINDOWS_NL;
   String windowsScript = windowsWrapperScriptHead + fillingWindows + windowsWrapperScriptTail;
   File windowsScriptFile = new File(scriptDestinationDir, "gradlew.bat");
   FileUtils.writeStringToFile(windowsScriptFile, transformIntoWindowsNewLines(windowsScript));
 }
示例#5
0
 /** Puts a response loopback path together */
 private String buildResponseLoopbackPath(
     String root, String serviceName, EEnvironment environment) throws ServiceException {
   String result = "";
   String servicePath = FilenameUtils.concat(root, serviceName);
   String environmentPath = FilenameUtils.concat(servicePath, environment.value());
   String loopbackPath = FilenameUtils.concat(environmentPath, "Loopbacks");
   String loopbackResponse = FilenameUtils.concat(loopbackPath, "Response");
   if (folderExists(loopbackResponse)) result = loopbackResponse;
   else {
     try {
       createLogFolder(servicePath);
       createLogFolder(environmentPath);
       createLogFolder(loopbackPath);
       createLogFolder(loopbackResponse);
     } catch (IOException e) {
       throw new ServiceException(
           "COR006#Could not build path(s);"
               + servicePath
               + ":"
               + environmentPath
               + ":"
               + loopbackPath);
     }
   }
   return result;
 }
示例#6
0
 /**
  * Find in the url the filename
  *
  * @param url
  * @return
  */
 private String findFileName(URL url) {
   String name = FilenameUtils.getName(url.getPath());
   if (isWellFormedFileName(name)) return name;
   name = FilenameUtils.getName(url.toString());
   if (isWellFormedFileName(name)) return name;
   return FilenameUtils.getName(url.getPath());
 }
 @Override
 public ComputationGraph getLatestModel() throws IOException {
   String confOut = FilenameUtils.concat(directory, bestFileNameConf);
   String paramOut = FilenameUtils.concat(directory, bestFileNameParam);
   String updaterOut = FilenameUtils.concat(directory, bestFileNameUpdater);
   return load(confOut, paramOut, updaterOut);
 }
示例#8
0
  /** Setup output directory and get template etc. */
  protected void createIndexFile() {
    String fName = outputDir.getAbsolutePath() + File.separator + "index.html"; // $NON-NLS-1$
    try {
      File html = new File(fName);
      BufferedWriter output = new BufferedWriter(new FileWriter(html));

      int inx = mapTemplate.indexOf(contentTag);
      String subContent = mapTemplate.substring(0, inx);
      output.write(
          StringUtils.replace(
              subContent,
              "<!-- Title -->",
              getResourceString("FormDisplayer.FORM_INDEX"))); // $NON-NLS-1$ //$NON-NLS-2$
      output.write("<UL>"); // $NON-NLS-1$

      Collections.sort(
          entries,
          new Comparator<Pair<String, File>>() {
            public int compare(Pair<String, File> o1, Pair<String, File> o2) {
              return o1.first.compareTo(o2.first);
            }
          });
      int cnt = 0;
      for (Pair<String, File> p : entries) {
        output.write(
            "<LI><a href=\""
                + FilenameUtils.getBaseName(p.second.getName())
                + ".html\">"
                + p.first
                + "</a></LI>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        String prvName =
            cnt == 0
                ? null
                : FilenameUtils.getBaseName(entries.get(cnt - 1).second.getName())
                    + ".html"; //$NON-NLS-1$
        String nxtName =
            cnt == entries.size() - 1
                ? null
                : FilenameUtils.getBaseName(entries.get(cnt + 1).second.getName())
                    + ".html"; //$NON-NLS-1$
        writeImageFile(p.first, p.second.getName(), prvName, nxtName);
        cnt++;
      }
      output.write("</UL>"); // $NON-NLS-1$
      output.write(mapTemplate.substring(inx + contentTag.length() + 1, mapTemplate.length()));

      output.close();

    } catch (Exception e) {
      edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
      edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormDisplayer.class, e);
      e.printStackTrace();
    }

    createFormImagesIndexFile();

    JOptionPane.showMessageDialog(
        getTopWindow(),
        String.format(getResourceString("FormDisplayer.OUTPUT"), outputDir.getAbsoluteFile()));
  }
  private void save(String filename, String uploadedBy) {
    message += "Start reading file from " + FilenameUtils.getName(filename) + "\n";
    String uuid = UploadUtils.generateUUID();
    Parser parser = null;
    UploadLog log = null;
    ParseDao dao = null;
    // save upload log table
    try {

      dao = new ParseDao();
      if (dao.isParsed(UploadUtils.getChecksumString(filename))) {
        message += "File already parsed before\n";
        return;
      }
      log = new UploadLog();
      log.setBatchID(uuid);
      log.setFilename(FilenameUtils.getName(filename));
      log.setChecksum(UploadUtils.getChecksumString(filename));
      log.setUploadedBy(uploadedBy);
      log.setDtStamp();
      dao.saveUploadLog(log);
      message += "Saved to upload log table\n";
      try {
        message += "Start parsing file\n";
        parser = new Parser();
        message += parser.doParse(filename, uuid) + "\n";
      } catch (Exception e) {
        message += "Error Parsing file " + e.getMessage();
      }
    } catch (Exception e) {
      message += "Error saving to log table " + e.getMessage();
    }
  }
示例#10
0
  /**
   * Creates a new StockFile entry in the database with the given StockFile object and establishes
   * an association between the StockFile object with the current user within UserSession
   *
   * @param file
   * @return
   * @throws SQLException
   */
  public boolean createFile(StockFile file) throws SQLException {
    if (!inDatabase(file)) {
      try {

        ps =
            conn.prepareStatement(
                "INSERT INTO "
                    + "file (version,last_sync_by,created_by,file_name,file_path) "
                    + "VALUES (?,?,?,?,?);");

        ps.setFloat(1, file.getVersion());
        ps.setString(2, file.getLastSyncBy());
        ps.setString(3, file.getCreatedBy());
        ps.setString(4, FilenameUtils.separatorsToUnix(file.getRelativePath()));
        ps.setString(5, FilenameUtils.separatorsToUnix(file.getRemoteHomePath()));

        ps.executeUpdate();
        System.out.println("Added file to database.");

      } catch (SQLException sqlex) {
        System.out.println("INS: Error code: " + sqlex.getErrorCode());
        throw sqlex;
      }
    } else {
      updateFile(file);
      return false;
    }

    this.psclose();
    return true;
  }
示例#11
0
  /**
   * Updates the entry in file and user_file table that corresponds to the given Stockfile object
   *
   * @param file
   * @return TODO
   * @throws SQLException
   */
  public boolean updateFile(StockFile file) throws SQLException {

    if (!inDatabase(file)) {
      file.setRemoteHomePath(
          "/stockfiles/" + StockFileSession.getInstance().getCurrentUser().getUserName());
      createFile(file);
      return false;
    } else {
      try {

        ps =
            conn.prepareStatement(
                "UPDATE file "
                    + "SET version = ?, last_sync_by = ?,created_by = ? "
                    + "WHERE file_name = ? AND file_path = ? ");

        ps.setFloat(1, file.getVersion());
        ps.setString(2, file.getLastSyncBy());
        ps.setString(3, file.getCreatedBy());
        ps.setString(4, FilenameUtils.separatorsToUnix(file.getRelativePath()));
        ps.setString(5, FilenameUtils.separatorsToUnix(file.getRemoteHomePath()));

        ps.executeUpdate();

      } catch (SQLException sqlex) {
        System.out.println("UPD Error code: " + sqlex.getErrorCode());
        throw sqlex;
      }
      this.psclose();
      return true;
    }
  }
示例#12
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;
        }
      }
    }
  }
示例#13
0
  private void createUnixScript(
      String jarPath, File scriptDestinationDir, String wrapperPropertiesPath) throws IOException {
    String unixWrapperScriptHead =
        IOUtils.toString(getClass().getResourceAsStream("unixWrapperScriptHead.txt"));
    String unixWrapperScriptTail =
        IOUtils.toString(getClass().getResourceAsStream("unixWrapperScriptTail.txt"));

    String fillingUnix =
        ""
            + UNIX_NL
            + "STARTER_MAIN_CLASS="
            + FULLY_QUALIFIED_WRAPPER_NAME
            + UNIX_NL
            + "CLASSPATH="
            + CURRENT_DIR_UNIX
            + "/"
            + FilenameUtils.separatorsToUnix(jarPath)
            + UNIX_NL
            + "WRAPPER_PROPERTIES="
            + CURRENT_DIR_UNIX
            + "/"
            + FilenameUtils.separatorsToUnix(wrapperPropertiesPath)
            + UNIX_NL;

    String unixScript = unixWrapperScriptHead + fillingUnix + unixWrapperScriptTail;
    File unixScriptFile = new File(scriptDestinationDir, "gradlew");
    FileUtils.writeStringToFile(unixScriptFile, unixScript);
    createExecutablePermission(unixScriptFile);
  }
示例#14
0
 /**
  * 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 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);
 }
  public String putBlob(String container, Blob blob) {
    try {

      String name = FilenameUtils.getName(blob.getMetadata().getName());
      String path = FilenameUtils.getPathNoEndSeparator(blob.getMetadata().getName());

      service.uploadInputStream(
          blob.getPayload().getInput(),
          container,
          path,
          name,
          blob.getPayload().getContentMetadata().getContentLength());

      return null;
    } catch (UploadException e) {
      e.printStackTrace();
      return null;
    } catch (MethodNotSupportedException e) {
      e.printStackTrace();
      return null;
    } catch (FileNotExistsException e) {
      e.printStackTrace();
      return null;
    }
  }
示例#17
0
  /** 修改头像 */
  @RequestMapping(value = "/avatar/mod", method = RequestMethod.POST)
  public ResponseMessage modAvatar(
      HttpServletRequest request, long uid, @RequestParam(value = "img") MultipartFile file)
      throws Exception {
    // save the source avatar image file, 原始尺寸
    String filename = ImageController.uploadImg(request, file).getValue();
    AvatarDetail origin = new AvatarDetail();
    origin.setPhoto(filename);
    origin.setUserId(uid);
    origin.setTime(new Timestamp(System.currentTimeMillis()));
    avatarDetailRepository.save(origin);

    // generate image of the specified size and save,指定尺寸
    String avatar =
        ThumbnailGen.getInstance(request)
            .setUploadPath(FilenameUtils.concat(ConfigManager.get("upload.basePath"), "avatar"))
            .setUid(String.valueOf(uid))
            .gen(FilenameUtils.concat(ServerHelper.getContextPath(request), filename));

    AvatarDetail thumbnail = new AvatarDetail();
    thumbnail.setPhoto(avatar);
    thumbnail.setUserId(uid);
    thumbnail.setTime(new Timestamp(System.currentTimeMillis()));
    avatarDetailRepository.save(thumbnail);

    User user = userRepository.findById(uid);
    user.setAvatar(avatar);
    userRepository.save(user);
    return new ResponseMessage().set("filename", avatar).set("url", WebMvcConfig.getUrl(avatar));
  }
示例#18
0
 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();
     }
   }
 }
  /**
   * Creates the script file.
   *
   * @return the string
   * @throws Exception the exception
   */
  public String createScriptFile() throws Exception {
    File tempScriptFile;

    if (meta.getGenerateScript()) {
      tempScriptFile = File.createTempFile(FilenameUtils.getBaseName(meta.getScriptFileName()), "");
    } else {
      tempScriptFile =
          File.createTempFile(FilenameUtils.getBaseName(meta.getExistingScriptFile()), "");
    }
    tempScriptFile.deleteOnExit();

    try {
      scriptFile = FileUtils.openOutputStream(tempScriptFile);
      scriptFilePrintStream = new PrintStream(scriptFile);
    } catch (IOException e) {
      throw new KettleException(
          BaseMessages.getString(
              PKG, "TeraDataBulkLoaderMeta.Exception.OpenScriptFile", scriptFile),
          e);
    }

    if (meta.getGenerateScript()) {
      createGeneratedScriptFile();
    } else {
      createFromExistingScriptFile();
    }
    scriptFilePrintStream.close();
    IOUtils.closeQuietly(scriptFile);
    return tempScriptFile.getAbsolutePath();
  }
  YouTubeDownload(TransferManager manager, YouTubeCrawledSearchResult sr) {
    this.manager = manager;
    this.sr = sr;
    this.downloadType = buildDownloadType(sr);
    this.size = sr.getSize();

    String filename = sr.getFilename();

    File savePath = SystemPaths.getTorrentData();

    ensureDirectoryExits(savePath);
    ensureDirectoryExits(SystemPaths.getTemp());

    completeFile = buildFile(savePath, filename);
    tempVideo = buildTempFile(FilenameUtils.getBaseName(filename), "m4v");
    tempAudio = buildTempFile(FilenameUtils.getBaseName(filename), "m4a");

    bytesReceived = 0;
    dateCreated = new Date();

    httpClientListener = new HttpDownloadListenerImpl();

    httpClient = HttpClientFactory.getInstance(HttpClientFactory.HttpContext.DOWNLOAD);
    httpClient.setListener(httpClientListener);

    if (TransferManager.isCurrentMountAlmostFull()) {
      this.status = STATUS_ERROR_DISK_FULL;
    }
  }
 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);
   }
 }
 @Override
 public void saveLatestModel(ComputationGraph net, double score) throws IOException {
   String confOut = FilenameUtils.concat(directory, latestFileNameConf);
   String paramOut = FilenameUtils.concat(directory, latestFileNameParam);
   String updaterOut = FilenameUtils.concat(directory, latestFileNameUpdater);
   save(net, confOut, paramOut, updaterOut);
 }
示例#23
0
  @PostConstruct
  public void init() {
    String genreFileName = PropertyTools.getProperty("yamj3.genre.fileName");
    if (StringUtils.isBlank(genreFileName)) {
      LOG.trace("No valid genre file name configured");
      return;
    }
    if (!StringUtils.endsWithIgnoreCase(genreFileName, "xml")) {
      LOG.warn("Invalid genre file name specified: {}", genreFileName);
      return;
    }

    File xmlFile;
    if (StringUtils.isBlank(FilenameUtils.getPrefix(genreFileName))) {
      // relative path given
      String path = System.getProperty("yamj3.home");
      if (StringUtils.isEmpty(path)) {
        path = ".";
      }
      xmlFile = new File(FilenameUtils.concat(path, genreFileName));
    } else {
      // absolute path given
      xmlFile = new File(genreFileName);
    }

    if (!xmlFile.exists() || !xmlFile.isFile()) {
      LOG.warn("Genres file does not exist: {}", xmlFile.getPath());
      return;
    }
    if (!xmlFile.canRead()) {
      LOG.warn("Genres file not readble: {}", xmlFile.getPath());
      return;
    }

    LOG.debug("Initialize genres from file: {}", xmlFile.getPath());

    try {
      XMLConfiguration c = new XMLConfiguration(xmlFile);

      List<HierarchicalConfiguration> genres = c.configurationsAt("genre");
      for (HierarchicalConfiguration genre : genres) {
        String masterGenre = genre.getString("[@name]");
        List<Object> subGenres = genre.getList("subgenre");
        for (Object subGenre : subGenres) {
          LOG.debug("New genre added to map: {} -> {}", subGenre, masterGenre);
          GENRES_MAP.put(((String) subGenre).toLowerCase(), masterGenre);
        }
      }

      try {
        this.commonStorageService.updateGenresXml(GENRES_MAP);
      } catch (Exception ex) {
        LOG.warn("Failed update genres xml in database", ex);
      }
    } catch (Exception ex) {
      LOG.error("Failed parsing genre input file: " + xmlFile.getPath(), ex);
    }
  }
  public boolean isSame(final File baseFolder, final MMapURI file) {
    final File theFile = this.fileUri.asFile(baseFolder);
    final File thatFile = file.asFile(baseFolder);

    final String theFilePath = FilenameUtils.normalize(theFile.getAbsolutePath());
    final String thatFilePath = FilenameUtils.normalize(thatFile.getAbsolutePath());

    return theFilePath.equals(thatFilePath);
  }
 @SneakyThrows
 public void writeFrameworkFiles(FilePath frameworkPath) {
   for (String asset : ASSETS) {
     String source = IOUtils.toString(getClass().getResourceAsStream(asset));
     String assetFileName = FilenameUtils.getName(asset);
     String destinationFilename = FilenameUtils.concat(frameworkPath.getPath(), assetFileName);
     FileUtils.write(new File(destinationFilename), source);
   }
 }
示例#26
0
  private void download(
      Context context,
      FeedFile item,
      FeedFile container,
      File dest,
      boolean overwriteIfExists,
      String username,
      String password,
      long ifModifiedSince,
      boolean deleteOnFailure,
      Bundle arguments) {
    final boolean partiallyDownloadedFileExists = item.getFile_url() != null;
    if (isDownloadingFile(item)) {
      Log.e(TAG, "URL " + item.getDownload_url() + " is already being downloaded");
      return;
    }
    if (!isFilenameAvailable(dest.toString())
        || (!partiallyDownloadedFileExists && dest.exists())) {
      Log.d(TAG, "Filename already used.");
      if (isFilenameAvailable(dest.toString()) && overwriteIfExists) {
        boolean result = dest.delete();
        Log.d(TAG, "Deleting file. Result: " + result);
      } else {
        // find different name
        File newDest = null;
        for (int i = 1; i < Integer.MAX_VALUE; i++) {
          String newName =
              FilenameUtils.getBaseName(dest.getName())
                  + "-"
                  + i
                  + FilenameUtils.EXTENSION_SEPARATOR
                  + FilenameUtils.getExtension(dest.getName());
          Log.d(TAG, "Testing filename " + newName);
          newDest = new File(dest.getParent(), newName);
          if (!newDest.exists() && isFilenameAvailable(newDest.toString())) {
            Log.d(TAG, "File doesn't exist yet. Using " + newName);
            break;
          }
        }
        if (newDest != null) {
          dest = newDest;
        }
      }
    }
    Log.d(TAG, "Requesting download of url " + item.getDownload_url());
    String baseUrl = (container != null) ? container.getDownload_url() : null;
    item.setDownload_url(URLChecker.prepareURL(item.getDownload_url(), baseUrl));

    DownloadRequest.Builder builder =
        new DownloadRequest.Builder(dest.toString(), item)
            .withAuthentication(username, password)
            .ifModifiedSince(ifModifiedSince)
            .deleteOnFailure(deleteOnFailure)
            .withArguments(arguments);
    DownloadRequest request = builder.build();
    download(context, request);
  }
 public static String getFilenameWOExtension(String filename) {
   String fileNameWOExt = null;
   if (FilenameUtils.indexOfExtension(filename) == -1) {
     fileNameWOExt = filename;
   } else {
     fileNameWOExt = FilenameUtils.removeExtension(filename);
   }
   return fileNameWOExt;
 }
示例#28
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);
 }
    /**
     * Prepare Olink database files for chunked HTML output.
     *
     * @param baseConfiguration Common configuration for all executions
     * @throws MojoExecutionException Failed to prepare the target DB files.
     */
    void buildChunkedHTMLOlinkDB(final ArrayList<MojoExecutor.Element> baseConfiguration)
        throws MojoExecutionException {
      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();
      cfg.add(element(name("xincludeSupported"), isXincludeSupported));
      cfg.add(
          element(
              name("sourceDirectory"),
              FilenameUtils.separatorsToUnix(xmlSourceDirectory.getPath())));
      cfg.add(element(name("chunkedOutput"), "true"));
      cfg.add(
          element(
              name("htmlCustomization"),
              FilenameUtils.separatorsToUnix(chunkedHTMLCustomization.getPath())));

      Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName());
      if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
      }

      for (String docName : docNames) {
        cfg.add(element(name("currentDocid"), docName));
        cfg.add(element(name("includes"), docName + "/" + getDocumentSrcName()));
        cfg.add(element(name("collectXrefTargets"), "only"));
        cfg.add(
            element(
                name("targetsFilename"),
                FilenameUtils.separatorsToUnix(getBuildDirectory().getPath())
                    + "/"
                    + docName
                    + "-chunked.target.db"));

        executeMojo(
            plugin(
                groupId("com.agilejava.docbkx"),
                artifactId("docbkx-maven-plugin"),
                version(getDocbkxVersion())),
            goal("generate-html"),
            configuration(cfg.toArray(new Element[0])),
            executionEnvironment(getProject(), getSession(), getPluginManager()));

        File outputDir =
            new File(
                getDocbkxOutputDirectory(),
                "html"
                    + File.separator
                    + docName
                    + File.separator
                    + FilenameUtils.getBaseName(getDocumentSrcName()));
        try {
          FileUtils.deleteDirectory(outputDir);
        } catch (IOException e) {
          throw new MojoExecutionException("Cannot delete " + outputDir);
        }
      }
    }
    /**
     * Build chunked HTML pages from DocBook XML sources.
     *
     * @param baseConfiguration Common configuration for all executions
     * @throws MojoExecutionException Failed to build the output.
     */
    void buildChunkedHTML(final ArrayList<MojoExecutor.Element> baseConfiguration)
        throws MojoExecutionException {
      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();
      cfg.addAll(baseConfiguration);
      cfg.add(element(name("includes"), "*/" + getDocumentSrcName()));
      cfg.add(element(name("chunkedOutput"), "true"));
      cfg.add(
          element(
              name("htmlCustomization"),
              FilenameUtils.separatorsToUnix(chunkedHTMLCustomization.getPath())));
      cfg.add(element(name("targetDatabaseDocument"), buildChunkedHTMLTargetDB()));

      // Copy images from source to build. DocBook XSL does not copy the
      // images, because XSL does not have a facility for copying files.
      // Unfortunately, neither does docbkx-tools.

      String baseName = FilenameUtils.getBaseName(getDocumentSrcName());

      Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName());
      if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
      }

      for (String docName : docNames) {
        File srcDir = new File(imageSourceDirectory, docName + File.separator + "images");
        File destDir =
            new File(
                getDocbkxOutputDirectory(),
                "html"
                    + File.separator
                    + docName
                    + File.separator
                    + baseName
                    + File.separator
                    + "images");
        try {
          if (srcDir.exists()) {
            FileUtils.copyDirectory(srcDir, destDir);
          }
        } catch (IOException e) {
          throw new MojoExecutionException(
              "Failed to copy images from " + srcDir + " to " + destDir);
        }
      }

      executeMojo(
          plugin(
              groupId("com.agilejava.docbkx"),
              artifactId("docbkx-maven-plugin"),
              version(getDocbkxVersion())),
          goal("generate-html"),
          configuration(cfg.toArray(new Element[0])),
          executionEnvironment(getProject(), getSession(), getPluginManager()));
    }