Beispiel #1
0
  public void rm() {

    File[] dirs = this.table.listFiles();
    if (dirs != null) {
      for (File dir : dirs) {
        if (!dir.isDirectory()) {
          System.err.println(dir.getName() + " is not directory");
          System.exit(-1);
        }
        File[] dats = dir.listFiles();
        if (dats.length == 0) {
          System.err.println("Empty folders found");
          System.exit(-1);
        }
        for (File dat : dats) {
          if (!dat.delete()) {
            System.out.println("Error while reading table " + tableName);
          }
        }
        if (!dir.delete()) {
          System.out.println("Error while reading table " + tableName);
        }
      }
    }
  }
  private void saveConfiguration(
      BundleInfo[] configuration, File outputFile, URI installArea, boolean backup)
      throws IOException {
    if (backup && outputFile.exists()) {
      File backupFile = Utils.getSimpleDataFormattedFile(outputFile);
      if (!outputFile.renameTo(backupFile)) {
        throw new IOException("Fail to rename from (" + outputFile + ") to (" + backupFile + ")");
      }
    }

    org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo[] simpleInfos =
        convertBundleInfos(configuration, installArea);

    // if empty remove the configuration file
    if (simpleInfos == null || simpleInfos.length == 0) {
      if (outputFile.exists()) {
        outputFile.delete();
      }
      File parentDir = outputFile.getParentFile();
      if (parentDir.exists()) {
        parentDir.delete();
      }
      return;
    }
    SimpleConfiguratorManipulatorUtils.writeConfiguration(simpleInfos, outputFile);
    if (CONFIG_LIST.equals(outputFile.getName())
        && installArea != null
        && isSharedInstallSetup(URIUtil.toFile(installArea), outputFile))
      rememberSharedBundlesInfoTimestamp(installArea, outputFile.getParentFile());
  }
  /**
   * 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();
      }
    }
  }
Beispiel #4
0
  /** Save the contents of the FS image */
  void saveFSImage(File fullimage, File edits) throws IOException {
    File curFile = new File(fullimage, FS_IMAGE);
    File newFile = new File(fullimage, NEW_FS_IMAGE);
    File oldFile = new File(fullimage, OLD_FS_IMAGE);

    //
    // Write out data
    //
    DataOutputStream out =
        new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));
    try {
      out.writeInt(rootDir.numItemsInTree() - 1);
      rootDir.saveImage("", out);
    } finally {
      out.close();
    }

    //
    // Atomic move sequence
    //
    // 1.  Move cur to old
    curFile.renameTo(oldFile);

    // 2.  Move new to cur
    newFile.renameTo(curFile);

    // 3.  Remove pending-edits file (it's been integrated with newFile)
    edits.delete();

    // 4.  Delete old
    oldFile.delete();
  }
 // 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;
 }
Beispiel #6
0
  /**
   * Load in the filesystem image. It's a big list of filenames and blocks. Return whether we should
   * "re-save" and consolidate the edit-logs
   */
  boolean loadFSImage(File fsdir, File edits) throws IOException {
    //
    // Atomic move sequence, to recover from interrupted save
    //
    File curFile = new File(fsdir, FS_IMAGE);
    File newFile = new File(fsdir, NEW_FS_IMAGE);
    File oldFile = new File(fsdir, OLD_FS_IMAGE);

    // Maybe we were interrupted between 2 and 4
    if (oldFile.exists() && curFile.exists()) {
      oldFile.delete();
      if (edits.exists()) {
        edits.delete();
      }
    } else if (oldFile.exists() && newFile.exists()) {
      // Or maybe between 1 and 2
      newFile.renameTo(curFile);
      oldFile.delete();
    } else if (curFile.exists() && newFile.exists()) {
      // Or else before stage 1, in which case we lose the edits
      newFile.delete();
    }

    //
    // Load in bits
    //
    if (curFile.exists()) {
      DataInputStream in =
          new DataInputStream(new BufferedInputStream(new FileInputStream(curFile)));
      try {
        int numFiles = in.readInt();
        for (int i = 0; i < numFiles; i++) {
          UTF8 name = new UTF8();
          name.readFields(in);
          int numBlocks = in.readInt();
          if (numBlocks == 0) {
            unprotectedAddFile(name, null);
          } else {
            Block blocks[] = new Block[numBlocks];
            for (int j = 0; j < numBlocks; j++) {
              blocks[j] = new Block();
              blocks[j].readFields(in);
            }
            unprotectedAddFile(name, blocks);
          }
        }
      } finally {
        in.close();
      }
    }

    if (edits.exists() && loadFSEdits(edits) > 0) {
      return true;
    } else {
      return false;
    }
  }
 private static void delete(File directory) {
   for (File file : directory.listFiles()) {
     if (file.isDirectory()) {
       delete(file);
     } else {
       assertTrue(file.delete());
     }
   }
   assertTrue(directory.delete());
 }
