Java Code Examples for org.apache.commons.io.FilenameUtils#normalizeNoEndSeparator()

The following examples show how to use org.apache.commons.io.FilenameUtils#normalizeNoEndSeparator() . 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
Source File: TemplateFileService.java    From youran with Apache License 2.0 6 votes vote down vote up
/**
 * 标准化文件目录
 *
 * @param fileDir
 * @return
 */
private String normalizeTemplateFileDir(String fileDir) {
    fileDir = StringUtils.trim(fileDir);
    if (StringUtils.isBlank(fileDir)) {
        return "/";
    }
    fileDir = FilenameUtils.normalizeNoEndSeparator(fileDir, true);
    if (fileDir == null) {
        throw new BusinessException(ErrorCode.BAD_REQUEST, "目录不合法");
    }
    fileDir = fileDir.replaceAll("\\/+", "/");
    if (fileDir.endsWith("/")) {
        fileDir = fileDir.substring(0, fileDir.length() - 1);
    }
    if (!fileDir.startsWith("/")) {
        fileDir = "/" + fileDir;
    }
    return fileDir;
}
 
Example 2
Source File: LocalTransport.java    From pikatimer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void refreshConfig() {
    if(parent != null && parent.getBasePath() != null && ! parent.getBasePath().isEmpty()) {
        basePath = FilenameUtils.normalizeNoEndSeparator(parent.getBasePath());
        
        File baseDir = new File(basePath);
        
        stripAccents = parent.getStripAccents();

        // does it exist?
        if (!baseDir.exists()) {
          baseDir.mkdirs();
        }
        
        // it should now... 
        if (baseDir.exists()) {
            goodToGo = true;
        } else {
            goodToGo = false;
        }
        
    } else {
        basePath = null; 
    }
    
}
 
Example 3
Source File: FTPUtils.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
public void downloadFile(String directory, FTPFile fileToDownload, File destFile, int fileType, FTPTransferListener transferL) throws IOException, InterruptedException {
	try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(destFile))) {
		logger.debug("setting filetype to: "+fileType);
		setFileType(fileType);
		enterLocalPassiveMode();
		setCopyStreamListener(transferL);
		transferL.setOutputStream(outputStream);
		transferL.setFTPClient(this);
		
		directory = FilenameUtils.normalizeNoEndSeparator(directory)+"/";
		
		boolean success = retrieveFile(directory + fileToDownload.getName(), outputStream);
		
		if (!success) {
			throw new IOException("Error while downloading " + fileToDownload.getName());
		} else if (transferL.isCanceled()) {
			throw new InterruptedException("Download cancelled!");
		} else {
			transferL.downloaded(100);
		}

		logout();
	} catch (IOException e) {
		throw e;
	}
}
 
Example 4
Source File: FileUtils.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
public static boolean isRootFile(@Nonnull final File file) {
  boolean result = false;

  for (final File f : File.listRoots()) {
    if (f.equals(file)) {
      result = true;
      break;
    }
  }

  if (!result) {
    final String path = FilenameUtils.normalizeNoEndSeparator(file.getAbsolutePath());
    if (path.isEmpty()) {
      result = true;
    } else if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) {
      result = path.length() == 3 && path.endsWith(":\\"); //NOI18N
    } else {
      result = path.equals("/"); //NOI18N
    }
  }

  return result;
}
 
Example 5
Source File: FileUploadUtils.java    From es with Apache License 2.0 5 votes vote down vote up
private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException {

        uploadDir = FilenameUtils.normalizeNoEndSeparator(uploadDir);

        File desc = new File(uploadDir + File.separator + filename);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }
 
Example 6
Source File: DetectFileUtils.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
public static String extractFinalPieceFromPath(final String path) {
    if (path == null || path.length() == 0) {
        return "";
    }
    final String normalizedPath = FilenameUtils.normalizeNoEndSeparator(path, true);
    return normalizedPath.substring(normalizedPath.lastIndexOf('/') + 1, normalizedPath.length());
}
 
