コード例 #1
0
ファイル: Install.java プロジェクト: GUIpsp/gradle
 private void setExecutablePermissions(File gradleHome) {
   if (isWindows()) {
     return;
   }
   File gradleCommand = new File(gradleHome, "bin/gradle");
   String errorMessage = null;
   try {
     ProcessBuilder pb = new ProcessBuilder("chmod", "755", gradleCommand.getCanonicalPath());
     Process p = pb.start();
     if (p.waitFor() == 0) {
       System.out.println("Set executable permissions for: " + gradleCommand.getAbsolutePath());
     } else {
       BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
       Formatter stdout = new Formatter();
       String line;
       while ((line = is.readLine()) != null) {
         stdout.format("%s%n", line);
       }
       errorMessage = stdout.toString();
     }
   } catch (IOException e) {
     errorMessage = e.getMessage();
   } catch (InterruptedException e) {
     errorMessage = e.getMessage();
   }
   if (errorMessage != null) {
     System.out.println(
         "Could not set executable permissions for: " + gradleCommand.getAbsolutePath());
     System.out.println("Please do this manually if you want to use the Gradle UI.");
   }
 }
コード例 #2
0
  /**
   * This method will take in a string which will be a directory. It will make sure that the
   * directory exists and return the absolute path
   *
   * @return the value of the absolute directory
   */
  private String doesExistAndAbsolute(String dir) {

    File tempDirFile = new File(dir);
    try {
      if (tempDirFile.exists()) {
        if (tempDirFile.isAbsolute()) {
          return dir;
        } else {
          tempDirFile = new File(System.getProperty("user.dir") + sep + dir);
          if (tempDirFile.exists()) {
            return tempDirFile.getAbsolutePath();
          } else {
            throw new NotDirectoryException(
                ResourceHandler.getMessage("caption.reldirnotfound")
                    + ":  "
                    + tempDirFile.getAbsolutePath());
          }
        }
      } else {
        throw new NotDirectoryException(
            ResourceHandler.getMessage("caption.absdirnotfound")
                + ":  "
                + tempDirFile.getAbsolutePath());
      }

    } catch (NotDirectoryException e) {
      System.out.println(
          ResourceHandler.getMessage("caption.absdirnotfound")
              + ":  "
              + tempDirFile.getAbsolutePath());
      return null; // this is just so it would compile
    }
  }
