Ejemplo n.º 1
1
  @Parameters(name = "js={0}, opt={3}, strict={4}")
  public static Collection<Object[]> test262SuiteValues() throws IOException {
    List<Object[]> result = new ArrayList<Object[]>();
    List<File> tests = getTestFiles();
    for (File jsTest : tests) {
      String jsFileStr = (String) SourceReader.readFileOrUrl(jsTest.getPath(), true, "UTF-8");
      List<String> harnessFiles = new ArrayList<String>();
      harnessFiles.add("sta.js");
      harnessFiles.add("assert.js");

      Map header =
          (Map)
              YAML.load(
                  jsFileStr.substring(
                      jsFileStr.indexOf("/*---") + 5, jsFileStr.lastIndexOf("---*/")));
      if (header.containsKey("includes")) {
        harnessFiles.addAll((Collection) header.get("includes"));
      }

      EcmaErrorType errorType = EcmaErrorType._valueOf((String) header.get("negative"));
      List<String> flags =
          header.containsKey("flags") ? (List<String>) header.get("flags") : Collections.EMPTY_LIST;
      for (int optLevel : OPT_LEVELS) {
        if (!flags.contains("onlyStrict")) {
          result.add(
              new Object[] {jsTest.getPath(), jsFileStr, harnessFiles, optLevel, false, errorType});
        }
        if (!flags.contains("noStrict")) {
          result.add(
              new Object[] {jsTest.getPath(), jsFileStr, harnessFiles, optLevel, true, errorType});
        }
      }
    }
    return result;
  }
Ejemplo n.º 2
1
  protected Header readHeaderFromBuffer(ByteBuffer buffer) throws WWRuntimeException {
    // Read file code - first byte
    int fileCode = buffer.get();
    if (fileCode > 5) {
      String message = Logging.getMessage("SHP.NotADBaseFile", file.getPath());
      Logging.logger().log(java.util.logging.Level.SEVERE, message);
      throw new WWRuntimeException(message);
    }

    // Last update date
    int yy = 0xFF & buffer.get(); // unsigned
    int mm = buffer.get();
    int dd = buffer.get();

    // Number of records
    int numRecords = buffer.getInt();

    // Header struct length
    int headerLength = buffer.getShort();

    // Record length
    int recordLength = buffer.getShort();

    // Assemble header
    Header header = new Header();
    header.fileCode = fileCode;
    Calendar cal = Calendar.getInstance();
    cal.set(1900 + yy, mm - 1, dd);
    header.lastModificationDate = cal.getTime();
    header.numberOfRecords = numRecords;
    header.headerLength = headerLength;
    header.recordLength = recordLength;

    return header;
  }
 public static void copyDir(
     @NotNull File fromDir, @NotNull File toDir, @Nullable final FileFilter filter)
     throws IOException {
   ensureExists(toDir);
   if (isAncestor(fromDir, toDir, true)) {
     LOG.error(fromDir.getAbsolutePath() + " is ancestor of " + toDir + ". Can't copy to itself.");
     return;
   }
   File[] files = fromDir.listFiles();
   if (files == null)
     throw new IOException(
         CommonBundle.message("exception.directory.is.invalid", fromDir.getPath()));
   if (!fromDir.canRead())
     throw new IOException(
         CommonBundle.message("exception.directory.is.not.readable", fromDir.getPath()));
   for (File file : files) {
     if (filter != null && !filter.accept(file)) {
       continue;
     }
     if (file.isDirectory()) {
       copyDir(file, new File(toDir, file.getName()), filter);
     } else {
       copy(file, new File(toDir, file.getName()));
     }
   }
 }