Example 7
Source File: OnlineEditorController.java    From es with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/create/directory")
public String createDirectory(
        @RequestParam(value = "parentPath") String parentPath,
        @RequestParam(value = "name") String name,
        RedirectAttributes redirectAttributes) throws IOException {

    //删除最后的/
    name = FilenameUtils.normalizeNoEndSeparator(name);

    if(isValidFileName(name)) {
        String rootPath = sc.getRealPath(ROOT_DIR);
        parentPath = URLDecoder.decode(parentPath, Constants.ENCODING);

        File parent = new File(rootPath + File.separator + parentPath);
        File currentDirectory = new File(parent, name);
        boolean result = currentDirectory.mkdirs();
        if(result == false) {
            redirectAttributes.addFlashAttribute(Constants.ERROR, "名称为[" + name + "]的文件/目录已经存在");
        } else {
            redirectAttributes.addFlashAttribute(Constants.MESSAGE, "创建成功!");
        }
    } else {
        redirectAttributes.addFlashAttribute(Constants.ERROR, "名称为[" + name + "]不是合法的文件名,请重新命名");
    }

    redirectAttributes.addAttribute("path", parentPath);
    return redirectToUrl(viewName("list"));
}
 
Example 8
Source File: CrafterPageViewResolver.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public View resolveViewName(String renderUrl, Locale locale)  {
    String storeUrl = urlTransformationService.transform(renderUrlToStoreUrlTransformerName, renderUrl, cacheUrlTransformations);
    View view = getCachedLocalizedView(storeUrl, locale);

    if (view instanceof CrafterPageView) {
        CrafterPageView pageView = (CrafterPageView)view;

        if (SiteProperties.isRedirectToTargetedUrl()) {
            String finalStoreUrl = pageView.getPage().getStoreUrl();
            String finalRenderUrl = urlTransformationService.transform(storeUrlToRenderUrlTransformerName, finalStoreUrl,
                                                                       cacheUrlTransformations);

            renderUrl = FilenameUtils.normalizeNoEndSeparator(renderUrl);
            finalRenderUrl = FilenameUtils.normalizeNoEndSeparator(finalRenderUrl);

            if (!renderUrl.equals(finalRenderUrl)) {
                return getRedirectView(finalRenderUrl, true);
            }
        }

        accessManager.checkAccess(pageView.getPage());

        pageView.setDisableVariableRestrictions(disableVariableRestrictions);
    }

    return view;
}
 
Example 9
Source File: FTPUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public void uploadFile(String directory, File sourceFile, FTPUploadListener uploadL) throws IOException, InterruptedException {
	try (InputStream is = new BufferedInputStream(new FileInputStream(sourceFile))) {
		setFileType(FTP.BINARY_FILE_TYPE);
		enterLocalPassiveMode();
		setCopyStreamListener(uploadL);
		uploadL.setInputStream(is);
		
		boolean success = true;
		directory = FilenameUtils.normalizeNoEndSeparator(directory);
		if(directory != null && !directory.isEmpty()){
			success = changeWorkingDirectory(directory + "/");
			
			logger.info(success ? "Changed dir to " + printWorkingDirectory() : "Could not change dir to: " + directory);
		}
		if(success){
			success = storeFile(sourceFile.getName(), is);
		}
		
		if (!success) {
			throw new IOException("Error while uploading " + sourceFile.getName());
		} else if (uploadL.isCanceled()) {
			throw new InterruptedException("Upload cancelled!");
		} else {
			uploadL.uploaded(100);
		}

		logout();
	} catch (IOException e) {
		throw e;
	}
}
 
Example 10
Source File: DetectFileFinder.java    From hub-detect with Apache License 2.0 5 votes vote down vote up
public String extractFinalPieceFromPath(final String path) {
    if (path == null || path.length() == 0) {
        return "";
    }
    final String normalizedPath = FilenameUtils.normalizeNoEndSeparator(path, true);
    return normalizedPath.substring(normalizedPath.lastIndexOf("/") + 1, normalizedPath.length());
}
 
Example 11
Source File: PathUtils.java    From gdx-texture-packer-gui with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the relative path from one file to another.
 * @return in unix format
 */
