Java Code Examples for java.io.File#isAbsolute()

The following examples show how to use java.io.File#isAbsolute() . 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: LibrariesSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Properly converts possibly relative file path to URI.
 * @param path file path to convert; can be relative; cannot be null
 * @return uri
 * @since org.netbeans.modules.project.libraries/1 1.18
 */
public static URI convertFilePathToURI(final @NonNull String path) {
    Parameters.notNull("path", path);   //NOI18N
    try {
        File f = new File(path);
        if (f.isAbsolute()) {
            return BaseUtilities.toURI(f);
        } else {
            // create hierarchical relative URI (that is no schema)
            return new URI(null, null, path.replace('\\', '/'), null);
        }

    } catch (URISyntaxException ex) {
 IllegalArgumentException y = new IllegalArgumentException();
 y.initCause(ex);
 throw y;
    }
}
 
Example 2
Source File: ESLintSettingsPage.java    From eslint-plugin with MIT License 6 votes vote down vote up
private boolean validatePath(String path, boolean allowEmpty) {
    if (StringUtils.isEmpty(path)) {
        return allowEmpty;
    }
    File filePath = new File(path);
    if (filePath.isAbsolute()) {
        if (!filePath.exists() || !filePath.isFile()) {
            return false;
        }
    } else {
        if (project.isDefault()) {
            return false;
        }
        VirtualFile child = project.getBaseDir().findFileByRelativePath(path);
        if (child == null || !child.exists() || child.isDirectory()) {
            return false;
        }
    }
    return true;
}
 
Example 3
Source File: SpellingPreferenceBlock.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
private void validateAbsoluteFilePath() {
    MyStatus ms = new MyStatus(IStatus.OK, XdsEditorsPlugin.PLUGIN_ID, null);
    String path = fDictionaryPath == null ? "" : fDictionaryPath.getText().trim(); //$NON-NLS-1$
    if (!path.isEmpty()) {
   	    IStringVariableManager variableManager= VariablesPlugin.getDefault().getStringVariableManager();
   	    try {
   	        path= variableManager.performStringSubstitution(path);
   	        if (path.length() > 0) {
   	            final File file= new File(path);
   	            if (!file.exists() || !file.isFile() || !file.isAbsolute() || !file.canRead()) {
                       ms = new MyStatus(IStatus.ERROR, XdsEditorsPlugin.PLUGIN_ID, Messages.SpellingPreferenceBlock_BadDictFile);
   	            } else if (!file.getParentFile().canWrite() || !file.canWrite()) {
   	                ms = new MyStatus(IStatus.ERROR, XdsEditorsPlugin.PLUGIN_ID, Messages.SpellingPreferenceBlock_RWAccessRequired);
   	            }
   	        }
   	    } catch (CoreException e) {
   	        ms = new MyStatus(IStatus.ERROR, XdsEditorsPlugin.PLUGIN_ID, e.getLocalizedMessage());
   	    }
    }
    
    if (ms.matches(IStatus.ERROR) || fFileStatus.matches(IStatus.ERROR)) {
        fFileStatus = ms;
        updateStatus();
    }
}
 
Example 4
Source File: RandomCSVReader.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
public RandomCSVReader(String filename, String encoding,
                       String delim, boolean randomOrder,
                       boolean hasVariableNames, boolean firstLineIsHeader,
                       boolean isRewindOnEndOfList) {
    File f = new File(filename);
    this.file = (f.isAbsolute() || f.exists()) ? f : new File(FileServer.getFileServer().getBaseDir(), filename);
    this.encoding = encoding;
    this.delim = checkDelimiter(delim).charAt(0);
    this.isSkipFirstLine = !(!firstLineIsHeader && hasVariableNames);
    this.randomOrder = randomOrder;
    this.isRewindOnEndOfList = isRewindOnEndOfList;
    try {
        initOffsets();
        if (randomOrder) {
            initRandom();
        } else {
            initConsistentReader();
        }
        initHeader();
    } catch (IOException ex) {
        LOGGER.error("Cannot initialize RandomCSVReader, because of error: ", ex);
        throw new RuntimeException("Cannot initialize RandomCSVReader, because of error: " + ex.getMessage(), ex);
    }
}
 
Example 5
Source File: Builder.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
public Cmd(File basedir) {
	_basedir = basedir;
	String path = System.getProperty("launch4j.bindir");
	if (path == null) {
		_bindir = new File(basedir, "bin");
	} else {
		File bindir = new File(path);
		_bindir = bindir.isAbsolute() ? bindir : new File(basedir, path);
	}
}
 
