public static void main(String[] args) { // create new file try { File file = new File("src/IOTasks/output/test.txt"); if (file.createNewFile()) { System.out.println("File is created"); } else { System.out.println("File already exisits"); } } catch (IOException e) { e.printStackTrace(); } // construct filepath try { String filename = "file.txt"; String workingDirectory = System.getProperty("user.dir"); // String absoluteFilePath = workingDirectory + File.separator + filename; // File file1 = new File(absoluteFilePath); File file1 = new File(workingDirectory, filename); file1.createNewFile(); System.out.println("Final pathname : " + file1.getAbsolutePath()); file1.setExecutable(false); file1.setReadOnly(); if (file1.exists()) { System.out.println("executable : " + file1.canExecute()); System.out.println("writable : " + file1.canWrite()); } file1.setWritable(true); File file2 = new File("src/IOTasks/input/file.jpg"); long lastModifiedTime = file2.lastModified(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss"); System.out.println("Last modified : " + sdf.format(lastModifiedTime)); String newLastModified = "31/01/2015 10:15:21"; // convert to miliseconds in long Date newDate = sdf.parse(newLastModified); file2.setLastModified(newDate.getTime()); long size = file2.length(); System.out.println(size / 1024 + " kB"); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } // get file size }
@Override protected Boolean doInBackground(Void... params) { File ffmpegFile = new File(FileUtils.getFFmpeg(context)); if (ffmpegFile.exists() && isDeviceFFmpegVersionOld() && !ffmpegFile.delete()) { return false; } if (!ffmpegFile.exists()) { boolean isFileCopied = FileUtils.copyBinaryFromAssetsToData( context, cpuArchNameFromAssets + File.separator + FileUtils.ffmpegFileName, FileUtils.ffmpegFileName); // make file executable if (isFileCopied) { if (!ffmpegFile.canExecute()) { Log.d("FFmpeg is not executable, trying to make it executable ..."); if (ffmpegFile.setExecutable(true)) { return true; } } else { Log.d("FFmpeg is executable"); return true; } } } return ffmpegFile.exists() && ffmpegFile.canExecute(); }
private void copyFile(String sourcePath, String absoluteTargetPath, ChannelSftp channelSftp) throws MachineException { try { channelSftp.put(sourcePath, absoluteTargetPath); // apply permissions File file = new File(sourcePath); // read int permissions = 256; // execute if (file.canExecute()) { permissions += 64; } // write if (file.canWrite()) { permissions += 128; } channelSftp.chmod(permissions, absoluteTargetPath); } catch (SftpException e) { throw new MachineException( format( "Sftp copying of file %s failed. Error: %s", absoluteTargetPath, e.getLocalizedMessage())); } }
private void showFiles(File file) { TableItem tableItem = null; String fileName = null; String filePath = null; float fileSize = -1; String columns[] = new String[3]; if (file.canRead() && file.canExecute() && file.isDirectory()) { File currentFile[] = file.listFiles(); for (int i = 0; i < currentFile.length; i++) { if (currentFile[i].isFile()) { tableItem = new TableItem(table, SWT.NONE); fileName = currentFile[i].getName(); filePath = currentFile[i].getPath(); fileSize = currentFile[i].length(); columns[0] = fileName; if (fileSize >= 512) { columns[1] = fileSize / 1024 + "KB"; } else { columns[1] = fileSize + "Bytes"; } columns[2] = filePath; tableItem.setText(columns); table.setLinesVisible(true); } } } }
@Override public void initialize( @NotNull ManagingFS managingFS, @NotNull FileWatcherNotificationSink notificationSink) { myManagingFS = managingFS; myNotificationSink = notificationSink; boolean disabled = Boolean.parseBoolean(System.getProperty(PROPERTY_WATCHER_DISABLED)); myExecutable = getExecutable(); if (disabled) { LOG.info("Native file watcher is disabled"); } else if (myExecutable == null) { LOG.info("Native file watcher is not supported on this platform"); } else if (!myExecutable.exists()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.found"), null); } else if (!myExecutable.canExecute()) { notifyOnFailure( ApplicationBundle.message("watcher.exe.not.exe", myExecutable), new NotificationListener() { @Override public void hyperlinkUpdate( @NotNull Notification notification, @NotNull HyperlinkEvent event) { ShowFilePathAction.openFile(myExecutable); } }); } else { try { startupProcess(false); LOG.info("Native file watcher is operational."); } catch (IOException e) { LOG.warn(e.getMessage()); notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null); } } }
@Override public CommandRunner.CommandOutput runCommandAndWaitForExit( File workingDir, List<String> arguments) throws IOException, InterruptedException { File binary = new File(arguments.get(0)); if (!binary.exists()) { logger.error("Binary {} does not exists, fix your configuration!", binary.getAbsolutePath()); return createErrorCommandOutput(); } if (!binary.canExecute()) { logger.error( "Binary {} can't be executed, fix your configuration!", binary.getAbsolutePath()); return createErrorCommandOutput(); } ProcessBuilder pb = new ProcessBuilder(arguments); pb.directory(workingDir); Process process = pb.start(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); CommandRunnerImpl.StreamGobbler sgerr = new CommandRunnerImpl.StreamGobbler(process.getErrorStream(), stderr); CommandRunnerImpl.StreamGobbler sgout = new CommandRunnerImpl.StreamGobbler(process.getInputStream(), stdout); sgerr.start(); sgout.start(); int exitCode = process.waitFor(); sgerr.join(); sgout.join(); CommandRunner.CommandOutput result = new CommandRunner.CommandOutput(stdout.toByteArray(), stderr.toByteArray()); result.setExitCode(exitCode); return result; }
private boolean ffmpegIsCorrectlyInstalled() { File ffmpegTargetLocation = AndroidFFMPEGLocator.ffmpegTargetLocation(); // assumed to be correct if existing and executable and larger than 1MB: return ffmpegTargetLocation.exists() && ffmpegTargetLocation.canExecute() && ffmpegTargetLocation.length() > 1000000; }
@Override public String check() { LOGGER.info("Checking msmsEval worker"); if (!msmsEvalExecutable.canExecute()) { return "msmsEval is not executable: " + msmsEvalExecutable.getAbsolutePath(); } return null; }
/** * Given a program name, lookup the fully qualified path. Throws an exception if the program is * missing or not authorized. * * @param path The path of the program. * @return The path of the validated program. */ public String validateProgram(String path) throws NotAuthorizedException, IOException { File f = new File(path); if (f.canExecute()) { return f.getCanonicalPath(); } else { throw new NotAuthorizedException("Unable to access program: " + path); } }
/** * Ejecuta el script PowerShell para la generación del almacén de claves SSL. * * @param appConfigDir Directorio de configuración de AutoFirma. * @param profilesDir Directorio de perfiles de Mozilla Firefox. * @throws IOException Cuando ocurre un error * @throws GeneralSecurityException Cuando ocurre un error en la inserción del certificado * en el KeyStore. */ private static void executeCertUtilToImport(final File appConfigDir, final File profilesDir) throws IOException, GeneralSecurityException { final File certutilFile = new File(appConfigDir, DIR_CERTUTIL + File.separator + CERTUTIL_EXE); if (!certutilFile.exists() || !certutilFile.isFile() || !certutilFile.canExecute()) { throw new IOException( "No se encuentra o no se puede leer el ejecutable para la instalacion en Firefox"); //$NON-NLS-1$ } // Obtenemos todos los directorios de perfil de Firefox del usuario boolean error = false; for (final File profileDir : profilesDir.listFiles()) { if (!profileDir.isDirectory()) { continue; } final String[] certutilCommands = new String[] { certutilFile.getAbsolutePath(), "-A", //$NON-NLS-1$ "-d", //$NON-NLS-1$ profileDir.getAbsolutePath(), "-i", //$NON-NLS-1$ new File(appConfigDir, FILE_AUTOFIRMA_CERTIFICATE).getAbsolutePath(), "-n", //$NON-NLS-1$ "\"" + CERT_ALIAS + "\"", // $NON-NLS-1$ //$NON-NLS-2$ "-t", //$NON-NLS-1$ "\"C,,\"" //$NON-NLS-1$ }; final Process process = new ProcessBuilder(certutilCommands).start(); // Cuando se instala correctamente no hay salida de ningun tipo, asi que se interpreta // cualquier salida como un error String line; try (final InputStream resIs = process.getInputStream(); final BufferedReader resReader = new BufferedReader(new InputStreamReader(resIs)); ) { while ((line = resReader.readLine()) != null) { error = true; LOGGER.severe(line); } } try (final InputStream errIs = process.getErrorStream(); final BufferedReader errReader = new BufferedReader(new InputStreamReader(errIs)); ) { while ((line = errReader.readLine()) != null) { error = true; LOGGER.severe(line); } } } if (error) { throw new KeyStoreException( "Error la instalacion del certificado de CA en alguno de los perfiles de usuario de Firefox"); //$NON-NLS-1$ } }
/** * Ensures that the File associated with this stub (if any) is in a writable location * * @param stub */ protected <T> void validateOutputPath(final Stub<T> stub) { if (stub.getOutputFile() != null && !(IOUtils.isSpecialFile(stub.getOutputFile()))) { final File parentDir = stub.getOutputFile().getAbsoluteFile().getParentFile(); if (!(parentDir.canWrite() && parentDir.canExecute())) throw new UserException.CouldNotCreateOutputFile( stub.getOutputFile(), "either the containing directory doesn't exist or it isn't writable"); } }
static boolean validatePath(String path) { if (path == null || path.isEmpty()) return true; try { File s = new File(path.trim()); return s.isFile() && s.canExecute(); } catch (Exception e) { return false; } }
private static void checkBatFile() throws Exception { File batFile = new File(mainFrame.getBatFilePath()); if (!batFile.exists()) throw new Exception("Bat file does not exist (" + batFile.getAbsolutePath() + ")"); if (!batFile.canExecute()) throw new Exception( "[Linux] Bat file can not be executed - set it as application (" + batFile.getAbsolutePath() + ")"); }
/** * Constructor. * * @param needleApp String holding the path to the NEEDLE application. * @throws FileNotFoundException if NEEDLE application can not be found at given path or is not * executable. */ public Needle(final File needleApp) throws FileNotFoundException { if (!needleApp.exists()) { throw new FileNotFoundException( "ERROR: NEEDLE application does " + "not reside at " + needleApp.getAbsolutePath()); } else if (!needleApp.canExecute()) { throw new FileNotFoundException("ERROR: NEEDLE application is " + "not executable!"); } else { this.needle = needleApp; } }
static String getAjavaCmd(String cmdStr) { File binDir = new File(JavaHome, "bin"); File unpack200File = IsWindows ? new File(binDir, cmdStr + ".exe") : new File(binDir, cmdStr); String cmd = unpack200File.getAbsolutePath(); if (!unpack200File.canExecute()) { throw new RuntimeException("please check" + cmd + " exists and is executable"); } return cmd; }
/** * Ensure that the dart VM is executable. If it is not, make it executable and log that it was * necessary for us to do so. */ @DartBlockBody({}) private void ensureVmIsExecutable() { File dartVm = getVmExecutable(); if (dartVm != null) { if (!dartVm.canExecute()) { FileUtilities.makeExecutable(dartVm); AnalysisEngine.getInstance().getLogger().logError(dartVm.getPath() + " was not executable"); } } }
public void setGitBinaryPath(File gitBinaryPath) { if (!gitBinaryPath.exists()) { logger.warn("Path '" + gitBinaryPath + "' for GIT binary does not exist."); } else if (!gitBinaryPath.isFile()) { logger.warn("Path '" + gitBinaryPath + "' for GIT binary is not a file."); } else if (!gitBinaryPath.canExecute()) { logger.warn("Path '" + gitBinaryPath + "' for GIT binary is not executable."); } else { this.gitBinaryPath = gitBinaryPath; } }
public static void checkReadableDirectory(File dir) throws IOException { if (dir == null) { Throw.ioe(TAG, "Directory object File is null."); } else { if (!dir.exists()) Throw.ioe(TAG, "Directory does not exist: " + dir.getAbsolutePath()); if (!dir.isDirectory()) Throw.ioe(TAG, "Not a directory: " + dir.getAbsolutePath()); if (!dir.canRead()) Throw.ioe(TAG, "No read permission: " + dir.getAbsolutePath()); if (!dir.canExecute()) Throw.ioe(TAG, "No execute (access files) permission: " + dir.getAbsolutePath()); } }
private void doDeleteJarFileTest(File file) { boolean b = file.delete(); if (!b) { throw new SpagoBIPluginException( "Can't delete the file " + file.getAbsolutePath() + " the file is writtable? " + file.canWrite() + " " + file.canExecute()); } }
public JavaTask(String fullyQualifiedClassName, File startDir) throws RuntimeException { _className = fullyQualifiedClassName; _classpath = System.getProperty("java.class.path"); _startDir = startDir; String javaHome = System.getProperty("java.home"); File jvm = new File(javaHome, "bin/javaw.exe"); if (jvm.canExecute()) { _jvm = jvm; } else { jvm = new File(javaHome, "bin/java.exe"); if (jvm.canExecute()) { _jvm = jvm; } else { jvm = new File(javaHome, "bin/java"); if (jvm.canExecute()) { _jvm = jvm; } else { throw new RuntimeException("Cannot find JVM"); } } } }
public OperaLauncherRunner(OperaSettings s) { super(s); // Locate the bundled launcher from OperaLaunchers project and copy it to its default location // on users system if it's not there or outdated URL bundledLauncher = OperaLaunchers.class.getClassLoader().getResource("launchers/" + LAUNCHER_NAME); if (bundledLauncher == null) { throw new OperaRunnerException("Not able to locate bundled launcher: " + bundledLauncher); } File launcher = settings.getLauncher(); try { if (launcher.getCanonicalPath().equals(LAUNCHER_DEFAULT_LOCATION.getCanonicalPath()) && (!launcher.exists() || isLauncherOutdated(launcher))) { extractLauncher(bundledLauncher, launcher); } } catch (IOException e) { throw new OperaRunnerException(e); } if (!launcher.canExecute()) { if (!launcher.setExecutable(true)) { throw new OperaRunnerException("Unable to make launcher executable: " + launcher.getPath()); } } // Find a suitable Opera executable based on requested product if no binary has already been // specified if (settings.getBinary() == null) { // Do check for null here since OperaBinary's sanitization throws a cryptic null pointer File binary = OperaBinary.find(settings.getProduct()); if (binary == null) { throw new OperaRunnerException( String.format("Unable to find executable for product %s", settings.getProduct())); } // Calls new OperaBinary(b) which will check that the binary is executable and that it's not a // directory settings.setBinary(binary); } // Create list of arguments for launcher binary arguments = buildArguments(); logger.config("launcher arguments: " + arguments); init(); }
/** * @param binName the binary to look for (eg 'kudu-tserver') * @return the absolute path of that binary * @throws FileNotFoundException if no such binary is found */ public static String findBinary(String binName) throws FileNotFoundException { String binDir = System.getProperty(BIN_DIR_PROP); if (binDir != null) { LOG.info("Using binary directory specified by property: {}", binDir); } else { binDir = findBuildDir(); } File candidate = new File(binDir, binName); if (candidate.canExecute()) { return candidate.getAbsolutePath(); } throw new FileNotFoundException( "Cannot find binary " + binName + " in binary directory " + binDir); }
public static void createTree(TreeItem rootNode, File parent) { if (parent.isDirectory() && parent.canRead() && parent.canExecute()) { for (File file : parent.listFiles()) { if (file.isDirectory()) { TreeItem treeNode = new TreeItem(rootNode, SWT.CHECK); treeNode.setData(file); treeNode.setText(file.getName()); System.out.println(file.getPath()); createTree(treeNode, file); } } } }
private static int dependencies() { String dependencies[] = {"trid", "7z", "unrtf"}; int result = 0; for (int count = 0; count < dependencies.length; count++) { File test = new File(dependencies[count]); if (!(test.exists() && test.isFile() && test.canExecute())) { System.err.println(" Dependency check failed for: " + dependencies[count]); result = 2; } } return result; }
protected TestSuite buildSuite() { TestSuite suite = new TestSuite("Shared Dart tests"); if (!V8Launcher.isConfigured()) { return configurationProblem( suite, "Please set the system property com.google.dart.runner.d8"); } File file = new File(listTests[0]); if (!file.canExecute()) { return configurationProblem(suite, file.getPath() + " is not executable"); } ProcessBuilder builder = new ProcessBuilder(listTests); try { Process process = builder.start(); InputStream inputStream = process.getInputStream(); StringBuilder sb = new StringBuilder(); try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); LineReader lineReader = new LineReader(inputStreamReader); String line; while ((line = lineReader.readLine()) != null) { if (!line.startsWith("dartc/")) { suite.addTest(SharedTestCase.getInstance(line, false)); } else if (line.startsWith("dartc/client/")) { suite.addTest(SharedTestCase.getInstance(line, true)); } } } finally { inputStream.close(); process.getOutputStream().close(); InputStreamReader inputStreamReader = new InputStreamReader(process.getErrorStream()); CharStreams.copy(inputStreamReader, sb); process.getErrorStream().close(); } process.waitFor(); if (process.exitValue() != 0) { sb.insert(0, file.getPath()); sb.insert(0, " returned non-zero exit code.\n"); return configurationProblem(suite, sb.toString()); } } catch (IOException e) { throw new AssertionError(e); } catch (InterruptedException e) { throw new AssertionError(e); } return suite; }
public static void initializeCacheRoot(File cacheRoot) { if (CACHE_ROOT.compareAndSet(null, checkNotNull(cacheRoot))) { if (!cacheRoot.exists() && !cacheRoot.mkdirs()) { throw new SetUpException( "Failed to create required OSGI cache directory: " + cacheRoot.getAbsolutePath()); } if (!cacheRoot.isDirectory() || !cacheRoot.canRead() || !cacheRoot.canWrite() || !cacheRoot.canExecute()) { throw new SetUpException( "Cannot access OSGI cache directory: " + cacheRoot.getAbsolutePath()); } m_self = new ModuleManager(cacheRoot); } }
/** * Computes the default Hadoop command path. * * @param environmentVariables the current environment variables * @return the detected command path, or {@code null} if the command path is not found * @since 0.6.0 */ public static File findHadoopCommand(Map<String, String> environmentVariables) { assert environmentVariables != null; File command = getExplicitHadoopCommand(environmentVariables); if (command != null) { return command; } File home = getExplicitHadoopDirectory(environmentVariables); if (home != null && home.isDirectory()) { command = new File(home, PATH_HADOOP_COMMAND); } else { command = findHadoopCommandFromPath(environmentVariables); } if (command == null || command.canExecute() == false) { return null; } return command; }
public static String getBuildDirectoryPath() { String envPath = System.getenv("TEST_DIR"); if (envPath != null) { File path = new File(envPath); path.mkdirs(); if (!path.exists() || !path.isDirectory() || !path.canRead() || !path.canWrite() || !path.canExecute()) { throw new RuntimeException("Could not create test directory"); } return envPath; } else { return "."; } }
public void checkExecutePermissionForIOSDebugProxyLauncher() throws IOException { input = new FileInputStream("config.properties"); prop.load(input); String serverPath = prop.getProperty("APPIUM_JS_PATH"); File file = new File(serverPath); File curentPath = new File(file.getParent()); System.out.println(curentPath); file = new File(curentPath + "/.." + "/.."); File executePermission = new File(file.getCanonicalPath() + "/bin/ios-webkit-debug-proxy-launcher.js"); if (executePermission.exists()) { if (executePermission.canExecute() == false) { executePermission.setExecutable(true); System.out.println("Access Granted for iOSWebKitProxyLauncher"); } else { System.out.println("iOSWebKitProxyLauncher File already has access to execute"); } } }
/** * Return an empty string if short circuit read is properly enabled. If not, return an error * string describing the issues. */ private String checkShortCircuitRead(Configuration conf) { StringBuilder output = new StringBuilder(); String errorMessage = "ERROR: short-circuit local reads is disabled because\n"; String prefix = " - "; StringBuilder errorCause = new StringBuilder(); // dfs.domain.socket.path must be set properly String domainSocketPath = conf.getTrimmed( DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY, DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_DEFAULT); if (domainSocketPath.isEmpty()) { errorCause.append(prefix); errorCause.append(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY); errorCause.append(" is not configured.\n"); } else { // The socket path parent directory must be readable and executable. File socketFile = new File(domainSocketPath); File socketDir = socketFile.getParentFile(); if (socketDir == null || !socketDir.canRead() || !socketDir.canExecute()) { errorCause.append(prefix); errorCause.append("Impala cannot read or execute the parent directory of "); errorCause.append(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY); errorCause.append("\n"); } } // dfs.client.read.shortcircuit must be set to true. if (!conf.getBoolean( DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY, DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_DEFAULT)) { errorCause.append(prefix); errorCause.append(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY); errorCause.append(" is not enabled.\n"); } if (errorCause.length() > 0) { output.append(errorMessage); output.append(errorCause); } return output.toString(); }