public static String relativize(String targetPath, String basePath) {
	if (basePath == null || basePath.equals("")) return targetPath;
	if (targetPath == null || targetPath.equals("")) return "";

	String pathSeparator = File.separator;

	// Normalize the paths
	String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
	String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

	if (normalizedBasePath.equals(normalizedTargetPath)) return ".";

	// Undo the changes to the separators made by normalization
	if (pathSeparator.equals("/")) {
		normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
		normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
	} else if (pathSeparator.equals("\\")) {
		normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
		normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
	} else {
		throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
	}

	String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
	String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

	// First get all the common elements. Store them as a string,
	// and also count how many of them there are.
	StringBuilder common = new StringBuilder();

	int commonIndex = 0;
	while (commonIndex < target.length && commonIndex < base.length
		&& target[commonIndex].equals(base[commonIndex])) {
		common.append(target[commonIndex]).append(pathSeparator);
		commonIndex++;
	}

	if (commonIndex == 0) {
		return normalizedTargetPath;
	}

	// The number of directories we have to backtrack depends on whether the base is a file or a dir
	// For example, the relative path from
	//
	// /foo/bar/baz/gg/ff to /foo/bar/baz
	//
	// ".." if ff is a file
	// "../.." if ff is a directory
	//
	// The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
	// the resource referred to by this path may not actually exist, but it's the best I can do
	boolean baseIsFile = true;

	File baseResource = new File(normalizedBasePath);

	if (baseResource.exists()) {
		baseIsFile = baseResource.isFile();
	} else if (basePath.endsWith(pathSeparator)) {
		baseIsFile = false;
	}

	StringBuilder relative = new StringBuilder();

	if (base.length != commonIndex) {
		int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;
		for (int i = 0; i < numDirsUp; i++) {
			relative.append("..").append(pathSeparator);
		}
	}

	relative.append(normalizedTargetPath.substring(common.length()));
	// Return path in unix format
	relative = Strings.replace(relative, File.separator, "/");
	return relative.toString();
}
 
Example 12
Source File: ClassNameUtil.java    From kalang with MIT License 4 votes vote down vote up
public static String getClassName(File dir,File file){
    String dirPath = FilenameUtils.normalizeNoEndSeparator(dir.getAbsolutePath());
    String fname =FilenameUtils.normalizeNoEndSeparator(file.getAbsolutePath());
    String ext = FilenameUtils.getExtension(fname);
    return fname.substring(dirPath.length() + 1, fname.length() - ext.length()-1).replace(File.separator, ".");
}
 
Example 13
Source File: TOCManager.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
public static String getRelativePathFromWiki(final String targetPath/* , String basePath, String pathSeparator */) {

		final File tmp = new File(Constants.WIKI_FOLDER);
		final String basePath = tmp.getAbsolutePath();
		final String pathSeparator = "/";

		// Normalize the paths
		String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
		String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

		// Undo the changes to the separators made by normalization
		if (pathSeparator.equals("/")) {
			normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
			normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

		} else if (pathSeparator.equals("\\")) {
			normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
			normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);

		} else {
			throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
		}

		final String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
		final String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

		// First get all the common elements. Store them as a string,
		// and also count how many of them there are.
		final StringBuffer common = new StringBuffer();

		int commonIndex = 0;
		while (commonIndex < target.length && commonIndex < base.length
				&& target[commonIndex].equals(base[commonIndex])) {
			common.append(target[commonIndex] + pathSeparator);
			commonIndex++;
		}

		if (commonIndex == 0) {
			// No single common path element. This most
			// likely indicates differing drive letters, like C: and D:.
			// These paths cannot be relativized.
			throw new PathResolutionException(
					"No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + "'");
		}

		// The number of directories we have to backtrack depends on whether the base is a file or a dir
		// For example, the relative path from
		//
		// /foo/bar/baz/gg/ff to /foo/bar/baz
		//
		// ".." if ff is a file
		// "../.." if ff is a directory
		//
		// The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
		// the resource referred to by this path may not actually exist, but it's the best I can do
		boolean baseIsFile = true;

		final File baseResource = new File(normalizedBasePath);

		if (baseResource.exists()) {
			baseIsFile = baseResource.isFile();

		} else if (basePath.endsWith(pathSeparator)) {
			baseIsFile = false;
		}

		final StringBuffer relative = new StringBuffer();

		if (base.length != commonIndex) {
			final int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

			for (int i = 0; i < numDirsUp; i++) {
				relative.append(".." + pathSeparator);
			}
		}
		relative.append(normalizedTargetPath.substring(common.length()));
		return relative.toString();
	}
 