Ejemplo n.º 4
0
  /**
   * given a list of sequences, creates a db for use with blat
   *
   * @param seqList is the list of sequences to create the database with
   * @return the full path of the location of the database
   */
  private String dumpToFile(Map<String, String> seqList) {

    File tmpdir;
    BufferedWriter out;
    File seqFile = null;

    /*
    open temp file
     */
    try {
      seqFile = new File(tmpDirFile, "reads.fa");
      out = new BufferedWriter(new FileWriter(seqFile.getPath()));

      /*
      write out the sequences to file
      */
      for (String key : seqList.keySet()) {
        assert (seqList.get(key) != null);
        out.write(">" + key + "\n");
        out.write(seqList.get(key) + "\n");
      }

      /*
      close temp file
       */
      out.close();

    } catch (Exception e) {
      log.error(e);
      return null;
    }

    return seqFile.getPath();
  }
  /**
   * Scan all output dirs for artifacts and remove those files (artifacts?) that are not recognized
   * as such, in the javac_state file.
   */
  public void removeUnidentifiedArtifacts() {
    Set<File> allKnownArtifacts = new HashSet<>();
    for (Package pkg : prev.packages().values()) {
      for (File f : pkg.artifacts().values()) {
        allKnownArtifacts.add(f);
      }
    }
    // Do not forget about javac_state....
    allKnownArtifacts.add(javacState);

    for (File f : binArtifacts) {
      if (!allKnownArtifacts.contains(f)) {
        Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state.");
        f.delete();
      }
    }
    for (File f : headerArtifacts) {
      if (!allKnownArtifacts.contains(f)) {
        Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state.");
        f.delete();
      }
    }
    for (File f : gensrcArtifacts) {
      if (!allKnownArtifacts.contains(f)) {
        Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state.");
        f.delete();
      }
    }
  }
Ejemplo n.º 6
0
 /**
  * Expands list of files to process into full list of all files that can be found by recursively
  * descending directories.
  */
 void expand(File dir, String[] files, boolean isUpdate) {
   if (files == null) {
     return;
   }
   for (int i = 0; i < files.length; i++) {
     File f;
     if (dir == null) {
       f = new File(files[i]);
     } else {
       f = new File(dir, files[i]);
     }
     if (f.isFile()) {
       if (entries.add(f)) {
         if (isUpdate) entryMap.put(entryName(f.getPath()), f);
       }
     } else if (f.isDirectory()) {
       if (entries.add(f)) {
         if (isUpdate) {
           String dirPath = f.getPath();
           dirPath = (dirPath.endsWith(File.separator)) ? dirPath : (dirPath + File.separator);
           entryMap.put(entryName(dirPath), f);
         }
         expand(f, f.list(), isUpdate);
       }
     } else {
       error(formatMsg("error.nosuch.fileordir", String.valueOf(f)));
       ok = false;
     }
   }
 }
Ejemplo n.º 7
0
  public static void copyDirectory(
      File source, File destination, boolean hardLinks, FileFilter filter) {
    if (source.exists() && source.isDirectory()) {
      if (!destination.exists()) {
        destination.mkdirs();
      }

      File[] fileArray = filter != null ? source.listFiles(filter) : source.listFiles();

      for (int i = 0; i < fileArray.length; i++) {
        if (fileArray[i].getName().endsWith("xml")) {
          String name = fileArray[i].getName();
          Logger.info(FileUtil.class, "copy " + name);
        }

        if (fileArray[i].isDirectory()) {
          copyDirectory(
              fileArray[i],
              new File(destination.getPath() + File.separator + fileArray[i].getName()),
              hardLinks,
              filter);
        } else {
          copyFile(
              fileArray[i],
              new File(destination.getPath() + File.separator + fileArray[i].getName()),
              hardLinks);
        }
      }
    }
  }
