List of usage examples for java.io File setExecutable
public boolean setExecutable(boolean executable, boolean ownerOnly)
From source file:com.opengamma.maven.scripts.ScriptableScriptGeneratorMojo.java
@SuppressWarnings("unchecked") @Override/*from w w w. j a v a 2 s .c om*/ public void execute() throws MojoExecutionException, MojoFailureException { boolean templateSet = !StringUtils.isBlank(_template); boolean templateMapSet = _baseClassTemplateMap != null && _baseClassTemplateMap.isEmpty(); if ((templateSet && templateMapSet) || (!templateSet && !templateMapSet)) { throw new MojoExecutionException("Exactly one of 'template' or 'baseClassTemplateMap' must be set"); } if (!_outputDir.exists()) { try { getLog().debug("Creating output directory " + _outputDir); if (!_outputDir.mkdirs()) { throw new MojoExecutionException( "Unable to create output directory " + _outputDir.getAbsolutePath()); } } catch (Exception e) { throw new MojoExecutionException("Error creating output directory " + _outputDir.getAbsolutePath()); } } List<String> classpathElementList; try { classpathElementList = _project.getCompileClasspathElements(); } catch (DependencyResolutionRequiredException e) { throw new MojoExecutionException("Error obtaining dependencies", e); } URL[] classpathUrls = ClasspathUtils.getClasspathURLs(classpathElementList); Set<String> annotationClasses = ClassNameAnnotationScanner.scan(classpathUrls, Scriptable.class.getName()); getLog().info("Generating " + annotationClasses.size() + " scripts"); ClassLoader classLoader = new URLClassLoader(classpathUrls, this.getClass().getClassLoader()); Map<Class<?>, Template> templateMap = resolveTemplateMap(classLoader); for (String className : annotationClasses) { Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("className", className); Template template = getTemplateForClass(className, classLoader, templateMap); if (template == null) { getLog().warn("No template for scriptable class " + className); continue; } ScriptsGenerator.generate(className, _outputDir, template, templateData); } if (_additionalScripts != null) { getLog().info("Copying " + _additionalScripts.length + " additional script(s)"); for (String script : _additionalScripts) { File scriptFile = new File(script); if (scriptFile.exists()) { if (!scriptFile.isFile()) { throw new MojoExecutionException( "Can only copy files, but additional script '" + scriptFile + "' is not a file"); } try { FileUtils.copyFileToDirectory(scriptFile, _outputDir); File copiedFile = new File(_outputDir, scriptFile.getName()); copiedFile.setReadable(true, false); copiedFile.setExecutable(true, false); } catch (IOException e) { throw new MojoExecutionException("Unable to copy additional script '" + scriptFile + "'", e); } } } } }
From source file:com.clustercontrol.agent.job.CommandThread.java
private void createScriptFile(String scriptContent, String encoding) throws IOException { PrintWriter pw = null;//from ww w . j av a 2s. c o m try { File f = new File(scriptFile); pw = new PrintWriter(f, encoding); pw.print(scriptContent.replaceAll("\n", System.getProperty("line.separator"))); f.setExecutable(true, false); m_log.debug("createScriptFile() : " + scriptFile); } finally { if (pw != null) { pw.close(); } } }
From source file:org.rhq.enterprise.server.plugins.jdr.JdrServerPluginComponent.java
private void writeAccessToken() { File dataDir = new File(System.getProperty("jboss.server.data.dir")); if (!dataDir.exists() || !dataDir.canWrite()) { log.error("Failed to write access token, jboss.server.data.dir=" + dataDir + " does not exist or not writable"); return;/*www .j a va2s . c o m*/ } File file = new File(dataDir, TOKEN_FILE_NAME); try { PrintWriter pw = new PrintWriter(file); pw.println(accessToken); pw.close(); file.setWritable(true, true); file.setReadable(true, true); file.setExecutable(false, false); boolean isWindows = (File.separatorChar == '\\'); if (!isWindows) { try { Runtime.getRuntime().exec("chmod 600 " + file.getAbsolutePath()); } catch (IOException e) { log.error("Unable to set file permissions", e); } } } catch (FileNotFoundException fnfe) { log.error("Failed to write acces token, jboss.server.data.dir=" + file.getParent() + " does not exist or not writable"); } }
From source file:co.cask.tigon.sql.internal.StreamBinaryGenerator.java
private void unzipFile(File libZip) throws IOException, ArchiveException { String path = libZip.toURI().getPath(); String outDir = libZip.getParentFile().getPath(); TarArchiveInputStream archiveInputStream = new TarArchiveInputStream( new GZIPInputStream(new FileInputStream(path))); try {// w w w . j a v a 2 s . c om TarArchiveEntry entry = archiveInputStream.getNextTarEntry(); while (entry != null) { File destFile = new File(outDir, entry.getName()); destFile.getParentFile().mkdirs(); if (!entry.isDirectory()) { ByteStreams.copy(archiveInputStream, Files.newOutputStreamSupplier(destFile)); //TODO: Set executable permission based on entry.getMode() destFile.setExecutable(true, false); } entry = archiveInputStream.getNextTarEntry(); } } finally { archiveInputStream.close(); } }
From source file:org.ngrinder.common.util.CompressionUtil.java
/** * Untar an input file into an output file. * /*ww w. j a v a 2 s .c o m*/ * The output file is created in the output folder, having the same name as the input file, * minus the '.tar' extension. * * @param inFile * the input .tar file * @param outputDir * the output directory file. * @throws IOException * @throws FileNotFoundException * * @return The {@link List} of {@link File}s with the untared content. * @throws ArchiveException */ public static List<File> untar(final File inFile, final File outputDir) { final List<File> untaredFiles = new LinkedList<File>(); try { final InputStream is = new FileInputStream(inFile); final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory() .createArchiveInputStream("tar", is); TarArchiveEntry entry = null; while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException( String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { File parentFile = outputFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } final OutputStream outputFileStream = new FileOutputStream(outputFile); IOUtils.copy(debInputStream, outputFileStream); outputFileStream.close(); if (FilenameUtils.isExtension(outputFile.getName(), EXECUTABLE_EXTENSION)) { outputFile.setExecutable(true, true); } outputFile.setReadable(true); outputFile.setWritable(true, true); } untaredFiles.add(outputFile); } debInputStream.close(); } catch (Exception e) { LOGGER.error("Error while untar {} file by {}", inFile, e.getMessage()); LOGGER.debug("Trace is : ", e); throw new NGrinderRuntimeException("Error while untar file", e); } return untaredFiles; }
From source file:org.eclipse.thym.blackberry.core.bdt.BlackBerryProjectGenerator.java
private void copyFilesToProject(HybridMobileLibraryResolver resolver, IPath project_path) throws IOException { IPath nodeModulesDest = project_path.append("cordova").append("node_modules"); IPath bbtoolsBinDest = project_path.append("cordova").append("dependencies").append("bb-tools") .append("bin"); IPath bbtoolsLibDest = project_path.append("cordova").append("dependencies").append("bb-tools") .append("lib"); String bbNativePackager = "blackberry-nativepackager"; String bbSigner = "blackberry-signer"; String bbDeploy = "blackberry-deploy"; String bbDebugTokenRequest = "blackberry-debugtokenrequest"; // create project using template directory if (!project_path.toFile().exists()) { project_path.toFile().mkdir();//from w w w. jav a 2 s . c o m } directoryCopy(resolver.getTemplateFile(new Path("templateDir")), toURL(project_path.toFile())); // copy repo level target tool to project fileCopy(resolver.getTemplateFile(new Path("target")), toURL(project_path.append("cordova").toFile())); fileCopy(resolver.getTemplateFile(new Path("target.bat")), toURL(project_path.append("cordova").toFile())); fileCopy(resolver.getTemplateFile(new Path("lib/target.js")), toURL(project_path.append("cordova").append("lib").toFile())); fileCopy(resolver.getTemplateFile(new Path("lib.config.js")), toURL(project_path.append("cordova").append("lib").toFile())); // copy repo level init script to project fileCopy(resolver.getTemplateFile(new Path("whereis.cmd")), toURL(project_path.append("cordova").toFile())); fileCopy(resolver.getTemplateFile(new Path("init.bat")), toURL(project_path.append("cordova").toFile())); fileCopy(resolver.getTemplateFile(new Path("init")), toURL(project_path.append("cordova").toFile())); //copy VERSION file [used to identify corresponding ~/.cordova/lib directory for dependencies] URL versionFile = resolver.getTemplateFile(new Path("VERSION")); fileCopy(versionFile, toURL(project_path.toFile())); String version = ""; BufferedReader r = null; try { r = new BufferedReader(new FileReader(versionFile.getFile())); String line = r.readLine(); version = line.replaceAll("([^\\x00-\\xFF]|\\s)*", ""); } finally { if (r != null) { r.close(); } } // copy repo level check_reqs script to project fileCopy(resolver.getTemplateFile(new Path("check_reqs.bat")), toURL(project_path.append("cordova").toFile())); fileCopy(resolver.getTemplateFile(new Path("check_reqs")), toURL(project_path.append("cordova").toFile())); // change file permission for cordova scripts because ant copy doesn't preserve file permissions project_path.toFile().setExecutable(true); project_path.toFile().setWritable(true); project_path.toFile().setReadable(true); //copy cordova-*version*.js to www fileCopy(resolver.getTemplateFile(new Path("cordova.js")), toURL(project_path.append("www").toFile())); //copy node modules to cordova build directory File nodeModules = project_path.append("cordova").append("node_modules").toFile(); if (!nodeModules.exists()) { nodeModules.mkdir(); } nodeModules.setExecutable(true, false); nodeModules.setWritable(true, false); nodeModules.setReadable(true, false); directoryCopy(resolver.getTemplateFile(new Path("node_modules")), toURL(nodeModules)); //copy framework bootstrap for (String target : TARGETS) { IPath chromeDir = project_path.append("native").append(target).append("chrome"); IPath frameworkLibDir = chromeDir.append("lib"); if (!frameworkLibDir.toFile().exists()) { frameworkLibDir.toFile().mkdir(); } directoryCopy(resolver.getTemplateFile(new Path("bootstrapDir")), toURL(chromeDir.toFile())); directoryCopy(resolver.getTemplateFile(new Path("frameworkLibDir")), toURL(frameworkLibDir.toFile())); } // save release IPath updateDir = project_path.append("lib").append("cordova.").append(version); if (!updateDir.toFile().exists()) { updateDir.toFile().mkdir(); } directoryCopy(resolver.getTemplateFile(new Path("buildDir")), toURL(updateDir.toFile())); }
From source file:gov.jgi.meta.MetaUtils.java
public static File createTempDir(String prefix, String tmpDir) throws IOException { final File sysTempDir = new File(tmpDir); File newTempDir; final int maxAttempts = 9; int attemptCount = 0; do {//from w w w. j a va 2 s . c o m attemptCount++; if (attemptCount > maxAttempts) { throw new IOException( "The highly improbable has occurred! Failed to create a unique temporary directory after " + maxAttempts + " attempts."); } String dirName = prefix + UUID.randomUUID().toString(); newTempDir = new File(sysTempDir, dirName); } while (newTempDir.exists()); try { FileUtils.forceMkdir(newTempDir); } catch (Exception e) { throw new IOException("Failed to create temp dir named " + newTempDir.getAbsolutePath() + ". Reason: " + e.getMessage(), e); } if (!(newTempDir.setExecutable(true, false) && newTempDir.setReadable(true, false) && newTempDir.setWritable(true, false))) { throw new IOException("unable to set RWX bits to 777"); } return (newTempDir); }
From source file:org.ngrinder.common.util.CompressionUtils.java
/** * Untar an input file into an output file. * The output file is created in the output folder, having the same name as * the input file, minus the '.tar' extension. * * @param inFile the input .tar file//from w w w . j av a 2 s.c o m * @param outputDir the output directory file. * @return The {@link List} of {@link File}s with the untared content. */ @SuppressWarnings("resource") public static List<File> untar(final File inFile, final File outputDir) { final List<File> untaredFiles = new LinkedList<File>(); InputStream is = null; TarArchiveInputStream debInputStream = null; try { is = new FileInputStream(inFile); debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is); TarArchiveEntry entry; while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException( String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { File parentFile = outputFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } final OutputStream outputFileStream = new FileOutputStream(outputFile); try { IOUtils.copy(debInputStream, outputFileStream); } finally { IOUtils.closeQuietly(outputFileStream); } if (FilenameUtils.isExtension(outputFile.getName(), EXECUTABLE_EXTENSION)) { outputFile.setExecutable(true, true); } outputFile.setReadable(true); outputFile.setWritable(true, true); } untaredFiles.add(outputFile); } } catch (Exception e) { throw processException("Error while untar file", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(debInputStream); } return untaredFiles; }
From source file:de.taimos.daemon.plugin.AbstractJarHeaderMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { File artifactFile = new File(this.artifact); if (!artifactFile.exists()) { throw new MojoExecutionException("artifact does not exist: " + this.artifact); }// ww w.jav a2 s . co m File artifactTmpFile = new File(this.artifact + ".tmp"); try (FileOutputStream fos = new FileOutputStream(artifactTmpFile); FileInputStream fis = new FileInputStream(artifactFile)) { StringBuilder header = new StringBuilder(); header.append("#!/bin/bash"); header.append('\n'); header.append(this.getCommand()); header.append('\n'); header.append("exit"); header.append('\n'); fos.write(header.toString().getBytes()); IOUtils.copy(fis, fos); artifactTmpFile.setExecutable(true, false); } catch (Exception e) { throw new MojoExecutionException("Error writing stream", e); } artifactFile.delete(); artifactTmpFile.renameTo(artifactFile); }
From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String) *//* ww w .j a va 2 s.c om*/ public synchronized boolean createKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#createKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } boolean isComplete = false; OutputStream publicStream = null; OutputStream privateStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { if (!(keyDirectory.mkdirs())) { throw new KeyManagementException( "Configured key directory does not exist and unable to create it"); } } keyDirectory.setExecutable(true, true); SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm()); keyGenerator.initialize(keyConfig.getKeySize(), random); KeyPair keyPair = keyGenerator.generateKeyPair(); if (keyPair != null) { File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (!(privateFile.createNewFile())) { throw new IOException("Failed to store private key file"); } if (!(publicFile.createNewFile())) { throw new IOException("Failed to store public key file"); } privateFile.setWritable(true, true); publicFile.setWritable(true, true); privateStream = new FileOutputStream(privateFile); publicStream = new FileOutputStream(publicFile); IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream); IOUtils.write(keyPair.getPublic().getEncoded(), publicStream); // assume success, as we'll get an IOException if the write failed isComplete = true; } else { throw new KeyManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (publicStream != null) { IOUtils.closeQuietly(publicStream); } if (privateStream != null) { IOUtils.closeQuietly(privateStream); } } return isComplete; }