// Derived from http://stackoverflow.com/a/3054692/250076
  public static File getRelativeFile(File targetFile, File baseFile) {
    try {
      targetFile = targetFile.getCanonicalFile();
      baseFile = baseFile.getCanonicalFile();
    } catch (IOException ignored) {
    }
    String pathSeparator = File.separator;
    String basePath = baseFile.getAbsolutePath();
    String normalizedTargetPath = normalize(targetFile.getAbsolutePath(), pathSeparator);
    String normalizedBasePath = normalize(basePath, pathSeparator);

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length
        && commonIndex < base.length
        && target[commonIndex].equals(base[commonIndex])) {
      common.append(target[commonIndex]).append(pathSeparator);
      commonIndex++;
    }

    if (commonIndex == 0) {
      throw new Error(
          "No common path element found for '"
              + normalizedTargetPath
              + "' and '"
              + normalizedBasePath
              + '\'');
    }

    boolean baseIsFile = true;

    if (baseFile.exists()) {
      baseIsFile = baseFile.isFile();
    } else if (basePath.endsWith(pathSeparator)) {
      baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
      int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

      for (int i = 0; i < numDirsUp; i++) {
        relative.append("..").append(pathSeparator);
      }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return new File(relative.toString());
  }
  private void changeDirectory(File dir) {
    JFileChooser fc = getFileChooser();
    // Traverse shortcuts on Windows
    if (dir != null && FilePane.usesShellFolder(fc)) {
      try {
        ShellFolder shellFolder = ShellFolder.getShellFolder(dir);

        if (shellFolder.isLink()) {
          File linkedTo = shellFolder.getLinkLocation();

          // If linkedTo is null we try to use dir
          if (linkedTo != null) {
            if (fc.isTraversable(linkedTo)) {
              dir = linkedTo;
            } else {
              return;
            }
          } else {
            dir = shellFolder;
          }
        }
      } catch (FileNotFoundException ex) {
        return;
      }
    }
    fc.setCurrentDirectory(dir);
    if (fc.getFileSelectionMode() == JFileChooser.FILES_AND_DIRECTORIES
        && fc.getFileSystemView().isFileSystem(dir)) {

      setFileName(dir.getAbsolutePath());
    }
  }
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
Exemple #4
0
  String ls(String args[], boolean relative) {
    if (args.length < 2)
      throw new IllegalArgumentException(
          "the ${ls} macro must at least have a directory as parameter");

    File dir = domain.getFile(args[1]);
    if (!dir.isAbsolute())
      throw new IllegalArgumentException(
          "the ${ls} macro directory parameter is not absolute: " + dir);

    if (!dir.exists())
      throw new IllegalArgumentException(
          "the ${ls} macro directory parameter does not exist: " + dir);

    if (!dir.isDirectory())
      throw new IllegalArgumentException(
          "the ${ls} macro directory parameter points to a file instead of a directory: " + dir);

    Collection<File> files = new ArrayList<File>(new SortedList<File>(dir.listFiles()));

    for (int i = 2; i < args.length; i++) {
      Instructions filters = new Instructions(args[i]);
      files = filters.select(files, true);
    }

    List<String> result = new ArrayList<String>();
    for (File file : files) result.add(relative ? file.getName() : file.getAbsolutePath());

    return Processor.join(result, ",");
  }
  public void loadProperty() {

    try {

      File file = new File(confFileName);

      log.debug("file=" + file.getAbsolutePath());

      confProperties = new Properties();
      confProperties.loadFromXML(new FileInputStream(file));

      bonitaApiHost = confProperties.getProperty("bonita.api.host");
      bonitaApiUsername = confProperties.getProperty("bonita.api.username");
      bonitaApiPassword = confProperties.getProperty("bonita.api.password");
      bonitaApiHttpUsername = confProperties.getProperty("bonita.api.http.username");
      bonitaApiHttpPassword = confProperties.getProperty("bonita.api.http.password");
      bonitaApiPath = confProperties.getProperty("bonita.api.path");

      rallyApiHost = confProperties.getProperty("rally.api.host");
      rallyApiHttpUsername = confProperties.getProperty("rally.api.http.username");
      rallyApiHttpPassword = confProperties.getProperty("rally.api.http.password");
      rallyProjectIds = confProperties.getProperty("rally.project.ids");

      // bonitaProcessId=properties.getProperty("bonita.process.xp_code.id");

      workflowServiceUrl = confProperties.getProperty("service.url");

    } catch (Exception e) {
      log.error("", e);
    }
  }
 private void listFiles(String basePath, String path, String extension, Vector<String> vector) {
   File folder = new File(path);
   String[] list = folder.list();
   if (list != null) {
     for (String item : list) {
       if (item.charAt(0) == '.') continue;
       File file = new File(path, item);
       String newPath = file.getAbsolutePath();
       if (newPath.startsWith(basePath)) {
         newPath = newPath.substring(basePath.length());
       }
       if (extension == null || item.toLowerCase().endsWith(extension)) {
         vector.add(newPath);
       }
       if (file.isDirectory()) {
         listFiles(basePath, file.getAbsolutePath(), extension, vector);
       }
     }
   }
 }
 // #718
 // http://code.google.com/p/processing/issues/detail?id=718
 private String[] listFiles(File folder, boolean relative, String extension) {
   String path = folder.getAbsolutePath();
   Vector<String> vector = new Vector<String>();
   if (extension != null) {
     if (!extension.startsWith(".")) {
       extension = "." + extension;
     }
   }
   listFiles(relative ? (path + File.separator) : "", path, extension, vector);
   String outgoing[] = new String[vector.size()];
   vector.copyInto(outgoing);
   return outgoing;
 }
    // Writes the program to a source file, compiles it, and runs it.
    private void compileAndRun(String fileName, String code) {
      // Exceptions here can pick and choose what font to use, as needed.
      // Exceptions thrown by the program, that cause the Playground to be unstable, should be in
      // blue.

      println("Deleting old temp files...", progErr);
      new File(fileName + ".java").delete();
      new File(fileName + ".class").delete();

      println("Creating source file...", progErr);
      file = new File(fileName + ".java");

      println("Writing code to source file...", progErr);
      try {
        new FileWriter(file).append(code).close();
      } catch (IOException i) {
        println("Had an IO Exception when trying to write the code. Stack trace:", error);
        i.printStackTrace();
        return; // Exit on error
      }

      println("Compiling code...", progErr);
      // This should only ever be called if the JDK isn't installed. How you'd get here, I don't
      // know.
      if (compiler == null) {
        println("Fatal Error: JDK not installed. Go to java.sun.com and install.", error);
        return;
      }

      // Tries to compile. Success code is 0, so if something goes wrong, do stuff.
      int result =
          compiler.run(
              null,
              null,
              null,
              file
                  .getAbsolutePath()); // Possibly add a new outputstream to parse through the
                                       // compiler errors
      if (result != 0) {
        displayLog();
        println("Failed to compile.", error);
        return; // Return on error
      }

      println("Code compiled with 0 errors.", progErr);

      println("Attempting to run code...", progErr);
      run(fileName);
    }
