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

The following examples show how to use org.apache.commons.io.FilenameUtils#normalize() . 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: ObjectStateServiceImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
@ValidateParams
public String setObjectState(@ValidateStringParam(name = "site") String site,
                             @ValidateSecurePathParam(name = "path") String path,
                             @ValidateStringParam(name = "state") String state, boolean systemProcessing) {
    path = FilenameUtils.normalize(path, true);
    Map<String, String> params = new HashMap<String, String>();
    params.put("site", site);
    params.put("path", path);
    ItemState objectState = itemStateMapper.getObjectStateBySiteAndPath(params);
    if (objectState == null) {
        insertNewEntry(site, path);
        objectState = itemStateMapper.getObjectStateBySiteAndPath(params);
    }
    objectState.setState(state);
    objectState.setSystemProcessing(systemProcessing ? 1 : 0);
    itemStateMapper.setObjectState(objectState);
    return "Success";
}
 
Example 2
Source File: GoLangFileMatchTest.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch() throws IOException {
    String pattern = testCase.pattern;
    String s = testCase.s;
    if (GoLangFileMatch.IS_WINDOWS) {
        if (pattern.indexOf('\\') >= 0) {
            // no escape allowed on windows.
            return;
        }
        pattern = FilenameUtils.normalize(pattern);
        s = FilenameUtils.normalize(s);
    }
    try {
        Boolean matched = GoLangFileMatch.match(pattern, s);
        if (testCase.expectException) {
            fail("Expected GoFileMatchException");
        }
        assertEquals(testCase.toString(), testCase.matches, matched);
    } catch (GoLangFileMatchException e) {
        if (!testCase.expectException) {
            throw e;
        }
    }
}
 
Example 3
Source File: OpenviduConfig.java    From openvidu with Apache License 2.0 6 votes vote down vote up
public File getDotenvFile() {
	if (getDotenvPath() != null && !getDotenvPath().isEmpty()) {

		Path path = getDotenvFilePathFromDotenvPath(getDotenvPath());
		String normalizePath = FilenameUtils.normalize(path.toAbsolutePath().toString());
		File file = new File(normalizePath);

		if (file.exists()) {
			return file;
		} else {
			log.error(".env file not found at {}", file.getAbsolutePath().toString());
		}

	} else {
		log.warn("DOTENV_PATH configuration property is not defined");
	}
	return null;
}
 
Example 4
Source File: ObjectStateServiceImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
@ValidateParams
public boolean isInWorkflow(@ValidateStringParam(name = "site") String site,
                            @ValidateSecurePathParam(name = "path") String path) {
    path = FilenameUtils.normalize(path, true);
    ItemState state = getObjectState(site, path);
    if (state != null) {
        return State.isInWorkflow(State.valueOf(state.getState()));
    } else {
        return false;
    }
}
 
Example 5
Source File: FileResource.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setExcludes(String[] excludes) {
	if (excludes != null && System.getProperty("os.name").toLowerCase().contains("windows")) {
		for (int i = 0; i < excludes.length; i++) {
			excludes[i] = FilenameUtils.normalize(excludes[i], true);
		}
	}
	this.excludes = excludes;
}
 
Example 6
Source File: TemplateFilePO.java    From youran with Apache License 2.0 5 votes vote down vote up
/**
 * 针对文件名渲染文件,获取对应的文件内容路径
 *
 * @return
 */
public String fetchContentPathForFilenameFile() {
    if (TemplateFileType.FILENAME.getValue().equals(this.fileType)) {
        if (!this.fileName.startsWith("__")) {
            throw new BusinessException(ErrorCode.INNER_DATA_ERROR,
                "文件名渲染文件必须是双下划线开头:" + this.fetchFilePath());
        }
        String filename = this.fileDir + "/" + this.fileName.substring(2);
        return FilenameUtils.normalize(filename.replaceAll("\\/+", "/"), true);
    }
    throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR,
        "该模板文件不是文件名渲染文件:" + this.fetchFilePath());
}
 
Example 7
Source File: AbstractFileWriter.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected boolean isValid(File out) throws IOException {

        boolean write = true;
        if (out != null) {
            String aux = FilenameUtils.normalize(out.getCanonicalPath(), true);
            if (excludes != null) {
                for (int i = 0; i < excludes.length && write; i++) {
                    if (!excludes[i].startsWith(normalizedOutputDirectory)) {
                        excludes[i] = normalizedOutputDirectory + "/" + excludes[i];
                        if (excludes[i].endsWith("\\*\\*")) {
                            excludes[i] = excludes[i].substring(0, excludes[i].length() - 2);
                        }
                    }
                    write = !(excludes[i].startsWith(aux) || FilenameUtils.wildcardMatch(aux, excludes[i]));
                }
            }
            if (includes != null && write) {
                write = false;
                for (int i = 0; i < includes.length && !write; i++) {
                    if (!includes[i].startsWith(normalizedOutputDirectory)) {
                        includes[i] = normalizedOutputDirectory + "/" + includes[i];
                        if (includes[i].endsWith("\\*\\*")) {
                            includes[i] = includes[i].substring(0, includes[i].length() - 2);
                        }
                    }

                    write = includes[i].startsWith(aux) || FilenameUtils.wildcardMatch(aux, includes[i]);
                }
            }
        }
        return write;
    }
 
