下面列出了java.io.File#getCanonicalPath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Checks whether given file resides inside give directory.
*/
private static boolean isChildOf(File f, String dirName) {
try {
File dir = new File(dirName);
String canonicalDirName = dir.getCanonicalPath();
if (!canonicalDirName.endsWith(File.separator)) {
canonicalDirName += File.separator;
}
String canonicalFileName = f.getCanonicalPath();
return canonicalFileName.startsWith(canonicalDirName);
} catch (IOException e) {
/* we do not expect the IOException here, because invocation
* of this function is always preceded by isFile() call.
*/
return false;
}
}
/**
* Check if the file represents the root folder of an external or internal SD card.
*
* @param file The file to be checked.
* @return true if root folder of an SD card.
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
public static boolean isSdCardPath(final File file) {
String filePath;
try {
filePath = file.getCanonicalPath();
}
catch (IOException e) {
filePath = file.getAbsolutePath();
}
if (filePath.equals(getSdCardPath())) {
return true;
}
for (String path : getExtSdCardPaths()) {
if (filePath.equals(path)) {
return true;
}
}
return false;
}
private SecretValue getSecretValue(ToggleGroup valueSource, String value, String generated, File file) {
Toggle current = valueSource.getSelectedToggle();
String secretString;
if (current.getUserData().equals("value")) {
secretString = value;
} else if (current.getUserData().equals("generated")) {
Integer numBytesToGenerate = Integer.valueOf(generated);
// TODO: store as plain bytes?
byte[] random = Singleton.randomGenerator.generateRandom(numBytesToGenerate);
secretString = Base64.encodeAsString(random);
} else {
String path = null;
try {
path = file.getCanonicalPath();
return SecretValueConverter.inferEncoding(Files.readAllBytes(Paths.get(path)), SecretType.OPAQUE);
} catch (IOException e) {
throw new RuntimeException("Failed to read secret from file");
}
}
return new SecretValue(secretString, SecretType.OPAQUE);
}
private String createDotFormat(File file) throws IOException {
String filename = file.getCanonicalPath();
if (!filename.startsWith(sourcePath)) {
throw new IOException("Test file not in test directory");
}
if (filename.equals(sourcePath)) {
return "AllTests";
}
filename = filename.substring(sourcePath.length() + 1);
filename = filename.replace(File.separatorChar, '.');
if (file.isDirectory()) {
return filename + ".AllTests";
} else {
return filename.substring(0, filename.length() - 3);
}
}
public static boolean isMediaDirectory(File file)
{
try
{
String path = file.getCanonicalPath();
for (String directory : new String[]{Environment.DIRECTORY_DCIM,
Environment.DIRECTORY_MUSIC,
Environment.DIRECTORY_PICTURES})
{
if (path.startsWith(Environment.getExternalStoragePublicDirectory(directory)
.getAbsolutePath()))
return true;
}
return false;
} catch (IOException e)
{
e.printStackTrace();
return false;
}
}
private static String getPathName(final File file)
{
try
{
if (projectRoot == null)
{
projectRoot = new File(".").getCanonicalPath();
}
final String pathName = file.getCanonicalPath();
if (!pathName.startsWith(projectRoot))
{
throw new CodeException("Not in project folder: " + file.getPath());
}
// normalize path name by removing root and using forward slash separators
return pathName.substring(projectRoot.length() + 1).replace('\\', '/');
}
catch (final IOException e)
{
e.printStackTrace();
throw new CodeException("Cannot getCanonicalPath for: " + file.getPath());
}
}
/**
* A small implementation of UNIX find.
* @param matchRegex Only collect paths that match this regex.
* @param pruneRegex Don't recurse down a path that matches this regex. May be null.
* @throws IOException if File.getCanonicalPath() fails.
*/
public static List<File> find(final File startpath, final String matchRegex, final String pruneRegex) throws IOException{
final Pattern matchPattern = Pattern.compile(matchRegex, Pattern.CASE_INSENSITIVE);
final Pattern prunePattern = pruneRegex == null ? null : Pattern.compile(pruneRegex, Pattern.CASE_INSENSITIVE);
final Set<String> visited = new HashSet<String>();
final List<File> found = new ArrayList<File>();
class Search{
void search(final File path) throws IOException{
if(prunePattern != null && prunePattern.matcher(path.getAbsolutePath()).matches()) return;
String cpath = path.getCanonicalPath();
if(!visited.add(cpath)) return;
if(matchPattern.matcher(path.getAbsolutePath()).matches())
found.add(path);
if(path.isDirectory())
for(File sub : path.listFiles())
search(sub);
}
}
new Search().search(startpath);
return found;
}
protected String asWritableFileSystemPath(String property) {
try {
String stringPath = this.asNonEmptyString(property);
Paths.get(stringPath);
File f = new File(stringPath);
f.getCanonicalPath();
f.toURI().toString();
if (!f.exists()) {
if (!f.mkdirs()) {
throw new Exception(
"The path does not exist and OpenVidu Server does not have enough permissions to create it");
}
}
if (!f.canWrite()) {
throw new Exception(
"OpenVidu Server does not have permissions to write on path " + f.getCanonicalPath());
}
stringPath = stringPath.endsWith("/") ? stringPath : (stringPath + "/");
return stringPath;
} catch (Exception e) {
addError(property, "Is not a valid writable file system path. " + e.getMessage());
return null;
}
}
/**
* Extracts the given path to the native library in the resource directory into the target directory.
* If the native library already exists in the target library, the existing native library will be used.
*/
@NonNull
@SuppressFBWarnings("DE_MIGHT_IGNORE")
private static File extract(@NonNull String libResPath, @NonNull String targetDir)
throws IOException, InterruptedException {
final File targetFile = new File(targetDir, new File(libResPath).getName());
if (targetFile.exists()) { return targetFile; }
final File dir = new File(targetDir);
if (!dir.mkdirs() && !dir.exists()) {
throw new IOException("Cannot create target directory: " + dir.getCanonicalPath());
}
// Extract the library to the target directory:
try (
InputStream in = NativeLibrary.class.getResourceAsStream(libResPath);
OutputStream out = Files.newOutputStream(targetFile.toPath());
) {
if (in == null) { throw new IOException("Native library not found at " + libResPath); }
final byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); }
}
// On non-windows systems set up permissions for the extracted native library.
if (!System.getProperty("os.name").toLowerCase(Locale.getDefault()).contains("windows")) {
Runtime.getRuntime().exec(new String[] {"chmod", "755", targetFile.getCanonicalPath()}).waitFor();
}
return targetFile;
}
private String getInspectorAirGapPath(File detectJar, final String inspectorLocationProperty, final String inspectorName) {
if (StringUtils.isBlank(inspectorLocationProperty) && detectJar != null) {
try {
final File inspectorsDirectory = new File(detectJar.getParentFile(), "packaged-inspectors");
final File inspectorAirGapDirectory = new File(inspectorsDirectory, inspectorName);
return inspectorAirGapDirectory.getCanonicalPath();
} catch (final Exception e) {
logger.debug(String.format("Exception encountered when guessing air gap path for %s, returning the detect property instead", inspectorName));
logger.debug(e.getMessage());
}
}
return inspectorLocationProperty;
}
protected boolean isSymLink(IResource resource) {
File file = resource.getLocation().toFile();
try {
if (!file.exists())
return true;
else {
String cnnpath = file.getCanonicalPath();
String abspath = file.getAbsolutePath();
return !abspath.equals(cnnpath);
}
} catch(IOException ex) {
return true;
}
}
public static void main(String args[]) throws Exception {
File file = new File(System.getProperty("test.src", "."), "jars");
String fileURL = "file:" + file.getCanonicalPath() + file.separator +
"test.jar";
test(fileURL);
String jarURL = "jar:" + fileURL + "!/";
test(jarURL);
if (testFailed) {
throw new Exception("Test failed - getLastModified returned 0");
}
}
private boolean isGeneratedSource(File file) {
try {
String path = file.getCanonicalPath() + File.separator;
String projectPath = this.project.getBasedir().getCanonicalPath();
return path.startsWith(projectPath)
&& (path.contains(GENERATED_SOURCES) || path.contains(GENERATED_TEST_SOURCES));
}
catch (IOException ex) {
return false;
}
}
private File unzipToTemp() throws IOException, InterruptedException {
File dir = Files.createTempDirectory("cps_unzip").toFile();
dir.deleteOnExit();
ProcessBuilder builder =
new ProcessBuilder("unzip", Client.RESOURCE_DIR + "/cps.zip", "-d", dir.getCanonicalPath());
int retval = builder.start().waitFor();
if (retval != 0) {
throw new IOException("Failed to unzip resource_controllers zip with error code: " + retval);
}
log.error("unzipped to: " + dir.getAbsolutePath());
return dir;
}
/**
* Helper method to extract the canonical path from a file.
*
* @param file
* @return canonical path
*/
private static String getCanonicalPath(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
LOGGER.error("Unable to get canonical path for file: "+file.getAbsolutePath(), e);
}
return null;
}
/**
* ��ʼ��AndroidAppium
* @param properties �����ļ�����
* @return ���ذ�appium����
* @throws IOException ���쳣
*/
public static AndroidDriver<AndroidElement> setAndroidAppium(Properties properties) throws IOException {
AndroidDriver<AndroidElement> appium;
DesiredCapabilities capabilities = new DesiredCapabilities();
File directory = new File("");
File app = new File(directory.getCanonicalPath() + File.separator + properties.getProperty("appname"));
capabilities.setCapability("app", app.getAbsolutePath());
// �Զ������Է���
capabilities.setCapability("automationName", properties.getProperty("automationName"));
// �豸����
capabilities.setCapability("deviceName", properties.getProperty("deviceName"));
// ƽ̨����
capabilities.setCapability("platformName", properties.getProperty("platformName"));
// ϵͳ�汾
capabilities.setCapability("platformVersion", properties.getProperty("platformVersion"));
// ģ�����ϵ�ip��ַ
capabilities.setCapability("udid", properties.getProperty("udid"));
// AndroidӦ�õİ���
capabilities.setCapability("appPackage", properties.getProperty("appPackage"));
// ������Android Activity
capabilities.setCapability("appActivity", properties.getProperty("appActivity"));
// ֧���������룬���Զ���װUnicode����
capabilities.setCapability("unicodeKeyboard", Boolean.valueOf(properties.getProperty("unicodeKeyboard")));
// �������뷨��ԭ��״̬
capabilities.setCapability("resetKeyboard", Boolean.valueOf(properties.getProperty("resetKeyboard")));
// ������ǩ��apk
capabilities.setCapability("noSign", Boolean.valueOf(properties.getProperty("noSign")));
// �Ƿ�������°�װAPP
capabilities.setCapability("noReset", Boolean.valueOf(properties.getProperty("noReset")));
// �ȴ���ʱû���յ�����ر�appium
capabilities.setCapability("newCommandTimeout", properties.getProperty("newCommandTimeout"));
String url="http://" + properties.getProperty("appiumsever") + "/wd/hub";
appium = new AndroidDriver<>(new URL(url), capabilities);
int waittime = Integer.parseInt(properties.getProperty("implicitlyWait"));
appium.manage().timeouts().implicitlyWait(waittime, TimeUnit.SECONDS);
return appium;
}
/**
* Return true if this file is an alias to another file.
*
* @param file
* the file to check against.
* @return true if this file is an alias to another file.
*/
public static boolean isAlias(File file) {
try {
if (!file.exists()) {
return false;
} else {
String cnnpath = file.getCanonicalPath();
String abspath = file.getAbsolutePath();
boolean returnValue = !abspath.equals(cnnpath);
return returnValue;
}
} catch (IOException ex) {
return false;
}
}
private void verifyIncrementalBackupPerformed() {
Log.getLogWriter().info("BackupRestoreTest.verifyIncrementalBackupPerformed");
String restoreFile = RESTORE_LINUX;
if (HostHelper.isWindows()) {
restoreFile = RESTORE_WINDOWS;
}
boolean doBackup = BackupAndRestorePrms.getDoBackup();
Log.getLogWriter().info("BackupRestoreTest.verifyIncrementalBackupPerformed-doBackup=" + doBackup);
// Check if we are to perform backups
if (doBackup) {
// Check if we are to perform incremental backups
boolean incrementalBackups = BackupAndRestorePrms.getIncrementalBackups();
Log.getLogWriter()
.info("BackupRestoreTest.verifyIncrementalBackupPerformed-incrementalBackups=" + incrementalBackups);
// How many backups have we done?
long BackupCntr = BackupAndRestoreBB.getBB().getSharedCounters().read(BackupAndRestoreBB.BackupCtr);
Log.getLogWriter().info("BackupRestoreTest.verifyIncrementalBackupPerformed-BackupCntr=" + BackupCntr);
// If we are doing incremental backups and we have done at least two backups, then we should have done an incremental backup
if (incrementalBackups && BackupCntr > 1) {
File latestBackupDir = findLatestBackupDir();
if (latestBackupDir == null) {
throw new TestException("Expecting the test directory to contain at least 1 backup directory, but none were found.");
}
// Check the contents of the backup directory
for (File hostVMDir : latestBackupDir.listFiles()) {
// Check the contents of the host's backup directories
for (File aFile : hostVMDir.listFiles()) {
// Find the restore script
if (aFile.getName().equals(restoreFile)) {
// Check the script file for incremental
try {
String restoreScriptFullFilename = aFile.getCanonicalPath();
boolean isBackupIncremental = FileUtil.hasLinesContaining(restoreScriptFullFilename, INCREMENTAL_TEXT);
Log.getLogWriter()
.info("BackupRestoreTest.verifyIncrementalBackupPerformed-isBackupIncremental=" + isBackupIncremental);
if (!isBackupIncremental) {
throw new TestException("Expecting the restore script to be of type incremental, but it wasn't.");
}
} catch (IOException e) {
throw new TestException(TestHelper.getStackTrace(e));
}
break;
}
}
}
}
}
}
public void testUnixSearchFile() throws Exception {
System.out.println("Test testUnixSearchFile()"); // NOI18N
ExecutionEnvironment env = ExecutionEnvironmentFactory.getLocal();
HostInfo info = HostInfoUtils.getHostInfo(env);
assertNotNull(info);
if (info.getShell() == null) {
return;
}
if (!info.getOSFamily().isUnix()) {
System.out.println("Skipped on " + info.getOSFamily().name()); // NOI18N
return;
}
File testDir = new File(info.getTempDirFile(), "some dir"); // NOI18N
testDir.mkdir();
File testFile = File.createTempFile("some (", ") file", testDir); // NOI18N
testFile.createNewFile();
System.out.println("Use file '" + testFile.getCanonicalPath() + "' for testing"); // NOI18N
try {
String result = null;
result = HostInfoUtils.searchFile(env, Arrays.asList("/wrong Path", testDir.getCanonicalPath(), "/usr/bin"), testFile.getName(), true); // NOI18N
assertNotNull(result);
String expectedPath = testFile.getCanonicalPath();
if (info.getOSFamily() == HostInfo.OSFamily.WINDOWS) {
expectedPath = WindowsSupport.getInstance().convertToShellPath(result);
}
assertEquals(expectedPath, result);
result = HostInfoUtils.searchFile(env, Arrays.asList("/wrongPath", "/bin", "/usr/bin"), "rm", true); // NOI18N
assertNotNull(result);
result = HostInfoUtils.searchFile(env, Arrays.asList("/wrongPath", "/bin", "/usr/bin"), "rm", false); // NOI18N
assertNotNull(result);
result = HostInfoUtils.searchFile(env, Arrays.asList("/wrongPath"), "ls", true); // NOI18N
assertNotNull(result);
result = HostInfoUtils.searchFile(env, Arrays.asList("/wrongPath"), "ls", false); // NOI18N
assertNull(result);
} finally {
testFile.delete();
testDir.delete();
}
}
@Test
public void testVersioningStateOutputJsonFile()
throws Exception
{
// given
File baseDir = tmpFolderRule.newFolder();
String basePath = baseDir.getCanonicalPath();
File pomFile = getResourceFile();
copyFile( pomFile, new File( baseDir, "pom.xml" ) );
// when
Map<String, String> params = new HashMap<>();
params.put( "restURL", mockServer.getUrl() );
params.put( VersioningState.INCREMENT_SERIAL_SUFFIX_SYSPROP, AddSuffixJettyHandler.SUFFIX );
params.put( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "0" );
Integer exitValue = runCli( Collections.emptyList(), params, basePath );
// then
assertEquals( (Integer) 0, exitValue );
File outputJsonFile = Paths.get( basePath, "target", "manipulation.json" ).toFile();
assertTrue( outputJsonFile.exists() );
JsonNode rootNode = MAPPER.readTree( outputJsonFile );
JsonNode executionRootModified = rootNode.get( "executionRoot" );
assertNotNull( executionRootModified );
JsonNode groupId = executionRootModified.get( "groupId" );
JsonNode artifactId = executionRootModified.get( "artifactId" );
JsonNode version = executionRootModified.get( "version" );
assertNotNull( groupId );
assertNotNull( artifactId );
assertNotNull( version );
assertEquals( "org.commonjava.maven.ext.versioning.test", groupId.textValue() );
assertEquals( "project-version", artifactId.textValue() );
assertEquals( "1.0.0.redhat-2", version.textValue() );
}