Beispiel #8
0
 public boolean edtImport(File fi, String date, String tags) {
   if (!fi.exists()) {
     System.err.println("import: file " + fi.getAbsolutePath() + " doesnt exist");
     return false;
   }
   String pname = fi.getName();
   if (store.containsEntry(pname)) {
     System.err.println("import: already have a file named " + pname);
     return false;
   }
   long size = fi.length() / KILOBYTE;
   File save = sec.encryptMainFile(fi, storeLocs.get(0), true);
   if (save == null) {
     System.err.println("import: Encryption failure");
     return false;
   }
   if (checkImports) {
     boolean success = true;
     File checkfi = new File(idx + ".check");
     File checkOut = sec.encryptSpecialFile(save, checkfi, false);
     if (checkOut == null) success = false;
     else {
       String fiHash = sec.digest(fi);
       String outHash = sec.digest(checkOut);
       if (fiHash == null || outHash == null || fiHash.length() < 1 || !fiHash.equals(outHash))
         success = false;
     }
     checkfi.delete();
     if (!success) {
       save.delete();
       if (JOptionPane.showConfirmDialog(
               frm,
               "Confirming "
                   + fi.getName()
                   + "failed\n\n - Would you like to re-import the file?",
               "Import failed",
               JOptionPane.YES_NO_OPTION)
           == JOptionPane.YES_OPTION) {
         String j = impJob(fi, date, tags);
         synchronized (jobs) {
           if (priorityExport) jobs.addLast(j);
           else jobs.addFirst(j);
         }
       }
       return false;
     }
   }
   if (!fi.delete()) {
     System.err.println("import: Couldnt delete old file - continuing");
   }
   store.add(save.getName(), pname, date, size, tags, 0);
   needsSave = true;
   return true;
 }
  /**
   * Loop through the ZIP file, copying its entries into a new, temporary ZIP file, skipping the
   * entry to be deleted. Then replace the original file with the new one.
   */
  protected Integer deleteEntry() throws XMLDataStoreException {
    try {
      ZipInputStream inStream = this.buildZipInputStream();
      File outFile = this.buildTempFile();
      ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(outFile));

      byte[] buffer = new byte[32768];
      int inCount = 0;
      int outCount = 0;

      // copy all the entries except the one to be deleted
      ZipEntry entry = inStream.getNextEntry();
      while (entry != null) {
        inCount++;
        if (!this.getZipEntryName().equals(entry.getName())) {
          outCount++;
          outStream.putNextEntry(entry);
          int byteCount;
          while ((byteCount = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, byteCount);
          }
          outStream.closeEntry();
        }
        entry = inStream.getNextEntry();
      }
      inStream.close();
      if (outCount == 0) {
        // add a dummy record to an empty file so we can close it
        // this is required by ZipOutputStream
        outStream.putNextEntry(new ZipEntry("delete.txt"));
        outStream.write(
            "This file is a place-holder. The containing ZIP file should be deleted.".getBytes());
        outStream.closeEntry();
      }
      outStream.close();
      if (outCount == inCount) {
        // no entries were removed - just delete the temp file
        outFile.delete();
      } else {
        // at least one entry removed - delete the original file
        this.getFile().delete();
        if (outCount == 0) {
          // NO entries remain - just delete the temp file too
          outFile.delete();
        } else {
          // entries remain - replace original file with temp file
          outFile.renameTo(this.getFile());
        }
      }
      return new Integer(inCount - outCount); // should be 0 or 1
    } catch (IOException ex) {
      throw XMLDataStoreException.ioException(ex);
    }
  }