コード例 #3
0
ファイル: IgvTools.java プロジェクト: IntersectAustralia/IGV
  public void doSort(String ifile, String ofile, String tmpDirName, int maxRecords) {

    System.out.println("Sorting " + ifile + "  -> " + ofile);
    File inputFile = new File(ifile);
    File outputFile = new File(ofile);
    Sorter sorter = Sorter.getSorter(inputFile, outputFile);
    if (tmpDirName != null && tmpDirName.trim().length() > 0) {
      File tmpDir = new File(tmpDirName);
      if (!tmpDir.exists()) {
        System.err.println(
            "Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
        throw new PreprocessingException(
            "Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
      }
      sorter.setTmpDir(tmpDir);
    }

    sorter.setMaxRecords(maxRecords);
    try {
      sorter.run();
    } catch (Exception e) {
      e.printStackTrace();
      // Delete output file as its probably corrupt
      if (outputFile.exists()) {
        outputFile.delete();
      }
    }
    System.out.println("Done");
    System.out.flush();
  }
コード例 #4
0
    /** @param workTokDir Token directory (common for multiple nodes). */
    private void cleanupResources(File workTokDir) {
      RandomAccessFile lockFile = null;

      FileLock lock = null;

      try {
        lockFile = new RandomAccessFile(new File(workTokDir, LOCK_FILE_NAME), "rw");

        lock = lockFile.getChannel().lock();

        if (lock != null) processTokenDirectory(workTokDir);
        else if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (OverlappingFileLockException ignored) {
        if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (FileLockInterruptionException ignored) {
        Thread.currentThread().interrupt();
      } catch (IOException e) {
        U.error(log, "Failed to process directory: " + workTokDir.getAbsolutePath(), e);
      } finally {
        U.releaseQuiet(lock);
        U.closeQuiet(lockFile);
      }
    }
コード例 #5
0
 public static void createNgramsFromFolder(
     File input_folder, File output_folder, int ngram_value) {
   Stack<File> stack = new Stack<File>();
   stack.push(input_folder);
   while (!stack.isEmpty()) {
     File child = stack.pop();
     if (child.isDirectory()) {
       for (File f : child.listFiles()) stack.push(f);
     } else if (child.isFile()) {
       try {
         System.out.println("Processing: " + child.getAbsolutePath());
         FileReader fr = new FileReader(child.getAbsolutePath());
         FileWriter outputFile = new FileWriter(output_folder + "/file" + file_no);
         BufferedReader br = new BufferedReader(fr);
         String readline = "";
         while ((readline = br.readLine()) != null) {
           String[] words = readline.split("\\s+");
           for (int i = 0; i < words.length - ngram_value + 1; i++) {
             String ngram = "";
             for (int j = 0; j < ngram_value; j++) ngram = ngram + " " + words[i + j];
             outputFile.write(ngram + "\n");
           }
         }
         file_no++;
         outputFile.close();
         br.close();
         fr.close();
       } catch (Exception e) {
         System.out.println("File not found:" + e);
       }
     }
   }
 }
コード例 #6
0
ファイル: HelpLoader.java プロジェクト: TUM-LRR/Jasmin
 /**
  * automatically generate non-existing help html files for existing commands in the CommandLoader
  *
  * @param cl the CommandLoader where you look for the existing commands
  */
 public void createHelpText(CommandLoader cl) {
   File dir = new File((getClass().getResource("..").getPath()));
   dir = new File(dir, language);
   if (!dir.exists() && !dir.mkdirs()) {
     System.out.println("Failed to create " + dir.getAbsolutePath());
     return;
   }
   for (String mnemo : cl.getMnemoList()) {
     if (!exists(mnemo)) {
       File file = new File(dir, mnemo + ".htm");
       try {
         file.createNewFile();
         BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
         PrintStream ps = new PrintStream(os);
         ps.println("<html>\n<head>\n<title>" + mnemo + "\n</title>\n</head>\n<body>");
         ps.println("Command: " + mnemo.toUpperCase() + "<br>");
         ps.println("arguments: <br>");
         ps.println("effects: <br>");
         ps.println("flags to be set: <br>");
         ps.println("approx. clockcycles: <br>");
         ps.println("misc: <br>");
         ps.println("</body>\n</html>");
         ps.flush();
         ps.close();
       } catch (IOException e) {
         System.out.println("failed to create " + file.getAbsolutePath());
       }
     }
   }
 }
コード例 #7
0
  public void testGetAttributesForThisTestClass() throws IOException {
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
      System.out.println("WARNING: Unsupported OS, skipping test");
      return;
    }

    URL resource =
        Thread.currentThread()
            .getContextClassLoader()
            .getResource(getClass().getName().replace('.', '/') + ".class");

    if (resource == null) {
      throw new IllegalStateException(
          "SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER.");
    }

    File f = new File(resource.getPath().replaceAll("%20", " "));

    Map attrs =
        PlexusIoResourceAttributeUtils.getFileAttributesByPath(
            f, new ConsoleLogger(Logger.LEVEL_INFO, "test"), Logger.LEVEL_DEBUG);

    PlexusIoResourceAttributes fileAttrs =
        (PlexusIoResourceAttributes) attrs.get(f.getAbsolutePath());

    System.out.println("Got attributes for: " + f.getAbsolutePath() + fileAttrs);

    assertNotNull(fileAttrs);
    assertTrue(fileAttrs.isOwnerReadable());
    assertEquals(System.getProperty("user.name"), fileAttrs.getUserName());
  }
コード例 #8
0
 public static String createTempImageFile(String origFile, String prefix, String suffix)
     throws Exception {
   File outputFile = createTempFile(prefix, suffix);
   outputFile.deleteOnExit();
   copyFile(outputFile.getAbsolutePath(), origFile);
   return outputFile.getAbsolutePath();
 }
コード例 #9
0
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }
コード例 #10
0
ファイル: Bundle.java プロジェクト: tdanford/neurocommons
  public Bundle(File dir) throws IOException {
    if (!dir.exists()) {
      throw new IllegalArgumentException(String.format("%s does not exist", dir.getAbsolutePath()));
    }
    if (!dir.canRead()) {
      throw new IllegalArgumentException(String.format("%s cannot be read", dir.getAbsolutePath()));
    }
    if (!dir.isDirectory()) {
      throw new IllegalArgumentException(
          String.format("%s is not a directory", dir.getAbsolutePath()));
    }

    this.dir = dir;

    config = new BundleConfig(new File(dir, "Config.pl"));

    dataFiles = new ArrayList<File>();

    dataFiles.addAll(
        Arrays.asList(
            dir.listFiles(
                new FilenameFilter() {
                  public boolean accept(File dir, String name) {
                    String upper = name.toUpperCase();
                    return (upper.endsWith(".rdf")
                            || upper.endsWith(".owl")
                            || upper.endsWith(".n3")
                            || upper.endsWith(".ttl"))
                        && new File(dir, name).canRead();
                  }
                })));
  }
コード例 #11
0
ファイル: HelpLoader.java プロジェクト: TUM-LRR/Jasmin
  /** initialization. load all files. */
  private void init() {
    URL home = getClass().getResource("..");
    File local;
    if (home != null) {
      System.out.println("looks like you are not starting from a jar-package");
      local = new File(home.getPath() + "/" + helproot + "/" + language + "/");
      System.out.println("local: " + local.getAbsolutePath());
      initFile(local);
      try {
        local =
            new File(
                new File(home.getPath()).getParentFile().getParentFile(),
                helproot + "/" + language);
        System.out.println("local: " + local.getAbsolutePath());
        initFile(local);
      } catch (Exception e) {
        System.out.println("but not loading from the developer workbench?!");
      }

    } else {
      System.out.println("looks like you are starting from a jar-package");
      local = CommandLoader.getLocation();
      initJar(local);
    }
    List<String> l = getLanguages();
    for (String aL : l) {
      System.out.println("language found: " + aL);
    }
  }
コード例 #12
0
  /** @param args the command line arguments */
  public static void main(String[] args) throws Exception {

    // boolean Chinese = true;
    // File f = new File("C:/Users/Xin/Documents/opt/allign-zh-trans");
    // File out = new File("C:/Users/Xin/Documents/opt/out-zh");
    boolean Chinese = false;
    File f = new File("C:/Users/Xin/Documents/optest/allign-es-trans");
    File out = new File("C:/Users/Xin/Documents/optest/out-es");
    File seg = new File("C:/Users/Xin/Documents/optest/segmented-zh");

    out.mkdirs();
    seg.mkdirs();

    for (String name : f.list()) {

      String fullName = f.getAbsolutePath() + "/" + name;
      String outName = out.getAbsolutePath() + "/" + name;

      if (Chinese == true) {

        String segName = seg.getAbsolutePath() + "/" + name;
        ChineseSegment(fullName, segName);
        BlEUClaculatorOnefile(segName, outName, Chinese);
      } else {

        BlEUClaculatorOnefile(fullName, outName, Chinese);
      }
    }
  }
コード例 #13
0
ファイル: IgvTools.java プロジェクト: IntersectAustralia/IGV
  private void doGCTtoIGV(
      String typeString,
      String ifile,
      File ofile,
      String probefile,
      int maxRecords,
      String tmpDirName,
      Genome genome)
      throws IOException {

    System.out.println("gct -> igv: " + ifile + " -> " + ofile.getAbsolutePath());

    File tmpDir = null;
    if (tmpDirName != null && tmpDirName.trim().length() > 0) {
      tmpDir = new File(tmpDirName);
      if (!tmpDir.exists()) {
        System.err.println(
            "Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
        throw new PreprocessingException(
            "Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
      }
    }

    ResourceLocator locator = new ResourceLocator(ifile);
    locator.setType(typeString);
    GCTtoIGVConverter.convert(locator, ofile, probefile, maxRecords, tmpDir, genome);
  }
コード例 #14
0
 public int runDirectorToInstall(
     String message, File installFolder, String sourceRepo, String iuToInstall) {
   String[] command =
       new String[] { //
         "-application",
         "org.eclipse.equinox.p2.director", //
         "-repository",
         sourceRepo,
         "-installIU",
         iuToInstall, //
         "-destination",
         installFolder.getAbsolutePath(), //
         "-bundlepool",
         installFolder.getAbsolutePath(), //
         "-roaming",
         "-profile",
         "PlatformProfile",
         "-profileProperties",
         "org.eclipse.update.install.features=true", //
         "-p2.os",
         Platform.getOS(),
         "-p2.ws",
         Platform.getWS(),
         "-p2.arch",
         Platform.getOSArch()
       };
   return runEclipse(message, command);
 }
コード例 #15
0
  /**
   * Shuts down the test harness, and makes the best attempt possible to delete dataDir, unless the
   * system property "solr.test.leavedatadir" is set.
   */
  @Override
  public void tearDown() throws Exception {
    log.info("####TEARDOWN_START " + getTestName());
    if (factoryProp == null) {
      System.clearProperty("solr.directoryFactory");
    }

    if (h != null) {
      h.close();
    }
    String skip = System.getProperty("solr.test.leavedatadir");
    if (null != skip && 0 != skip.trim().length()) {
      System.err.println(
          "NOTE: per solr.test.leavedatadir, dataDir will not be removed: "
              + dataDir.getAbsolutePath());
    } else {
      if (!recurseDelete(dataDir)) {
        System.err.println(
            "!!!! WARNING: best effort to remove " + dataDir.getAbsolutePath() + " FAILED !!!!!");
      }
    }

    resetExceptionIgnores();
    super.tearDown();
  }
コード例 #16
0
 /*
  * Set up the platform binary download and get it ready to run the tests.
  * This method is not intended to be called by clients, it will be called
  * automatically when the clients use a ReconcilerTestSuite. If the executable isn't
  * found on the file-system after the call, then we fail.
  */
 public void initialize() throws Exception {
   initialized = false;
   File file = getPlatformZip();
   output = getUniqueFolder();
   toRemove.add(output);
   // for now we will exec to un-tar archives to keep the executable bits
   if (file.getName().toLowerCase().endsWith(".zip")) {
     try {
       FileUtils.unzipFile(file, output);
     } catch (IOException e) {
       fail("0.99", e);
     }
   } else {
     untar("1.0", file);
   }
   File exe = new File(output, getExeFolder() + "eclipse.exe");
   if (!exe.exists()) {
     exe = new File(output, getExeFolder() + "eclipse");
     if (!exe.exists())
       fail(
           "Executable file: "
               + exe.getAbsolutePath()
               + "(or .exe) not found after extracting: "
               + file.getAbsolutePath()
               + " to: "
               + output);
   }
   initialized = true;
 }
コード例 #17
0
 protected int runEclipse(String message, File location, String[] args, File extensions) {
   File root = new File(Activator.getBundleContext().getProperty("java.home"));
   root = new File(root, "bin");
   File exe = new File(root, "javaw.exe");
   if (!exe.exists()) exe = new File(root, "java");
   assertTrue("Java executable not found in: " + exe.getAbsolutePath(), exe.exists());
   List<String> command = new ArrayList<String>();
   Collections.addAll(
       command,
       new String[] {
         (new File(location == null ? output : location, getExeFolder() + "eclipse"))
             .getAbsolutePath(),
         "--launcher.suppressErrors",
         "-nosplash",
         "-vm",
         exe.getAbsolutePath()
       });
   Collections.addAll(command, args);
   Collections.addAll(command, new String[] {"-vmArgs", "-Dosgi.checkConfiguration=true"});
   // command-line if you want to run and allow a remote debugger to connect
   if (debug)
     Collections.addAll(
         command,
         new String[] {
           "-Xdebug", "-Xnoagent", "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8787"
         });
   int result = run(message, command.toArray(new String[command.size()]));
   // 13 means that we wrote something out in the log file.
   // so try and parse it and fail via that message if we can.
   if (result == 13) parseExitdata(message);
   return result;
 }
コード例 #18
0
  private static String getArtifactResolverJar(boolean isMaven3) throws IOException {
    Class marker =
        isMaven3 ? MavenArtifactResolvedM3RtMarker.class : MavenArtifactResolvedM2RtMarker.class;

    File classDirOrJar = new File(PathUtil.getJarPathForClass(marker));

    if (!classDirOrJar.isDirectory()) {
      return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation.
    }

    // it's a classes directory, we are in development mode.
    File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar");
    tempFile.deleteOnExit();

    ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile));
    try {
      ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null);

      if (isMaven3) {
        File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class));

        String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/');
        ZipUtil.addDirToZipRecursively(
            zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null);
      }
    } finally {
      zipOutput.close();
    }

    return tempFile.getAbsolutePath();
  }
