List of usage examples for java.io File isAbsolute
public boolean isAbsolute()
From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java
/** * Transforms a relative path so that it is relative to the location of the * order file. If an absolute path is given, it will be returned unchanged.<p> * The location of it's order file is always considered as the 'working' * directory for any given settings./*from ww w . j a v a2 s . co m*/ * @param path A relative path to a file (or directory) * @return The same path modified so that it is relative to the file level * location of the order file for the settings handler. */ public File getPathRelativeToWorkingDirectory(String path) { File f = new File(path); // If path is not absolute, set f's directory // relative to the path of the order file if (!f.isAbsolute()) { f = new File(this.getOrderFile().getParent(), path); } return f; }
From source file:cross.io.InputDataFactory.java
/** * Create a collection of files from the given string resource paths. * * @param input the string resource paths * @return a collection of files/*from w ww . j a va 2s . c o m*/ */ @Override public Collection<File> getInputFiles(String[] input) { LinkedHashSet<File> files = new LinkedHashSet<>(); for (String inputString : input) { log.debug("Processing input string {}", inputString); //separate wildcards from plain files String name = FilenameUtils.getName(inputString); boolean isWildcard = name.contains("?") || name.contains("*"); String fullPath = FilenameUtils.getFullPath(inputString); File path = new File(fullPath); File baseDirFile = new File(this.basedir); if (!baseDirFile.exists()) { throw new ExitVmException("Input base directory '" + baseDirFile + "' does not exist!"); } if (!baseDirFile.isDirectory()) { throw new ExitVmException("Input base directory '" + baseDirFile + "' is not a directory!"); } log.debug("Path is absolute: {}", path.isAbsolute()); //identify absolute and relative files if (!path.isAbsolute()) { log.info("Resolving relative file against basedir: {}", this.basedir); path = new File(this.basedir, fullPath); } //normalize filenames fullPath = FilenameUtils.normalize(path.getAbsolutePath()); log.debug("After normalization: {}", fullPath); IOFileFilter dirFilter = this.recurse ? TrueFileFilter.INSTANCE : null; if (isWildcard) { log.debug("Using wildcard matcher for {}", name); files.addAll(FileUtils.listFiles(new File(fullPath), new WildcardFileFilter(name, IOCase.INSENSITIVE), dirFilter)); } else { log.debug("Using name for {}", name); File f = new File(fullPath, name); if (!f.exists()) { throw new ExitVmException("Input file '" + f + "' does not exist!"); } files.add(f); } } return files; }
From source file:de.iritgo.aktario.core.Engine.java
/** * Since Engine is a singleton, this constructor is private. * * @param commandLine Command line options. */// ww w . ja va2s .c o m private Engine(String name, CommandLine commandLine) { this.name = name; this.commandLine = commandLine; userHomeDir = System.getProperty("user.home"); systemDir = System.getProperty("user.dir"); fileSeparator = System.getProperty("file.separator"); if (commandLine.hasOption("s")) { File dir = new File(commandLine.getOptionValue("s").trim()); if (dir.isAbsolute()) { systemDir = dir.getPath(); } else { systemDir += fileSeparator + dir.getPath(); } } else if (System.getProperty("iritgo.system.dir") != null) { File dir = new File(System.getProperty("iritgo.system.dir").trim()); if (dir.isAbsolute()) { systemDir = dir.getPath(); } else { systemDir += fileSeparator + dir.getPath(); } } }
From source file:com.streamsets.pipeline.stage.processor.geolocation.GeolocationProcessor.java
@Override protected List<ConfigIssue> init() { List<ConfigIssue> result = super.init(); File database = new File(geoIP2DBFile); if ((getContext().getExecutionMode() == ExecutionMode.CLUSTER_BATCH || getContext().getExecutionMode() == ExecutionMode.CLUSTER_YARN_STREAMING || getContext().getExecutionMode() == ExecutionMode.CLUSTER_MESOS_STREAMING) && database.isAbsolute()) { //Do not allow absolute geoIP2DBFile in cluster mode result.add(//from w ww .j a va 2 s . c o m getContext().createConfigIssue("GEOLOCATION", "geoIP2DBFile", Errors.GEOIP_10, geoIP2DBFile)); } else { if (!database.isAbsolute()) { database = new File(getContext().getResourcesDirectory(), geoIP2DBFile).getAbsoluteFile(); } if (database.isFile()) { try { reader = new DatabaseReader.Builder(database).build(); for (GeolocationFieldConfig config : configs) { try { switch (config.targetType) { case COUNTRY_NAME: case COUNTRY_ISO_CODE: reader.country(KNOWN_GOOD_ADDRESS); break; case CITY_NAME: case LATITUDE: case LONGITUDE: reader.city(KNOWN_GOOD_ADDRESS); break; default: throw new IllegalStateException( Utils.format("Unknown configuration value: ", config.targetType)); } } catch (UnsupportedOperationException ex) { result.add(getContext().createConfigIssue("GEOLOCATION", "geoIP2DBFile", Errors.GEOIP_05, config.targetType.name())); LOG.info(Utils.format(Errors.GEOIP_05.getMessage(), config.targetType.name()), ex); } catch (GeoIp2Exception ex) { result.add(getContext().createConfigIssue("GEOLOCATION", "geoIP2DBFile", Errors.GEOIP_07, ex)); LOG.error(Utils.format(Errors.GEOIP_07.getMessage(), ex), ex); } } } catch (IOException ex) { result.add(getContext().createConfigIssue("GEOLOCATION", "geoIP2DBFile", Errors.GEOIP_01, database.getPath(), ex)); LOG.info(Utils.format(Errors.GEOIP_01.getMessage(), ex), ex); } } else { result.add(getContext().createConfigIssue("GEOLOCATION", "geoIP2DBFile", Errors.GEOIP_00, geoIP2DBFile)); } } if (configs.isEmpty()) { result.add(getContext().createConfigIssue("GEOLOCATION", "fieldTypeConverterConfigs", Errors.GEOIP_04)); } for (GeolocationFieldConfig config : configs) { if (config.inputFieldName == null || config.inputFieldName.isEmpty()) { result.add(getContext().createConfigIssue("GEOLOCATION", "fieldTypeConverterConfigs", Errors.GEOIP_08)); } else if (config.outputFieldName == null || config.outputFieldName.isEmpty()) { result.add(getContext().createConfigIssue("GEOLOCATION", "fieldTypeConverterConfigs", Errors.GEOIP_09)); } } countries = CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<Field, CountryResponse>() { @Override public CountryResponse load(Field field) throws Exception { return Utils.checkNotNull(reader, "DatabaseReader").country(toAddress(field)); } }); cities = CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<Field, CityResponse>() { @Override public CityResponse load(Field field) throws Exception { return Utils.checkNotNull(reader, "DatabaseReader").city(toAddress(field)); } }); return result; }
From source file:interactivespaces.workbench.tasks.WorkbenchTaskContext.java
/** * process an extension file./*from w w w . j av a 2 s . c om*/ * * @param files * the collection of jars described in the extension files * @param extensionFile * the extension file to process * @param controllerBaseDir * base directory of the controller */ private void processExtensionFile(List<File> files, File extensionFile, File controllerBaseDir) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(extensionFile)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.isEmpty()) { int pos = line.indexOf(EXTENSION_FILE_PATH_KEYWORD); if (pos == 0 && line.length() > EXTENSION_FILE_PATH_KEYWORD_LENGTH) { String classpathAddition = line.substring(EXTENSION_FILE_PATH_KEYWORD_LENGTH).trim(); // Want to be able to have files relative to the controller File classpathFile = fileSupport.newFile(classpathAddition); if (!classpathFile.isAbsolute()) { classpathFile = fileSupport.newFile(controllerBaseDir, classpathAddition); } files.add(classpathFile); } } } } catch (Exception e) { handleError("Error while creating project", e); } finally { Closeables.closeQuietly(reader); } }
From source file:jeplus.EPlusTask.java
/** * Preprocess the input file (.imf/.idf), including calling EP-Macro * @param config// w w w. ja v a 2 s .c o m * @return Operation successful or not */ public boolean preprocessInputFile(JEPlusConfig config) { boolean ok = true; String[] SearchStrings = SearchStringList.toArray(new String[0]); String[] Newvals = AltValueList.toArray(new String[0]); if (WorkEnv.isIMF()) { // If the input template file is for EP-Macro (.imf) // Check if #fileprefix is available String fprefixstr = IDFmodel.getIncludeFilePrefix(WorkEnv.IDFDir + WorkEnv.IDFTemplate); if (fprefixstr != null) { File fprefix = new File(fprefixstr); if (!fprefix.isAbsolute()) { fprefix = new File(WorkEnv.IDFDir.concat(fprefixstr)); } if (!(fprefix.isDirectory() && fprefix.exists())) { System.err.println("IMF processing error: ##fileprefix (" + fprefix.getAbsolutePath() + ") is not a folder or does not exist. Current folder is assumed."); fprefix = new File(WorkEnv.IDFDir); } try { fprefixstr = fprefix.getCanonicalPath(); } catch (IOException ex) { logger.error("", ex); ok = false; } } // Update the imf template ok = ok && EPlusWinTools.updateIMFFile(WorkEnv.IDFDir + WorkEnv.IDFTemplate, fprefixstr, SearchStrings, Newvals, getWorkingDir()); if (ok) { // If imf template was successfully updated ("in.imf" is created), run EP-Macro EPlusWinTools.runEPMacro(config, getWorkingDir()); // Test EP-Macro was successful or not by checking the presence of "out.idf" ok = EPlusWinTools.isFileAvailable("out.idf", getWorkingDir()); // If ok, update the out.idf with the search strings and values again. ok = (ok && EPlusWinTools.updateIDFFile(getWorkingDir() + "out.idf", SearchStrings, Newvals, getWorkingDir())); } } else { // Otherwise it is for EPlus (.idf) ok = EPlusWinTools.updateIDFFile(WorkEnv.IDFDir + WorkEnv.IDFTemplate, SearchStrings, Newvals, getWorkingDir()); } if (ok) { // Collect E+ include files (e.g. in Schedule:File objects) ArrayList<String> incfiles = IDFmodel.getScheduleFiles(getWorkingDir() + EPlusConfig.getEPDefIDF()); if (!incfiles.isEmpty()) { try (PrintWriter outs = (config.getScreenFile() == null) ? null : new PrintWriter(new FileWriter(getWorkingDir() + config.getScreenFile(), true));) { if (outs != null) { outs.println("# Copying dependant files - " + (new SimpleDateFormat()).format(new Date())); outs.flush(); } // Copy them to working dir for (String incfile : incfiles) { File ori = new File(RelativeDirUtil.checkAbsolutePath(incfile, WorkEnv.IDFDir)); File dest = new File(getWorkingDir() + ori.getName()); try { // Log to console.log if (outs != null) { outs.println(incfile); outs.flush(); } FileUtils.copyFile(ori, dest); } catch (IOException ex) { logger.error("", ex); // Log to console.log if (outs != null) { outs.println(ex.getMessage()); outs.flush(); } ok = false; break; } } } catch (Exception ex) { logger.error("", ex); } } // Update idf if (ok && incfiles.size() > 0) { ok = IDFmodel.replaceScheduleFiles(getWorkingDir() + EPlusConfig.getEPDefIDF(), incfiles); } } return ok; }
From source file:psiprobe.AbstractTomcatContainer.java
@Override public void remove(String name) throws Exception { name = formatContextName(name);/*from w w w.ja v a 2s . c om*/ Context ctx = findContext(name); if (ctx != null) { try { stop(name); } catch (Exception e) { logger.info("Stopping '{}' threw this exception:", name, e); } File appDir; File docBase = new File(ctx.getDocBase()); if (!docBase.isAbsolute()) { appDir = new File(getAppBase(), ctx.getDocBase()); } else { appDir = docBase; } logger.debug("Deleting '{}'", appDir.getAbsolutePath()); Utils.delete(appDir); String warFilename = formatContextFilename(name); File warFile = new File(getAppBase(), warFilename + ".war"); logger.debug("Deleting '{}'", warFile.getAbsolutePath()); Utils.delete(warFile); File configFile = getConfigFile(ctx); if (configFile != null) { logger.debug("Deleting " + configFile.getAbsolutePath()); Utils.delete(configFile); } removeInternal(name); } }
From source file:com.boundlessgeo.geoserver.api.controllers.StoreController.java
private String sourceFile(String file) { File baseDirectory = dataDir().getResourceLoader().getBaseDirectory(); File f = new File(file); return f.isAbsolute() ? file : Paths.convert(baseDirectory, f); }
From source file:org.outofbits.sesame.schemagen.SchemaGeneration.java
/** * Gets the vocabulary the given input is pointing to. The input can either be a file path or * a HTTP {@link java.net.URL}, otherwise a {@link VocabularyNotFoundException} will be thrown. * Also if the vocabulary cannot be accessed or read, a {@link VocabularyNotFoundException} will * be thrown.//from w w w . j av a2 s. c o m * * @param input path to a file or a valid {@link java.net.URL}. Schemagen supports the * protocols 'http' and 'file'. Input must not be null. * @param format the format of the document representing the vocabulary. The format can be * null. * @param workingDir the working directory. * @return {@link Model} containing all statements of the vocabulary pointed to by input. * @throws VocabularyNotFoundException if the vocabulary cannot be found or accessed. */ private Model getVocabularyModel(String input, RDFFormat format, String workingDir) throws VocabularyNotFoundException { assert input != null; try { URL documentUrl = new URL(input); switch (documentUrl.getProtocol()) { case "file": File sourceFile = new File(documentUrl.getFile()); if (sourceFile.isAbsolute()) { return readVocabularyFromFile(sourceFile, format); } else { return readVocabularyFromFile(new File(workingDir, sourceFile.getPath()), format); } case "http": return readVocabularyFromHTTPSource(documentUrl, format); default: throw new VocabularyNotFoundException( String.format("The protocol '%s' is not supported.", documentUrl.getProtocol())); } } catch (MalformedURLException e) { try { File sourceFile = new File(input); if (sourceFile.isAbsolute()) { return readVocabularyFromFile(sourceFile, format); } else { return readVocabularyFromFile(new File(workingDir, sourceFile.getPath()), format); } } catch (IOException io) { throw new VocabularyNotFoundException(e); } } catch (Exception e) { throw new VocabularyNotFoundException(e); } }
From source file:com.npower.dm.setup.task.ModelTask.java
protected void processModelBasicInformation() throws SetupException { List<String> filenames = this.getFilenames(); ManagementBeanFactory factory = null; try {/*from www . j a va 2 s.c om*/ factory = this.getManagementBeanFactory(); ModelBean modelBean = factory.createModelBean(); if (System.getProperty("otas.dm.home") == null) { log.error("ModelTask: " + "Could not found 'otas.dm.home' from system properties, please set 'otas.dm.home'."); } DDFTreeBean ddfBean = factory.createDDFTreeBean(); // Import Model, DDF, TACs for (String filename : filenames) { // Process the file, and import data into database. File file = new File(filename); if (!file.isAbsolute()) { file = new File(this.getSetup().getWorkDir(), filename); } this.getSetup().getConsole().println(" Loading file [ " + file.getAbsolutePath() + " ]"); List<ManufacturerItem> items = this.loadManufacturerItems(file.getAbsolutePath()); for (ManufacturerItem manufacturerItem : items) { List<ModelItem> modelItems = manufacturerItem.getModels(); Manufacturer manufacturer = modelBean .getManufacturerByExternalID(manufacturerItem.getExternalID()); for (ModelItem modelItem : modelItems) { Model model = modelBean.getModelByManufacturerModelID(manufacturer, modelItem.getExternalID()); if (model == null) { log.info("Create a new model: " + manufacturer.getExternalId() + " " + modelItem.getExternalID()); model = modelBean.newModelInstance(); model.setManufacturer(manufacturer); } else { log.info("Modify a model: " + manufacturer.getExternalId() + " " + modelItem.getExternalID()); } // Copy information from family this.copyFromFamily(modelItem); // Copy item into model entity this.copy(modelItem, model); this.getSetup().getConsole() .println(" * Importing [" + manufacturer.getExternalId() + " " + model.getManufacturerModelId() + "] from [ " + modelItem.getDefinedByFilename() + " ]"); factory.beginTransaction(); modelBean.update(model); this.getSetup().getConsole().println(" * Basic information processed"); // ModelSpec: Icon, ... String iconFilename = modelItem.getIconFile(); if (StringUtils.isEmpty(iconFilename)) { iconFilename = this.getSetup().getPropertyValue("model.default.icon.file"); } File iconFile = new File(iconFilename); if (!iconFile.isAbsolute()) { iconFile = new File(this.getSetup().getWorkDir(), iconFilename); } if (iconFile.exists()) { model.setIconBinary(new FileInputStream(iconFile)); } else { this.getSetup().getConsole() .println(" Could not found icon file: " + iconFile.getAbsolutePath()); } modelBean.update(model); Map<String, String> specMap = modelItem.getSpecifications(); for (String specName : specMap.keySet()) { String category = null; String name = specName; int index = specName.indexOf("."); if (index >= 0) { category = specName.substring(0, index); name = specName.substring(index + 1, specName.length()); } String value = specMap.get(specName); List<ModelCharacter> characters = modelBean.findModelCharacters(model, category, name); ModelCharacter character = null; if (characters != null && characters.size() > 0) { // Update exists character character = characters.get(0); } else { // Create a new character character = modelBean.newModelCharacterInstance(model, category, name); } character.setValue(value); modelBean.update(character); } this.getSetup().getConsole().println(" * Specifications processed"); // TACs for (String tac : modelItem.getTacs()) { if (StringUtils.isNotEmpty(tac)) { modelBean.addTACInfo(model, tac); this.getSetup().getConsole().println(" * TAC information processed"); } } // DDF Files for (String ddfFilename : modelItem.getDdfFiles()) { File ddfFile = new File(ddfFilename); if (!ddfFile.isAbsolute()) { ddfFile = new File(this.getSetup().getWorkDir(), ddfFilename); } DDFTree ddfTree = null; try { ddfTree = ddfBean.parseDDFTree(new FileInputStream(ddfFile)); } catch (Exception e) { throw new DMException("Error to parse DDF File: " + ddfFile.getAbsolutePath(), e); } ddfBean.addDDFTree(ddfTree); modelBean.attachDDFTree(model, ddfTree.getID()); this.getSetup().getConsole() .println(" * DDF information [ " + ddfFile + " ] processed"); } factory.commit(); } } } } catch (Exception ex) { if (factory != null) { factory.rollback(); } throw new SetupException("Error in import models.", ex); } finally { if (factory != null) { factory.release(); } } }