Example 8
Source File: DarwinResolver.java    From unidbg with Apache License 2.0 5 votes vote down vote up
@Override
public FileResult<DarwinFileIO> resolve(Emulator<DarwinFileIO> emulator, String path, int oflags) {
    if ("".equals(path)) {
        return FileResult.failed(UnixEmulator.ENOENT);
    }

    FileSystem<DarwinFileIO> fileSystem = emulator.getFileSystem();
    if (".".equals(path)) {
        return FileResult.success(createFileIO(fileSystem.createWorkDir(), path, oflags));
    }

    if (path.endsWith("/Library/Preferences/.GlobalPreferences.plist")) {
        if (_GlobalPreferences == null) {
            Locale locale = Locale.getDefault();
            Map<String, Object> map = new HashMap<>();
            map.put("AppleICUForce24HourTime", true);
            map.put("AppleLanguages", new String[] { locale.getLanguage() });
            map.put("AppleLocale", locale.toString());
            NSDictionary root = (NSDictionary) NSDictionary.fromJavaObject(map);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                PropertyListParser.saveAsBinary(root, outputStream);
            } catch (IOException e) {
                throw new IllegalStateException("save .GlobalPreferences.plist failed", e);
            }
            _GlobalPreferences = outputStream.toByteArray();
        }
        return FileResult.<DarwinFileIO>success(new ByteArrayFileIO(oflags, path, _GlobalPreferences));
    }

    String iosResource = FilenameUtils.normalize("/ios/" + version + "/" + path, true);
    File file = ResourceUtils.extractResource(DarwinResolver.class, iosResource, path);
    if (file != null) {
        return FileResult.fallback(createFileIO(file, path, oflags));
    }

    return null;
}
 
Example 9
Source File: AbstractFileWriter.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setExcludes(String[] excludes) {
    if (excludes != null && System.getProperty("os.name").toLowerCase().contains("windows")) {
        for (int i = 0; i < excludes.length; i++) {
            excludes[i] = FilenameUtils.normalize(excludes[i], true);
        }
    }
    this.excludes = excludes;
}
 
Example 10
Source File: LocalDocWriter.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
@Deprecated
	/*
	 * Use {@link DocExporter#writeRawDoc}
	 * @deprecated
	 */
	public static void writeTrpDoc(TrpDoc doc, String path, ExportCache cache) throws Exception {
		if (doc == null) {
			throw new Exception("Null document given!");
		}
//		if (doc.getMd().getLocalFolder()==null)
//			throw new Exception("This is not a local document!");
				
		File dir = new File(path);
		FileUtils.forceMkdir(dir);
		
		String pathN = FilenameUtils.normalize(path);
		
		// write metadata:
		if (doc.getMd()!=null) {
			writeTrpDocMetadata(doc, path);
		}
		
		// write all images and page xml:
		for (TrpPage p : doc.getPages()) {
			File imgFile = copyImgFile(p, p.getUrl(), pathN);
			logger.debug("Written image file "+imgFile.getAbsolutePath());
			
			File xmlFile = copyTranscriptFile(p, pathN+"/"+LocalDocConst.PAGE_FILE_SUB_FOLDER, cache);
			if (xmlFile != null)
				logger.debug("Written transcript xml file "+xmlFile.getAbsolutePath());	
			else
				logger.debug("No transcript found for page "+p.getPageNr());
		}
	}
 
Example 11
Source File: ARM64SyscallHandler.java    From unidbg with Apache License 2.0 5 votes vote down vote up
/**
 * lstat() is identical to stat(), except that if pathname is a symbolic link, then it returns information about the link itself, not the file that it refers to.
 */
private int lstat(Emulator<DarwinFileIO> emulator, int offset) {
    RegisterContext context = emulator.getContext();
    Pointer pathname = context.getPointerArg(offset);
    Pointer stat = context.getPointerArg(offset + 1);
    String pathStr = pathname.getString(0);
    String path = FilenameUtils.normalize(pathStr);
    int ret = stat64(emulator, path, stat);
    if (log.isDebugEnabled()) {
        log.debug("lstat path=" + path + ", pathStr=" + pathStr + ", stat=" + stat + ", ret=" + ret + ", LR=" + context.getLRPointer());
    }
    return ret;
}
 
Example 12
Source File: ARM64SyscallHandler.java    From unidbg with Apache License 2.0 5 votes vote down vote up
private int unlink(Emulator<?> emulator) {
    RegisterContext context = emulator.getContext();
    Pointer pathname = context.getPointerArg(0);
    String path = FilenameUtils.normalize(pathname.getString(0));
    emulator.getFileSystem().unlink(path);
    return 0;
}
 
Example 13
Source File: ObjectStateServiceImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
@ValidateParams
public void deleteObjectStateForPath(@ValidateStringParam(name = "site") String site,
                                     @ValidateSecurePathParam(name = "path") String path) {
    path = FilenameUtils.normalize(path, true);
    Map<String, String> params = new HashMap<String, String>();
    params.put("site", site);
    params.put("path", path);
    itemStateMapper.deleteObjectStateForSiteAndPath(params);
}
 