コード例 #19
0
  /**
   * Load classes from given file. File could be either directory or JAR file.
   *
   * @param clsLdr Class loader to load files.
   * @param file Either directory or JAR file which contains classes or references to them.
   * @return Set of found and loaded classes or empty set if file does not exist.
   * @throws GridSpiException Thrown if given JAR file references to none existed class or
   *     IOException occurred during processing.
   */
  static Set<Class<? extends GridTask<?, ?>>> getClasses(ClassLoader clsLdr, File file)
      throws GridSpiException {
    Set<Class<? extends GridTask<?, ?>>> rsrcs = new HashSet<Class<? extends GridTask<?, ?>>>();

    if (file.exists() == false) {
      return rsrcs;
    }

    GridUriDeploymentFileResourceLoader fileRsrcLdr =
        new GridUriDeploymentFileResourceLoader(clsLdr, file);

    if (file.isDirectory()) {
      findResourcesInDirectory(fileRsrcLdr, file, rsrcs);
    } else {
      try {
        for (JarEntry entry : U.asIterable(new JarFile(file.getAbsolutePath()).entries())) {
          Class<? extends GridTask<?, ?>> rsrc = fileRsrcLdr.createResource(entry.getName(), false);

          if (rsrc != null) {
            rsrcs.add(rsrc);
          }
        }
      } catch (IOException e) {
        throw new GridSpiException(
            "Failed to discover classes in file: " + file.getAbsolutePath(), e);
      }
    }

    return rsrcs;
  }