Beispiel #10
0
 /** Deletes all files and dirs in dir, but not dir itself */
 protected static void deleteContents(File dir) {
   File[] contents = dir.listFiles();
   if (contents != null) {
     for (File file : contents) {
       if (file.isDirectory()) {
         deleteContents(file);
         file.delete();
       } else file.delete();
     }
   }
 }
  /**
   * Rename the ZIP file to a temporary file, then copy its entries back into the original ZIP file,
   * leaving the stream open and returning it.
   */
  protected Writer buildWriteStream(boolean entryShouldExist) throws XMLDataStoreException {
    try {
      File inFile = this.buildTempFile();
      inFile.delete(); // the file actually gets created - delete it
      boolean renameSucceeded = this.getFile().renameTo(inFile);
      ZipInputStream inStream = this.buildZipInputStream(inFile);
      ZipOutputStream outStream = this.buildZipOutputStream();

      boolean entryActuallyExists = false;
      byte[] buffer = new byte[32768];
      ZipEntry entry = inStream.getNextEntry();
      while (entry != null) {
        boolean weWantToWriteTheEntry = true;
        if (this.getZipEntryName().equals(entry.getName())) {
          entryActuallyExists = true;

          // if we were expecting the entry, skip it;
          // if we were NOT expecting the entry, allow it to be rewritten
          // so the file is restored to its original condition
          if (entryShouldExist) {
            weWantToWriteTheEntry = false;
          }
        }
        if (weWantToWriteTheEntry) {
          outStream.putNextEntry(entry);
          int byteCount;
          while ((byteCount = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, byteCount);
          }
          outStream.closeEntry();
        }
        entry = inStream.getNextEntry();
      }

      // close and delete the temporary file
      inStream.close();
      inFile.delete();
      // check for invalid state
      if (entryShouldExist != entryActuallyExists) {
        outStream.close(); // close it since we will not be returning it
        // need more helpful exceptions here
        if (entryActuallyExists) {
          throw XMLDataStoreException.fileAlreadyExists(new File(this.getZipEntryName()));
        } else {
          throw XMLDataStoreException.fileNotFound(new File(this.getZipEntryName()), null);
        }
      }
      outStream.putNextEntry(new ZipEntry(this.getZipEntryName()));
      return new OutputStreamWriter(outStream);
    } catch (IOException ex) {
      throw XMLDataStoreException.ioException(ex);
    }
  }
 public static void deleteRecursive(File file) {
   if (!file.exists()) {
     return;
   }
   if (file.isFile()) {
     file.delete();
   } else if (file.isDirectory()) {
     File[] files = file.listFiles();
     for (int i = 0; i < files.length; i++) {
       deleteRecursive(files[i]);
     }
     file.delete();
   }
 }
Beispiel #13
0
 public static boolean deleteDirectory(File directory) {
     if (directory.exists()) {
         File[] files = directory.listFiles();
         if (files != null) {
             for (File f : files) {
                 if (f.isDirectory()) {
                     deleteDirectory(f);
                 } else {
                     f.delete();
                 }
             }
         }
     }
     return directory.delete();
 }
Beispiel #14
0
 public boolean edtExport(File cip, File pla) {
   if (!cip.exists()) {
     System.err.println(
         "export: file " + cip.getAbsolutePath() + " doesnt exist for " + pla.getName());
     pla.delete();
     return false;
   }
   File save = sec.encryptSpecialFile(cip, pla, false);
   if (save == null) {
     System.err.println("export: Encryption failure");
     pla.delete();
     return false;
   }
   return true;
 }
 private void cleanUp(File f) {
   if (!f.delete()) {
     showError("trouble deleting " + f.getName());
   } else {
     // do something here?
   }
 }
