Beispiel #1
1
  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

  }
Beispiel #2
0
 private void setBinaryPermissions() {
   busybox.setExecutable(true);
   busybox.setReadable(true);
   flash_image.setExecutable(true);
   flash_image.setReadable(true);
   dump_image.setExecutable(true);
   dump_image.setReadable(true);
 }
  private String executeScript(String name) {
    File scriptFile = writeAssetToCacheFile(name);
    if (scriptFile == null) return "Could not find asset \"" + name + "\"";

    File busybox = writeAssetToCacheFile("busybox-xposed");
    if (busybox == null) {
      scriptFile.delete();
      return "Could not find asset \"busybox-xposed\"";
    }

    scriptFile.setReadable(true, false);
    scriptFile.setExecutable(true, false);

    busybox.setReadable(true, false);
    busybox.setExecutable(true, false);

    try {
      Process p =
          Runtime.getRuntime()
              .exec(
                  new String[] {
                    "su",
                    "-c",
                    "cd "
                        + getActivity().getCacheDir()
                        + "; "
                        + scriptFile.getAbsolutePath()
                        + " "
                        + android.os.Process.myUid()
                        + " 2>&1"
                  });
      BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
      BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      StringBuilder sb = new StringBuilder();
      String line;
      while ((line = stdout.readLine()) != null) {
        sb.append(line);
        sb.append('\n');
      }
      while ((line = stderr.readLine()) != null) {
        sb.append(line);
        sb.append('\n');
      }
      stdout.close();
      return sb.toString();

    } catch (IOException e) {
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      return sw.toString();
    } finally {
      scriptFile.delete();
      busybox.delete();
    }
  }
  private static EventFiringWebDriver getChromeInstance() {
    String chromeBinaryPath = "";
    String osName = System.getProperty("os.name").toUpperCase();

    if (osName.contains("WINDOWS")) {
      chromeBinaryPath = "/chromedriver_win32/chromedriver.exe";
    } else if (osName.contains("MAC")) {
      chromeBinaryPath = "/chromedriver_mac32/chromedriver";

      File chromedriver =
          new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath).getPath());

      // set application user permissions to 455
      chromedriver.setExecutable(true);
    } else if (osName.contains("LINUX")) {
      chromeBinaryPath = "/chromedriver_linux64/chromedriver";

      File chromedriver =
          new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath).getPath());

      // set application user permissions to 455
      chromedriver.setExecutable(true);
    }

    System.setProperty(
        "webdriver.chrome.driver",
        new File(ClassLoader.getSystemResource("ChromeDriver" + chromeBinaryPath).getPath())
            .getPath());

    // TODO change mobile tests to use @UserAgent annotation
    if ("CHROMEMOBILEMERCURY".equals(browserName)) {
      chromeOptions.addArguments("--user-agent=" + userAgentRegistry.getUserAgent("iPhone"));
    }

    //    chromeOptions.addArguments("user-data-dir="
    //        + ClassLoader.getSystemResource("ChromeProfiles/default/").getPath().substring(1));

    if ("true".equals(Configuration.getDisableFlash())) {
      chromeOptions.addArguments("disable-bundled-ppapi-flash");
      chromeOptions.addArguments("process-per-site");
      chromeOptions.addArguments("start-maximized");
    }

    caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

    setBrowserLogging(Level.SEVERE);

    ExtHelper.addExtensions(Configuration.getExtensions());

    return new EventFiringWebDriver(new ChromeDriver(caps));
  }
  protected Boolean process(String command) {
    File script;
    String suffix = ".sh";
    if (SystemUtils.IS_OS_WINDOWS) {
      suffix = ".bat";
    }
    if ((script = setData(command, suffix)) == null) {
      return false;
    }
    script.setExecutable(true);
    // starts and wait for the process
    ProcessBuilder pb = new ProcessBuilder("." + File.separator + script.getName());
    pb.directory(new File(script.getAbsolutePath().replace(script.getName(), File.separator)));
    try {
      Process p = pb.start();
      p.waitFor();
      BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
      StringBuilder builder = new StringBuilder();
      String line = null;
      while ((line = br.readLine()) != null) {
        builder.append(line);
        builder.append(System.getProperty("line.separator"));
      }
      String result = builder.toString();
      log.info(result);

    } catch (IOException | InterruptedException e) {
      LogHandler.writeStackTrace(log, e, Level.SEVERE);
      return false;
    }
    // deletes the script
    script.delete();
    return true;
  }
  /* good1() changes true to false */
  private void good1() throws Throwable {
    if (false) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      File tempFile = null;

      try {
        tempFile = File.createTempFile("temp", "1234");
        IO.writeLine(tempFile.toString());

        /* FIX: Call deleteOnExit() so that the file will be deleted */
        tempFile.deleteOnExit();

        /* Set the permissions to avoid insecure temporary file incidentals  */
        if (!tempFile.setWritable(true, true)) {
          IO.logger.log(Level.WARNING, "Could not set Writable permissions");
        }
        if (!tempFile.setReadable(true, true)) {
          IO.logger.log(Level.WARNING, "Could not set Readable permissions");
        }
        if (!tempFile.setExecutable(false)) {
          IO.logger.log(Level.WARNING, "Could not set Executable permissions");
        }
      } catch (IOException exceptIO) {
        IO.logger.log(Level.WARNING, "Could not create temporary file", exceptIO);
      }
    }
  }
  /**
   * Copy the required binaries and libraries to the data folder
   *
   * @return
   */
  private boolean copyBinaries() {
    try {
      String files[] = {
        "autooptimiser",
        "pto_gen",
        "cpfind",
        "multiblend",
        "enfuse",
        "nona",
        "pano_modify",
        "ptclean",
        "tiffinfo",
        "align_image_stack",
        "pto_var",
        "libexiv2.so",
        "libglib-2.0.so",
        "libgmodule-2.0.so",
        "libgobject-2.0.so",
        "libgthread-2.0.so",
        "libjpeg.so",
        "libpano13.so",
        "libtiff.so",
        "libtiffdecoder.so",
        "libvigraimpex.so"
      };

      final AssetManager am = mContext.getAssets();

      for (String file : files) {
        InputStream is = am.open("picsphere/" + file);

        // Create the output file
        File dir = mContext.getFilesDir();
        File outFile = new File(dir, file);

        if (outFile.exists()) outFile.delete();

        OutputStream os = new FileOutputStream(outFile);

        // Copy the file
        byte[] buffer = new byte[1024];
        int read;
        while ((read = is.read(buffer)) != -1) {
          os.write(buffer, 0, read);
        }

        if (!outFile.getName().endsWith(".so") && !outFile.setExecutable(true)) {
          return false;
        }

        os.flush();
        os.close();
        is.close();
      }
    } catch (Exception e) {
      Log.e(TAG, "Error copying libraries and binaries", e);
      return false;
    }
    return true;
  }
  /**
   * Writes the script to start the emulator in the background for windows based environments.
   *
   * @return absolute path name of start script
   * @throws IOException
   * @throws MojoExecutionException
   */
  private String writeEmulatorStartScriptWindows() throws MojoExecutionException {

    String filename = scriptFolder + "\\maven-android-plugin-emulator-start.vbs";

    File file = new File(filename);
    PrintWriter writer = null;
    try {
      writer = new PrintWriter(new FileWriter(file));

      // command needs to be assembled before unique window title since it parses settings and sets
      // up parsedAvd
      // and others.
      String command = assembleStartCommandLine();
      String uniqueWindowTitle = "MavenAndroidPlugin-AVD" + parsedAvd;
      writer.println("Dim oShell");
      writer.println("Set oShell = WScript.CreateObject(\"WScript.shell\")");
      String cmdPath = System.getenv("COMSPEC");
      if (cmdPath == null) {
        cmdPath = "cmd.exe";
      }
      String cmd =
          cmdPath + " /X /C START /SEPARATE \"\"" + uniqueWindowTitle + "\"\"  " + command.trim();
      writer.println("oShell.run \"" + cmd + "\"");
    } catch (IOException e) {
      getLog().error("Failure writing file " + filename);
    } finally {
      if (writer != null) {
        writer.flush();
        writer.close();
      }
    }
    file.setExecutable(true);
    return filename;
  }
  private void good1() throws Throwable {

    String fn = ".\\src\\testcases\\CWE379_File_Creation_in_Insecure_Dir\\basic\\insecureDir";
    File dir = new File(fn);
    if (dir.exists()) {
      IO.writeLine("Directory already exists");
      if (dir.delete()) {
        IO.writeLine("Directory deleted");
      } else {
        return;
      }
    }
    if (!dir.getParentFile().canWrite()) {
      IO.writeLine("Cannot write to parent dir");
    }

    /* FIX: explicitly set directory permissions */
    dir.setExecutable(false, true);
    dir.setReadable(true);
    dir.setWritable(false, true);
    try {
      boolean success = dir.mkdir();
      if (success) {
        IO.writeLine("Directory created");
        File file = new File(dir.getAbsolutePath() + "\\newFile.txt");
        file.createNewFile();
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  @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();
  }
Beispiel #11
0
 /** Copies assets to /data/data/com.binoy.vibhinna/bin and sets permissions */
 public void copyAssets() {
   // FIXME use package name.
   Toast.makeText(context, R.string.copying_binaries, Toast.LENGTH_SHORT).show();
   String[] assetslist = null;
   try {
     assetslist = context.getAssets().list(ASSETS_FOLDER);
   } catch (IOException e) {
     Toast.makeText(context, R.string.error_copying_binaries, Toast.LENGTH_SHORT).show();
   }
   for (int i = 0; i < assetslist.length; i++) {
     try {
       InputStream in = context.getAssets().open(ASSETS_FOLDER + Constants.SLASH + assetslist[i]);
       FileOutputStream out =
           new FileOutputStream(Constants.BINARY_PATH + Constants.SLASH + assetslist[i]);
       int read;
       byte[] buffer = new byte[4096];
       while ((read = in.read(buffer)) > 0) {
         out.write(buffer, 0, read);
       }
       out.close();
       in.close();
       File assetfile = new File(Constants.BINARY_PATH + Constants.SLASH + assetslist[i]);
       assetfile.setReadable(true, false);
       assetfile.setExecutable(true, false);
     } catch (FileNotFoundException e) {
       e.printStackTrace();
       Log.w(TAG, "Error : File not found " + assetslist[i]);
     } catch (IOException e) {
       e.printStackTrace();
       Log.w(TAG, "IO Error " + assetslist[i]);
     }
   }
 }
  private String Commands2script(String[] cmdLine, String... aScriptNames) {
    String aScriptName = "script.sh";
    if (aScriptNames.length > 0) {
      aScriptName = aScriptNames[0];
    }
    FileWriter out = null;
    String scriptName = "/data/data/" + mPackName + "/" + aScriptName;
    File file = new File(scriptName);
    if (file.exists()) {
      file.delete();
    }
    if (D) Log.d(TAG, "Create");
    try {
      file.createNewFile();
      file.setExecutable(true, false);
      file.setWritable(true, false);
      file.setReadable(true, false);
      out = new FileWriter(file);
      out.write("#! /system/bin/sh" + "\n");
      for (String s : cmdLine) {
        out.write(s + "\n");
        if (D) Log.d(TAG, s);
      }
      out.write("\n");
      out.close();
      String s = exec(mSU + " -c " + scriptName);
      if (!D) file.delete();
      return s;

    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
 private void doInstall(File target, RandomAccessFile file) throws IOException {
   file.setLength(0L);
   file.write(bytes);
   if (executable) {
     target.setExecutable(true);
   }
 }
  /**
   * Writes the script to start the emulator in the background for unix based environments.
   *
   * @return absolute path name of start script
   * @throws IOException
   * @throws MojoExecutionException
   */
  private String writeEmulatorStartScriptUnix() throws MojoExecutionException {
    String filename = scriptFolder + "/maven-android-plugin-emulator-start.sh";

    File sh;
    sh = new File("/bin/bash");
    if (!sh.exists()) {
      sh = new File("/usr/bin/bash");
    }
    if (!sh.exists()) {
      sh = new File("/bin/sh");
    }

    File file = new File(filename);
    PrintWriter writer = null;
    try {
      writer = new PrintWriter(new FileWriter(file));
      writer.println("#!" + sh.getAbsolutePath());
      writer.print(assembleStartCommandLine());
      writer.print(" 1>/dev/null 2>&1 &"); // redirect outputs and run as background task
    } catch (IOException e) {
      getLog().error("Failure writing file " + filename);
    } finally {
      if (writer != null) {
        writer.flush();
        writer.close();
      }
    }
    file.setExecutable(true);
    return filename;
  }
 @SuppressWarnings("ResultOfMethodCallIgnored") // intended, nothing useful can be done
 @SuppressLint("SetWorldReadable") // intended, default permission
 private static void setFilePermissions(File outputFile) {
   // Try change permission to rwxr-xr-x
   outputFile.setReadable(true, false);
   outputFile.setExecutable(true, false);
   outputFile.setWritable(true);
 }
Beispiel #16
0
 private File getBuildSonarScript(final File sonarBaseDir) {
   if (Environment.isWindowsPlatform()) {
     return new File(sonarBaseDir, "war/build-war.bat");
   }
   File file = new File(sonarBaseDir, "war/build-war.sh");
   file.setExecutable(true);
   return file;
 }
 private synchronized void createSettingsDir() {
   // create settings directory (for settings accessed from core libraries)
   File settingsDir = new File("/data/system/privacy/");
   settingsDir.mkdirs();
   // make it readable for everybody
   settingsDir.setReadable(true, false);
   settingsDir.setExecutable(true, false);
 }
 private void ensureExecutable(File scriptFile) {
   boolean success = scriptFile.setExecutable(true, true);
   if (!success) {
     String msg = "Cannot ensure that script [" + scriptFile + "] is executable";
     audit("ensureExecutable", BundleResourceDeploymentHistory.Status.FAILURE, msg);
     throw new RuntimeException(msg);
   }
   return;
 }
Beispiel #19
0
 /** Copy necessary files needed for the MPI program */
 private static void copyFiles() {
   Map<String, String> envs = System.getenv();
   String mpiExecDir = envs.get("MPIEXECDIR");
   LocalFileUtils.mkdirs(mpiExecDir);
   File mpiexecCwd = new File("./MPIExec");
   File mpiexecSame = new File(mpiExecDir + "/MPIExec");
   LocalFileUtils.copyFile(mpiexecCwd, mpiexecSame);
   mpiexecSame.setExecutable(true);
 }
  /**
   * This method is called before any of test methods are called, but it's only called once per test
   * suite.
   *
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {

    /*
     * Create a short perl script for test purposes. This code looks cryptic,
     * but serves to exercise the stdin/stdout/stderr streams. This script takes
     * two arguments:
     *    1) The number of letters to write on the stdout, and equally, the number of
     *       digits to write on the stderr.
     *    2) The exit code to terminate with.
     * This script starts by echoing it's stdin to its stdout, then displays N letters/digits
     * on the stdout/stderr respectively.
     */
    ourTempExe = File.createTempFile("tempExecutable", null);
    PrintStream tmpStream = new PrintStream(ourTempExe);
    tmpStream.println("#!/usr/bin/perl");
    tmpStream.println("while (<STDIN>) { print $_; };");
    tmpStream.println("my $count = $ARGV[0];");
    tmpStream.println("my $rc = $ARGV[1];");
    tmpStream.println("for (my $i = 0; $i != $count; $i++) {");
    tmpStream.println("  my $ch = 65 + ($i % 26);");
    tmpStream.println("  my $num = ($i % 10);");
    tmpStream.println("  print STDOUT chr($ch);");
    tmpStream.println("  print STDERR $num;");
    tmpStream.println("}");
    tmpStream.println("exit($rc);");
    tmpStream.close();

    /* set execute permission - only works on Unix */
    ourTempExe.setExecutable(true);

    /*
     * Next, create a temporary directory full of files and subdirectories, for the purpose of
     * testing traverseFileSystem(). Note, we create a temporary directory name by first creating
     * a temporary file, then stealing (reusing) the same name for a directory.
     */
    ourTempDir = File.createTempFile("tempDir", null);
    ourTempDir.delete();
    ourTempDir.mkdir();

    /* create some subdirectories */
    File dirA = new File(ourTempDir.getPath() + "/dirA");
    File dirB = new File(ourTempDir.getPath() + "/dirA/nested/dirB");
    File dirC = new File(ourTempDir.getPath() + "/dirC");
    dirA.mkdirs();
    dirB.mkdirs();
    dirC.mkdirs();

    new File(ourTempDir + "/topLevelFile").createNewFile();
    new File(dirA + "/fileInDirA").createNewFile();
    new File(dirB + "/fileInDirB").createNewFile();
    new File(dirB + "/anotherFileInDirB").createNewFile();
    new File(dirB + "/aThirdFileInDirB").createNewFile();
    new File(dirB + "/onelastFileInDirB").createNewFile();
  }
Beispiel #21
0
  /**
   * Extract the specified library file to the target folder.
   *
   * @param libFolderForCurrentOS
   * @param libraryFileName
   * @param targetFolder
   * @return
   */
  private File extractLibraryFile(
      String libFolderForCurrentOS, String libraryFileName, String targetFolder) {
    final String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;

    // Attach UUID to the native library file to ensure multiple class
    // loaders can read it multiple times.
    final String uuid = UUID.randomUUID().toString();
    final String extractedLibFileName =
        String.format("nativelib-%s-%s-%s", getVersion(), uuid, libraryFileName);

    File extractedLibFile = new File(targetFolder, extractedLibFileName);

    try {
      // Extract a native library file into the target directory
      InputStream reader = NativeLibLoader.class.getResourceAsStream(nativeLibraryFilePath);
      FileOutputStream writer = new FileOutputStream(extractedLibFile);
      try {
        byte[] buffer = new byte[8192];
        int bytesRead = 0;
        while ((bytesRead = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, bytesRead);
        }
      } finally {
        // Delete the extracted lib file on JVM exit.
        extractedLibFile.deleteOnExit();

        if (writer != null) writer.close();
        if (reader != null) reader.close();
      }

      // Set executable (x) flag to enable Java to
      // load the native library.
      extractedLibFile.setReadable(true);
      extractedLibFile.setWritable(true, true);
      extractedLibFile.setExecutable(true);

      // Check whether the contents are properly copied
      // from the resource folder.
      {
        InputStream nativeIn = NativeLibLoader.class.getResourceAsStream(nativeLibraryFilePath);
        InputStream extractedLibIn = new FileInputStream(extractedLibFile);
        try {
          if (!contentsEquals(nativeIn, extractedLibIn)) throw new IOException();
        } finally {
          if (nativeIn != null) nativeIn.close();
          if (extractedLibIn != null) extractedLibIn.close();
        }
      }
      return new File(targetFolder, extractedLibFileName);
    } catch (IOException e) {
      return null;
    }
  }
Beispiel #22
0
  public static void main(String[] args) throws IOException {

    String fileName = "myfile";
    String prefix = "unpacked-";
    String suffix = "-" + fileName;
    File unpackedFile = File.createTempFile(prefix, suffix);
    unpackedFile.deleteOnExit();
    unpackedFile.setExecutable(true, false);
    String path = unpackedFile.getAbsolutePath();
    //        System.load(path);
    System.out.println("path:" + path);
    //       System.out.println("Loaded native gpl library from the embedded binaries");
  }
Beispiel #23
0
  @Before
  public void setUp() throws Exception {
    tempFolder =
        TestFileUtil.createTempFolder("tempCommandLineTestFolder-" + System.currentTimeMillis());
    toDelete.add(tempFolder);

    subFolder = new File(tempFolder, "subFolder");
    subFolder.mkdirs();
    File file = new File("./originalCommand");
    file.createNewFile();
    file.setExecutable(true);
    toDelete.add(file);
  }
Beispiel #24
0
  /**
   * Set permissions to the required value. Uses the java primitives instead of forking if group ==
   * other.
   *
   * @param f the file to change
   * @param permission the new permissions
   * @throws IOException
   */
  public static void setPermission(File f, FsPermission permission) throws IOException {
    FsAction user = permission.getUserAction();
    FsAction group = permission.getGroupAction();
    FsAction other = permission.getOtherAction();

    // use the native/fork if the group/other permissions are different
    // or if the native is available
    if (group != other || NativeIO.isAvailable()) {
      execSetPermission(f, permission);
      return;
    }

    boolean rv = true;

    // read perms
    rv = f.setReadable(group.implies(FsAction.READ), false);
    checkReturnValue(rv, f, permission);
    if (group.implies(FsAction.READ) != user.implies(FsAction.READ)) {
      f.setReadable(user.implies(FsAction.READ), true);
      checkReturnValue(rv, f, permission);
    }

    // write perms
    rv = f.setWritable(group.implies(FsAction.WRITE), false);
    checkReturnValue(rv, f, permission);
    if (group.implies(FsAction.WRITE) != user.implies(FsAction.WRITE)) {
      f.setWritable(user.implies(FsAction.WRITE), true);
      checkReturnValue(rv, f, permission);
    }

    // exec perms
    rv = f.setExecutable(group.implies(FsAction.EXECUTE), false);
    checkReturnValue(rv, f, permission);
    if (group.implies(FsAction.EXECUTE) != user.implies(FsAction.EXECUTE)) {
      f.setExecutable(user.implies(FsAction.EXECUTE), true);
      checkReturnValue(rv, f, permission);
    }
  }
Beispiel #25
0
 public static void inputStreamToFile(final InputStream inputStream, final File outputFile)
     throws IOException, FileNotFoundException {
   outputFile.createNewFile();
   outputFile.setExecutable(true);
   final OutputStream out = new FileOutputStream(outputFile);
   int read = 0;
   final byte[] bytes = new byte[1024];
   while ((read = inputStream.read(bytes)) != -1) {
     out.write(bytes, 0, read);
   }
   inputStream.close();
   out.flush();
   out.close();
 }
Beispiel #26
0
 protected void doInstall(File installDir, String executable) throws IOException {
   if (!config.getTmpDir().equals(installDir) || !executable.equals(config.getExecutableName())) {
     File destFile = new File(installDir, executable);
     FileUtils.copyFile(new File(config.getTmpDir(), config.getExecutableName()), destFile);
     destFile.setExecutable(true, false);
   }
   for (File f : config.getOsArchDepLibDir().listFiles()) {
     if (f.getName().matches(".*\\.(so|dylib)(\\.1)?")) {
       FileUtils.copyFileToDirectory(f, installDir);
     }
   }
   stripArchives(installDir);
   copyResources(installDir);
 }
  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();
  }
  // Extract transcoder to data directory
  public TranscodeService() {
    InputStream inputStream = null;
    OutputStream outputStream;

    // Get transcoder
    if (SystemUtils.IS_OS_WINDOWS) {
      inputStream = getClass().getResourceAsStream("ffmpeg.exe");
    } else if (SystemUtils.IS_OS_LINUX) {
      inputStream = getClass().getResourceAsStream("ffmpeg");
    }

    // Check we found the transcoder
    if (inputStream == null) {
      LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME, "Transcoder not found!", null);
      return;
    }

    // Copy transcoder to filesystem
    try {
      LogService.getInstance().addLogEntry(Level.INFO, CLASS_NAME, "Preparing transcoder.", null);
      File file = new File(TRANSCODER_FILE);

      int readBytes;
      byte[] buffer = new byte[4096];

      outputStream = new FileOutputStream(file);

      while ((readBytes = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, readBytes);
      }

      // Close streams
      inputStream.close();
      outputStream.close();

      // Check file copied successfully
      if (!file.exists()) {
        LogService.getInstance()
            .addLogEntry(Level.ERROR, CLASS_NAME, "Failed to extract transcoder!", null);
        return;
      }

      // Make sure file is executable
      file.setExecutable(true);
    } catch (IOException ex) {
      LogService.getInstance()
          .addLogEntry(Level.ERROR, CLASS_NAME, "Failed to extract transcoder!", ex);
    }
  }
Beispiel #29
0
  private void updateLinuxServiceInstaller() {
    try {
      File dir = new File(directory, "CTP");
      if (suppressFirstPathElement) dir = dir.getParentFile();
      Properties props = new Properties();
      String ctpHome = dir.getAbsolutePath();
      cp.appendln(Color.black, "...CTP_HOME: " + ctpHome);
      ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\");
      props.put("CTP_HOME", ctpHome);
      File javaHome = new File(System.getProperty("java.home"));
      String javaBin = (new File(javaHome, "bin")).getAbsolutePath();
      cp.appendln(Color.black, "...JAVA_BIN: " + javaBin);
      javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\");
      props.put("JAVA_BIN", javaBin);

      File linux = new File(dir, "linux");
      File install = new File(linux, "ctpService-ubuntu.sh");
      cp.appendln(Color.black, "Linux service installer:");
      cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
      String bat = getFileText(install);
      bat = replace(bat, props); // do the substitutions
      bat = bat.replace("\r", "");
      setFileText(install, bat);

      // If this is an ISN installation, put the script in the correct place.
      String osName = System.getProperty("os.name").toLowerCase();
      if (programName.equals("ISN") && !osName.contains("windows")) {
        install = new File(linux, "ctpService-red.sh");
        cp.appendln(Color.black, "ISN service installer:");
        cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
        bat = getFileText(install);
        bat = replace(bat, props); // do the substitutions
        bat = bat.replace("\r", "");
        File initDir = new File("/etc/init.d");
        File initFile = new File(initDir, "ctpService");
        if (initDir.exists()) {
          setOwnership(initDir, "edge", "edge");
          setFileText(initFile, bat);
          initFile.setReadable(true, false); // everybody can read //Java 1.6
          initFile.setWritable(true); // only the owner can write //Java 1.6
          initFile.setExecutable(true, false); // everybody can execute //Java 1.6
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Unable to update the Linux service ctpService.sh file");
    }
  }
Beispiel #30
0
  @Test
  @RunIf(
      value = EnhancedOSChecker.class,
      arguments = {DO_NOT_RUN_ON, OSChecker.WINDOWS})
  public void shouldBeAbleToRunCommandsFromRelativeDirectories() throws IOException {
    File shellScript = new File(tempFolder, "hello-world.sh");
    FileUtil.writeContentToFile("echo ${PWD}", shellScript);
    assertThat(shellScript.setExecutable(true), is(true));

    CommandLine line = CommandLine.createCommandLine("../hello-world.sh").withWorkingDir(subFolder);

    InMemoryStreamConsumer out = new InMemoryStreamConsumer();
    line.execute(out, new EnvironmentVariableContext(), null).waitForExit();

    assertThat(out.getAllOutput().trim(), endsWith("subFolder"));
  }