Example 6
Source File: ThirdEyeDashboardApplication.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private static File getRootCauseDefinitionsFile(ThirdEyeDashboardConfiguration config) {
  if(config.getRootCause().getDefinitionsPath() == null)
    throw new IllegalArgumentException("definitionsPath must not be null");
  File rcaConfigFile = new File(config.getRootCause().getDefinitionsPath());
  if(!rcaConfigFile.isAbsolute())
    return new File(config.getRootDir() + File.separator + rcaConfigFile);
  return rcaConfigFile;
}
 
Example 7
Source File: AbstractSvnTestCase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected SVNUrl getFileUrl(File file) {
    if (file.isAbsolute()) {
        return getFileUrl(getPathRelativeToWC(file));
    } else {
        return getFileUrl(file.getPath());
    }
}
 
Example 8
Source File: FileUtils.java    From opensim-gui with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param folder name of folder to search
 * @param baseName starting guess for unused filename located under folder
 * @return name of unused filename that can be created under folder in the form base_X 
 */
public static String getNextAvailableName(String folder, String baseName) {
    File baseFile = new File(baseName);
    if (baseFile.isAbsolute()){ // user specified a full path. Ignore passed in folder
        folder = baseFile.getParent();
    }
    else
        baseName = folder+baseName;
    // Here folder and baseName are consistent for a file and a parent directory
    File parentDir = new File(folder);
    // Handle extension
    String stripExtension = baseName.substring(0, baseName.lastIndexOf('.'));
    if (stripExtension.contains("_"))
        stripExtension = stripExtension.substring(0, baseName.lastIndexOf('_'));
    String extensionString = baseName.substring(baseName.lastIndexOf('.')); // includes .
    // Cycle thru and check if the file exists, return first available
    boolean found = false;
    int index=1;
    while(!found){
        String suffix = "_"+String.valueOf(index);
        File nextCandidate = new File(stripExtension+suffix+extensionString);
        if (!nextCandidate.exists()){
            return stripExtension+suffix+extensionString;
        }
        index++;
    }
    // unreached
    return null;
}
 
Example 9
Source File: FileSystemView.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determines if the given file is a root in the navigable tree(s).
 * Examples: Windows 98 has one root, the Desktop folder. DOS has one root
 * per drive letter, <code>C:\</code>, <code>D:\</code>, etc. Unix has one root,
 * the <code>"/"</code> directory.
 *
 * The default implementation gets information from the <code>ShellFolder</code> class.
 *
 * @param f a <code>File</code> object representing a directory
 * @return <code>true</code> if <code>f</code> is a root in the navigable tree.
 * @see #isFileSystemRoot
 */