Beispiel #16
0
 public static boolean HTTPRequestToFile(
     File file, String inUrl, String method, String data, List headers) {
   boolean success = false;
   try {
     if (file.exists()) file.delete();
   } catch (Exception e) {
     Logger.getLogger(com.bombdiggity.util.HTTPUtils.class)
         .error(
             (new StringBuilder("HTTPUtils.HTTPRequestToFile delete ("))
                 .append(file)
                 .append("): ")
                 .append(e.toString())
                 .toString());
   }
   try {
     DataOutputStream printout = null;
     DataInputStream input = null;
     URL url = new URL(inUrl);
     URLConnection urlConn = url.openConnection();
     urlConn.setDoInput(true);
     urlConn.setDoOutput(true);
     urlConn.setUseCaches(false);
     if (headers != null) {
       for (Iterator iter = headers.iterator(); iter.hasNext(); ) {
         Map nameValuePair = (Map) iter.next();
         String key;
         String value;
         for (Iterator iter2 = nameValuePair.keySet().iterator();
             iter2.hasNext();
             urlConn.setRequestProperty(key, value)) {
           key = (String) iter2.next();
           value = (String) nameValuePair.get(key);
         }
       }
     }
     if (data != null) {
       byte inData[] = data.getBytes("UTF-8");
       printout = new DataOutputStream(urlConn.getOutputStream());
       printout.write(inData);
       printout.flush();
       printout.close();
       printout = null;
     }
     input = new DataInputStream(urlConn.getInputStream());
     DataOutputStream dataOut = new DataOutputStream(new FileOutputStream(file, false));
     int rChunk = 0x10000;
     byte myData[] = new byte[rChunk];
     do {
       int bytesRead = input.read(myData, 0, rChunk);
       if (bytesRead == -1) break;
       dataOut.write(myData, 0, bytesRead);
       Thread.sleep(1L);
     } while (true);
     input.close();
     input = null;
     success = true;
   } catch (Exception exception) {
   }
   return success;
 }
  public SaikuDatasource addDatasource(SaikuDatasource datasource) {
    try {
      String uri = repoURL.toURI().toString();
      if (uri != null && datasource != null) {
        uri += datasource.getName().replace(" ", "_");
        File dsFile = new File(new URI(uri));
        if (dsFile.exists()) {
          dsFile.delete();
        } else {
          dsFile.createNewFile();
        }
        FileWriter fw = new FileWriter(dsFile);
        Properties props = datasource.getProperties();
        props.store(fw, null);
        fw.close();
        datasources.put(datasource.getName(), datasource);
        return datasource;

      } else {
        throw new SaikuServiceException(
            "Cannot save datasource because uri or datasource is null uri(" + (uri == null) + ")");
      }
    } catch (Exception e) {
      throw new SaikuServiceException("Error saving datasource", e);
    }
  }
  /**
   * Delete a student from the database. Also deletes the student's folders. Throws
   * InvalidDBRequestException if any error in database connection.
   *
   * @param username student's user name
   * @throws InvalidDBRequestException
   */
  private void purgeStudent(String username) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete from scores
      count = stmt.executeUpdate("delete from scores where user_login = '******'");

      // delete from student
      count = stmt.executeUpdate("delete from student where login = '******'");

      // delete student's folder
      File studentDir = new File("./StudentQuizzes/" + username);
      if (!(studentDir.delete())) {
        System.err.println("Error in deleting folder for student: " + username);
      }

      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Beispiel #19