Exemple #9
0
 void getTable() {
   if (chooser == null) {
     File userdir = new File(System.getProperty("user.dir"));
     chooser = new JFileChooser(userdir);
   }
   if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
     file = chooser.getSelectedFile();
     fileLength = file.length();
     setTitle(windowTitle + ": " + file.getAbsolutePath());
     int size = Key.getEncryptionKeySize(this, true);
     key = Key.getEncryptionKey(this, true, size);
     if (key == null) key = defaultKey;
     initCipher();
   } else System.exit(0);
 }
  /**
   * @param data
   * @param target
   * @throws Exception
   * @throws IOException
   */
  public String createService(ServiceData data) throws Exception, IOException {

    File sdir = new File(serviceDir, data.name);
    if (!sdir.exists() && !sdir.mkdirs()) {
      throw new IOException("Could not create directory " + data.sdir);
    }
    data.sdir = sdir.getAbsolutePath();

    File lock = new File(data.sdir, LOCK);
    data.lock = lock.getAbsolutePath();

    if (data.work == null) data.work = new File(data.sdir, "work").getAbsolutePath();
    if (data.user == null) data.user = platform.user();

    if (data.user == null) data.user = "******";

    new File(data.work).mkdir();

    if (data.log == null) data.log = new File(data.sdir, "log").getAbsolutePath();

    // TODO
    // if (Data.validate(data) != null)
    // return "Invalid service data: " + Data.validate(data);

    if (service == null)
      throw new RuntimeException(
          "Missing biz.aQute.jpm.service in repo, should have been installed by init, try reiniting");

    data.serviceLib = service.getAbsolutePath();

    platform.chown(data.user, true, new File(data.sdir));

    String s = platform.createService(data, null, false);
    if (s == null) storeData(new File(data.sdir, "data"), data);
    return s;
  }
  public HarbisonTable(File dir, String key) throws IOException {
    inputFile = new File(dir, String.format("ratiobygene_forpaper_%s_abbr.txt", key));
    if (!inputFile.exists()) {
      throw new IllegalArgumentException(
          String.format("Unknown Harbison Key: %s (%s)", key, inputFile.getAbsolutePath()));
    }

    exptIndices = new TreeMap<String, Integer>();
    table = new HashMap<String, Float[]>();

    int count = parse();
    System.out.println(
        String.format(
            "Harbison: %d expts, %d probes, %d values", experiments.length, table.size(), count));
  }
  public IyerTable(File dir) throws IOException {
    inputFile = new File(dir, "HuIyer_TFKO_expression.txt");
    if (!inputFile.exists()) {
      throw new IllegalArgumentException(
          String.format("Unknown Iyer File: %s", inputFile.getAbsolutePath()));
    }

    exptIndices = new TreeMap<String, Integer>();
    table = new HashMap<String, Float[]>();

    int count = parse();
    System.out.println(
        String.format(
            "Iyer: %d expts, %d probes, %d values", experiments.length, table.size(), count));
  }
  /**
   * @param data
   * @param target
   * @throws Exception
   * @throws IOException
   */
  public String createCommand(CommandData data, boolean force) throws Exception, IOException {

    // TODO
    // if (Data.validate(data) != null)
    // return "Invalid command data: " + Data.validate(data);

    Map<String, String> map = null;
    if (data.trace) {
      map = new HashMap<String, String>();
      map.put("java.security.manager", "aQute.jpm.service.TraceSecurityManager");
      reporter.trace("tracing");
    }
    String s = platform.createCommand(data, map, force, service.getAbsolutePath());
    if (s == null) storeData(new File(commandDir, data.name), data);
    return s;
  }
  public ArtifactData get(byte[] sha) throws Exception {
    String name = Hex.toHexString(sha);
    File data = IO.getFile(repoDir, name + ".json");
    reporter.trace("artifact data file %s", data);
    if (data.isFile()) { // Bin + metadata
      ArtifactData artifact = codec.dec().from(data).get(ArtifactData.class);
      artifact.file = IO.getFile(repoDir, name).getAbsolutePath();
      return artifact;
    }
    File bin = IO.getFile(repoDir, name);
    if (bin.exists()) { // Only bin
      ArtifactData artifact = new ArtifactData();
      artifact.file = bin.getAbsolutePath();
      artifact.sha = sha;
      return artifact;
    }

    return null;
  }