Ejemplo n.º 8
0
  /**
   * copies a file from DFS to local working directory
   *
   * @param dfsPath is the pathname to a file in DFS
   * @return the path of the new file in local scratch space
   * @throws IOException if it can't access the files
   */
  private String copyDBFile(String dfsPath) throws IOException {

    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);

    Path filenamePath = new Path(dfsPath);
    File localFile = new File(tmpDirFile, filenamePath.getName());

    if (!fs.exists(filenamePath)) {
      throw new IOException("file not found: " + dfsPath);
    }

    FSDataInputStream in = fs.open(filenamePath);
    BufferedReader d = new BufferedReader(new InputStreamReader(in));

    BufferedWriter out = new BufferedWriter(new FileWriter(localFile.getPath()));

    String line;
    line = d.readLine();

    while (line != null) {
      out.write(line + "\n");
      line = d.readLine();
    }
    in.close();
    out.close();

    return localFile.getPath();
  }
 // Allows tests to have more control over when directories are cleaned up.
 @VisibleForTesting
 ExternalShuffleBlockResolver(
     TransportConf conf, File registeredExecutorFile, Executor directoryCleaner)
     throws IOException {
   this.conf = conf;
   this.registeredExecutorFile = registeredExecutorFile;
   if (registeredExecutorFile != null) {
     Options options = new Options();
     options.createIfMissing(false);
     options.logger(new LevelDBLogger());
     DB tmpDb;
     try {
       tmpDb = JniDBFactory.factory.open(registeredExecutorFile, options);
     } catch (NativeDB.DBException e) {
       if (e.isNotFound() || e.getMessage().contains(" does not exist ")) {
         logger.info("Creating state database at " + registeredExecutorFile);
         options.createIfMissing(true);
         try {
           tmpDb = JniDBFactory.factory.open(registeredExecutorFile, options);
         } catch (NativeDB.DBException dbExc) {
           throw new IOException("Unable to create state store", dbExc);
         }
       } else {
         // the leveldb file seems to be corrupt somehow.  Lets just blow it away and create a new
         // one, so we can keep processing new apps
         logger.error(
             "error opening leveldb file {}.  Creating new file, will not be able to "
                 + "recover state for existing applications",
             registeredExecutorFile,
             e);
         if (registeredExecutorFile.isDirectory()) {
           for (File f : registeredExecutorFile.listFiles()) {
             if (!f.delete()) {
               logger.warn("error deleting {}", f.getPath());
             }
           }
         }
         if (!registeredExecutorFile.delete()) {
           logger.warn("error deleting {}", registeredExecutorFile.getPath());
         }
         options.createIfMissing(true);
         try {
           tmpDb = JniDBFactory.factory.open(registeredExecutorFile, options);
         } catch (NativeDB.DBException dbExc) {
           throw new IOException("Unable to create state store", dbExc);
         }
       }
     }
     // if there is a version mismatch, we throw an exception, which means the service is unusable
     checkVersion(tmpDb);
     executors = reloadRegisteredExecutors(tmpDb);
     db = tmpDb;
   } else {
     db = null;
     executors = Maps.newConcurrentMap();
   }
   this.directoryCleaner = directoryCleaner;
 }
Ejemplo n.º 10
0
 public void load(File xml, File mapping)
     throws SAXException, ParserConfigurationException, IOException {
   System.out.println("Loading " + xml.getPath() + " with " + mapping.getPath());
   XMLValidator.validate(xml, false);
   TagMap loader = new TagMap();
   loader.load(mapping, actionMap, targetMap, attributeMaps);
   getParser(false).parse(xml, new Parser(actionMap, targetMap, attributeMaps));
   {
   } // System.out.println("---------------------------------------------------------------------------------------");
 }
Ejemplo n.º 11
0
 /**
  * Add the specified file to the list of file dependencies.
  *
  * @param file a file
  */
 void addFile(File file) {
   mLogger.debug("addFile Path is " + file.getPath());
   FileInfo fi = new FileInfo(file.getPath());
   try {
     fi.mPathname = file.getCanonicalPath();
   } catch (java.io.IOException e) {
     throw new ChainedException(e);
   }
   mDependencies.add(fi);
 }
Ejemplo n.º 12
0
  private void reportIOErrorWithJars(File original, File target, IOException e) {
    LOG.warn(e);

    String path = original.getPath();
    myFileSystem.setNoCopyJarForPath(path);

    String message =
        VfsBundle.message("jar.copy.error.message", path, target.getPath(), e.getMessage());
    ERROR_COPY_NOTIFICATION
        .getValue()
        .createNotification(message, NotificationType.ERROR)
        .notify(null);
  }
Ejemplo n.º 13
0
  /**
   * Extracts next entry from JAR file, creating directories as needed. If the entry is for a
   * directory which doesn't exist prior to this invocation, returns that entry, otherwise returns
   * null.
   */
  ZipEntry extractFile(InputStream is, ZipEntry e) throws IOException {
    ZipEntry rc = null;
    String name = e.getName();
    File f = new File(e.getName().replace('/', File.separatorChar));
    if (e.isDirectory()) {
      if (f.exists()) {
        if (!f.isDirectory()) {
          throw new IOException(formatMsg("error.create.dir", f.getPath()));
        }
      } else {
        if (!f.mkdirs()) {
          throw new IOException(formatMsg("error.create.dir", f.getPath()));
        } else {
          rc = e;
        }
      }

      if (vflag) {
        output(formatMsg("out.create", name));
      }
    } else {
      if (f.getParent() != null) {
        File d = new File(f.getParent());
        if (!d.exists() && !d.mkdirs() || !d.isDirectory()) {
          throw new IOException(formatMsg("error.create.dir", d.getPath()));
        }
      }
      try {
        copy(is, f);
      } finally {
        if (is instanceof ZipInputStream) ((ZipInputStream) is).closeEntry();
        else is.close();
      }
      if (vflag) {
        if (e.getMethod() == ZipEntry.DEFLATED) {
          output(formatMsg("out.inflated", name));
        } else {
          output(formatMsg("out.extracted", name));
        }
      }
    }
    if (!useExtractionTime) {
      long lastModified = e.getTime();
      if (lastModified != -1) {
        f.setLastModified(lastModified);
      }
    }
    return rc;
  }