Example 14
Source File: ExtraFile.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
public boolean isSameOrHasParent(@Nullable final File baseFolder, @Nonnull 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());

  if (theFilePath.startsWith(thatFilePath)) {
    final String diff = theFilePath.substring(thatFilePath.length());
    return diff.isEmpty() || diff.startsWith("\\") || diff.startsWith("/") || thatFilePath.endsWith("/") || thatFilePath.endsWith("\\");
  } else {
    return false;
  }
}
 
Example 15
Source File: ObjectStateServiceImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
@ValidateParams
public boolean isScheduled(@ValidateStringParam(name = "site") String site,
                           @ValidateSecurePathParam(name = "path") String path) {
    path = FilenameUtils.normalize(path, true);
    ItemState state = getObjectState(site, path);
    if (state != null) {
        return State.isScheduled(State.valueOf(state.getState()));
    } else {
        return false;
    }
}
 
Example 16
Source File: ObjectMetadataManagerImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
@ValidateParams
public void deleteObjectMetadataForFolder(@ValidateStringParam(name = "site") String site,
                                          @ValidateSecurePathParam(name = "path") String path) {
    path = FilenameUtils.normalize(path, true);
    Map<String, String> params = new HashMap<>();
    params.put("site", site);
    params.put("path", path + "/%");
    itemMetadataMapper.deleteFolder(params);
}
 
Example 17
Source File: PathUtils.java    From opoopress with Apache License 2.0 5 votes vote down vote up
public static String getRelativePath(String baseDir, File file){
	String filePath = FilenameUtils.normalize(file.getAbsolutePath(), true);

	if(!baseDir.endsWith("/")){
		baseDir += "/";
	}

	if(filePath.startsWith(baseDir)){
		return filePath.substring(baseDir.length());
	}else {
		throw new IllegalArgumentException("File '" + file + "' not in base directory '" + baseDir + "'");
	}
}
 
Example 18
Source File: ARM64SyscallHandler.java    From unidbg with Apache License 2.0 4 votes vote down vote up
private int unlink(Emulator<?> emulator) {
    Pointer pathname = UnicornPointer.register(emulator, ArmConst.UC_ARM_REG_R0);
    String path = FilenameUtils.normalize(pathname.getString(0));
    log.info("unlink path=" + path);
    return 0;
}
 
Example 19
Source File: CopyTool.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Imports the files that hold the table data into the child instance.
 * @param childTableName the name of the child table to import.
 * @throws Exception
 */
public void importFilesToChildTable(final String childTableName) throws Exception {
    final String normalizedChildTableName = FilenameUtils.normalize(childTableName);
    if (normalizedChildTableName == null) {
        throw new Exception("Invalid child table name: " + childTableName);
    }

    final Configuration childConfig = MergeToolMapper.getChildConfig(conf);
    final AccumuloRdfConfiguration childAccumuloRdfConfiguration = new AccumuloRdfConfiguration(childConfig);
    childAccumuloRdfConfiguration.setTablePrefix(childTablePrefix);
    final Connector childConnector = AccumuloRyaUtils.setupConnector(childAccumuloRdfConfiguration);
    final TableOperations childTableOperations = childConnector.tableOperations();

    final Path localWorkDir = getPath(localCopyFileImportDir, normalizedChildTableName);
    final Path hdfsBaseWorkDir = getPath(baseImportDir, normalizedChildTableName);

    final FileSystem fs = FileSystem.get(conf);
    if (fs.exists(hdfsBaseWorkDir)) {
        fs.delete(hdfsBaseWorkDir, true);
    }

    log.info("Importing from the local directory: " + localWorkDir);
    log.info("Importing to the HDFS directory: " + hdfsBaseWorkDir);
    copyLocalToHdfs(localWorkDir, hdfsBaseWorkDir);

    final Path files = getPath(hdfsBaseWorkDir.toString(), "files");
    final Path failures = getPath(hdfsBaseWorkDir.toString(), "failures");

    // With HDFS permissions on, we need to make sure the Accumulo user can read/move the files
    final FsShell hdfs = new FsShell(conf);
    if (!fs.isDirectory(hdfsBaseWorkDir)) {
        throw new IllegalArgumentException("Configured working directory is not a valid directory" + hdfsBaseWorkDir.toString());
    }
    hdfs.run(new String[] {"-chmod", "777", hdfsBaseWorkDir.toString()});
    if (fs.exists(failures)) {
        fs.delete(failures, true);
    }
    fs.mkdirs(failures);

    childTableOperations.importDirectory(normalizedChildTableName, files.toString(), failures.toString(), false);
}
 
Example 20
Source File: ExtraFile.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean containsPattern(@Nullable final File baseFolder, @Nonnull final Pattern pattern) {
  final String filePathAsText = FilenameUtils.normalize(this.fileUri.asFile(baseFolder).getAbsolutePath());
  return pattern.matcher(filePathAsText).find();
}