Exemple #15
0
 public String _osfile(String args[]) {
   verifyCommand(args, _fileHelp, null, 3, 3);
   File base = new File(args[1]);
   File f = Processor.getFile(base, args[2]);
   return f.getAbsolutePath();
 }
  public void run() {
    if (!new File(m_generatorPy).exists()) {
      Base.showMessage(
          "ERROR", String.format("Could not find generator python script at %s", m_generatorPy));
    }
    Sketch sketch = m_editor.getSketch();
    if (sketch.isModified()) {
      try {
        sketch.save();
      } catch (java.io.IOException ex) {
        // Base.showMessage("ERROR", "Could not save sketch before trying to generate." );
      }
    }

    // String sketchName = sketch.getName();
    // SketchCode codeObject = sketch.getCurrentCode();
    // String code = codeObject.getProgram();
    try {
      String code = m_editor.getCurrentTab().getText();
      // String code = m_editor.getText();
      int start = code.indexOf("BEGIN AUTOMATION");
      if (start != -1) {
        int end = code.indexOf("END AUTOMATION", start);
        if (end != -1) {
          String automationCode = code.substring(start + "BEGIN AUTOMATION".length(), end);
          automationCode = automationCode.replaceAll("\\*\\s+", "");
          // SketchData sketchData = new MySketchData(sketch.getMainFilePath());
          // File buildFolder = BaseNoGui.getBuildFolder(sketchData);
          File buildFolder = getBuildFolder(sketch);
          // File codeFolder = sketchData.getCodeFolder();
          File codeFolder = new File(sketch.getFolder(), "code");
          Files.createDirectories(codeFolder.toPath());
          File automationFileName = new File(buildFolder, "automation.automation");
          FileWriter writer = new FileWriter(automationFileName);
          writer.write("name automation\n");
          writer.write("import " + sketch.getMainFilePath().toString() + "\n");
          writer.write(automationCode);
          writer.close();

          try {
            ProcessBuilder processBuilder = null;
            if (m_isWindows) {
              processBuilder =
                  new ProcessBuilder(
                      m_pythonPath.getAbsolutePath(),
                      m_generatorPy,
                      "-s",
                      "--arduino",
                      automationFileName.getAbsolutePath());
            } else {
              processBuilder =
                  new ProcessBuilder(
                      m_generatorPy, "-s", "--arduino", automationFileName.getAbsolutePath());
            }
            processBuilder.directory(codeFolder);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            inheritIO(process.getInputStream(), System.out);
            int result = process.waitFor();

            String includeLibLine = "#include \"SequantoAutomation.h\"\n";
            if (!code.contains(includeLibLine)) {
              code = includeLibLine + code;
            }

            /*
              File generatedFileName = new File(codeFolder, "automation_automation.c" );
              String includeLine = String.format("#include \"%s\"\n", generatedFileName.getAbsolutePath());
              if ( !code.contains(includeLine) )
              {
              int i = code.indexOf(includeLibLine);
              code = code.substring(0, i + includeLibLine.length()) +
              includeLine +
              code.substring ( i + includeLibLine.length(), code.length() );
              }
            */

            String includeLine = String.format("#include \"code/automation_automation.h\"\n");
            if (!code.contains(includeLine)) {
              int i = code.indexOf(includeLibLine);
              code =
                  code.substring(0, i + includeLibLine.length())
                      + includeLine
                      + code.substring(i + includeLibLine.length(), code.length());
            }

            String includeCodeLine = String.format("\n#include \"code/automation_automation.c\"\n");
            if (!code.contains(includeCodeLine)) {
              code = code + includeCodeLine;
            }

            if (m_editor.getCurrentTab().getText() != code) {
              // System.out.println ( "Setting code to" );
              // System.out.println ( code );
              // System.out.println ( "Current text was" );
              // System.out.println ( m_editor.getText() );
              m_editor.getCurrentTab().setText(code);
            }

            if (result == 0) {
              System.out.println("Sequanto automation code generated successfully!");
            } else {
              System.out.println("ERROR!!!");
            }
          } catch (Exception ex) {
            Base.showMessage("ERROR", String.format("Could not start generator script: %s", ex));
          }
        } else {
          Base.showMessage("ERROR", "Can not find END AUTOMATION.");
        }
      } else {
        Base.showMessage("ERROR", "Can not find BEGIN AUTOMATION.");
      }
    } catch (java.io.IOException ex) {
      Base.showMessage("ERROR", String.format("IO Error: %s.", ex));
    }
  }