Ejemplo n.º 14
0
  public void testSourcesHaveLicense() throws IOException {
    // get a list of all the files in our source directories
    final List<File> sourceFiles = getSourceFiles();

    // check each source file and add it to the failure set if it doesn't contain the license header
    // comment
    final Set<String> failures = new HashSet<String>();
    for (File src : sourceFiles) {
      if (src.getPath().toLowerCase().endsWith(".java") && !sourceHasLicense(src))
        failures.add(src.getPath());
    }

    // fail if there were failures
    if (!failures.isEmpty())
      fail("the following files do not have the correct license header" + failures);
  }
	// post方式发送email
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		File file = doAttachment(request);
		EmailAttachment attachment = new EmailAttachment();
		attachment.setPath(file.getPath());
		attachment.setDisposition(EmailAttachment.ATTACHMENT);
		attachment.setName(file.getName());
		MultiPartEmail email = new MultiPartEmail();
		email.setCharset("UTF-8");
		email.setHostName("smtp.sina.com");
		email.setAuthentication("T-GWAP", "dangdang");
		try {
			email.addTo(parameters.get("to"));
			email.setFrom(parameters.get("from"));
			email.setSubject(parameters.get("subject"));
			email.setMsg(parameters.get("body"));
			email.attach(attachment);
			email.send();
			request.setAttribute("sendmail.message", "邮件发送成功!");
		} catch (EmailException e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送不成功", e);
			request.setAttribute("sendmail.message", "邮件发送不成功!");
		}
		request.getRequestDispatcher("/sendResult.jsp").forward(request,
				response);
	}
 public List<ShelvedChangeList> importChangeLists(
     final Collection<VirtualFile> files, final Consumer<VcsException> exceptionConsumer) {
   final List<ShelvedChangeList> result = new ArrayList<ShelvedChangeList>(files.size());
   try {
     final FilesProgress filesProgress = new FilesProgress(files.size(), "Processing ");
     for (VirtualFile file : files) {
       filesProgress.updateIndicator(file);
       final String description = file.getNameWithoutExtension().replace('_', ' ');
       final File patchPath = getPatchPath(description);
       final ShelvedChangeList list =
           new ShelvedChangeList(
               patchPath.getPath(),
               description,
               new SmartList<ShelvedBinaryFile>(),
               file.getTimeStamp());
       try {
         final List<TextFilePatch> patchesList =
             loadPatches(myProject, file.getPath(), new CommitContext());
         if (!patchesList.isEmpty()) {
           FileUtil.copy(new File(file.getPath()), patchPath);
           // add only if ok to read patch
           myShelvedChangeLists.add(list);
           result.add(list);
         }
       } catch (IOException e) {
         exceptionConsumer.consume(new VcsException(e));
       } catch (PatchSyntaxException e) {
         exceptionConsumer.consume(new VcsException(e));
       }
     }
   } finally {
     notifyStateChanged();
   }
   return result;
 }
Ejemplo n.º 17
0
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
  void outputProject(boolean files, boolean paths, boolean clss, boolean opts, IvyXmlWriter xw) {
    if (xw == null) return;

    xw.begin("PROJECT");
    xw.field("NAME", project_name);
    xw.field("PATH", base_directory.getPath());
    xw.field("WORKSPACE", project_manager.getWorkSpaceDirectory().getPath());
    if (python_interpreter != null) {
      xw.textElement("EXE", python_interpreter.getExecutable().getPath());
    }

    if (paths) {
      for (IPathSpec ps : project_paths) {
        ps.outputXml(xw);
      }
    }
    if (files) {
      for (IFileSpec fs : project_files) {
        fs.outputXml(xw);
      }
    }

    if (opts) pybase_prefs.outputXml(xw, true);

    xw.end("PROJECT");
  }
