List of usage examples for java.io File setExecutable
public boolean setExecutable(boolean executable)
From source file:klapersuite.prismanalysis.linux.PrismRunner.java
public boolean extractTar() throws IOException { logger.info("Extract prism archive: " + prismArchive); InputStream gzStream = prismArchive.openStream(); TarInputStream tarStream = new TarInputStream(new GZIPInputStream(gzStream)); TarEntry tarEntry;/* w ww .ja va 2 s .c om*/ while ((tarEntry = tarStream.getNextEntry()) != null) { File destPath = new File(prismDestinationDir, tarEntry.getName()); if (tarEntry.isDirectory()) { destPath.mkdir(); continue; } FileOutputStream fout = new FileOutputStream(destPath); tarStream.copyEntryContents(fout); fout.close(); if (tarEntry.getName().endsWith("install.sh")) destPath.setExecutable(true); } tarStream.close(); gzStream.close(); return true; }
From source file:com.asakusafw.yaess.basic.BasicScriptHandlerTestRoot.java
/** * Puts source file into the path as an executable file. * @param source original contents on classpath * @param file target file path//ww w . j a v a 2s. c om * @return the put file * @throws IOException if failed */ protected File putScript(String source, File file) throws IOException { Assume.assumeThat("Windows does not supported", SystemUtils.IS_OS_WINDOWS, is(false)); LOG.debug("Deploy script: {} -> {}", source, file); try (InputStream in = getClass().getResourceAsStream(source)) { assertThat(source, in, is(notNullValue())); copyTo(in, file); } file.setExecutable(true); return file; }
From source file:com.streamsets.datacollector.cluster.TestClusterProviderImpl.java
@Test public void testCopyDirectory() throws Exception { File copyTempDir = new File(tempDir, "copy"); File srcDir = new File(copyTempDir, "somedir"); File dstDir = new File(copyTempDir, "dst"); Assert.assertTrue(srcDir.mkdirs());//ww w.ja v a2 s . c o m Assert.assertTrue(dstDir.mkdirs()); File link1 = new File(copyTempDir, "link1"); File link2 = new File(copyTempDir, "link2"); File dir1 = new File(copyTempDir, "dir1"); File file1 = new File(dir1, "f1"); File file2 = new File(dir1, "f2"); Assert.assertTrue(dir1.mkdirs()); Assert.assertTrue(file1.createNewFile()); Assert.assertTrue(file2.createNewFile()); file2.setReadable(false); file2.setWritable(false); file2.setExecutable(false); Files.createSymbolicLink(link1.toPath(), dir1.toPath()); Files.createSymbolicLink(link2.toPath(), link1.toPath()); Files.createSymbolicLink(new File(srcDir, "dir1").toPath(), link2.toPath()); File clone = ClusterProviderImpl.createDirectoryClone(srcDir, srcDir.getName(), dstDir); File cloneF1 = new File(new File(clone, "dir1"), "f1"); Assert.assertTrue(cloneF1.isFile()); }
From source file:com.buaa.cfs.utils.FileUtil.java
/** * Platform independent implementation for {@link File#setExecutable(boolean)} File#setExecutable does not work as * expected on Windows. Note: revoking execute permission on folders does not have the same behavior on Windows as * on Unix platforms. Creating, deleting or renaming a file within that folder will still succeed on Windows. * * @param f input file/* www. j a v a 2 s .com*/ * @param executable * * @return true on success, false otherwise */ public static boolean setExecutable(File f, boolean executable) { if (Shell.WINDOWS) { try { String permission = executable ? "u+x" : "u-x"; FileUtil.chmod(f.getCanonicalPath(), permission, false); return true; } catch (IOException ex) { return false; } } else { return f.setExecutable(executable); } }
From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java
private static void copyFiles(String dicomProxyDir, String resourceDir, String[] scripts, boolean setExecutable, boolean overwrite) { try {/*from w ww . j a va2 s . c o m*/ // Copy start/stop scripts over (mainly for docker) File scriptDir = new File(dicomProxyDir); if (!scriptDir.exists()) scriptDir.mkdirs(); for (String scriptFile : scripts) { log.info("File " + scriptFile); File file = new File(scriptDir, scriptFile); log.info("File " + scriptFile + (file.exists() ? " exists" : " not exists") + " in " + scriptDir); if (overwrite || !file.exists()) { InputStream in = null; OutputStream out = null; try { in = new Dcm4CheeOperations().getClass().getClassLoader() .getResourceAsStream(resourceDir + scriptFile); out = new FileOutputStream(file); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (Exception x) { } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } if (setExecutable && file.exists()) file.setExecutable(true); } } catch (Exception x) { log.warning("Exception in script copy", x); } }
From source file:org.openmrs.module.emrmonitor.metric.ConfigurableMetricProducerTest.java
protected void copyResourceToConfigurationFile(String filename) throws Exception { InputStream in = null;//from w ww . j a v a 2 s .c om OutputStream out = null; File outFile = new File(ConfigurableMetricProducer.getConfigurationDirectory(), filename); try { in = OpenmrsClassLoader.getInstance().getResourceAsStream("org/openmrs/module/emrmonitor/" + filename); out = new FileOutputStream(outFile); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } outFile.setExecutable(true); }
From source file:com.splout.db.engine.RedisManager.java
@Override public void init(File dbFile, Configuration config, List<String> initStatements) throws EngineException { File dbFolder = dbFile.getParentFile(); String redisExecutable = config.getString(REDIS_EXECUTABLE_CONF, null); if (redisExecutable == null) { throw new EngineException( "A Redis executable path should be specified in configuration '" + REDIS_EXECUTABLE_CONF + "'", null);/*from w ww. j ava 2s . com*/ } if (!new File(redisExecutable).exists()) { throw new EngineException("The specified Redis executable doesn't exist: " + redisExecutable, null); } int basePort = config.getInt(BASE_PORT_CONF, DEFAULT_BASE_PORT); logger.info("Redis executable -> " + redisExecutable + "; base port -> " + basePort); File thisServer = new File(dbFolder, "redis-server"); File thisDataFile = new File(dbFolder, "dump.rdb"); File actualDataFile = dbFile; try { Runtime.getRuntime().exec( new String[] { "ln", "-s", actualDataFile.getAbsolutePath(), thisDataFile.getAbsolutePath() }) .waitFor(); FileUtils.copyFile(new File(redisExecutable), thisServer); thisServer.setExecutable(true); PortLock portLock = PortUtils.getNextAvailablePort(basePort); try { logger.info("Using port from port lock: " + portLock.getPort()); redisServer = new RedisServer(thisServer, portLock.getPort()); redisServer.start(); jedis = new Jedis("localhost", portLock.getPort()); } finally { portLock.release(); } } catch (InterruptedException e) { throw new EngineException(e); } catch (IOException e) { throw new EngineException(e); } }
From source file:org.expretio.maven.plugins.capnp.CapnProtoMojo.java
private File copyResource(URL source, File target) throws MojoExecutionException { try {/*from w w w . j av a2s . co m*/ String fileName = new File(source.getPath()).getName(); File targetFile = new File(target, fileName); try (InputStream in = new BufferedInputStream(source.openStream()); OutputStream out = new BufferedOutputStream(new FileOutputStream(targetFile));) { ByteStreams.copy(in, out); targetFile.setExecutable(true); return targetFile; } } catch (Exception e) { throw new MojoExecutionException("Unable to copy natives to work directory: " + workDirectory, e); } }
From source file:org.apache.oodt.cas.workflow.misc.WingsTask.java
public void run(Metadata metadata, WorkflowTaskConfiguration config) { Properties props = config.getProperties(); // Component Info String compid = props.getProperty("COMPONENT_ID"); String tname = props.getProperty("TASKNAME"); String jobid = props.getProperty("JOBID"); String argstring = props.getProperty("ARGUMENT"); ArrayList<String> inputs = fetchFromProps(props, "INPUT"); ArrayList<String> outputs = fetchFromProps(props, "OUTPUT"); // Following paths should be Shared across the cluster //String script = props.getProperty("SCRIPT_PATH"); String origjobdir = props.getProperty("JOB_DIR"); String jobdir = origjobdir;//from www . j a va 2 s . c o m //String datadir = props.getProperty("DATA_DIR"); // File Manager Access String fmurl = props.getProperty("FM_URL"); String fmprefix = props.getProperty("FM_PREFIX"); // Logging specific info String logfile = props.getProperty("LOGFILE"); String wlogfile = props.getProperty("W_LOGFILE"); String tplid = wlogfile.replace(".log", ""); PrintStream wlogout = null; PrintStream logout = null; XmlRpcFileManagerClient fmclient = null; try { fmclient = new XmlRpcFileManagerClient(new URL(fmurl)); DataTransfer dt = new RemoteDataTransferFactory().createDataTransfer(); dt.setFileManagerUrl(new URL(fmurl)); // Check if outputs already exist in the file manager boolean outputs_already_present = true; for (String op : outputs) { String prodid = fmprefix + op; Product prod = null; try { prod = fmclient.getProductById(prodid); } catch (Exception e) { } if (prod == null) { outputs_already_present = false; } } // If outputs already present, no need to execute if (outputs_already_present) return; File tmpdir = File.createTempFile("oodt-run-", ""); if (tmpdir.delete() && tmpdir.mkdirs()) jobdir = tmpdir.getAbsolutePath() + File.separator; argstring = argstring.replace(origjobdir, jobdir); wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true)); logout = new PrintStream(jobdir + logfile); wlogout.println(jobid + " (" + tname + "): RUNNING"); wlogout.close(); this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(), fmclient); wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true)); logout.println("[INFO]: Component Initializing"); logout.println(tname + " " + argstring); // Fetch input files from file manager if not already present in directory for (String ip : inputs) { File f = new File(jobdir + ip); if (!f.exists()) { logout.println("[INFO] Fetching Input from File Manager: " + ip); Product prod = fmclient.getProductById(fmprefix + ip); prod.setProductReferences(fmclient.getProductReferences(prod)); dt.retrieveProduct(prod, new File(jobdir)); } } logout.flush(); // Fetch component from file manager File compdir = new File(jobdir + File.separator + "comp"); compdir.mkdir(); Product cprod = fmclient.getProductById(compid); cprod.setProductReferences(fmclient.getProductReferences(cprod)); dt.retrieveProduct(cprod, compdir); String scriptPath = null; for (File czip : compdir.listFiles()) { if (czip.getName().endsWith(".zip")) { this.unZipIt(czip.getAbsolutePath(), compdir.getAbsolutePath()); File tmpf = new File(compdir.getAbsolutePath() + File.separator + "run"); if (!tmpf.exists()) tmpf = new File(compdir.getAbsolutePath() + File.separator + "run.bat"); scriptPath = tmpf.getAbsolutePath(); } else scriptPath = czip.getAbsolutePath(); } File scriptf = new File(scriptPath); scriptf.setExecutable(true); // Create command execution ArrayList<String> command = new ArrayList<String>(); command.add(scriptf.getAbsolutePath()); for (String s : argstring.split(" ")) { command.add(s); } ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(jobdir)); builder.redirectErrorStream(true); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { logout.println(line); } process.waitFor(); int exitStatus = process.exitValue(); if (exitStatus != 0) throw new Exception("[ERROR] Component failed with a non-zero exit code"); // Ingest output files to file manager for (String op : outputs) { File f = new File(jobdir + op); File metf = new File(jobdir + op + ".met"); HashMap<String, String> cmeta = new HashMap<String, String>(); if (metf.exists()) { for (Object ln : FileUtils.readLines(metf)) { String metline = (String) ln; String[] kv = metline.split("\\s*=\\s*"); if (kv.length == 2) cmeta.put(kv[0], kv[1]); } } if (!f.exists()) throw new Exception("[ERROR] Missing Output " + op); if (f.exists()) { logout.println("[INFO] Putting Output into File Manager: " + op); // Get Output Metadata & Product Type String typeid = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; Metadata meta = metadata.getSubMetadata(op); String prodtypeid = meta.getMetadata(typeid); meta.removeMetadata(typeid); // Override metadata with custom metadata (if any) for (String key : meta.getAllKeys()) { String[] nsname = key.split("#"); if (nsname.length == 2) { if (cmeta.containsKey(nsname[1])) { meta.removeMetadata(key); meta.addMetadata(key, cmeta.get(nsname[1])); } } } // Upload output to file manager String prodid = fmprefix + op; this.uploadProduct(prodid, op, prodtypeid, f, meta, fmclient); } if (metf.exists()) { String metname = op + ".met"; String prodid = fmprefix + metname; this.uploadProduct(prodid, metname, "GenericFile", metf, new Metadata(), fmclient); } } logout.println("SUCCESS: Component finished successfully !"); logout.close(); wlogout.println(jobid + " (" + tname + "): SUCCESS"); wlogout.close(); } catch (Exception e) { if (logout != null) { logout.println(e.getMessage()); logout.println("FAILURE: Component Failed"); logout.close(); wlogout.println(jobid + " (" + tname + "): FAILURE"); wlogout.close(); } } try { if (fmclient != null) { this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(), fmclient); String logid = tplid + "-" + logfile; this.uploadProduct(logid, logid, "GenericFile", new File(jobdir + logfile), new Metadata(), fmclient); } } catch (CatalogException e) { e.printStackTrace(); } catch (RepositoryManagerException e) { e.printStackTrace(); } }
From source file:org.eclipse.thym.ios.core.xcode.XcodeProjectGenerator.java
@Override protected void generateNativeFiles(HybridMobileLibraryResolver resolver) throws CoreException { try {/* w w w . j a v a 2 s .co m*/ HybridProject hybridProject = HybridProject.getHybridProject(getProject()); if (hybridProject == null) { throw new CoreException(new Status(IStatus.ERROR, IOSCore.PLUGIN_ID, "Not a hybrid mobile project, can not generate files")); } File destinationDir = getDestination(); Path destinationPath = new Path(destinationDir.toString()); String name = hybridProject.getBuildArtifactAppName(); IPath prjPath = destinationPath.append(name); Widget widgetModel = WidgetModel.getModel(hybridProject).getWidgetForRead(); String packageName = widgetModel.getId(); File prjdir = prjPath.toFile(); if (!prjdir.exists()) {//create the project directory prjdir.mkdirs(); } // /${project_name} directoryCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME)), toURL(prjdir)); //Delete these two files. Because we use them directly from the template location // Cordova CLI renames them after copying, we end up with dangling template files // which in some cases confuses the config file actions for plugin installation. FileUtils.deleteQuietly(new File(prjdir, "__PROJECT_NAME__-Info.plist")); FileUtils.deleteQuietly(new File(prjdir, "__PROJECT_NAME__-Prefix.pch")); handleIcons(widgetModel, hybridProject); handleSplashScreens(widgetModel, hybridProject); // cordova IPath cordovaScriptPath = destinationPath.append("cordova"); directoryCopy(resolver.getTemplateFile(cordovaScriptPath.makeRelativeTo(destinationPath)), toURL(cordovaScriptPath.toFile())); //Copy node_modules to cordova/node_modules. cordova-ios >3.9.0 uses them during build IPath nodeModules = cordovaScriptPath.append("node_modules"); directoryCopy(resolver.getTemplateFile(nodeModules.makeRelativeTo(destinationPath)), toURL(nodeModules.toFile())); // cordova-ios >3.9.0 does not need need this anymore but uses node.js scripts. File wwwwCopyScript = cordovaScriptPath.append("lib").append("copy-www-build-step.sh").toFile(); if (wwwwCopyScript.exists()) { wwwwCopyScript.setExecutable(true); } HashMap<String, String> values = new HashMap<String, String>(); values.put("__TESTING__", name); values.put("__PROJECT_NAME__", name); // replaced __TESTING__ after 3.4.0 values.put("--ID--", packageName); // /${project_name}/${project_name}-Info.plist IPath templatePath = prjPath.append(name + "-Info.plist"); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + "/" + VAR_APP_NAME + "-Info.plist")), toURL(templatePath.toFile()), values); // /${project_name}/${project_name}-Prefix.pch templatePath = prjPath.append(name + "-Prefix.pch"); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + "/" + VAR_APP_NAME + "-Prefix.pch")), toURL(templatePath.toFile()), values); // /${project_name}.xcodeproj/project.pbxproj IPath xcodeprojDirPath = destinationPath.append(name + ".xcodeproj"); File xcodeDir = xcodeprojDirPath.toFile();//create the xcodeproj folder first if (!xcodeDir.exists()) { xcodeDir.mkdir(); } IPath xcodeprojectFilePath = xcodeprojDirPath.append("project.pbxproj"); File xcodeprojectFile = xcodeprojectFilePath.toFile(); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + ".xcodeproj/project.pbxproj")), toURL(xcodeprojectFile), values); // /${project_name}/Classes/AppDelegate.h IPath classesPath = prjPath.append("Classes"); templatePath = classesPath.append("AppDelegate.h"); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + "/Classes/AppDelegate.h")), toURL(templatePath.toFile()), values); // /${project_name}/Classes/AppDelegate.m templatePath = classesPath.append("AppDelegate.m"); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + "/Classes/AppDelegate.m")), toURL(templatePath.toFile()), values); // /${project_name}/Classes/MainViewController.h templatePath = classesPath.append("MainViewController.h"); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + "/Classes/MainViewController.h")), toURL(templatePath.toFile()), values); // /${project_name}/Classes/MainViewController.h templatePath = classesPath.append("MainViewController.m"); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + "/Classes/MainViewController.m")), toURL(templatePath.toFile()), values); // /${project_name}/main.m templatePath = prjPath.append("main.m"); templatedFileCopy(resolver.getTemplateFile(new Path(VAR_APP_NAME + "/main.m")), toURL(templatePath.toFile()), values); //CordovaLib IPath cordovaLibDirectory = getCordovaLibPath(); directoryCopy(resolver.getTemplateFile(new Path("CordovaLib")), toURL(cordovaLibDirectory.toFile())); updateCordovaSubProjectPath(xcodeprojectFile, "CordovaLib/CordovaLib.xcodeproj", "<group>"); //iOS config.xml needs to be copied outside www to be used File configxml = hybridProject.getConfigFile().getLocation().toFile(); fileCopy(toURL(configxml), toURL(new File(prjdir, "/" + PlatformConstants.FILE_XML_CONFIG))); } catch (IOException e) { throw new CoreException( new Status(IStatus.ERROR, IOSCore.PLUGIN_ID, "Error generating the native iOS project", e)); } }