コード例 #20
0
ファイル: Dashutil.java プロジェクト: vikrampatange/Nice-A
 public int compare(Object o1, Object o2) {
   File f1 = (File) o1;
   File f2 = (File) o2;
   if (f1.isDirectory()) {
     if (f2.isDirectory()) {
       switch (mode) {
           // Filename or Type
         case 1:
         case 4:
           return sign
               * f1.getAbsolutePath()
                   .toUpperCase()
                   .compareTo(f2.getAbsolutePath().toUpperCase());
           // Filesize
         case 2:
           return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
           // Date
         case 3:
           return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified())));
         default:
           return 1;
       }
     } else return -1;
   } else if (f2.isDirectory()) return 1;
   else {
     switch (mode) {
       case 1:
         return sign
             * f1.getAbsolutePath().toUpperCase().compareTo(f2.getAbsolutePath().toUpperCase());
       case 2:
         return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
       case 3:
         return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified())));
       case 4:
         { // Sort by extension
           int tempIndexf1 = f1.getAbsolutePath().lastIndexOf('.');
           int tempIndexf2 = f2.getAbsolutePath().lastIndexOf('.');
           if ((tempIndexf1 == -1) && (tempIndexf2 == -1)) { // Neither have an extension
             return sign
                 * f1.getAbsolutePath()
                     .toUpperCase()
                     .compareTo(f2.getAbsolutePath().toUpperCase());
           }
           // f1 has no extension
           else if (tempIndexf1 == -1) return -sign;
           // f2 has no extension
           else if (tempIndexf2 == -1) return sign;
           // Both have an extension
           else {
             String tempEndf1 = f1.getAbsolutePath().toUpperCase().substring(tempIndexf1);
             String tempEndf2 = f2.getAbsolutePath().toUpperCase().substring(tempIndexf2);
             return sign * tempEndf1.compareTo(tempEndf2);
           }
         }
       default:
         return 1;
     }
   }
 }
コード例 #21
0
 /*
  * Untar the given file in the output directory.
  */
 private void untar(String message, File file) {
   String name = file.getName();
   File gzFile = new File(output, name);
   output.mkdirs();
   run(message, new String[] {"cp", file.getAbsolutePath(), gzFile.getAbsolutePath()});
   run(message, new String[] {"tar", "-zpxf", gzFile.getAbsolutePath()});
   gzFile.delete();
 }
コード例 #22
0
 void clearPath(File f) {
   String root = dir.getAbsolutePath();
   String dir = f.getAbsolutePath();
   if (dir.startsWith(root)) {
     String[] dirNames = dir.substring(root.length()).split(File.separator + "subdir");
     if (clearPath(f, dirNames, 1)) return;
   }
   clearPath(f, null, -1);
 }
コード例 #23
0
ファイル: MapBuilder.java プロジェクト: GOancea/MDMI
 /**
  * Builds an object graph representing an MDMI map.
  *
  * @param filePath XMI file containing the map definition.
  * @return
  */
 public static List<MessageGroup> build(File file, ModelValidationResults valResults) {
   try {
     return buildFromRawModel(XMIParser.parse(file), valResults);
   } catch (FileNotFoundException exc) {
     throw new MdmiException(exc, "MapBuilder: file {0} not found!", file.getAbsolutePath());
   } catch (XMLStreamException exc) {
     throw new MdmiException(
         exc, "MapBuilder: file {0} is not a valid XML file!", file.getAbsolutePath());
   }
 }
コード例 #24
0
ファイル: M2Exporter.java プロジェクト: merfed/mcapps
  /** Display a dialog which allows the user to export a scene to an OBJ file. */
  public static void exportFile(BFrame parent, Scene theScene) {
    // Display a dialog box with options on how to export the scene.

    // ValueField errorField = new ValueField(0.05, ValueField.POSITIVE);
    // final ValueField widthField = new ValueField(200.0, ValueField.INTEGER+ValueField.POSITIVE);
    // final ValueField heightField = new ValueField(200.0, ValueField.INTEGER+ValueField.POSITIVE);
    // final ValueSlider qualitySlider = new ValueSlider(0.0, 1.0, 100, 0.5);
    // final BCheckBox smoothBox = new BCheckBox(Translate.text("subdivideSmoothMeshes"), true);
    final BCheckBox injectChoice = new BCheckBox(Translate.text("Inject"), true);
    // final BCheckBox UVChoice = new BCheckBox(Translate.text("Export UV"), true);

    /*BComboBox exportChoice = new BComboBox(new String [] {
      Translate.text("exportWholeScene"),
      Translate.text("selectedObjectsOnly")
    });*/

    ComponentsDialog dlg;
    if (theScene.getSelection().length > 0)
      dlg =
          new ComponentsDialog(
              parent,
              Translate.text("InjectToM2"),
              new Widget[] {injectChoice},
              new String[] {null, null, null, null, null});
    else
      dlg =
          new ComponentsDialog(
              parent,
              Translate.text("exportToM2"),
              new Widget[] {injectChoice},
              new String[] {null, null, null, null});
    if (!dlg.clickedOk()) return;

    // Ask the user to select the output file.

    BFileChooser fc = new BFileChooser(BFileChooser.SAVE_FILE, Translate.text("exportToWMO"));
    fc.setSelectedFile(new File("Untitled.m2"));
    if (ArtOfIllusion.getCurrentDirectory() != null)
      fc.setDirectory(new File(ArtOfIllusion.getCurrentDirectory()));
    if (!fc.showDialog(parent)) return;
    File dir = fc.getDirectory();
    f = fc.getSelectedFile();
    String name = f.getName();
    String baseName = (name.endsWith(".m2") ? name.substring(0, name.length() - 3) : name);
    ArtOfIllusion.setCurrentDirectory(dir.getAbsolutePath());

    m2 obj = null;
    try {
      obj = new m2(fileLoader.openBuffer(f.getAbsolutePath()));
    } catch (InvalidClassException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    writeScene(theScene, obj, false, 0.05, false, injectChoice.getState());
  }
コード例 #25
0
ファイル: Graph.java プロジェクト: midiablo/CoarseWordNet
 public Graph(WeightedBVGraph graph, String[] names) {
   org.apache.log4j.Logger logger =
       org.apache.log4j.Logger.getLogger("it.unimi.dsi.webgraph.ImmutableGraph");
   logger.setLevel(org.apache.log4j.Level.FATAL);
   if (names.length != graph.numNodes())
     throw new Error("Problem with the list of names for the nodes in the graph.");
   try {
     File auxFile = File.createTempFile("graph-maps-" + System.currentTimeMillis(), "aux");
     auxFile.deleteOnExit();
     RecordManager recMan = RecordManagerFactory.createRecordManager(auxFile.getAbsolutePath());
     nodes = recMan.hashMap("nodes");
     nodesReverse = recMan.hashMap("nodesReverse");
   } catch (IOException ex) {
     throw new Error(ex);
   }
   nodes.clear();
   nodesReverse.clear();
   Constructor[] cons = WeightedArc.class.getDeclaredConstructors();
   for (int i = 0; i < cons.length; i++) cons[i].setAccessible(true);
   this.graph = graph;
   WeightedArcSet list = new WeightedArcSet();
   ArcLabelledNodeIterator it = graph.nodeIterator();
   while (it.hasNext()) {
     if (commit++ % COMMIT_SIZE == 0) {
       commit();
       list.commit();
     }
     Integer aux1 = it.nextInt();
     Integer aux2 = null;
     ArcLabelledNodeIterator.LabelledArcIterator suc = it.successors();
     while ((aux2 = suc.nextInt()) != null && aux2 >= 0 && (aux2 < graph.numNodes()))
       try {
         WeightedArc arc = (WeightedArc) cons[0].newInstance(aux2, aux1, suc.label().getFloat());
         list.add(arc);
         this.nodes.put(aux1, names[aux1]);
         this.nodes.put(aux2, names[aux2]);
         this.nodesReverse.put(names[aux1], aux1);
         this.nodesReverse.put(names[aux2], aux2);
       } catch (Exception ex) {
         throw new Error(ex);
       }
   }
   reverse = new WeightedBVGraph(list.toArray(new WeightedArc[0]));
   numArcs = list.size();
   iterator = nodeIterator();
   try {
     File auxFile = File.createTempFile("graph" + System.currentTimeMillis(), "aux");
     auxFile.deleteOnExit();
     String basename = auxFile.getAbsolutePath();
     store(basename);
   } catch (IOException ex) {
     throw new Error(ex);
   }
   commit();
 }
コード例 #26
0
  protected static DefaultFontMapper getMapper() {
    if (mapper == null) {
      //      long t = System.currentTimeMillis();
      mapper = new DefaultFontMapper();

      if (PApplet.platform == PApplet.MACOSX) {
        try {
          String homeLibraryFonts = System.getProperty("user.home") + "/Library/Fonts";
          mapper.insertDirectory(homeLibraryFonts);
        } catch (Exception e) {
          // might be a security issue with getProperty() and user.home
          // if this sketch is running from the web
        }
        // add the system font paths
        mapper.insertDirectory("/System/Library/Fonts");
        mapper.insertDirectory("/Library/Fonts");

      } else if (PApplet.platform == PApplet.WINDOWS) {
        // how to get the windows fonts directory?
        // could be c:\winnt\fonts or c:\windows\fonts or not even c:
        // maybe do a Runtime.exec() on echo %WINDIR% ?
        // Runtime.exec solution might be a mess on systems where the
        // the backslash/colon characters not really used (i.e. JP)

        // find the windows fonts folder
        File roots[] = File.listRoots();
        for (int i = 0; i < roots.length; i++) {
          if (roots[i].toString().startsWith("A:")) {
            // Seems to be a problem with some machines that the A:
            // drive is returned as an actual root, even if not available.
            // This won't fix the issue if the same thing happens with
            // other removable drive devices, but should fix the
            // initial/problem as cited by the bug report:
            // http://dev.processing.org/bugs/show_bug.cgi?id=478
            // If not, will need to use the other fileExists() code below.
            continue;
          }

          File folder = new File(roots[i], "WINDOWS/Fonts");
          if (folder.exists()) {
            mapper.insertDirectory(folder.getAbsolutePath());
            break;
          }
          folder = new File(roots[i], "WINNT/Fonts");
          if (folder.exists()) {
            mapper.insertDirectory(folder.getAbsolutePath());
            break;
          }
        }
      }
      //      System.out.println("mapping " + (System.currentTimeMillis() - t));
    }
    return mapper;
  }
コード例 #27
0
  public static void main(String[] args) {

    BackgroundEstimation estimation = new BolstadEMBackgroundEstimation();
    // BackgroundEstimation estimation = new UniformBackgroundEstimation();

    String key = args[0];

    WorkflowProperties props = new WorkflowProperties();
    File fplus = new File(props.getDirectory(), String.format("%s_plus.raw", key));
    File fminus = new File(props.getDirectory(), String.format("%s_negative.raw", key));

    // LogTransform transform = LogTransform.NONE;
    LogTransform transform = LogTransform.LOG_TO_EXP;

    BackgroundRemoval norm = new BackgroundRemoval(estimation, transform);

    try {
      System.out.println(String.format("Loading: %s", fplus.getName()));
      norm.load(new WorkflowDataLoader(fplus));
      System.out.println(String.format("Loading: %s", fminus.getName()));
      norm.load(new WorkflowDataLoader(fminus));

      WorkflowIndexing indexing = props.getIndexing(key);

      System.out.println(String.format("Removing background..."));
      norm.removeBackground();

      Filter<ProbeLine, ProbeLine> plus =
          new Filter<ProbeLine, ProbeLine>() {
            public ProbeLine execute(ProbeLine p) {
              return p.strand.equals("+") ? p : null;
            }
          };
      Filter<ProbeLine, ProbeLine> minus =
          new Filter<ProbeLine, ProbeLine>() {
            public ProbeLine execute(ProbeLine p) {
              return p.strand.equals("-") ? p : null;
            }
          };

      System.out.println(String.format("Outputting background-removed results..."));
      File plusOut = new File(props.getDirectory(), String.format("%s_plus.corrected", key));
      File minusOut = new File(props.getDirectory(), String.format("%s_negative.corrected", key));

      outputProbes(new FilterIterator<ProbeLine, ProbeLine>(plus, norm.iterator()), plusOut);
      System.out.println(String.format("\t%s", plusOut.getAbsolutePath()));

      outputProbes(new FilterIterator<ProbeLine, ProbeLine>(minus, norm.iterator()), minusOut);
      System.out.println(String.format("\t%s", minusOut.getAbsolutePath()));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #28
0
 public void addResource(File object) {
   ResourceModel rm = new ResourceModel();
   rm.setName(object.getName());
   rm.setFilePath(object.getAbsolutePath());
   String filePath = rm.getFilePath();
   if (filePath.endsWith(".jpeg") || filePath.endsWith(".gif")) rm.setDataType("Image");
   else if (filePath.endsWith(".au")) rm.setDataType("AudioStream");
   if (rm.getDataType().equals("Image")) rm.setImage(loadImage(object.getAbsolutePath()));
   else if (rm.getDataType().equals("AudioStream"))
     rm.setAudioStream(loadAudio(object.getAbsolutePath()));
   resources.put(rm.getName(), rm);
 }
コード例 #29
0
  /** Returns false if Exception is thrown. */
  private boolean setDirectory() {
    String pathStr = dirTF.getText().trim();
    if (pathStr.equals("")) pathStr = System.getProperty("user.dir");
    try {
      File dirPath = new File(pathStr);
      if (!dirPath.isDirectory()) {
        if (!dirPath.exists()) {
          if (recursiveCheckBox.isSelected())
            throw new NotDirectoryException(dirPath.getAbsolutePath());
          else throw new NotFileException(dirPath.getAbsolutePath());
        } else {
          convertSet.setFile(dirPath);
          convertSet.setDestinationPath(dirPath.getParentFile());
        }
      } else {
        // Set the descriptors
        setMatchingFileNames();

        FlexFilter flexFilter = new FlexFilter();
        flexFilter.addDescriptors(descriptors);
        flexFilter.setFilesOnly(!recursiveCheckBox.isSelected());

        convertSet.setSourcePath(dirPath, flexFilter);
        convertSet.setDestinationPath(dirPath);
      }
    } catch (NotDirectoryException e1) {
      final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption1");

      MessageFormat formatter;
      String info_msg;
      if (pathStr.equals("")) {
        info_msg = ResourceHandler.getMessage("notdirectory_dialog.info5");
      } else {
        formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info0"));
        info_msg = formatter.format(new Object[] {pathStr});
      }
      final String info = info_msg;

      JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE);
      return false;
    } catch (NotFileException e2) {
      final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption0");

      MessageFormat formatter =
          new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info1"));
      final String info = formatter.format(new Object[] {pathStr});

      JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE);
      return false;
    }

    return true; // no exception thrown
  }
コード例 #30
0
 String askForReadFilename() {
   int returnVal = sqlLoadChooser.showOpenDialog(this);
   if (returnVal == JFileChooser.APPROVE_OPTION) {
     File file = sqlLoadChooser.getSelectedFile();
     System.out.println("Selected read file " + file.getAbsolutePath());
     // return file.getName();
     return file.getAbsolutePath();
   } else {
     System.out.println("Open command cancelled by user.");
   }
   return null;
 }