List of usage examples for java.io File getCanonicalFile
public File getCanonicalFile() throws IOException
From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java
/** * Creates a new instance of PythonTestScript * * @throws FileNotFoundException/*from w w w . j av a 2 s.co m*/ * @throws IOException */ public JythonTestScript(List<LinkedHashMap<String, String>> data, List<TestRequirement> requirements, File fileName, File testSuiteDirectory, TestSuite testSuite) throws IOException { super(fileName.getParentFile(), testSuiteDirectory, fileName.getParentFile().getName(), new TestDataSet(data), requirements, testSuite); this.fileName = fileName.getCanonicalFile().getAbsoluteFile(); String version = VersionControl.getInstance().getSUTVersion(fileName.getParentFile().getPath()); //String version = parseVersion(fileName.getParentFile().getPath()); setVersion(version); scriptTestData = new ScriptTestData(); scriptBreakpoint = new ScriptBreakpoint(); }
From source file:com.dsh105.commodus.data.Updater.java
/** * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit *//* ww w . j a v a 2 s .com*/ private void unzip(String file) { try { final File fSourceZip = new File(file); final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte buffer[] = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginFile(name)) { destinationFilePath.renameTo( new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name)); } } entry = null; destinationFilePath = null; } e = null; zipFile.close(); zipFile = null; // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. for (final File dFile : new File(zipPath).listFiles()) { if (dFile.isDirectory()) { if (this.pluginFile(dFile.getName())) { final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir final File[] contents = oFile.listFiles(); // List of existing files in the current dir for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir { boolean found = false; for (final File xFile : contents) // Loop through contents to see if it exists { if (xFile.getName().equals(cFile.getName())) { found = true; break; } } if (!found) { // Move the new file into the current dir cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); } else { // This file already exists, so we don't need it anymore. cFile.delete(); } } } } dFile.delete(); } new File(zipPath).delete(); fSourceZip.delete(); } catch (final IOException ex) { this.plugin.getLogger() .warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; ex.printStackTrace(); } new File(file).delete(); }
From source file:org.apache.storm.daemon.logviewer.handler.LogviewerLogSearchHandler.java
@VisibleForTesting Matched findNMatches(List<File> logs, int numMatches, int fileOffset, int offset, String search) { logs = drop(logs, fileOffset);//from w w w. j av a 2 s . c om List<Map<String, Object>> matches = new ArrayList<>(); int matchCount = 0; while (true) { if (logs.isEmpty()) { break; } File firstLog = logs.get(0); Map<String, Object> theseMatches; try { LOG.debug("Looking through {}", firstLog); theseMatches = substringSearch(firstLog, search, numMatches - matchCount, offset); } catch (InvalidRequestException e) { LOG.error("Can't search past end of file.", e); theseMatches = new HashMap<>(); } String fileName = WorkerLogs.getTopologyPortWorkerLog(firstLog); final List<Map<String, Object>> newMatches = new ArrayList<>(matches); Map<String, Object> currentFileMatch = new HashMap<>(theseMatches); currentFileMatch.put("fileName", fileName); Path firstLogAbsPath; try { firstLogAbsPath = firstLog.getCanonicalFile().toPath(); } catch (IOException e) { throw new RuntimeException(e); } currentFileMatch.put("port", truncatePathToLastElements(firstLogAbsPath, 2).getName(0)); newMatches.add(currentFileMatch); int newCount = matchCount + ((List<?>) theseMatches.get("matches")).size(); if (theseMatches.isEmpty()) { // matches and matchCount is not changed logs = rest(logs); offset = 0; fileOffset = fileOffset + 1; } else if (newCount >= numMatches) { matches = newMatches; break; } else { matches = newMatches; logs = rest(logs); offset = 0; fileOffset = fileOffset + 1; matchCount = newCount; } } return new Matched(fileOffset, search, matches); }
From source file:org.intermine.install.swing.ProjectEditor.java
/** * Load the project from the given <code>project.xml</code> file. * /*from w w w.ja va 2s . c o m*/ * @param projectFile The file to load. * * @see ProjectLoader#loadProject(File) */ public void loadProject(File projectFile) { try { if (projectLoader == null) { projectLoader = new ProjectLoader(); } project = projectLoader.loadProject(projectFile); initialise(projectFile.getCanonicalFile(), project); MineManagerBackingStore.getInstance().setLastProjectFile(this.projectFile); loadModel(); switchToLoadedButtonState(); if (project.getSources().getSource().isEmpty()) { JOptionPane.showMessageDialog(this, Messages.getMessage("project.empty.message"), Messages.getMessage("project.empty.title"), JOptionPane.INFORMATION_MESSAGE); } } catch (Exception e) { logger.error(Messages.getMessage("project.load.failed.message"), e); StringWriter swriter = new StringWriter(); PrintWriter writer = new PrintWriter(swriter); writer.println(Messages.getMessage("project.load.failed.message")); e.printStackTrace(writer); writer.close(); JOptionPane.showMessageDialog(this, swriter.toString(), Messages.getMessage("project.load.failed.title"), JOptionPane.ERROR_MESSAGE); } }
From source file:net.bpelunit.framework.SpecificationLoader.java
public TestSuite loadTestSuite(File suite) throws SpecificationException { try {//from w ww .ja v a 2 s . c om fLogger.info("Loading test suite from file " + suite); String path = suite.getCanonicalFile().getParent() + File.separator; fLogger.info("Using base path: " + path); XMLTestSuiteDocument doc = XMLTestSuiteDocument.Factory.parse(suite); validateTestSuite(doc); extractConditionGroups(doc); TestSuite testSuite = parseSuite(path, doc); fLogger.info("Loaded test suite with name \"" + testSuite.getName() + "\" and " + testSuite.getTestCaseCount() + " test cases."); return testSuite; } catch (XmlException e) { throw new SpecificationException("An XML reading error occurred when reading the test suite file.", e); } catch (IOException e) { throw new SpecificationException("An I/O error occurred when reading the test suite file.", e); } }
From source file:org.apache.hadoop.hive.ant.QTestGenTask.java
public void execute() throws BuildException { if (getTemplatePath().equals("")) { throw new BuildException("No templatePath attribute specified"); }// w w w . j a va 2 s .c o m if (template == null) { throw new BuildException("No template attribute specified"); } if (outputDirectory == null) { throw new BuildException("No outputDirectory specified"); } if (queryDirectory == null && queryFile == null) { throw new BuildException("No queryDirectory or queryFile specified"); } if (logDirectory == null) { throw new BuildException("No logDirectory specified"); } if (className == null) { throw new BuildException("No className specified"); } Set<String> includeOnly = null; if (includeQueryFile != null && !includeQueryFile.isEmpty()) { includeOnly = Sets.<String>newHashSet(TEST_SPLITTER.split(includeQueryFile)); } List<File> qFiles; HashMap<String, String> qFilesMap = new HashMap<String, String>(); File hiveRootDir = null; File queryDir = null; File outDir = null; File resultsDir = null; File logDir = null; try { System.out.println("Starting Generation of: " + className); System.out.println("Include Files: " + includeQueryFile); System.out.println("Excluded Files: " + excludeQueryFile); System.out.println("Query Files: " + queryFile); System.out.println("Query Files Regex: " + queryFileRegex); // queryDirectory should not be null queryDir = new File(queryDirectory); // dedup file list Set<File> testFiles = new HashSet<File>(); if (queryFile != null && !queryFile.equals("")) { // The user may have passed a list of files - comma separated for (String qFile : TEST_SPLITTER.split(queryFile)) { if (null != queryDir) { testFiles.add(new File(queryDir, qFile)); } else { testFiles.add(new File(qFile)); } } } else if (queryFileRegex != null && !queryFileRegex.equals("")) { for (String regex : TEST_SPLITTER.split(queryFileRegex)) { testFiles.addAll(Arrays.asList(queryDir.listFiles(new QFileRegexFilter(regex)))); } } else if (runDisabled != null && runDisabled.equals("true")) { testFiles.addAll(Arrays.asList(queryDir.listFiles(new DisabledQFileFilter(includeOnly)))); } else { testFiles.addAll(Arrays.asList(queryDir.listFiles(new QFileFilter(includeOnly)))); } if (excludeQueryFile != null && !excludeQueryFile.equals("")) { // Exclude specified query files, comma separated for (String qFile : TEST_SPLITTER.split(excludeQueryFile)) { if (null != queryDir) { testFiles.remove(new File(queryDir, qFile)); } else { testFiles.remove(new File(qFile)); } } } hiveRootDir = new File(hiveRootDirectory); if (!hiveRootDir.exists()) { throw new BuildException( "Hive Root Directory " + hiveRootDir.getCanonicalPath() + " does not exist"); } qFiles = new ArrayList<File>(testFiles); Collections.sort(qFiles); for (File qFile : qFiles) { qFilesMap.put(qFile.getName(), relativePath(hiveRootDir, qFile)); } // Make sure the output directory exists, if it doesn't then create it. outDir = new File(outputDirectory); if (!outDir.exists()) { outDir.mkdirs(); } logDir = new File(logDirectory); if (!logDir.exists()) { throw new BuildException("Log Directory " + logDir.getCanonicalPath() + " does not exist"); } if (resultsDirectory != null) { resultsDir = new File(resultsDirectory); if (!resultsDir.exists()) { throw new BuildException( "Results Directory " + resultsDir.getCanonicalPath() + " does not exist"); } } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e); } VelocityEngine ve = new VelocityEngine(); try { ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, getTemplatePath()); if (logFile != null) { File lf = new File(logFile); if (lf.exists()) { System.out.println("Log file already exists: " + lf.getCanonicalPath()); if (!lf.delete()) { System.out.println("Could not delete log file " + lf.getCanonicalPath()); logFile = createAlternativeFile(lf); } } ve.setProperty(RuntimeConstants.RUNTIME_LOG, logFile); } ve.init(); Template t = ve.getTemplate(template); if (clusterMode == null) { clusterMode = ""; } if (hadoopVersion == null) { hadoopVersion = ""; } File qFileNames = new File(outputDirectory, className + "QFileNames.txt"); String qFileNamesFile = qFileNames.toURI().getPath(); if (qFileNames.exists()) { System.out.println("Query file names containing file already exists: " + qFileNamesFile); if (!qFileNames.delete()) { System.out.println( "Could not delete query file names containing file " + qFileNames.getCanonicalPath()); qFileNamesFile = createAlternativeFile(qFileNames); } else if (!qFileNames.createNewFile()) { System.out.println("Could not create query file names containing file " + qFileNamesFile); qFileNamesFile = createAlternativeFile(qFileNames); } } FileWriter fw = new FileWriter(qFileNames.getCanonicalFile()); BufferedWriter bw = new BufferedWriter(fw); for (File qFile : qFiles) { bw.write(qFile.getName()); bw.newLine(); } bw.close(); // For each of the qFiles generate the test System.out.println("hiveRootDir = " + hiveRootDir); VelocityContext ctx = new VelocityContext(); ctx.put("className", className); ctx.put("hiveRootDir", escapePath(hiveRootDir.getCanonicalPath())); System.out.println("hiveRootDir = " + hiveRootDir); System.out.println("queryDir = " + queryDir); String strQueryDir = relativePath(hiveRootDir, queryDir); System.out.println("queryDir = " + strQueryDir); ctx.put("queryDir", strQueryDir); ctx.put("qfiles", qFiles); ctx.put("qFileNamesFile", qFileNamesFile); ctx.put("qfilesMap", qFilesMap); if (resultsDir != null) { ctx.put("resultsDir", relativePath(hiveRootDir, resultsDir)); } ctx.put("logDir", relativePath(hiveRootDir, logDir)); ctx.put("clusterMode", clusterMode); if (hiveConfDir == null || hiveConfDir.isEmpty()) { ctx.put("hiveConfDir", ""); } else { System.out.println("hiveConfDir = " + hiveConfDir); hiveConfDir = relativePath(hiveRootDir, new File(hiveConfDir)); System.out.println("hiveConfDir = " + hiveConfDir); if (!(new File(hiveRootDir, hiveConfDir)).isDirectory()) { throw new BuildException("hiveConfDir is not dir " + new File(hiveRootDir, hiveConfDir)); } ctx.put("hiveConfDir", hiveConfDir); } ctx.put("hadoopVersion", hadoopVersion); ctx.put("initScript", initScript); ctx.put("cleanupScript", cleanupScript); File outFile = new File(outDir, className + ".java"); FileWriter writer = new FileWriter(outFile); t.merge(ctx, writer); writer.close(); System.out.println("Generated " + outFile.getCanonicalPath() + " from template " + template); } catch (BuildException e) { throw e; } catch (MethodInvocationException e) { throw new BuildException("Exception thrown by '" + e.getReferenceName() + "." + e.getMethodName() + "'", e.getWrappedThrowable()); } catch (ParseErrorException e) { throw new BuildException("Velocity syntax error", e); } catch (ResourceNotFoundException e) { throw new BuildException("Resource not found", e); } catch (Exception e) { e.printStackTrace(); throw new BuildException("Generation failed", e); } }
From source file:display.containers.FileManager.java
/** * Rentre dans un repertoire/* w w w .j a va2s . co m*/ * @param row * @param column */ protected void mouseDblClicked(int row, int column) { final File file = ((FileTableModel) table.getModel()).getFile(row); if (file.isDirectory()) { try { setCurrentDir(file.getCanonicalFile()); showChildren(Paths.get(file.getCanonicalPath())); } catch (IOException e) { WindowManager.mwLogger.log(Level.WARNING, "FileManager mouseDblClicked error.", e); } } else { // si on est dans la vue admin et qu'on clic sur un nifti encrypte if (file.getName().endsWith(".nii" + AESCrypt.ENCRYPTSUFFIX) && mode == 2) { WindowManager.MAINWINDOW.getProgressBarPanel().setVisible(true); Thread tr = new Thread(new Runnable() { @Override public void run() { try { copySelectedFilesAndDecryptTo(SystemSettings.SERVER_INFO.getTempDir().toFile()); File copiedFile = new File(SystemSettings.SERVER_INFO.getTempDir() + File.separator + file.getName().substring(0, file.getName().length() - 4)); WindowManager.MAINWINDOW.getViewerPanel().open(copiedFile.toPath()); WindowManager.MAINWINDOW.getOngletPane() .setSelectedComponent(WindowManager.MAINWINDOW.getViewerPanel()); copiedFile.deleteOnExit(); WindowManager.MAINWINDOW.getProgressBarPanel().setVisible(false); } catch (final Exception e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(WindowManager.MAINWINDOW, "Exception : " + e.toString(), "Openning error", JOptionPane.ERROR_MESSAGE); } }); WindowManager.MAINWINDOW.getProgressBarPanel().setVisible(false); WindowManager.mwLogger.log(Level.WARNING, "FileManager Openning error.", e); } } }); tr.start(); } else { // si c'est un nifti non crypte if (file.getName().endsWith(".nii") || file.getName().endsWith(".img") || file.getName().endsWith(".nii.gz") || file.getName().endsWith(".hdr")) { WindowManager.MAINWINDOW.getProgressBarPanel().setVisible(true); WindowManager.MAINWINDOW.getOngletPane() .setSelectedComponent(WindowManager.MAINWINDOW.getViewerPanel()); Thread tr = new Thread(new Runnable() { @Override public void run() { try { WindowManager.MAINWINDOW.getViewerPanel().open(file.toPath()); WindowManager.MAINWINDOW.getProgressBarPanel().setVisible(false); } catch (final Exception e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(WindowManager.MAINWINDOW, "Exception : " + e.toString(), "Openning error", JOptionPane.ERROR_MESSAGE); } }); WindowManager.MAINWINDOW.getProgressBarPanel().setVisible(false); WindowManager.mwLogger.log(Level.WARNING, "FileManager Openning error.", e); } } }); tr.start(); } else { try { desktop.open(file); } catch (Throwable t) { showThrowable(t); WindowManager.mwLogger.log(Level.WARNING, "FileManager Openning error.", t); } } } } }
From source file:org.apache.cocoon.servlet.CocoonServlet.java
/** * Set the ConfigFile for the Cocoon object. * * @param configFileName The file location for the cocoon.xconf * * @throws ServletException//from w w w . j av a 2 s . com */ private URL getConfigFile(final String configFileName) throws ServletException { final String usedFileName; if (configFileName == null) { if (getLogger().isWarnEnabled()) { getLogger().warn( "Servlet initialization argument 'configurations' not specified, attempting to use '/WEB-INF/cocoon.xconf'"); } usedFileName = "/WEB-INF/cocoon.xconf"; } else { usedFileName = configFileName; } if (getLogger().isDebugEnabled()) { getLogger().debug("Using configuration file: " + usedFileName); } URL result; try { // test if this is a qualified url if (usedFileName.indexOf(':') == -1) { result = this.servletContext.getResource(usedFileName); } else { result = new URL(usedFileName); } } catch (Exception mue) { String msg = "Init parameter 'configurations' is invalid : " + usedFileName; getLogger().error(msg, mue); throw new ServletException(msg, mue); } if (result == null) { File resultFile = new File(usedFileName); if (resultFile.isFile()) { try { result = resultFile.getCanonicalFile().toURL(); } catch (Exception e) { String msg = "Init parameter 'configurations' is invalid : " + usedFileName; getLogger().error(msg, e); throw new ServletException(msg, e); } } } if (result == null) { String msg = "Init parameter 'configuration' doesn't name an existing resource : " + usedFileName; getLogger().error(msg); throw new ServletException(msg); } return result; }
From source file:com.naryx.tagfusion.expression.function.file.Unzip.java
private void performUnzip(cfSession _session, File _zipfile, File _destination, String charset, boolean _flatten, boolean overwrite) throws cfmRunTimeException { ZipFile zFile = null;/* w ww.j a v a 2s . c o m*/ try { zFile = new ZipFile(_zipfile, charset); } catch (IOException ze) { throwException(_session, "Failed to extract zip file. Check the file is a valid zip file."); } BufferedInputStream in = null; InputStream zIn = null; FileOutputStream fout = null; File nextFile = null; String destinationFilename; byte[] buffer = new byte[4096]; int read; try { Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries(); if (files == null) { throwException(_session, "Failed to extract zip file. Check the file is a valid zip file."); } ZipArchiveEntry nextEntry; // while unzip stuff goes here while (files.hasMoreElements()) { nextEntry = files.nextElement(); destinationFilename = nextEntry.getName(); File checkFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); if (checkFile.exists() && !overwrite) { throwException(_session, "File already exist"); } else { if (!nextEntry.isDirectory()) { if (_flatten) { int pathEnd = destinationFilename.lastIndexOf('/'); if (pathEnd != -1) destinationFilename = destinationFilename.substring(pathEnd + 1); } nextFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); try { nextFile = nextFile.getCanonicalFile(); } catch (IOException ignore) { } // use original nextFile if getCanonicalFile() fails File parent = nextFile.getParentFile(); if (parent != null) { parent.mkdirs(); // create the parent directory structure if needed } try { zIn = zFile.getInputStream(nextEntry); in = new BufferedInputStream(zIn); fout = new FileOutputStream(nextFile, false); while ((read = in.read(buffer)) != -1) { fout.write(buffer, 0, read); } fout.flush(); } catch (IOException ioe) { throwException(_session, "Failed to extract entry [" + nextEntry.getName() + "] from zip file to " + nextFile.getAbsolutePath() + ". Check the permissions are suitable to allow this file to be written."); } finally { StreamUtil.closeStream(in); StreamUtil.closeStream(zIn); StreamUtil.closeStream(fout); } } else if (!_flatten) { destinationFilename = nextEntry.getName(); nextFile = new File( _destination.getAbsolutePath() + File.separatorChar + destinationFilename); try { nextFile = nextFile.getCanonicalFile(); } catch (IOException ignore) { // use original nextFile if getCanonicalFile() fails } nextFile.mkdirs(); } } } } finally { try { zFile.close(); } catch (IOException ignored) { } } }
From source file:com.qq.tars.maven.gensrc.TarsBuildMojo.java
private void createConfigScript(File binDir, File dataDir, File binLogDir, File configFile) throws Exception { InputStream in = null;//from w w w. j a v a 2 s .co m FileWriter out = null; try { File servicesXMLFile = new File(war, "WEB-INF" + File.separator + "servants.xml"); if (!servicesXMLFile.exists()) { throw new MojoExecutionException( "failed to find WEB-INF/servants.xml, " + " servants will be disabled"); } XMLConfigFile cfg = new XMLConfigFile(); cfg.parse(new FileInputStream(servicesXMLFile)); XMLConfigElement root = cfg.getRootElement(); ArrayList<XMLConfigElement> elements = root.getChildList(); in = getConfigTemplate(); InputStreamReader reader = new InputStreamReader(getConfigTemplate()); Map<Object, Object> context = new HashMap<Object, Object>(); context.put("LOCALIP", getLocalIp()); context.put("APP", getApp()); context.put("SERVER", getServer()); context.put("BASEPATH", binDir.getCanonicalPath()); context.put("DATAPATH", dataDir.getCanonicalFile()); context.put("LOGPATH", binLogDir.getCanonicalPath()); context.put("JVMPARAMS", getJvmParams()); context.put("MAINCLASS", MAIN_CLASS); context.put("CONFIG", configFile.getAbsolutePath()); StringBuffer suf = new StringBuffer(); for (XMLConfigElement element : elements) { if ("servant".equals(element.getName())) { if (suf.length() > 0) { suf.append("\n"); } Servant servant = new Servant(); servant.setName(element.getStringAttribute("name")); servant.setProtocol(element.getStringAttribute("protocol", TARS_PROTOCOL)); servant.setPort(element.getStringAttribute("port")); suf.append(readServantScript(servant)); if (servant.getProtocol() != null && isJceOrWup(servant.getProtocol())) { context.put("ADMINPORT", servant.getPort()); } } } context.put("SERVANTADAPTER", suf.toString()); InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader(reader, context, "$", "$"); out = new FileWriter(configFile); IOUtil.copy(interpolationFilterReader, out); } catch (FileNotFoundException e) { throw new MojoExecutionException("Failed to get template for config file.", e); } catch (IOException e) { throw new MojoExecutionException("Failed to write config file.", e); } finally { IOUtil.close(out); IOUtil.close(in); } }