Example 14
Source File: CommonUtils.java    From sahagin-java with Apache License 2.0 4 votes vote down vote up
public static File relativize(File target, File baseDir) {
    String separator = File.separator;
    try {
        String absTargetPath = target.getAbsolutePath();
        absTargetPath = FilenameUtils.normalizeNoEndSeparator(
                FilenameUtils.separatorsToSystem(absTargetPath));
        String absBasePath = baseDir.getAbsolutePath();
        absBasePath = FilenameUtils.normalizeNoEndSeparator(
                FilenameUtils.separatorsToSystem(absBasePath));

        if (filePathEquals(absTargetPath, absBasePath)) {
            throw new IllegalArgumentException("target and base are equal: " + absTargetPath);
        }

        String[] absTargets = absTargetPath.split(Pattern.quote(separator));
        String[] absBases = absBasePath.split(Pattern.quote(separator));

        int minLength = Math.min(absTargets.length, absBases.length);

        int lastCommonRoot = -1;
        for (int i = 0; i < minLength; i++) {
            if (filePathEquals(absTargets[i], absBases[i])) {
                lastCommonRoot = i;
            } else {
                break;
            }
        }

        if (lastCommonRoot == -1) {
            // This case can happen on Windows when drive of two file paths differ.
            throw new IllegalArgumentException("no common root");
        }

        String relativePath = "";

        for (int i = lastCommonRoot + 1; i < absBases.length; i++) {
            relativePath = relativePath + ".." + separator;
        }

        for (int i = lastCommonRoot + 1; i < absTargets.length; i++) {
            relativePath = relativePath + absTargets[i];
            if (i != absTargets.length - 1) {
                relativePath = relativePath + separator;
            }
        }
        return new File(relativePath);
    } catch (Exception e) {
        throw new RuntimeException(String.format(
                "target: %s; baseDir: %s; separator: %s", target, baseDir, separator), e);
    }
}
 
Example 15
Source File: Utils.java    From floobits-intellij with Apache License 2.0 4 votes vote down vote up
public static Boolean isSamePath (String p1, String p2) {
    p1 = FilenameUtils.normalizeNoEndSeparator(p1);
    p2 = FilenameUtils.normalizeNoEndSeparator(p2);
    return FilenameUtils.equalsNormalizedOnSystem(p1, p2);
}
 
Example 16
Source File: Utils.java    From floobits-intellij with Apache License 2.0 4 votes vote down vote up
/** 
 * see http://stackoverflow.com/questions/204784/how-to-construct-a-relative-file-in-java-from-two-absolute-paths-or-urls/3054692#3054692
 * Get the relative file from one file to another, specifying the directory separator.
 * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
 * '\'.
 * 
 * @param targetPath targetPath is calculated to this file
 * @param basePath basePath is calculated from this file
 * @return String
 */
public static String getRelativePath (String targetPath, String basePath) throws  PathResolutionException{
    if (targetPath == null || basePath == null) {
        return null;
    }
    // Normalize the paths
    String pathSeparator = File.separator;
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);

    // Undo the changes to the separators made by normalization
    if (pathSeparator.equals("/")) {
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
    } else if (pathSeparator.equals("\\")) {
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
    } else {
        throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex]).append(pathSeparator);
        commonIndex++;
    }

    if (commonIndex == 0) {
        // No single common file element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        throw new PathResolutionException("No common file element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath
                + "'");
    }   

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative file from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    // 
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
    // the resource referred to by this file may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
        baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(pathSeparator)) {
        baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
        int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

        for (int i = 0; i < numDirsUp; i++) {
            relative.append("..").append(pathSeparator);
        }
    }
    String commonStr = common.toString();
    // Handle missing trailing slash issues with base project directory:
    if (normalizedTargetPath.equals(commonStr.substring(0, commonStr.length() - 1))) {
        return "";
    }
    relative.append(normalizedTargetPath.substring(commonStr.length()));
    return relative.toString();
}
 
Example 17
Source File: LocalTransport.java    From pikatimer with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void test(ReportDestination parent, StringProperty output) {
    
    
    basePath = FilenameUtils.normalizeNoEndSeparator(parent.getBasePath());
        
    File baseDir = new File(basePath);

    stripAccents = parent.getStripAccents();

    

    
    if (baseDir.exists() && baseDir.isDirectory()) {
        Platform.runLater(() -> output.set(output.getValueSafe() + "Target Directory exists." ));
    } else {
        // try and create it
        Platform.runLater(() -> output.set(output.getValueSafe() + "Target Directory does not exist\nAttempting to create it..." ));
        baseDir.mkdirs();

        if (baseDir.exists() && baseDir.isDirectory()) {
            Platform.runLater(() -> output.set(output.getValueSafe() + "\nSuccessfuly created target directory." ));
        } else {
            Platform.runLater(() -> output.set(output.getValueSafe() + "\n\nFailure! Unable to create target directory." ));
            return;
        }

    }
    
    UUID tmpFileName = UUID.randomUUID();
    File tmpFile = new File(baseDir,tmpFileName.toString());
    try {
        tmpFile.createNewFile();
        tmpFile.delete();
        Platform.runLater(() -> output.set(output.getValueSafe() + "\n\nSuccess! the target directory is writable." ));

    } catch (IOException ex) {
        Platform.runLater(() -> output.set(output.getValueSafe() + "\n\nFailure! Unable to write to the target directory." ));

    } 
}