Ejemplo n.º 19
0
  /**
   * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by
   * the interface (and its superinterfaces) will be invocable.
   */
  public <T> InAppServer(
      String name,
      String portFilename,
      InetAddress inetAddress,
      Class<T> exportedInterface,
      T handler) {
    this.fullName = name + "Server";
    this.exportedInterface = exportedInterface;
    this.handler = handler;

    // In the absence of authentication, we shouldn't risk starting a server as root.
    if (System.getProperty("user.name").equals("root")) {
      Log.warn(
          "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!");
      return;
    }

    try {
      File portFile = FileUtilities.fileFromString(portFilename);
      secretFile = new File(portFile.getPath() + ".secret");
      Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName);
      // If there are no other threads left, the InApp server shouldn't keep us alive.
      serverThread.setDaemon(true);
      serverThread.start();
    } catch (Throwable th) {
      Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th);
    }
    writeNewSecret();
  }
Ejemplo n.º 20
0
    public static String relPath(String path1, String path2) {
        String a = unifyPath(path1);
        String b = unifyPath(path2);

        String[] as = a.split("[/\\\\]");
        String[] bs = b.split("[/\\\\]");

        int i;
        for (i = 0; i < Math.min(as.length, bs.length); i++) {
            if (!as[i].equals(bs[i])) {
                break;
            }
        }

        int ups = as.length - i - 1;

        File res = null;

        for (int x = 0; x < ups; x++) {
            res = new File(res, "..");
        }

        for (int y = i; y < bs.length; y++) {
            res = new File(res, bs[y]);
        }

        if (res == null) {
            return null;
        } else {
            return res.getPath();
        }
    }
Ejemplo n.º 21
0
  public void restartApplication() {

    try {

      final String javaBin =
          System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw";
      final File currentJar =
          new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI());

      System.out.println("javaBin " + javaBin);
      System.out.println("currentJar " + currentJar);
      System.out.println("currentJar.getPath() " + currentJar.getPath());

      /* is it a jar file? */
      // if(!currentJar.getName().endsWith(".jar")){return;}

      try {

        // xmining = 0;
        // systemx.shutdown();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add("-Xms256m");
      command.add("-Xmx1024m");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();

      // try{Thread.sleep(10000);} catch (InterruptedException e){}

      // close and exit
      SystemTray.getSystemTray().remove(network.icon);
      System.exit(0);

    } // try
    catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getCause());
    }
  } // ******************************
Ejemplo n.º 22
0
 /**
  * This method deletes a plugin file. If deletion fails - typically happens on Windows due to file
  * locking - the file is scheduled for deletion on the next startup.
  *
  * @param f The file to delete.
  * @return true if deletion was successful, false if scheduled for later.
  */
 public static boolean deletePluginFile(File f) {
   boolean success = f.delete();
   if (success) return true;
   else {
     schedulePluginForDeletion(f.getPath());
     return false;
   }
 }
Ejemplo n.º 23
0
 /** Computes the crc32 of a File. This is necessary when the ZipOutputStream is in STORED mode. */
 private void crc32File(ZipEntry e, File f) throws IOException {
   CRC32OutputStream os = new CRC32OutputStream();
   copy(f, os);
   if (os.n != f.length()) {
     throw new JarException(formatMsg("error.incorrect.length", f.getPath()));
   }
   os.updateEntry(e);
 }
Ejemplo n.º 24
0
 private void initModulesDir() throws RuntimeConfigException {
   this.modulesDirPath = null;
   String modulesDirPath = getProperty(modulesDirKey);
   if (modulesDirPath != null) {
     File modulesDir = new File(modulesDirPath);
     if (!modulesDir.isDirectory()) {
       throw createInvalidPropertyValueException(modulesDirKey, modulesDirPath);
     }
     this.modulesDirPath = modulesDir.getPath();
   } else {
     // try default
     File modulesDir = new File(substitute(defaultHomeModulesDirPath));
     if (modulesDir.isDirectory()) {
       this.modulesDirPath = modulesDir.getPath();
     }
   }
 }
Ejemplo n.º 25
0
  // read or create index
  private void readOrCreateIndex(CollectionManager.Force ff, Formatter f) throws IOException {

    // force new index or test for new index needed
    boolean force =
        ((ff == CollectionManager.Force.always)
            || (ff == CollectionManager.Force.test && needsUpdate()));

    // otherwise, we're good as long as the index file exists
    File idx = gc.getIndexFile();
    if (force || !idx.exists() || !readIndex(idx.getPath())) {
      logger.info("GribCollection {}: createIndex {}", gc.getName(), idx.getPath());
      createIndex(idx, ff, f); // write out index
      gc.rafLocation = idx.getPath();
      gc.setRaf(new RandomAccessFile(idx.getPath(), "r"));
      readIndex(gc.getRaf()); // read back in index
    }
  }