public boolean isRoot(File f) {
    if (f == null || !f.isAbsolute()) {
        return false;
    }

    File[] roots = getRoots();
    for (File root : roots) {
        if (root.equals(f)) {
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: HTMLWriter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Write a hypertext link.
 * @param file the target for the link
 * @param body the body text for the link
 * @throws IOException if there is a problem closing the underlying stream
 */
public void writeLink(File file, String body) throws IOException {
    startTag(A);
    StringBuffer sb = new StringBuffer();
    String path = file.getPath().replace(File.separatorChar, '/');
    if (file.isAbsolute() && !path.startsWith("/"))
        sb.append('/');
    sb.append(path);
    writeAttr(HREF, sb.toString());
    write(body);
    endTag(A);
}
 
Example 11
Source File: ListenerConfigurator.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find a file in the given absolute path or relative to the HiveMQ home folder.
 *
 * @param fileLocation The absolute or relative path
 * @return a file
 */
private @NotNull File findAbsoluteAndRelative(final @NotNull String fileLocation) {
    final File file = new File(fileLocation);
    if (file.isAbsolute()) {
        return file;
    } else {
        return new File(systemInformation.getHiveMQHomeFolder(), fileLocation);
    }
}
 
Example 12
Source File: JFileChooser.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the selected file. If the file's parent directory is
 * not the current directory, changes the current directory
 * to be the file's parent directory.
 *
 * @beaninfo
 *   preferred: true
 *       bound: true
 *
 * @see #getSelectedFile
 *
 * @param file the selected file
 */
public void setSelectedFile(File file) {
    File oldValue = selectedFile;
    selectedFile = file;
    if(selectedFile != null) {
        if (file.isAbsolute() && !getFileSystemView().isParent(getCurrentDirectory(), selectedFile)) {
            setCurrentDirectory(selectedFile.getParentFile());
        }
        if (!isMultiSelectionEnabled() || selectedFiles == null || selectedFiles.length == 1) {
            ensureFileIsVisible(selectedFile);
        }
    }
    firePropertyChange(SELECTED_FILE_CHANGED_PROPERTY, oldValue, selectedFile);
}
 
Example 13
Source File: FileResourceConnector.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static File getFile(String absolutePath) {
    File f = new File(absolutePath);
    if (!f.isAbsolute()) {
        throw new IllegalArgumentException("Filename must be absolute: " + absolutePath);
    }
    return f;
}
 
Example 14
Source File: JFileChooser.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the selected file. If the file's parent directory is
 * not the current directory, changes the current directory
 * to be the file's parent directory.
 *
 * @beaninfo
 *   preferred: true
 *       bound: true
 *
 * @see #getSelectedFile
 *
 * @param file the selected file
 */
public void setSelectedFile(File file) {
    File oldValue = selectedFile;
    selectedFile = file;
    if(selectedFile != null) {
        if (file.isAbsolute() && !getFileSystemView().isParent(getCurrentDirectory(), selectedFile)) {
            setCurrentDirectory(selectedFile.getParentFile());
        }
        if (!isMultiSelectionEnabled() || selectedFiles == null || selectedFiles.length == 1) {
            ensureFileIsVisible(selectedFile);
        }
    }
    firePropertyChange(SELECTED_FILE_CHANGED_PROPERTY, oldValue, selectedFile);
}
 
Example 15
Source File: SystemIDResolver.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return true if the local path is an absolute path.
 *
 * @param systemId The path string
 * @return true if the path is absolute
 */
public static boolean isAbsolutePath(String systemId)
{
  if(systemId == null)
      return false;
  final File file = new File(systemId);
  return file.isAbsolute();

}
 
Example 16
Source File: AsyncAwaitEnhancerMojo.java    From tascalate-async-await with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private File computeDir(String dir) {
    File dirFile = new File(dir);
    if (dirFile.isAbsolute()) {
        return dirFile;
    } else {
        return new File(project.getBasedir(), buildDir).getAbsoluteFile();
    }
}
 
Example 17
Source File: MLeapProcessor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
protected List<ConfigIssue> init() {
  List<ConfigIssue> configIssues = super.init();
  errorRecordHandler = new DefaultErrorRecordHandler(getContext());
  if (configIssues.isEmpty()) {
    try {
      File mLeapModel = new File(conf.modelPath);
      if (!mLeapModel.isAbsolute()) {
        mLeapModel = new File(getContext().getResourcesDirectory(), conf.modelPath).getAbsoluteFile();
      }
      MleapContext mleapContext = new ContextBuilder().createMleapContext();
      BundleBuilder bundleBuilder = new BundleBuilder();
      mLeapPipeline = bundleBuilder.load(mLeapModel, mleapContext).root();
    } catch (Exception ex) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.MODEL_PATH_CONFIG,
          Errors.MLEAP_00,
          ex
      ));
      return configIssues;
    }

    leapFrameBuilder = new LeapFrameBuilder();
    leapFrameSupport = new LeapFrameSupport();

    for (InputConfig inputConfig : conf.inputConfigs) {
      fieldNameMap.put(inputConfig.pmmlFieldName, inputConfig.fieldName);
    }

    // Validate Input fields
    StructType inputSchema = mLeapPipeline.inputSchema();
    List<StructField> structFieldList = leapFrameSupport.getFields(inputSchema);
    List<String> missingInputFieldNames = structFieldList.stream()
        .filter(structField -> !fieldNameMap.containsKey(structField.name()))
        .map(StructField::name)
        .collect(Collectors.toList());
    if (!missingInputFieldNames.isEmpty()) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.INPUT_CONFIGS_CONFIG,
          Errors.MLEAP_01,
          missingInputFieldNames
      ));
    }

    // Validate Output field names
    if (conf.outputFieldNames.size() == 0) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.OUTPUT_FIELD_NAMES_CONFIG,
          Errors.MLEAP_02
      ));
      return configIssues;
    }

    StructType outputSchema = mLeapPipeline.outputSchema();
    List<StructField> outputStructFieldList = leapFrameSupport.getFields(outputSchema);
    List<String> outputFieldNamesCopy = new ArrayList<>(conf.outputFieldNames);
    outputFieldNamesCopy.removeAll(
        outputStructFieldList.stream().map(StructField::name).collect(Collectors.toList())
    );
    if (outputFieldNamesCopy.size() > 0) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.OUTPUT_FIELD_NAMES_CONFIG,
          Errors.MLEAP_03,
          outputFieldNamesCopy
      ));
    }

  }
  return configIssues;
}
 