Exemple #17
0
  public void signJar(Jar jar) {
    if (digestNames == null || digestNames.length == 0)
      error("Need at least one digest algorithm name, none are specified");

    if (keystoreFile == null || !keystoreFile.getAbsoluteFile().exists()) {
      error("No such keystore file: " + keystoreFile);
      return;
    }

    if (alias == null) {
      error("Private key alias not set for signing");
      return;
    }

    MessageDigest digestAlgorithms[] = new MessageDigest[digestNames.length];

    getAlgorithms(digestNames, digestAlgorithms);

    try {
      Manifest manifest = jar.getManifest();
      manifest.getMainAttributes().putValue("Signed-By", "Bnd");

      // Create a new manifest that contains the
      // Name parts with the specified digests

      ByteArrayOutputStream o = new ByteArrayOutputStream();
      manifest.write(o);
      doManifest(jar, digestNames, digestAlgorithms, o);
      o.flush();
      byte newManifestBytes[] = o.toByteArray();
      jar.putResource("META-INF/MANIFEST.MF", new EmbeddedResource(newManifestBytes, 0));

      // Use the bytes from the new manifest to create
      // a signature file

      byte[] signatureFileBytes = doSignatureFile(digestNames, digestAlgorithms, newManifestBytes);
      jar.putResource("META-INF/BND.SF", new EmbeddedResource(signatureFileBytes, 0));

      // Now we must create an RSA signature
      // this requires the private key from the keystore

      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

      KeyStore.PrivateKeyEntry privateKeyEntry = null;

      java.io.FileInputStream keystoreInputStream = null;
      try {
        keystoreInputStream = new java.io.FileInputStream(keystoreFile);
        char[] pw = password == null ? new char[0] : password.toCharArray();

        keystore.load(keystoreInputStream, pw);
        keystoreInputStream.close();
        privateKeyEntry =
            (PrivateKeyEntry) keystore.getEntry(alias, new KeyStore.PasswordProtection(pw));
      } catch (Exception e) {
        error(
            "No able to load the private key from the give keystore("
                + keystoreFile.getAbsolutePath()
                + ") with alias "
                + alias
                + " : "
                + e);
        return;
      } finally {
        IO.close(keystoreInputStream);
      }
      PrivateKey privateKey = privateKeyEntry.getPrivateKey();

      Signature signature = Signature.getInstance("MD5withRSA");
      signature.initSign(privateKey);

      signature.update(signatureFileBytes);

      signature.sign();

      // TODO, place the SF in a PCKS#7 structure ...
      // no standard class for this? The following
      // is an idea but we will to have do ASN.1 BER
      // encoding ...

      ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
      jar.putResource("META-INF/BND.RSA", new EmbeddedResource(tmpStream.toByteArray(), 0));
    } catch (Exception e) {
      error("During signing: " + e);
    }
  }