List of usage examples for java.io File isAbsolute
public boolean isAbsolute()
From source file:org.bedework.timezones.common.leveldb.LdbCachedData.java
private DB getDb() throws TzException { if (db != null) { return db; }/*from w ww . j a v a 2 s .c om*/ try { if ((lastConfigLevelDbPath == null) || (!lastConfigLevelDbPath.equals(cfg.getLeveldbPath()))) { lastConfigLevelDbPath = cfg.getLeveldbPath(); if (debug) { trace("Try to open leveldb at " + lastConfigLevelDbPath); } final File f = new File(lastConfigLevelDbPath); if (!f.isAbsolute()) { throw new TzException("levelDbPath must be absolute - found " + lastConfigLevelDbPath); } levelDbPath = lastConfigLevelDbPath; } final Options options = new Options(); options.createIfMissing(true); db = Iq80DBFactory.factory.open(new File(levelDbPath), options); } catch (final Throwable t) { // Always bad. error(t); throw new TzException(t); } return db; }
From source file:org.apache.catalina.startup.Embedded.java
protected void initDirs() { String catalinaHome = System.getProperty("catalina.home"); if (catalinaHome == null) { // Backwards compatibility patch for J2EE RI 1.3 String j2eeHome = System.getProperty("com.sun.enterprise.home"); if (j2eeHome != null) { catalinaHome = System.getProperty("com.sun.enterprise.home"); } else if (System.getProperty("catalina.base") != null) { catalinaHome = System.getProperty("catalina.base"); } else {//from w w w.java 2s .c om // Use IntrospectionUtils and guess the dir catalinaHome = IntrospectionUtils.guessInstall("catalina.home", "catalina.base", "catalina.jar"); if (catalinaHome == null) { catalinaHome = IntrospectionUtils.guessInstall("tomcat.install", "catalina.home", "tomcat.jar"); } } } if (catalinaHome != null) { File home = new File(catalinaHome); if (!home.isAbsolute()) { try { catalinaHome = home.getCanonicalPath(); } catch (IOException e) { catalinaHome = home.getAbsolutePath(); } } System.setProperty("catalina.home", catalinaHome); } if (System.getProperty("catalina.base") == null) { System.setProperty("catalina.base", System.getProperty("catalina.home")); } else { String catalinaBase = System.getProperty("catalina.base"); File base = new File(catalinaBase); if (!base.isAbsolute()) { try { catalinaBase = base.getCanonicalPath(); } catch (IOException e) { catalinaBase = base.getAbsolutePath(); } } System.setProperty("catalina.base", catalinaBase); } }
From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java
/** * @see it.greenvulcano.util.remotefs.RemoteManager#get(String, String, * String, String, java.util.Map)// w ww. j a v a2 s . c o m */ @Override public boolean get(String remoteDirectory, String remoteFile, String localDirectory, String localFile, Map<String, String> optProperties) throws RemoteManagerException { checkConnected(); boolean result = false; OutputStream output = null; try { logger.debug("Downloading remote file " + remoteFile + " from " + (remoteDirectory != null ? " remote directory " + remoteDirectory : " current remote working directory") + "..."); File localPathname = new File(localDirectory, (localFile != null ? localFile : remoteFile)); if (!localPathname.isAbsolute()) { throw new RemoteManagerException("Local pathname (" + localPathname + ") is NOT absolute."); } logger.debug("Saving to " + localPathname); output = new FileOutputStream(localPathname); if (remoteDirectory != null) { changeWorkingDirectory(remoteDirectory); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.retrieveFile(remoteFile, output); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { logger.debug("Remote file " + remoteFile + " saved to " + localPathname); result = true; } else { logger.warn("FTP Server NEGATIVE response: "); logServerReply(Level.WARN); } return result; } catch (IOException exc) { throw new RemoteManagerException("I/O error", exc); } catch (Exception exc) { throw new RemoteManagerException("Generic error", exc); } finally { if (output != null) { try { output.close(); } catch (IOException exc) { logger.warn("Error while closing local file output stream"); } } if (isAutoconnect()) { disconnect(); } } }
From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java
protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir, InputStream input) throws IOException { // Create the result object TestJobResult.TransformResult result = new TestJobResult.TransformResult(); CountingOutputStream output = null;/* w ww . java 2s. c o m*/ CountingOutputStream error = null; try { // Create and open temporary file for standard output File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir); output = new CountingOutputStream(new FileOutputStream(outputFile)); // Create and open temporary file for standard error File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir); error = new CountingOutputStream(new FileOutputStream(errorFile)); // If executable is relative, try to resolve in working directory // (This emulates the behavior of Streaming) if (!executable.isAbsolute()) { File resolvedExecutable = new File(workingDir, executable.toString()); if (resolvedExecutable.isFile()) { resolvedExecutable.setExecutable(true); executable = resolvedExecutable.getAbsoluteFile(); } } // Run the transform CommandLine command; if (_switchUserCommand == null) command = new CommandLine(executable); else { command = CommandLine.parse(_switchUserCommand); HashMap<String, String> substitutionMap = new HashMap<String, String>(); substitutionMap.put("cmd", executable.toString()); command.setSubstitutionMap(substitutionMap); } DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT); PumpStreamHandler pump = new PumpStreamHandler(output, error, input); executor.setWorkingDirectory(workingDir); executor.setWatchdog(dog); executor.setStreamHandler(pump); executor.setExitValues(null); int exitCode = executor.execute(command); result.setExitCode(exitCode); // Check whether it produced any output if (output.getByteCount() == 0) { output.close(); outputFile.delete(); } else result.setOutputFile(outputFile); // Check whether it produced any error output if (error.getByteCount() == 0) { error.close(); errorFile.delete(); } else result.setErrorFile(errorFile); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(error); } return result; }
From source file:org.sonatype.nexus.integrationtests.AbstractNexusIntegrationTest.java
protected void copyConfigFile(String configFile, String destShortName, Map<String, String> variables, String path) throws IOException { // the test can override the test config. File testConfigFile = this.getOverridableFile(configFile); File parent = new File(path); if (!parent.isAbsolute()) { parent = new File(nexusBaseDir, path == null ? RELATIVE_CONF_DIR : path); }//from www .ja va 2 s . c om File destFile = new File(parent, destShortName); log.debug("copying " + configFile + " to: " + destFile); FileTestingUtils.interpolationFileCopy(testConfigFile, destFile, variables); }
From source file:net.sf.jabref.JabRef.java
public Optional<Vector<ParserResult>> processArguments(String[] args, boolean initialStartup) { cli = new JabRefCLI(args); if (!cli.isBlank() && cli.isDebugLogging()) { JabRefLogger.setDebug();/* w w w . j a v a 2 s . c o m*/ } if (initialStartup && cli.isShowVersion()) { cli.displayVersion(); } if (initialStartup && cli.isHelp()) { cli.printUsage(); return Optional.empty(); } // Check if we should reset all preferences to default values: if (cli.isPreferencesReset()) { String value = cli.getPreferencesReset(); if ("all".equals(value.trim())) { try { System.out.println(Localization.lang("Setting all preferences to default values.")); Globals.prefs.clear(); } catch (BackingStoreException e) { System.err.println(Localization.lang("Unable to clear preferences.")); e.printStackTrace(); } } else { String[] keys = value.split(","); for (String key : keys) { if (Globals.prefs.hasKey(key.trim())) { System.out.println(Localization.lang("Resetting preference key '%0'", key.trim())); Globals.prefs.clear(key.trim()); } else { System.out.println(Localization.lang("Unknown preference key '%0'", key.trim())); } } } } // Check if we should import preferences from a file: if (cli.isPreferencesImport()) { try { Globals.prefs.importPreferences(cli.getPreferencesImport()); CustomEntryTypesManager.loadCustomEntryTypes(Globals.prefs); ExportFormats.initAllExports(); } catch (JabRefException ex) { LOGGER.error("Cannot import preferences", ex); } } // Vector to put imported/loaded database(s) in. Vector<ParserResult> loaded = new Vector<>(); Vector<String> toImport = new Vector<>(); if (!cli.isBlank() && (cli.getLeftOver().length > 0)) { for (String aLeftOver : cli.getLeftOver()) { // Leftover arguments that have a "bib" extension are interpreted as // bib files to open. Other files, and files that could not be opened // as bib, we try to import instead. boolean bibExtension = aLeftOver.toLowerCase().endsWith("bib"); ParserResult pr = null; if (bibExtension) { pr = JabRef.openBibFile(aLeftOver, false); } if ((pr == null) || (pr == ParserResult.INVALID_FORMAT)) { // We will try to import this file. Normally we // will import it into a new tab, but if this import has // been initiated by another instance through the remote // listener, we will instead import it into the current database. // This will enable easy integration with web browsers that can // open a reference file in JabRef. if (initialStartup) { toImport.add(aLeftOver); } else { loaded.add(JabRef.importToOpenBase(aLeftOver).orElse(ParserResult.INVALID_FORMAT)); } } else if (pr != ParserResult.FILE_LOCKED) { loaded.add(pr); } } } if (!cli.isBlank() && cli.isFileImport()) { toImport.add(cli.getFileImport()); } for (String filenameString : toImport) { importFile(filenameString).ifPresent(loaded::add); } if (!cli.isBlank() && cli.isImportToOpenBase()) { importToOpenBase(cli.getImportToOpenBase()).ifPresent(loaded::add); } if (!cli.isBlank() && cli.isFetcherEngine()) { fetch(cli.getFetcherEngine()).ifPresent(loaded::add); } if (cli.isExportMatches()) { if (!loaded.isEmpty()) { String[] data = cli.getExportMatches().split(","); String searchTerm = data[0].replace("\\$", " "); //enables blanks within the search term: //? stands for a blank ParserResult pr = loaded.elementAt(loaded.size() - 1); BibDatabase dataBase = pr.getDatabase(); SearchQuery query = new SearchQuery(searchTerm, Globals.prefs.getBoolean(JabRefPreferences.SEARCH_CASE_SENSITIVE), Globals.prefs.getBoolean(JabRefPreferences.SEARCH_REG_EXP)); BibDatabase newBase = new DatabaseSearcher(query, dataBase).getDatabaseFromMatches(); //newBase contains only match entries //export database if ((newBase != null) && (newBase.getEntryCount() > 0)) { String formatName; //read in the export format, take default format if no format entered switch (data.length) { case 3: formatName = data[2]; break; case 2: //default ExportFormat: HTML table (with Abstract & BibTeX) formatName = "tablerefsabsbib"; break; default: System.err.println(Localization.lang("Output file missing").concat(". \n \t ") .concat(Localization.lang("Usage")).concat(": ") + JabRefCLI.getExportMatchesSyntax()); return Optional.empty(); } //end switch //export new database IExportFormat format = ExportFormats.getExportFormat(formatName); if (format == null) { System.err.println(Localization.lang("Unknown export format") + ": " + formatName); } else { // We have an ExportFormat instance: try { System.out.println(Localization.lang("Exporting") + ": " + data[1]); format.performExport(newBase, pr.getMetaData(), data[1], pr.getEncoding(), null); } catch (Exception ex) { System.err.println(Localization.lang("Could not export file") + " '" + data[1] + "': " + ex.getMessage()); } } } /*end if newBase != null*/ else { System.err.println(Localization.lang("No search matches.")); } } else { System.err.println(Localization.lang("The output option depends on a valid input option.")); } //end if(loaded.size > 0) } if (cli.isGenerateBibtexKeys()) { regenerateBibtexKeys(loaded); } if (cli.isAutomaticallySetFileLinks()) { automaticallySetFileLinks(loaded); } if (cli.isFileExport()) { if (!loaded.isEmpty()) { String[] data = cli.getFileExport().split(","); if (data.length == 1) { // This signals that the latest import should be stored in BibTeX // format to the given file. if (!loaded.isEmpty()) { ParserResult pr = loaded.elementAt(loaded.size() - 1); if (!pr.isInvalid()) { try { System.out.println(Localization.lang("Saving") + ": " + data[0]); SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs); Defaults defaults = new Defaults(BibDatabaseMode.fromPreference( Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE))); BibDatabaseWriter databaseWriter = new BibDatabaseWriter(); SaveSession session = databaseWriter.saveDatabase( new BibDatabaseContext(pr.getDatabase(), pr.getMetaData(), defaults), prefs); // Show just a warning message if encoding didn't work for all characters: if (!session.getWriter().couldEncodeAll()) { System.err.println(Localization.lang("Warning") + ": " + Localization.lang( "The chosen encoding '%0' could not encode the following characters:", session.getEncoding().displayName()) + " " + session.getWriter().getProblemCharacters()); } session.commit(new File(data[0])); } catch (SaveException ex) { System.err.println(Localization.lang("Could not save file.") + "\n" + ex.getLocalizedMessage()); } } } else { System.err .println(Localization.lang("The output option depends on a valid import option.")); } } else if (data.length == 2) { // This signals that the latest import should be stored in the given // format to the given file. ParserResult pr = loaded.elementAt(loaded.size() - 1); // Set the global variable for this database's file directory before exporting, // so formatters can resolve linked files correctly. // (This is an ugly hack!) File theFile = pr.getFile(); if (!theFile.isAbsolute()) { theFile = theFile.getAbsoluteFile(); } MetaData metaData = pr.getMetaData(); metaData.setFile(theFile); Globals.prefs.fileDirForDatabase = metaData.getFileDirectory(Globals.FILE_FIELD) .toArray(new String[0]); Globals.prefs.databaseFile = metaData.getFile(); System.out.println(Localization.lang("Exporting") + ": " + data[0]); IExportFormat format = ExportFormats.getExportFormat(data[1]); if (format == null) { System.err.println(Localization.lang("Unknown export format") + ": " + data[1]); } else { // We have an ExportFormat instance: try { format.performExport(pr.getDatabase(), pr.getMetaData(), data[0], pr.getEncoding(), null); } catch (Exception ex) { System.err.println(Localization.lang("Could not export file") + " '" + data[0] + "': " + ex.getMessage()); } } } } else { System.err.println(Localization.lang("The output option depends on a valid import option.")); } } LOGGER.debug("Finished export"); if (cli.isPreferencesExport()) { try { Globals.prefs.exportPreferences(cli.getPreferencesExport()); } catch (JabRefException ex) { LOGGER.error("Cannot export preferences", ex); } } if (!cli.isBlank() && cli.isAuxImport()) { boolean usageMsg = false; if (!loaded.isEmpty()) // bibtex file loaded { String[] data = cli.getAuxImport().split(","); if (data.length == 2) { ParserResult pr = loaded.firstElement(); AuxCommandLine acl = new AuxCommandLine(data[0], pr.getDatabase()); BibDatabase newBase = acl.perform(); boolean notSavedMsg = false; // write an output, if something could be resolved if (newBase != null) { if (newBase.getEntryCount() > 0) { String subName = StringUtil.getCorrectFileName(data[1], "bib"); try { System.out.println(Localization.lang("Saving") + ": " + subName); SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs); BibDatabaseWriter databaseWriter = new BibDatabaseWriter(); Defaults defaults = new Defaults(BibDatabaseMode.fromPreference( Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_DEFAULT_MODE))); SaveSession session = databaseWriter .saveDatabase(new BibDatabaseContext(newBase, defaults), prefs); // Show just a warning message if encoding didn't work for all characters: if (!session.getWriter().couldEncodeAll()) { System.err.println(Localization.lang("Warning") + ": " + Localization.lang( "The chosen encoding '%0' could not encode the following characters:", session.getEncoding().displayName()) + " " + session.getWriter().getProblemCharacters()); } session.commit(new File(subName)); } catch (SaveException ex) { System.err.println(Localization.lang("Could not save file.") + "\n" + ex.getLocalizedMessage()); } notSavedMsg = true; } } if (!notSavedMsg) { System.out.println(Localization.lang("no database generated")); } } else { usageMsg = true; } } else { usageMsg = true; } if (usageMsg) { System.out.println(Localization.lang("no base-BibTeX-file specified") + "!"); System.out.println(Localization.lang("usage") + " :"); System.out.println("jabref --aux infile[.aux],outfile[.bib] base-BibTeX-file"); } } return Optional.of(loaded); }
From source file:org.codehaus.mojo.license.UpdateFileHeaderMojo.java
protected Map<String, List<File>> obtainFilesToTreateByCommentStyle() { Map<String, List<File>> result = new HashMap<String, List<File>>(); // add for all known comment style (says transformer) a empty list // this permits not to have to test if there is an already list each time // we wants to add a new file... for (String commentStyle : transformers.keySet()) { result.put(commentStyle, new ArrayList<File>()); }//from w ww. j ava 2 s . com List<String> rootsList = new ArrayList<String>(roots.length); for (String root : roots) { File f = new File(root); if (f.isAbsolute()) { rootsList.add(f.getAbsolutePath()); } else { f = new File(getProject().getBasedir(), root); } if (f.exists()) { getLog().info("Will search files to update from root " + f); rootsList.add(f.getAbsolutePath()); } else { if (isVerbose()) { getLog().info("Skip not found root " + f); } } } // Obtain all files to treate Map<File, String[]> allFiles = new HashMap<File, String[]>(); getFilesToTreateForRoots(includes, excludes, rootsList, allFiles); // filter all these files according to their extension for (Map.Entry<File, String[]> entry : allFiles.entrySet()) { File root = entry.getKey(); String[] filesPath = entry.getValue(); // sort them by the associated comment style to their extension for (String path : filesPath) { String extension = FileUtils.extension(path); String commentStyle = extensionToCommentStyle.get(extension); if (StringUtils.isEmpty(commentStyle)) { // unknown extension, do not treate this file continue; } // File file = new File(root, path); List<File> files = result.get(commentStyle); files.add(file); } } return result; }
From source file:it.geosolutions.geobatch.task.TaskExecutor.java
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException { listenerForwarder.started();//from www. ja va 2 s . c om if (configuration == null) { final ActionException e = new ActionException(this, "DataFlowConfig is null."); listenerForwarder.failed(e); throw e; } if (events == null || events.size() == 0) { final ActionException e = new ActionException(this, "Empty or null incoming events list"); listenerForwarder.failed(e); throw e; } Queue<FileSystemEvent> outEvents = new LinkedList<FileSystemEvent>(); while (events.size() > 0) { // get the first event final FileSystemEvent event = events.remove(); final File inputFile = event.getSource(); if (inputFile == null) { final ActionException e = new ActionException(this, "Input File is null"); listenerForwarder.failed(e); throw e; } if (!inputFile.exists()) { final ActionException e = new ActionException(this, "Input File doesn't exist"); listenerForwarder.failed(e); throw e; } final String inputFilePath = inputFile.getAbsolutePath(); final String inputFileExt = FilenameUtils.getExtension(inputFilePath); // Getting XSL file definition final String xslPath = configuration.getXsl(); final boolean useDefaultScript; String defaultScriptPath = configuration.getDefaultScript(); if (inputFileExt.equalsIgnoreCase("xml")) { if (LOGGER.isInfoEnabled()) LOGGER.info("Using input file as script: " + inputFilePath); defaultScriptPath = inputFilePath; useDefaultScript = false; } else { if (LOGGER.isInfoEnabled()) LOGGER.info("Using default script: " + configuration.getDefaultScript()); useDefaultScript = true; } final String outputName = configuration.getOutputName(); File xslFile = null; InputStream is = null; try { if (xslPath != null && xslPath.trim().length() > 0) { final String path = Path.findLocation(xslPath, getConfigDir().getAbsolutePath()); if (path == null) { final ActionException e = new ActionException(this, "XSL file not found: " + path); listenerForwarder.failed(e); throw e; } xslFile = new File(path); } if (!xslFile.exists()) { final ActionException e = new ActionException(this, "XSL file not found: " + xslPath); listenerForwarder.failed(e); throw e; } File xmlFile = null; String outputFile = null; if (useDefaultScript) { if (defaultScriptPath != null && defaultScriptPath.trim().length() > 0) { final String path = Path.findLocation(xslPath, getConfigDir().getAbsolutePath()); if (path == null) { final ActionException e = new ActionException(this, "XSL file not found: " + path); listenerForwarder.failed(e); throw e; } xmlFile = new File(path); final File outXmlFile = File.createTempFile("script", ".xml", getTempDir()); // outXmlFile.deleteOnExit(); outputFile = setScriptArguments(xmlFile.getAbsolutePath(), inputFilePath, outputName, outXmlFile); xmlFile = outXmlFile; } } else { xmlFile = inputFile; } if (!xmlFile.exists()) { final ActionException e = new ActionException(this, "XML file not found: " + xmlFile); listenerForwarder.failed(e); throw e; } // Setup an XML source from the input XML file final Source xmlSource = new StreamSource(xmlFile); is = new FileInputStream(xslFile); // XML parsing to setup a command line final String argument = buildArgument(xmlSource, is); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Arguments: " + argument); } final Project project = new Project(); project.init(); final ExecTask execTask = new ExecTask(); execTask.setProject(project); // Setting environment variables coming from the configuration // as an instance: PATH, LD_LIBRARY_PATH and similar Map<String, String> variables = configuration.getVariables(); if (variables != null && !variables.isEmpty()) { for (String key : variables.keySet()) { Variable var = new Variable(); var.setKey(key); final String value = variables.get(key); if (value != null) { var.setValue(variables.get(key)); execTask.addEnv(var); } } } // Setting executable execTask.setExecutable(configuration.getExecutable()); // Setting Error logging final String errorFileName = configuration.getErrorFile(); if (errorFileName != null) { File errorFile = new File(errorFileName); if (!errorFile.exists()) { errorFile = Path.findLocation(errorFileName, getTempDir()); if (errorFile != null && !errorFile.exists()) { try { errorFile.createNewFile(); } catch (Throwable t) { final ActionException e = new ActionException(this, t.getLocalizedMessage(), t); listenerForwarder.failed(e); throw e; } } } if (errorFile.exists()) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Using error file: " + errorFile); execTask.setLogError(true); execTask.setAppend(true); execTask.setError(errorFile); execTask.setFailonerror(true); } } // Setting the timeout Long timeOut = configuration.getTimeOut(); if (timeOut != null) { execTask.setTimeout(timeOut); } // Setting command line argument execTask.createArg().setLine(argument); File output = null; if (configuration.getOutput() != null) { output = new File(configuration.getOutput()); if (output.exists() && output.isDirectory()) { final File outXmlFile = File.createTempFile("script", ".xml", getTempDir()); // TODO CHECKME: is this var used? // outXmlFile.deleteOnExit(); String destFile = getScriptArguments(xmlFile.getAbsolutePath(), "srcfile"); if (output.isAbsolute()) { // String basename = output = new File(output, FilenameUtils.getBaseName(destFile) + configuration .getOutputName().substring(configuration.getOutputName().indexOf("."))); } else { output = Path.findLocation(configuration.getOutput(), inputFile.getParentFile()); output = new File(output, FilenameUtils.getBaseName(inputFile.getName()) + configuration .getOutputName().substring(configuration.getOutputName().indexOf("."))); } } execTask.setOutput(output); } // Executing execTask.execute(); File outFile = (outputFile != null ? new File(outputFile) : null); if (configuration.getOutput() != null) { if (new File(configuration.getOutput()).isAbsolute()) { if (output.exists() && output.isFile()) { // outFile = output; final File outXmlFile = File.createTempFile("script", ".xml", getTempDir()); // outXmlFile.deleteOnExit(); outputFile = setScriptArguments(xmlFile.getAbsolutePath(), output.getAbsolutePath(), outputName, outXmlFile); outFile = new File(configuration.getOutput(), FilenameUtils.getBaseName(outputFile) + ".xml"); FileUtils.copyFile(outXmlFile, outFile); } } else { if (outFile == null) outFile = inputFile; } } else if (outFile == null) { outFile = inputFile; } outEvents.add(new FileSystemEvent(outFile, FileSystemEventType.FILE_ADDED)); } catch (Exception e) { listenerForwarder.failed(e); throw new ActionException(this, e.getMessage(), e); } finally { if (is != null) org.apache.commons.io.IOUtils.closeQuietly(is); } } listenerForwarder.completed(); return outEvents; }
From source file:org.codehaus.mojo.license.AbstractFileHeaderMojo.java
/** * Gets all files to process indexed by their comment style. * * @return for each comment style, list of files to process *//*from ww w . j av a 2s .c o m*/ protected Map<String, List<File>> obtainFilesToProcessByCommentStyle() { Map<String, List<File>> results = new HashMap<String, List<File>>(); // add for all known comment style (says transformer) a empty list // this permits not to have to test if there is an already list each time // we wants to add a new file... for (String commentStyle : transformers.keySet()) { results.put(commentStyle, new ArrayList<File>()); } List<String> rootsList = new ArrayList<String>(roots.length); for (String root : roots) { File f = new File(root); if (f.isAbsolute()) { rootsList.add(f.getAbsolutePath()); } else { f = new File(getProject().getBasedir(), root); } if (f.exists()) { getLog().info("Will search files to update from root " + f); rootsList.add(f.getAbsolutePath()); } else { if (isVerbose()) { getLog().info("Skip not found root " + f); } } } // Obtain all files to treat Map<File, String[]> allFiles = new HashMap<File, String[]>(); getFilesToTreateForRoots(includes, excludes, rootsList, allFiles); // filter all these files according to their extension for (Map.Entry<File, String[]> entry : allFiles.entrySet()) { File root = entry.getKey(); String[] filesPath = entry.getValue(); // sort them by the associated comment style to their extension for (String path : filesPath) { String extension = FileUtils.extension(path); String commentStyle = extensionToCommentStyle.get(extension); if (StringUtils.isEmpty(commentStyle)) { // unknown extension, do not treat this file continue; } // File file = new File(root, path); List<File> files = results.get(commentStyle); files.add(file); } } return results; }
From source file:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("SchemaDist plugin started"); try {//from w w w. j a v a 2 s . c om processArtifactItems(); } catch (InvalidVersionSpecificationException e) { handleFailure(e); } final File outDir = initializeOutDir(outputDirectory); CatalogManager catalogManager = new CatalogManager(); catalogManager.setVerbosity(999); for (ArtifactItem artifactItem : artifactItems) { Artifact artifact = artifactItem.getArtifact(); getLog().info("SchemaDist unpacking artifact " + artifact); File workDir = new File(workDirectory, artifact.getArtifactId()); initializeOutDir(workDir); artifactItem.setWorkDir(workDir); unpack(artifactItem, workDir); if (translateSchemaLocation) { String catalogPath = artifactItem.getCatalog(); File catalogFile = new File(workDir, catalogPath); if (!catalogFile.exists()) { throw new MojoExecutionException("No catalog file " + catalogPath + " in artifact " + artifact); } Catalog catalog = new Catalog(catalogManager); catalog.setupReaders(); try { // UGLY HACK. On Windows, file names like d:\abc\def\catalog.xml eventually get treated very strangely // (resulting in names like "file:<current-working-dir>d:\abc\def\catalog.xml" that are obviously wrong) // Prefixing such names with "file:/" helps. String prefix; if (catalogFile.isAbsolute() && !catalogFile.getPath().startsWith("/")) { prefix = "/"; } else { prefix = ""; } String fileName = "file:" + prefix + catalogFile.getPath(); getLog().debug("Calling parseCatalog with: " + fileName); catalog.parseCatalog(fileName); } catch (MalformedURLException e) { throw new MojoExecutionException( "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e); } catch (IOException e) { throw new MojoExecutionException( "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e); } artifactItem.setResolveCatalog(catalog); } } for (ArtifactItem artifactItem : artifactItems) { Artifact artifact = artifactItem.getArtifact(); getLog().info("SchemaDist processing artifact " + artifact); final File workDir = artifactItem.getWorkDir(); FileVisitor<Path> fileVisitor = new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // nothing to do return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException { String fileName = filePath.getFileName().toString(); if (fileName.endsWith(".xsd")) { getLog().debug("Processing file " + filePath); try { processXsd(filePath, workDir, outDir); } catch (MojoExecutionException | MojoFailureException e) { throw new RuntimeException(e.getMessage(), e); } } else if (fileName.endsWith(".wsdl")) { getLog().debug("Processing file " + filePath); try { processWsdl(filePath, workDir, outDir); } catch (MojoExecutionException | MojoFailureException e) { throw new RuntimeException(e.getMessage(), e); } } else { getLog().debug("Skipping file " + filePath); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.TERMINATE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // nothing to do return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(workDir.toPath(), fileVisitor); } catch (IOException e) { throw new MojoExecutionException("Error processing files of artifact " + artifact, e); } } getLog().info("SchemaDist plugin finished"); }