Ejemplo n.º 26
0
 public void initPlugin(LockssDaemon daemon, File file) throws PluginException {
   ExternalizableMap oneMap = new ExternalizableMap();
   oneMap.loadMap(file);
   if (oneMap.getErrorString() != null) {
     throw new PluginException(oneMap.getErrorString());
   }
   initPlugin(daemon, file.getPath(), oneMap, null);
 }
Ejemplo n.º 27
0
 private void processDelete(Node operation) {
   String path = absolutePath(operation.getTextContent());
   File target = new File(path);
   if (!target.exists()) {
     Utils.onError(new Error.FileNotFound(target.getPath()));
     return;
   }
   try {
     if (target.isDirectory()) {
       FileUtils.deleteDirectory(target);
     } else {
       FileUtils.forceDelete(target);
     }
   } catch (IOException ex) {
     Utils.onError(new Error.FileDelete(target.getPath()));
   }
 }
Ejemplo n.º 28
0
 /** Create a path value from a list of directories and jar files. */
 String createPath(File... files) {
   StringBuilder sb = new StringBuilder();
   for (File f : files) {
     if (sb.length() > 0) sb.append(File.pathSeparatorChar);
     sb.append(f.getPath());
   }
   return sb.toString();
 }
Ejemplo n.º 29
0
  /**
   * @param sourceFile File to read from
   * @return List of String objects with the shas
   */
  public static FileRequestFileContent readRequestFile(final File sourceFile) {
    if (!sourceFile.isFile() || !(sourceFile.length() > 0)) {
      return null;
    }
    Document d = null;
    try {
      d = XMLTools.parseXmlFile(sourceFile.getPath());
    } catch (final Throwable t) {
      logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t);
      return null;
    }

    if (d == null) {
      logger.log(Level.SEVERE, "Could'nt parse the request file");
      return null;
    }

    final Element rootNode = d.getDocumentElement();

    if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) {
      logger.severe(
          "Error: xml request file does not contain the root tag '"
              + TAG_FrostFileRequestFile
              + "'");
      return null;
    }

    final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp);
    if (timeStampStr == null) {
      logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'");
      return null;
    }
    final long timestamp = Long.parseLong(timeStampStr);

    final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList);
    if (nodelist.size() != 1) {
      logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'");
      return null;
    }

    final Element rootShaNode = nodelist.get(0);

    final List<String> shaList = new LinkedList<String>();
    final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha);
    for (final Element el : xmlKeys) {

      final Text txtname = (Text) el.getFirstChild();
      if (txtname == null) {
        continue;
      }

      final String sha = txtname.getData();
      shaList.add(sha);
    }

    final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList);
    return content;
  }
Ejemplo n.º 30
0
  public void getTextFilesFromDirectory() {
    while (nextDir.size() > 0) // size() returns number of elements in ArrayList nextDir
    {
      File pathName =
          new File(
              nextDir.get(
                  0)); // instantiate pathName with first element in ArrayList nextDir, which is a
                       // directory

      String[] fileNames =
          pathName
              .list(); // instantiates fileNames with an array of strings naming all files and
                       // directories in the

      System.out.println(fileNames);
      //      directory that pathName holds. Each string is a file name rather than a complete path.
      for (int i = 0; i < fileNames.length; i++) // iterate through array fileNames
      {

        File f =
            new File(
                pathName.getPath(),
                fileNames[
                    i]); // make new file with File contructor that receives parent and child
                         // parameters
        // uses getPath() to get the pathname string (converted from abstract pathname) for the
        // parent directory
        // in this loop, the child will continue to change, thus resinstantiating File f until we
        // reach the end of array fileNames.
        String string = f.getPath();
        int length1 = string.length() - 4;
        int length2 = string.length();
        String fileType = string.substring(length1, length2);

        if (f.isDirectory()) // if this file is a directory (as opposed to a file???)...
        {
          nextDir.add(f.getPath()); // and add pathname to ArrayList<String> nextDir
        } else if (fileType.equals(".txt")) {
          listOfFiles.add(f.getPath());
        }
      }
      nextDir.remove(
          0); // while nextDir.size() > 0, loop; at end of each loop delete element at position 0
    }
  }