0
 JavacState(Options op, boolean removeJavacState, PrintStream o, PrintStream e) {
   options = op;
   out = o;
   err = e;
   numCores = options.getNumCores();
   theArgs = options.getStateArgsString();
   binDir = Util.pathToFile(options.getDestDir());
   gensrcDir = Util.pathToFile(options.getGenSrcDir());
   headerDir = Util.pathToFile(options.getHeaderDir());
   stateDir = Util.pathToFile(options.getStateDir());
   javacState = new File(stateDir, "javac_state");
   if (removeJavacState && javacState.exists()) {
     javacState.delete();
   }
   newJavacState = false;
   if (!javacState.exists()) {
     newJavacState = true;
     // If there is no javac_state then delete the contents of all the artifact dirs!
     // We do not want to risk building a broken incremental build.
     // BUT since the makefiles still copy things straight into the bin_dir et al,
     // we avoid deleting files here, if the option --permit-unidentified-classes was supplied.
     if (!options.areUnidentifiedArtifactsPermitted()) {
       deleteContents(binDir);
       deleteContents(gensrcDir);
       deleteContents(headerDir);
     }
     needsSaving = true;
   }
   prev = new BuildState();
   now = new BuildState();
   taintedPackages = new HashSet<>();
   recompiledPackages = new HashSet<>();
   packagesWithChangedPublicApis = new HashSet<>();
 }
 public static void clear(String fileStr) throws Exception {
   File file = new File(fileStr);
   if (file.isFile()) {
     file.delete();
     return;
   }
   String[] fileNames = file.list();
   if (fileNames == null) {
     return;
   }
   for (int i = 0; i < fileNames.length; i++) {
     String newFileName = GlobalFile.getFileLocation(fileStr, fileNames[i]);
     clear(newFileName);
   }
   file.delete();
 }
  public void testSerial() {
    assertTrue(_nbhm.isEmpty());
    final String k1 = "k1";
    final String k2 = "k2";
    assertThat(_nbhm.put(k1, "v1"), nullValue());
    assertThat(_nbhm.put(k2, "v2"), nullValue());

    // Serialize it out
    try {
      FileOutputStream fos = new FileOutputStream("NBHM_test.txt");
      ObjectOutputStream out = new ObjectOutputStream(fos);
      out.writeObject(_nbhm);
      out.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read it back
    try {
      File f = new File("NBHM_test.txt");
      FileInputStream fis = new FileInputStream(f);
      ObjectInputStream in = new ObjectInputStream(fis);
      NonBlockingIdentityHashMap nbhm = (NonBlockingIdentityHashMap) in.readObject();
      in.close();
      assertThat(
          "serialization works",
          nbhm.toString(),
          anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}")));
      if (!f.delete()) throw new IOException("delete failed");
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
  }
Beispiel #22
0
  public boolean imp() {
    boolean res = false;

    DbVariable dbVariable = null;
    String fullFileName = "";
    String errMessage = null;
    DbImportFile dbInFile = new DbImportFile();
    try {
      dbVariable = new DbVariable();

      // Store the file on server filesystem
      fullFileName = dbInFile.storeImportFileBLOB(conn_viss, ifid);

      FileParser fileParser = new FileParser(fullFileName);
      fileParser.Parse(
          FileTypeDefinitionList.matchingDefinitions(
              FileTypeDefinition.VARIABLE, FileTypeDefinition.LIST));

      dbVariable.CreateVariables(fileParser, connection, sampleUnitId, Integer.parseInt(userId));

      errMessage = dbVariable.getErrorMessage();
      Assertion.assertMsg(errMessage == null || errMessage.trim().equals(""), errMessage);

      dbInFile.setStatus(conn_viss, ifid, "IMPORTED");
      // dbInFile.UpdateImportFile(connection,null,null,"Done",Integer.parseInt(ifid),Integer.parseInt(userId));

      // Add a message to the log
      dbInFile.addErrMsg(
          conn_viss,
          ifid,
          "File imported to sampling unit "
              + DbSamplingUnit.getSUName(conn_viss, Integer.toString(sampleUnitId))
              + "Note: Markers is always imported in Create mode.");
      res = true;
    } catch (Exception e) {
      Errors.logError("ImportVariables.imp(...)" + e.getMessage());

      dbInFile.setStatus(conn_viss, ifid, "ERROR");
      // dbInFile.UpdateImportFile(connection,null,null,e.getMessage(),Integer.parseInt(ifid),Integer.parseInt(userId));

      // Add a message to the log
      dbInFile.addErrMsg(conn_viss, ifid, e.getMessage());

      e.printStackTrace(System.err);
      if (errMessage == null) {
        errMessage = e.getMessage();
      }
    } finally {
      try {
        /*
         * Delete files uploaded
         */
        File tmp = new File(fullFileName);
        tmp.delete();
      } catch (Exception ignore) {
      }
    }

    return res;
  }
Beispiel #23
0
 public void secureDelete() {
   int rw = tblItems.getSelectedRow();
   if (rw == -1) {
     JOptionPane.showMessageDialog(frm, "No item selected", "Error", JOptionPane.ERROR_MESSAGE);
     return;
   }
   int idx = tblItems.convertRowIndexToModel(rw);
   if (JOptionPane.showConfirmDialog(
           frm,
           "Delete " + store.plainName(idx) + "?",
           "Confirm Delete",
           JOptionPane.YES_NO_OPTION)
       != JOptionPane.YES_OPTION) return;
   File del = store.delete(idx);
   store.fireTableDataChanged();
   if (del != null) {
     if (del.delete()) {
       // successful
       needsSave = true;
     } else {
       System.err.println("Delete " + del.getAbsolutePath() + " failed");
     }
   }
   updateStatus();
 }
Beispiel #24
0
  /**
   * Add the supplied data as an entry in the deployment.
   *
   * @param path The target path of the entry when added to the archive.
   * @param data The data. Pass null to create a directory.
   * @return This archive instance.
   */
  public Archive addEntry(String path, byte[] data) {
    AssertArgument.isNotNullAndNotEmpty(path, "path");

    File entryFile = new File(tmpDir, path);

    if (entryFile.exists()) {
      entryFile.delete();
    }

    entryFile.getParentFile().mkdirs();
    if (data == null) {
      entryFile.mkdir();
    } else {
      try {
        FileUtils.writeFile(data, entryFile);
      } catch (IOException e) {
        throw new IllegalStateException(
            "Unexpected error writing Archive file '" + entryFile.getAbsolutePath() + "'.", e);
      }
    }

    entries.put(trimLeadingSlash(path.trim()), entryFile);

    return this;
  }
Beispiel #25
0
  private void deleteLocation(LocationInfo info) {
    if (NavigineApp.Navigation == null) return;

    if (info != null) {
      try {
        (new File(info.archiveFile)).delete();
        info.localVersion = -1;
        info.localModified = false;

        String locationDir = LocationLoader.getLocationDir(mContext, info.title);
        File dir = new File(locationDir);
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; ++i) files[i].delete();
        dir.delete();

        String mapFile = NavigineApp.Settings.getString("map_file", "");
        if (mapFile.equals(info.archiveFile)) {
          NavigineApp.Navigation.loadArchive(null);
          SharedPreferences.Editor editor = NavigineApp.Settings.edit();
          editor.putString("map_file", "");
          editor.commit();
        }

        mAdapter.updateList();
      } catch (Throwable e) {
        Log.e(TAG, Log.getStackTraceString(e));
      }
    }
  }
Beispiel #26
0
  /**
   * Remove files if needed to make cache have less than maxBytes bytes file sizes. This will remove
   * files in sort order defined by fileComparator. The first files in the sort order are kept,
   * until the max bytes is exceeded, then they are deleted.
   *
   * @param maxBytes max number of bytes in cache.
   * @param fileComparator sort files first with this
   * @param sbuff write results here, null is ok.
   */
  public static void cleanCache(
      long maxBytes, Comparator<File> fileComparator, StringBuilder sbuff) {
    if (sbuff != null)
      sbuff.append("DiskCache clean maxBytes= " + maxBytes + "on dir " + root + "\n");

    File dir = new File(root);
    File[] files = dir.listFiles();
    List<File> fileList = Arrays.asList(files);
    Collections.sort(fileList, fileComparator);

    long total = 0, total_delete = 0;
    for (File file : fileList) {
      if (file.length() + total > maxBytes) {
        total_delete += file.length();
        if (sbuff != null) sbuff.append(" delete " + file + " (" + file.length() + ")\n");
        file.delete();
      } else {
        total += file.length();
      }
    }
    if (sbuff != null) {
      sbuff.append("Total bytes deleted= " + total_delete + "\n");
      sbuff.append("Total bytes left in cache= " + total + "\n");
    }
  }
  public static void recover() throws IOException {
    String directory = DatabaseDescriptor.getCommitLogLocation();
    File[] files =
        new File(directory)
            .listFiles(
                new FilenameFilter() {
                  public boolean accept(File dir, String name) {
                    return CommitLogSegment.possibleCommitLogFile(name);
                  }
                });
    if (files.length == 0) return;

    Arrays.sort(files, new FileUtils.FileComparator());
    logger.info("Replaying " + StringUtils.join(files, ", "));
    recover(files);
    for (File f : files) {
      FileUtils.delete(
          CommitLogHeader.getHeaderPathFromSegmentPath(
              f.getAbsolutePath())); // may not actually exist
      if (!f.delete())
        logger.error(
            "Unable to remove "
                + f
                + "; you should remove it manually or next restart will replay it again (harmless, but time-consuming)");
    }
    logger.info("Log replay complete");
  }
  public static int rollbackGUIConfigurationTransaction(String sConfigurationFileName) {

    String sConfigurationLockFile;
    File fFile;

    sConfigurationLockFile = new String(sConfigurationFileName + ".lck");

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    if (fFile.delete() == false) {
      JOptionPane.showMessageDialog(
          null,
          "fFile.delete on " + sConfigurationLockFile + " failed",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 3;
    }

    return 0;
  }
Beispiel #29
0
 protected void eraseTempDir() {
   File tmpdirF = new File(tmpdir);
   if (tmpdirF.exists()) {
     eraseFiles();
     tmpdirF.delete();
   }
 }
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }