示例#1
0
  public void run() throws Exception {
    File rtDir = new File("rt.dir");
    File javaHome = new File(System.getProperty("java.home"));
    if (javaHome.getName().equals("jre")) javaHome = javaHome.getParentFile();
    File rtJar = new File(new File(new File(javaHome, "jre"), "lib"), "rt.jar");
    expand(rtJar, rtDir);

    String[] rtDir_opts = {
      "-bootclasspath", rtDir.toString(),
      "-classpath", "",
      "-sourcepath", "",
      "-extdirs", ""
    };
    test(rtDir_opts, "HelloPathWorld");

    if (isJarFileSystemAvailable()) {
      String[] rtJar_opts = {
        "-bootclasspath", rtJar.toString(),
        "-classpath", "",
        "-sourcepath", "",
        "-extdirs", ""
      };
      test(rtJar_opts, "HelloPathWorld");

      String[] default_opts = {};
      test(default_opts, "HelloPathWorld");

      // finally, a non-trivial program
      test(default_opts, "CompileTest");
    } else System.err.println("jar file system not available: test skipped");
  }
示例#2
0
  /**
   * Construct a {@link SubProcessHeavy SubProcessHeavy} instance which when executed will fulfill
   * the given action agenda.
   *
   * <p>
   *
   * @param agenda The agenda to be accomplished by the action.
   * @param outFile The file to which all STDOUT output is redirected.
   * @param errFile The file to which all STDERR output is redirected.
   * @return The SubProcess which will fulfill the agenda.
   * @throws PipelineException If unable to prepare a SubProcess due to illegal, missing or
   *     imcompatable information in the action agenda or a general failure of the prep method code.
   */
  public SubProcessHeavy prep(ActionAgenda agenda, File outFile, File errFile)
      throws PipelineException {
    /* create the process to run the action */
    try {
      ArrayList<String> args = new ArrayList<String>();

      for (File file : agenda.getPrimaryTarget().getFiles()) args.add(file.toString());

      for (FileSeq fseq : agenda.getSecondaryTargets()) {
        for (File file : fseq.getFiles()) args.add(file.toString());
      }

      return new SubProcessHeavy(
          agenda.getNodeID().getAuthor(),
          getName() + "-" + agenda.getJobID(),
          "touch",
          args,
          agenda.getEnvironment(),
          agenda.getWorkingDir(),
          outFile,
          errFile);
    } catch (Exception ex) {
      throw new PipelineException(
          "Unable to generate the SubProcess to perform this Action!\n" + ex.getMessage());
    }
  }
  /**
   * Launch GIMP with a script which will compare the given two images using layers.
   *
   * <p>
   *
   * @param fileA The absolute path to the first file.
   * @param fileB The absolute path to the second file.
   * @param env The environment under which the comparator is run.
   * @param dir The working directory where the comparator is run.
   * @return The controlling <CODE>SubProcessLight</CODE> instance.
   * @throws PipelineException If unable to launch the comparator.
   * @see SubProcessLight
   */
  public SubProcessLight launch(File fileA, File fileB, Map<String, String> env, File dir)
      throws PipelineException {
    ArrayList<String> args = new ArrayList<String>();
    args.add(fileA.toString());
    args.add("-compare");
    args.add(fileB.toString());

    SubProcessLight proc = new SubProcessLight(getName(), getProgram(), args, env, dir);
    proc.start();

    return proc;
  }
    @Override
    public void run() {
      // long startTime = System.nanoTime();
      synchronized (configFile) {
        if (pendingDiskWrites.get() > 1) {
          // Writes can be skipped, because they are stored in a queue (in the executor).
          // Only the last is actually written.
          pendingDiskWrites.decrementAndGet();
          // LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() -
          // startTime) + " nsec.");
          return;
        }
        try {
          Files.createParentDirs(configFile);

          if (!configFile.exists()) {
            try {
              LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString()));
              if (!configFile.createNewFile()) {
                LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
                return;
              }
            } catch (IOException ex) {
              LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex);
              return;
            }
          }

          final FileOutputStream fos = new FileOutputStream(configFile);
          try {
            final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8);

            try {
              writer.write(data);
            } finally {
              writer.close();
            }
          } finally {
            fos.close();
          }
        } catch (IOException e) {
          LOGGER.log(Level.SEVERE, e.getMessage(), e);
        } finally {
          // LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() -
          // startTime) + " nsec.");
          pendingDiskWrites.decrementAndGet();
        }
      }
    }
 public FSDir(File dir) throws IOException {
   this.dir = dir;
   this.children = null;
   if (!dir.exists()) {
     if (!dir.mkdirs()) {
       throw new IOException("Mkdirs failed to create " + dir.toString());
     }
   } else {
     File[] files = dir.listFiles();
     int numChildren = 0;
     for (int idx = 0; idx < files.length; idx++) {
       if (files[idx].isDirectory()) {
         numChildren++;
       } else if (Block.isBlockFilename(files[idx])) {
         numBlocks++;
       }
     }
     if (numChildren > 0) {
       children = new FSDir[numChildren];
       int curdir = 0;
       for (int idx = 0; idx < files.length; idx++) {
         if (files[idx].isDirectory()) {
           children[curdir] = new FSDir(files[idx]);
           curdir++;
         }
       }
     }
   }
 }
示例#6
0
  void ReceiveFile() throws Exception {
    String fileName;

    fileName = din.readUTF();

    if (fileName != null && !fileName.equals("NOFILE")) {
      System.out.println("Receiving File");
      File f =
          new File(
              System.getProperty("user.home")
                  + "/Desktop"
                  + "/"
                  + fileName.substring(fileName.lastIndexOf("/") + 1));
      System.out.println(f.toString());
      f.createNewFile();
      FileOutputStream fout = new FileOutputStream(f);
      int ch;
      String temp;
      do {
        temp = din.readUTF();
        ch = Integer.parseInt(temp);
        if (ch != -1) {
          fout.write(ch);
        }
      } while (ch != -1);
      System.out.println("Received File : " + fileName);
      fout.close();
    } else {
    }
  }
  /**
   * Add fully-resolved directories (with filters) to the current class path.
   *
   * @param baseList is the list of library directories.
   * @param filterList is the corresponding list of filters.
   */
  protected void addDirsToClassPath(File[] baseList, FileFilter[] filterList)
      throws ManifoldCFException {
    int i = 0;
    while (i < baseList.length) {
      File base = baseList[i];
      FileFilter filter;
      if (filterList != null) filter = filterList[i];
      else filter = null;

      if (base.canRead() && base.isDirectory()) {
        File[] files = base.listFiles(filter);

        if (files != null && files.length > 0) {
          int j = 0;
          while (j < files.length) {
            File file = files[j++];
            currentClasspath.add(file);
            // Invalidate the current classloader
            classLoader = null;
          }
        }
      } else
        throw new ManifoldCFException(
            "Supposed directory '"
                + base.toString()
                + "' is either not a directory, or is unreadable.");
      i++;
    }
  }
  public ShelvedChangeList importFilePatches(
      final String fileName, final List<FilePatch> patches, final PatchEP[] patchTransitExtensions)
      throws IOException {
    try {
      final File patchPath = getPatchPath(fileName);
      myFileProcessor.savePathFile(
          new CompoundShelfFileProcessor.ContentProvider() {
            public void writeContentTo(final Writer writer, CommitContext commitContext)
                throws IOException {
              UnifiedDiffWriter.write(
                  myProject, patches, writer, "\n", patchTransitExtensions, commitContext);
            }
          },
          patchPath,
          new CommitContext());

      final ShelvedChangeList changeList =
          new ShelvedChangeList(
              patchPath.toString(),
              fileName.replace('\n', ' '),
              new SmartList<ShelvedBinaryFile>());
      myShelvedChangeLists.add(changeList);
      return changeList;
    } finally {
      notifyStateChanged();
    }
  }
示例#9
0
  /**
   * Maps a servlet-like URI to a jxp file.
   *
   * @param f File to check
   * @return new File with <root>.jxp if exists, orig file if not
   * @example /wiki/geir -> maps to wiki.jxp if exists
   */
  File tryServlet(File f) {
    if (f.exists()) return f;

    String uri = f.toString();

    if (uri.startsWith(_rootFile.toString())) uri = uri.substring(_rootFile.toString().length());

    if (_core != null && uri.startsWith(_core._base.toString()))
      uri = "/~~" + uri.substring(_core._base.toString().length());

    while (uri.startsWith("/")) uri = uri.substring(1);

    int start = 0;
    while (true) {

      int idx = uri.indexOf("/", start);
      if (idx < 0) break;
      String foo = uri.substring(0, idx);

      File temp = getFileSafe(foo + ".jxp");

      if (temp != null && temp.exists()) f = temp;

      start = idx + 1;
    }

    return f;
  }
示例#10
0
  private FileType fileExtensionCheck(File inFile, FileType previousFileType) {
    final String inFileName = inFile.toString().toLowerCase();

    if (inFileName.endsWith(".vcf")) {
      if (previousFileType == FileType.VCF || previousFileType == null) {
        return FileType.VCF;
      }
    }

    if (inFileName.endsWith(".bcf")) {
      if (previousFileType == FileType.BCF || previousFileType == null) {
        return FileType.BCF;
      }
    }

    for (String extension : AbstractFeatureReader.BLOCK_COMPRESSED_EXTENSIONS) {
      if (inFileName.endsWith(".vcf" + extension)) {
        if (previousFileType == FileType.BLOCK_COMPRESSED_VCF || previousFileType == null) {
          return FileType.BLOCK_COMPRESSED_VCF;
        }
      }
    }

    System.err.println(
        String.format("File extension for input file %s is not valid for CatVariants", inFile));
    printUsage();
    return FileType.INVALID;
  }
示例#11
0
 /**
  * Copy the given directory contents from the source package directory to the generated
  * documentation directory. For example for a package java.lang this method find out the source
  * location of the package using {@link SourcePath} and if given directory is found in the source
  * directory structure, copy the entire directory, to the generated documentation hierarchy.
  *
  * @param configuration The configuration of the current doclet.
  * @param path The relative path to the directory to be copied.
  * @param dir The original directory name to copy from.
  * @param overwrite Overwrite files if true.
  */
 public static void copyDocFiles(
     Configuration configuration, String path, String dir, boolean overwrite) {
   if (checkCopyDocFilesErrors(configuration, path, dir)) {
     return;
   }
   String destname = configuration.docFileDestDirName;
   File srcdir = new File(path + dir);
   if (destname.length() > 0 && !destname.endsWith(DirectoryManager.URL_FILE_SEPERATOR)) {
     destname += DirectoryManager.URL_FILE_SEPERATOR;
   }
   String dest = destname + dir;
   try {
     File destdir = new File(dest);
     DirectoryManager.createDirectory(configuration, dest);
     String[] files = srcdir.list();
     for (int i = 0; i < files.length; i++) {
       File srcfile = new File(srcdir, files[i]);
       File destfile = new File(destdir, files[i]);
       if (srcfile.isFile()) {
         if (destfile.exists() && !overwrite) {
           configuration.message.warning(
               (SourcePosition) null,
               "doclet.Copy_Overwrite_warning",
               srcfile.toString(),
               destdir.toString());
         } else {
           configuration.message.notice(
               "doclet.Copying_File_0_To_Dir_1", srcfile.toString(), destdir.toString());
           Util.copyFile(destfile, srcfile);
         }
       } else if (srcfile.isDirectory()) {
         if (configuration.copydocfilesubdirs
             && !configuration.shouldExcludeDocFileDir(srcfile.getName())) {
           copyDocFiles(
               configuration,
               path,
               dir + DirectoryManager.URL_FILE_SEPERATOR + srcfile.getName(),
               overwrite);
         }
       }
     }
   } catch (SecurityException exc) {
     throw new DocletAbortException();
   } catch (IOException exc) {
     throw new DocletAbortException();
   }
 }
示例#12
0
  public Template(File file) throws Exception {
    if (file.length() > maxF) tools.util.LogMgr.red(file.length() + " Large Size Template " + file);

    String templ = new String(SharedMethods.getBytesFromFile(file));
    m_template = new StringBuffer(templ);
    m_template2 = new StringBuffer(templ);
    m_file = file.toString();
  }
  public static void main(String[] args) {
    File root = new File("z:/a/b/c/d");
    File t1 = new File("z:/a/b/e/f");
    File t2 = new File("c:/t/r");
    File t3 = new File("z:/a/b/c/d/i/m");
    File t4 = new File("z:/a/b/c/d");

    System.out.println("Rel root, t1: " + makePathRelativeIfPossible(root, t1));
    System.out.println("Rel root, t2: " + makePathRelativeIfPossible(root, t2));
    System.out.println("Rel root, t3: " + makePathRelativeIfPossible(root, t3));
    System.out.println("Rel root, t4: " + makePathRelativeIfPossible(root, t4));

    File f1 = new File("f:\\a\\b");
    File f2 = new File("f:\\a\\c");
    File f3 = new File(f1, f2.toString());
    System.out.println("f3 = " + f3.toString());
  }
示例#14
0
  /**
   * Tries to find the given file, assuming that it's missing the ".jxp" extension
   *
   * @param f File to check
   * @return same file if not found to be missing the .jxp, or a new File w/ the .jxp appended
   */
  File tryNoJXP(File f) {
    if (f.exists()) return f;

    if (f.getName().indexOf(".") >= 0) return f;

    File temp = new File(f.toString() + ".jxp");
    return temp.exists() ? temp : f;
  }
示例#15
0
  public static void main(String[] args) {

    if (args.length == 1) {
      try {
        File f = new File(args[0]);
        if (f.isDirectory()) {
          TreeMap<Integer, LinkedList<String>> levels;
          levels = new TreeMap<Integer, LinkedList<String>>();
          File[] fl = f.listFiles();
          for (int x = 0; x < fl.length; x++) {
            File t = fl[x];
            if (t.isFile()) {
              FileInputStream is = new FileInputStream(t);
              int[] board = LevelIO.read(is);
              final int s = LevelStats.computeScore(board);
              System.out.println(t.toString() + " -> " + Integer.toString(s));
              LinkedList<String> strs = levels.get(s);
              if (strs != null) {
                strs.add(t.toString());
              } else {
                strs = new LinkedList<String>();
                strs.add(t.toString());
                levels.put(s, strs);
              }
            }
          }
          System.out.println("Sorted levels:");
          while (!levels.isEmpty()) {
            Integer score = levels.firstKey();
            Iterator<String> it = levels.remove(score).iterator();
            while (it.hasNext()) {
              String fn = it.next();
              System.out.println(fn + " -> " + score.toString());
            }
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      return;
    }

    LevelEditor editor = new LevelEditor();
    editor.show();
  }
  private DbJVPackage importFiles(Controller controller, int startJobDone, int endJobDone)
      throws IOException, DbException {
    controller.checkPoint(startJobDone);
    DbJVPackage topMostPackage = null;

    List<File> filesToImport = m_params.getFilesToImport();
    List<ErrorReport> errorLog = new ArrayList<ErrorReport>();

    int i = 0, nb = filesToImport.size();

    String pattern = LocaleMgr.misc.getString("ThereAreNbFilesToImport");
    String msg = MessageFormat.format(pattern, nb);
    controller.println(msg);
    int span = endJobDone - startJobDone;

    for (File file : filesToImport) {
      String filename = file.toString();
      int idx = filename.lastIndexOf('.');
      String ext = (idx == -1) ? null : filename.substring(idx + 1);
      int jobDone = startJobDone + (i * span) / nb;

      try {
        if ("class".equals(ext)) {
          DbJVClass claz = importClassFile(filename, controller);
          if (claz != null) {
            DbJVPackage pack = (DbJVPackage) claz.getCompositeOfType(DbJVPackage.metaClass);
            topMostPackage = findTopMostPackage(topMostPackage, pack);
            addToImportedPackage(pack);
          } // end if
        } else if ("jar".equals(ext)) {
          int nextJobDone = startJobDone + ((i + 1) * span) / nb;
          topMostPackage = importJarFile(file, topMostPackage, controller, jobDone, nextJobDone);
        } // end if
      } catch (Throwable th) {
        ErrorReport report = new ErrorReport(file, th);
        errorLog.add(report);
        controller.incrementErrorsCounter();
      } // end try

      // check job done
      i++;
      controller.checkPoint(jobDone);

      // stop to reverse engineer if user has cancelled
      boolean finished = controller.isFinalState();
      if (finished) {
        break;
      }
    } // end for

    if (!errorLog.isEmpty()) {
      reportErrors(errorLog, controller);
    } // end if

    controller.checkPoint(endJobDone);
    return topMostPackage;
  } // end importFiles()
示例#17
0
  public void jButton1_actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(parent);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File file = fc.getSelectedFile();
      jTextField1.setText(file.toString());
    }
  }
  public ShelvedChangeList shelveChanges(
      final Collection<Change> changes, final String commitMessage, final boolean rollback)
      throws IOException, VcsException {
    final List<Change> textChanges = new ArrayList<Change>();
    final List<ShelvedBinaryFile> binaryFiles = new ArrayList<ShelvedBinaryFile>();
    for (Change change : changes) {
      if (ChangesUtil.getFilePath(change).isDirectory()) {
        continue;
      }
      if (change.getBeforeRevision() instanceof BinaryContentRevision
          || change.getAfterRevision() instanceof BinaryContentRevision) {
        binaryFiles.add(shelveBinaryFile(change));
      } else {
        textChanges.add(change);
      }
    }

    final ShelvedChangeList changeList;
    try {
      File patchPath = getPatchPath(commitMessage);
      ProgressManager.checkCanceled();
      final List<FilePatch> patches =
          IdeaTextPatchBuilder.buildPatch(
              myProject, textChanges, myProject.getBaseDir().getPresentableUrl(), false);
      ProgressManager.checkCanceled();

      CommitContext commitContext = new CommitContext();
      baseRevisionsOfDvcsIntoContext(textChanges, commitContext);
      myFileProcessor.savePathFile(
          new CompoundShelfFileProcessor.ContentProvider() {
            public void writeContentTo(final Writer writer, CommitContext commitContext)
                throws IOException {
              UnifiedDiffWriter.write(myProject, patches, writer, "\n", commitContext);
            }
          },
          patchPath,
          commitContext);

      changeList =
          new ShelvedChangeList(
              patchPath.toString(), commitMessage.replace('\n', ' '), binaryFiles);
      myShelvedChangeLists.add(changeList);
      ProgressManager.checkCanceled();

      if (rollback) {
        new RollbackWorker(myProject, false)
            .doRollback(changes, true, null, VcsBundle.message("shelve.changes.action"));
      }
    } finally {
      notifyStateChanged();
    }

    return changeList;
  }
示例#19
0
 public static void openPlaylist(File sanou) throws Exception {
   if (logger.isDebugEnabled()) logger.debug("Open playlist.");
   if (Lecteur.CURRENTPLAYLIST.isEmpty()) {
     savePlaylist("Current Playlist isn't save ; to save now Enter the Playlist Name");
     new File(Lecteur.CURRENTPLAYLIST.NAME + ".dec").delete();
     copy(sanou, new File(Lecteur.CURRENTPLAYLIST.NAME));
   } else {
     copy(sanou, new File(Lecteur.CURRENTPLAYLIST.NAME));
   }
   currentNAME = sanou.toString();
 }
 public static void searchDirectoryByName(
     String baseDir, ArrayList<String> directoryLists, String dirName) {
   File sampleName = new File(baseDir);
   File[] fileArray = sampleName.listFiles();
   if (fileArray != null) {
     for (int i = 0; i < fileArray.length; i++) {
       File name = fileArray[i];
       if (name.isDirectory()) {
         if (name.toString()
             .subSequence(name.toString().lastIndexOf("/"), name.toString().length())
             .equals(dirName)) {
           directoryLists.add(name.getAbsolutePath());
         }
         searchDirectoryByName(fileArray[i].getAbsolutePath(), directoryLists, dirName);
       } else if (fileArray.length == i) {
         return;
       }
     }
   }
 }
示例#21
0
  public static void downloadFile(String url, File output, boolean verbose)
      throws java.lang.Exception {
    final URL website = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(output);
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    fos.close();

    if (verbose) {
      TFM_Log.info("Downloaded " + url + " to " + output.toString() + ".");
    }
  }
示例#22
0
  File tryOtherExtensions(File f) {
    if (f.exists()) return f;

    if (f.getName().indexOf(".") >= 0) return f;

    for (int i = 0; i < JSFileLibrary._srcExtensions.length; i++) {
      File temp = new File(f.toString() + JSFileLibrary._srcExtensions[i]);
      if (temp.exists()) return temp;
    }

    return f;
  }
示例#23
0
文件: CA.java 项目: jkwhite/nausicaa
 public void save(File file) throws IOException {
   if (file.getName().endsWith(".gif")) {
     ImageIO.write(_i, "png", file);
   } else if (file.getName().endsWith(".jpg")) {
     ImageIO.write(_i, "jpg", file);
   } else {
     if (!file.getName().endsWith(".png")) {
       file = new File(file.toString() + ".png");
     }
     ImageIO.write(_i, "png", file);
   }
 }
示例#24
0
文件: OpenFileDir.java 项目: NCIP/dwd
  /**
   * Use a JFileChooser in Save mode to select files to open. Use a filter for FileFilter subclass
   * to select for "*.java" files. If a file is selected, then this file will be used as final
   * output
   */
  boolean saveFile() {
    File file = null;
    JFileChooser fc = new JFileChooser();

    // Start in current directory
    fc.setCurrentDirectory(new File("."));

    // Set filter for Java source files.
    fc.setFileFilter(fJavaFilter);

    // Set to a default name for save.
    fc.setSelectedFile(fFile);

    // Open chooser dialog
    int result = fc.showSaveDialog(this);

    if (result == JFileChooser.CANCEL_OPTION) {
      return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
      fFile = fc.getSelectedFile();
      String textFile = fFile.toString();
      if (fileNo.equalsIgnoreCase("SAVE")) {
        UpLoadFile.outputfile.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVE2")) {
        UpLoadMAGEMLFile.outputfile1.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVE3")) {
        UpLoadMAGEMLFile.outputfile2.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVEJPAG")) {
        JPEGFileName = textFile;
        // System.out.println ("JPG filename OpenFileDir= " +JPEGFileName);
        File fFile = new File(JPEGFileName);
        if (fFile.exists()) {
          int response =
              JOptionPane.showConfirmDialog(
                  null,
                  "Overwrite existing file " + JPEGFileName + " ??",
                  "Confirm Overwrite",
                  JOptionPane.OK_CANCEL_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
          if (response == JOptionPane.CANCEL_OPTION) {
            /* go back to reload the file*/
            return false;
          }
        }
        SetUpPlotWindow.saveComponentAsJPEG(SetUpPlotWindow.content, JPEGFileName);
      }
      return true;

    } else {
      return false;
    }
  } // saveFile
示例#25
0
  public void runNext() throws TestFailException, UnsupportedEncodingException {
    // Get first file and remove it from list
    InputOutput current = inputOutput.remove(0);
    // Create List with only first input in
    List<String> inputFiles = new ArrayList<String>();
    inputFiles.add(null != commonInputFile ? commonInputFile : current.getName() + ".input");
    // Excute Main on that input
    List<String> cmdLine = new ArrayList<String>();
    cmdLine.add("--encoding");
    cmdLine.add(inputFileEncoding);
    classExecResult =
        Exec.execClass(
            className,
            testPath.toString(),
            cmdLine,
            inputFiles,
            Main.jflexTestVersion,
            outputFileEncoding);
    if (Main.verbose) {
      System.out.println("Running scanner on [" + current.getName() + "]");
    }

    // check for output conformance
    File expected = new File(current.getName() + ".output");

    if (expected.exists()) {
      DiffStream check = new DiffStream();
      String diff;
      try {
        diff =
            check.diff(
                jflexDiff,
                new StringReader(classExecResult.getOutput()),
                new InputStreamReader(new FileInputStream(expected), outputFileEncoding));
      } catch (FileNotFoundException e) {
        System.out.println("Error opening file " + expected);
        throw new TestFailException();
      } catch (UnsupportedEncodingException e) {
        System.out.println("Unsupported encoding '" + outputFileEncoding + "'");
        throw new TestFailException();
      }
      if (diff != null) {
        System.out.println("Test failed, unexpected output: " + diff);
        System.out.println("Test output: " + classExecResult.getOutput());
        throw new TestFailException();
      }
    } else {
      System.out.println("Warning: no file for expected output [" + expected + "]");
    }

    // System.out.println(classExecResult);
  }
示例#26
0
文件: OpenFileDir.java 项目: NCIP/dwd
  /*
   * This function just finds and loads the file
   */
  private boolean loadFile() {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Load File");

    // Choose only files, not directories
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

    // Start in current directory
    fc.setCurrentDirectory(new File("."));

    // Set filter for Java source files.
    fc.setFileFilter(fJavaFilter);

    // Now open chooser
    int result = fc.showOpenDialog(this);

    if (result == JFileChooser.CANCEL_OPTION) {
      // return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {

      fFile = fc.getSelectedFile();
      String textFile = fFile.toString();

      if (fileNo.equalsIgnoreCase("LOAD1")) {
        UpLoadFile.filePath1.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("LOAD2")) {
        UpLoadFile.filePath2.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("LOAD3")) {
        VisualizationInput.originalFilePath.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("LOAD4")) {
        VisualizationInput.DWDVecFilePath.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("LOAD5")) {
        VisualizationInput.DWDOutputFilePath.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("LOAD6")) {
        UpLoadMAGEMLFile.filePath1.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("LOAD7")) {
        UpLoadMAGEMLFile.filePath2.setText(textFile);
      }

      // Get the absolute path for the file being opened
      filePath = fFile.getAbsolutePath();

      if (filePath == null) {
        // fTextField.setText (filePath);
        return false;
      }

    } else {
      return false;
    }
    return true;
  } /*End of loadFile*/
    FSVolume(File currentDir, Configuration conf) throws IOException {
      this.reserved = conf.getLong("dfs.datanode.du.reserved", 0);
      boolean supportAppends = conf.getBoolean("dfs.support.append", false);
      File parent = currentDir.getParentFile();

      this.detachDir = new File(parent, "detach");
      if (detachDir.exists()) {
        recoverDetachedBlocks(currentDir, detachDir);
      }

      // Files that were being written when the datanode was last shutdown
      // are now moved back to the data directory. It is possible that
      // in the future, we might want to do some sort of datanode-local
      // recovery for these blocks. For example, crc validation.
      //
      this.tmpDir = new File(parent, "tmp");
      if (tmpDir.exists()) {
        if (supportAppends) {
          recoverDetachedBlocks(currentDir, tmpDir);
        } else {
          FileUtil.fullyDelete(tmpDir);
        }
      }
      this.dataDir = new FSDir(currentDir);
      if (!tmpDir.mkdirs()) {
        if (!tmpDir.isDirectory()) {
          throw new IOException("Mkdirs failed to create " + tmpDir.toString());
        }
      }
      if (!detachDir.mkdirs()) {
        if (!detachDir.isDirectory()) {
          throw new IOException("Mkdirs failed to create " + detachDir.toString());
        }
      }
      this.usage = new DF(parent, conf);
      this.dfsUsage = new DU(parent, conf);
      this.dfsUsage.start();
    }
示例#28
0
  /**
   * Generate an ant script that can be run to generate final p2 metadata for a product. Returns
   * null if p2 bundles aren't available.
   *
   * <p>If no product file is given, the generated p2 call generates final metadata for a
   * ${p2.root.name}_${p2.root.version} IU.
   *
   * <p>versionAdvice is a properties file with bsn=3.2.1.xyz entries
   *
   * @param workingDir - the directory in which to generate the script
   * @param productFileLocation - the location of a .product file (can be null)
   * @param versionAdvice - version advice (can be null)
   * @return The location of the generated script, or null
   * @throws CoreException
   */
  public static String generateP2ProductScript(
      String workingDir, String productFileLocation, Properties versionAdvice)
      throws CoreException {
    if (!loadP2Class()) return null;

    File working = new File(workingDir);
    working.mkdirs();

    File adviceFile = null;
    if (versionAdvice != null) {
      adviceFile = new File(working, "versionAdvice.properties"); // $NON-NLS-1$
      try {
        OutputStream os = new BufferedOutputStream(new FileOutputStream(adviceFile));
        try {
          versionAdvice.store(os, null);
        } finally {
          os.close();
        }
      } catch (IOException e) {
        String message = NLS.bind(Messages.exception_writingFile, adviceFile.toString());
        throw new CoreException(
            new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_WRITING_FILE, message, e));
      }
    }

    AntScript p2Script = null;
    try {
      p2Script = newAntScript(workingDir, "p2product.xml"); // $NON-NLS-1$
      p2Script.printProjectDeclaration(
          "P2 Product IU Generation", "main", "."); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      p2Script.println();
      p2Script.printProperty(PROPERTY_P2_APPEND, "true"); // $NON-NLS-1$
      p2Script.printProperty(PROPERTY_P2_COMPRESS, "false"); // $NON-NLS-1$
      p2Script.printProperty(PROPERTY_P2_METADATA_REPO_NAME, ""); // $NON-NLS-1$
      p2Script.printProperty(PROPERTY_P2_ARTIFACT_REPO_NAME, ""); // $NON-NLS-1$
      p2Script.printTargetDeclaration(
          "main",
          null,
          TARGET_P2_METADATA,
          null,
          "Generate the final Product IU"); //$NON-NLS-1$//$NON-NLS-2$
      generateP2FinalCall(
          p2Script, productFileLocation, adviceFile != null ? adviceFile.getAbsolutePath() : null);
      p2Script.printTargetEnd();
      p2Script.printProjectEnd();
    } finally {
      if (p2Script != null) p2Script.close();
    }
    return workingDir + "/p2product.xml"; // $NON-NLS-1$
  }
示例#29
0
 public static void saveAsPlaylist(String message) throws Exception {
   if (logger.isDebugEnabled()) logger.debug("Save as playlist.");
   String s = GUI.messageDialog2(message);
   if (s != null) {
     String s2 =
         Lecteur.CURRENTPLAYLIST.NAME.substring(0, Lecteur.CURRENTPLAYLIST.NAME.length() - 19);
     String sa = s2 + s + ".pl";
     File f = new File(sa);
     copy(new File(Lecteur.CURRENTPLAYLIST.NAME), f);
     currentNAME = f.toString();
     GUI.getInstance().createOpenItem(sa);
     GUI.getInstance().createdeleteItem(sa);
   }
 }
示例#30
0
 public void testCreateIllProv() throws Exception {
   File dir = getTempDir();
   File file = new File(dir, "test.ks");
   Properties p = initProps();
   p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString());
   p.put(KeyStoreUtil.PROP_KEYSTORE_TYPE, "JKS");
   p.put(KeyStoreUtil.PROP_KEYSTORE_PROVIDER, "not_a_provider");
   assertFalse(file.exists());
   try {
     KeyStoreUtil.createKeyStore(p);
     fail("Illegal keystore type should throw");
   } catch (NoSuchProviderException e) {
   }
   assertFalse(file.exists());
 }