Example 18
Source File: CodeFormatterApplication.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private File[] processCommandLine(String[] argsArray) {

		ArrayList args = new ArrayList();
		for (int i = 0, max = argsArray.length; i < max; i++) {
			args.add(argsArray[i]);
		}
		int index = 0;
		final int argCount = argsArray.length;

		final int DEFAULT_MODE = 0;
		final int CONFIG_MODE = 1;

		int mode = DEFAULT_MODE;
		final int INITIAL_SIZE = 1;
		int fileCounter = 0;

		File[] filesToFormat = new File[INITIAL_SIZE];

		loop: while (index < argCount) {
			String currentArg = argsArray[index++];

			switch(mode) {
				case DEFAULT_MODE :
					if (PDE_LAUNCH.equals(currentArg)) {
						continue loop;
					}
					if (ARG_HELP.equals(currentArg)) {
						displayHelp();
						return null;
					}
					if (ARG_VERBOSE.equals(currentArg)) {
						this.verbose = true;
						continue loop;
					}
					if (ARG_QUIET.equals(currentArg)) {
						this.quiet = true;
						continue loop;
					}
					if (ARG_CONFIG.equals(currentArg)) {
						mode = CONFIG_MODE;
						continue loop;
					}
					// the current arg should be a file or a directory name
					File file = new File(currentArg);
					if (file.exists()) {
						if (filesToFormat.length == fileCounter) {
							System.arraycopy(filesToFormat, 0, (filesToFormat = new File[fileCounter * 2]), 0, fileCounter);
						}
						filesToFormat[fileCounter++] = file;
					} else {
						String canonicalPath;
						try {
							canonicalPath = file.getCanonicalPath();
						} catch(IOException e2) {
							canonicalPath = file.getAbsolutePath();
						}
						String errorMsg = file.isAbsolute()?
										  Messages.bind(Messages.CommandLineErrorFile, canonicalPath):
										  Messages.bind(Messages.CommandLineErrorFileTryFullPath, canonicalPath);
						displayHelp(errorMsg);
						return null;
					}
					break;
				case CONFIG_MODE :
					this.configName = currentArg;
					this.options = readConfig(currentArg);
					if (this.options == null) {
						displayHelp(Messages.bind(Messages.CommandLineErrorConfig, currentArg));
						return null;
					}
					mode = DEFAULT_MODE;
					continue loop;
			}
		}

		if (mode == CONFIG_MODE || this.options == null) {
			displayHelp(Messages.bind(Messages.CommandLineErrorNoConfigFile));
			return null;
		}
		if (this.quiet && this.verbose) {
			displayHelp(
				Messages.bind(
					Messages.CommandLineErrorQuietVerbose,
					new String[] { ARG_QUIET, ARG_VERBOSE }
				));
			return null;
		}
		if (fileCounter == 0) {
			displayHelp(Messages.bind(Messages.CommandLineErrorFileDir));
			return null;
		}
		if (filesToFormat.length != fileCounter) {
			System.arraycopy(filesToFormat, 0, (filesToFormat = new File[fileCounter]), 0, fileCounter);
		}
		return filesToFormat;
	}
 
Example 19
Source File: TensorFlowProcessor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
protected List<ConfigIssue> init() {
  List<ConfigIssue> issues = super.init();
  String[] modelTags = new String[conf.modelTags.size()];
  modelTags = conf.modelTags.toArray(modelTags);

  if (Strings.isNullOrEmpty(conf.modelPath)) {
    issues.add(getContext().createConfigIssue(
        Groups.TENSOR_FLOW.name(),
        TensorFlowConfigBean.MODEL_PATH_CONFIG,
        Errors.TENSOR_FLOW_01
    ));
    return issues;
  }

  try {
    File exportedModelDir = new File(conf.modelPath);
    if (!exportedModelDir.isAbsolute()) {
      exportedModelDir = new File(getContext().getResourcesDirectory(), conf.modelPath).getAbsoluteFile();
    }
    this.savedModel = SavedModelBundle.load(exportedModelDir.getAbsolutePath(), modelTags);
  } catch (TensorFlowException ex) {
    issues.add(getContext().createConfigIssue(
        Groups.TENSOR_FLOW.name(),
        TensorFlowConfigBean.MODEL_PATH_CONFIG,
        Errors.TENSOR_FLOW_02,
        ex
    ));
    return issues;
  }

  this.session = this.savedModel.session();
  this.conf.inputConfigs.forEach(inputConfig -> {
        Pair<String, Integer> key = Pair.of(inputConfig.operation, inputConfig.index);
        inputConfigMap.put(key, inputConfig);
      }
  );

  fieldPathEval = getContext().createELEval("conf.inputConfigs");
  fieldPathVars = getContext().createELVars();

  errorRecordHandler = new DefaultErrorRecordHandler(getContext());

  return issues;
}
 
Example 20
Source File: CaConfs.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static String resolveFilePath(String filePath, String baseDir) {
  File file = new File(filePath);
  return file.isAbsolute() ? filePath : new File(baseDir, filePath).getPath();
}