Ejemplo n.º 1
2
  private void createReport() throws Exception {
    Logger.getLogger(ProcessPerformer.class.getName()).log(Level.INFO, "Creating reports ...");
    Logger.getLogger(ProcessPerformer.class.getName()).fine("Creating reports ...");

    File logDir = new File(LOG_PATH);

    File reportDir = new File(REPORT_PATH);

    if (reportDir.exists()) FileHelper.deleteDirectory(reportDir);

    reportDir.mkdirs();

    File output = new File(reportDir.getPath() + "/" + OUTPUT_CSV_FILE);
    output.createNewFile();

    StreamResult outputStream = new StreamResult(new FileOutputStream(output));

    FilenameFilter filter =
        new FilenameFilter() {
          @Override
          public boolean accept(File arg0, String arg1) {
            if (arg0.isDirectory()) {
              if (_experimentID == null) return true;
              else {
                if (!arg1.equals(_experimentID)) return false;
                else return true;
              }
            } else return false;
          }
        };

    // TODO: B Number of names of parameters is fixed, for future will be good to create a floating
    // number of names of parameters

    int numberOfParameters = 10;
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i < numberOfParameters + 1; ++i) {
      sb.append("p").append(i).append(";");
    }

    // outputStream.getOutputStream().write( ( CSV_HEADER + sb.append("\n").toString() ).getBytes()
    // );

    for (String dirName : logDir.list(filter)) {
      System.err.println(dirName);

      File logDirDir = new File(logDir.getPath() + "/" + dirName);
      Arrays.sort(logDirDir.list());

      for (String xmlFileName : logDirDir.list()) {
        String xmlPath = logDir.getPath() + "/" + dirName + "/" + xmlFileName;

        try {
          Transformer.getInstance().transformByXSLT(xmlPath, XSL_TEMPLATE, outputStream);
        } catch (Exception e) {
          Logger.getLogger(ProcessPerformer.class.getName()).fine(xmlPath);
        }
      }
    }
  }
Ejemplo n.º 2
1
  static void linkBlocks(File from, File to, int oldLV, HardLink hl) throws IOException {
    if (!from.exists()) {
      return;
    }
    if (!from.isDirectory()) {
      if (from.getName().startsWith(COPY_FILE_PREFIX)) {
        FileInputStream in = new FileInputStream(from);
        try {
          FileOutputStream out = new FileOutputStream(to);
          try {
            IOUtils.copyBytes(in, out, 16 * 1024);
            hl.linkStats.countPhysicalFileCopies++;
          } finally {
            out.close();
          }
        } finally {
          in.close();
        }
      } else {
        HardLink.createHardLink(from, to);
        hl.linkStats.countSingleLinks++;
      }
      return;
    }
    // from is a directory
    hl.linkStats.countDirs++;

    if (!to.mkdirs()) throw new IOException("Cannot create directory " + to);

    String[] blockNames =
        from.list(
            new java.io.FilenameFilter() {
              @Override
              public boolean accept(File dir, String name) {
                return name.startsWith(BLOCK_FILE_PREFIX);
              }
            });

    // Block files just need hard links with the same file names
    // but a different directory
    if (blockNames.length > 0) {
      HardLink.createHardLinkMult(from, blockNames, to);
      hl.linkStats.countMultLinks++;
      hl.linkStats.countFilesMultLinks += blockNames.length;
    } else {
      hl.linkStats.countEmptyDirs++;
    }

    // Now take care of the rest of the files and subdirectories
    String[] otherNames =
        from.list(
            new java.io.FilenameFilter() {
              @Override
              public boolean accept(File dir, String name) {
                return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(COPY_FILE_PREFIX);
              }
            });
    for (int i = 0; i < otherNames.length; i++)
      linkBlocks(new File(from, otherNames[i]), new File(to, otherNames[i]), oldLV, hl);
  }
Ejemplo n.º 3
0
  @Override
  public void onPathChanged(String path, Boolean creatPathView) {
    Log.d(TAG, "MainActivity  - onPathCahnged");
    Log.d(TAG, "current File Path   -   " + currentFilePath);
    Log.d(TAG, "path sent to method  -   " + path);

    currentFilePath = currentFilePath + path;
    currentFile = new File(currentFilePath);
    String[] currentFileList = currentFile.list();

    // If the array is null the app will crash on the .leangth method
    if (currentFileList != null) {
      int numOfFiles = currentFile.list().length;
      folderList.clear();

      for (int i = 0; i < numOfFiles; i++) {
        folderList.add(currentFileList[i]);
      }
    } else {
      folderList.clear();
    }

    listFragment.folderArray = folderList;
    listFragment.folderAdapter.notifyDataSetChanged();

    // Add the Path to Path Bar
    if (creatPathView) {
      createPathViews(path);
    }
  }
Ejemplo n.º 4
0
  /**
   * Get rid of ALL files and subdirectories in given directory, and all subdirs under it,
   *
   * @param dir would normally be an existing directory, can be a file aswell
   * @param recursive true if you want subdirs deleted as well
   * @param deleteDir true if dir needs to be deleted as well
   * @return true upon success
   */
  public static boolean deleteDirsAndFiles(File dir, boolean recursive, boolean deleteDir) {

    boolean success = true;

    if (dir == null) return false;

    // We must empty child subdirs contents before can get rid of immediate
    // child subdirs
    if (recursive) {
      String[] allDirs = dir.list();
      if (allDirs != null) {
        for (int i = 0; i < allDirs.length; i++) {
          success &= deleteDirsAndFiles(new File(dir, allDirs[i]), true, false);
        }
      }
    }

    // delete all files in this dir
    String[] allFiles = dir.list();
    if (allFiles != null) {
      for (int i = 0; i < allFiles.length; i++) {
        File deleteFile = new File(dir, allFiles[i]);
        success &= deleteFile.delete();
      }
    }

    // delete passed dir
    if (deleteDir) {
      success &= dir.delete();
    }
    return success;
  } // end deleteDirContents
Ejemplo n.º 5
0
  /**
   * Generar un nombre de archivo a grabar en el directorio temporal del usuario y asignarlo al
   * fileName del report.
   *
   * @return
   */
  public String generateFileNameTmp() {

    // Purgar directorio de ficheros temporales generados por gana con 2
    // horas de diferencia
    File dir = new File(EnvironmentVariables.getUserTmp());

    if (dir.list().length > 0) {

      for (String filename : dir.list()) {

        if (filename.indexOf("gana_tmp_") > -1) {

          File file = new File(EnvironmentVariables.getUserTmp() + filename);
          Date d = new Date(file.lastModified());

          if (DateUtils.getDiffHoursDates(d, new Date()) > 1) {
            file.delete();
          }
        }
      }
    }

    fileName =
        EnvironmentVariables.getUserTmp()
            + "gana_tmp_report_"
            + SystemUtils.getIdDocument()
            + ".xls";

    if (excel != null) excel.setFileName(fileName);

    return fileName;
  }
Ejemplo n.º 6
0
  @Override
  public void removeFile(OCFile file, boolean removeLocalCopy) {
    Uri file_uri = Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, "" + file.getFileId());
    if (getContentProvider() != null) {
      try {
        getContentProvider()
            .delete(
                file_uri,
                ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
                new String[] {mAccount.name});
      } catch (RemoteException e) {
        e.printStackTrace();
      }
    } else {
      getContentResolver()
          .delete(
              file_uri, ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] {mAccount.name});
    }
    if (file.isDown() && removeLocalCopy) {
      new File(file.getStoragePath()).delete();
    }
    if (file.isDirectory() && removeLocalCopy) {
      File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
      if (f.exists() && f.isDirectory() && (f.list() == null || f.list().length == 0)) {
        f.delete();
      }
    }

    if (file.getFileLength() > 0) {
      updateSizesToTheRoot(file.getParentId());
    }
  }
Ejemplo n.º 7
0
  /**
   * Reads local resources from - Jar files - Class folders - Jar Library folders
   *
   * @param fol
   * @param packName
   * @throws IOException
   */
  private void loadResource(File fol, String packName) throws IOException {
    if (fol.isFile()) {
      if (fol.getName().toLowerCase().endsWith(".class")) {
        loadClassContent(fol.getAbsolutePath(), packName);
      } else {
        if (fol.getName().toLowerCase().endsWith(".jar")) {
          loadJar(fol.getAbsolutePath());
        } else {
          loadResourceContent(fol.getAbsolutePath());
        }
      }

      return;
    }

    if (fol.list() != null) {
      for (String f : fol.list()) {
        File fl = new File(fol.getAbsolutePath() + "/" + f);

        String pn = packName;

        if (fl.isDirectory()) {

          if (!pn.equals("")) pn = pn + "/";

          pn = pn + fl.getName();
        }

        loadResource(fl, pn);
      }
    }
  }
Ejemplo n.º 8
0
 private static void deleteDirOrFile(File fileOrFolder) throws IOException {
   if (fileOrFolder.isDirectory()) {
     // directory is empty, then delete it
     if (fileOrFolder.list().length == 0) {
       fileOrFolder.delete();
       //				System.out.println("Directory is deleted : "
       //						+ fileOrFolder.getAbsolutePath());
     } else {
       // list all the directory contents
       String files[] = fileOrFolder.list();
       for (String temp : files) {
         // construct the file structure
         File fileDelete = new File(fileOrFolder, temp);
         // recursive delete
         deleteDirOrFile(fileDelete);
       }
       // check the directory again, if empty then delete it
       if (fileOrFolder.list().length == 0) {
         fileOrFolder.delete();
         //					System.out.println("Directory is deleted : "
         //							+ fileOrFolder.getAbsolutePath());
       }
     }
   } else {
     // if file, then delete it
     fileOrFolder.delete();
     //	System.out.println("File is deleted : " + fileOrFolder.getAbsolutePath());
   }
 }
Ejemplo n.º 9
0
  /**
   * Tests if fullyDelete deletes (a) dangling symlink to file properly (b) dangling symlink to
   * directory properly
   *
   * @throws IOException
   */
  @Test(timeout = 30000)
  public void testFullyDeleteDanglingSymlinks() throws IOException {
    setupDirs();
    // delete the directory tmp to make tmpDir a dangling link to dir tmp and
    // to make y as a dangling link to file tmp/x
    boolean ret = FileUtil.fullyDelete(tmp);
    Assert.assertTrue(ret);
    Assert.assertFalse(tmp.exists());

    // dangling symlink to file
    File link = new File(del, LINK);
    Assert.assertEquals(5, del.list().length);
    // Even though 'y' is dangling symlink to file tmp/x, fullyDelete(y)
    // should delete 'y' properly.
    ret = FileUtil.fullyDelete(link);
    Assert.assertTrue(ret);
    Assert.assertEquals(4, del.list().length);

    // dangling symlink to directory
    File linkDir = new File(del, "tmpDir");
    // Even though tmpDir is dangling symlink to tmp, fullyDelete(tmpDir) should
    // delete tmpDir properly.
    ret = FileUtil.fullyDelete(linkDir);
    Assert.assertTrue(ret);
    Assert.assertEquals(3, del.list().length);
  }
 @SuppressWarnings("unchecked")
 private TrainingDataManager() {
   traningTextDir = new File(defaultPath);
   if (!traningTextDir.isDirectory()) {
     throw new IllegalArgumentException("训练语料库搜索失败! [" + defaultPath + "]");
   }
   this.traningFileClassifications = traningTextDir.list();
   // 加载所有Map
   String ss[] = traningTextDir.list();
   for (int i = 0; i < ss.length; i++) {
     Map<String, Double> map = new HashMap<String, Double>();
     ObjectInputStream ois = null;
     try {
       FileInputStream is = new FileInputStream(defaultPath + ss[i] + "\\map");
       ois = new ObjectInputStream(is);
       map = (Map<String, Double>) ois.readObject();
     } catch (FileNotFoundException e) {
       e.printStackTrace();
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     } finally {
       try {
         ois.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     classMap.put(ss[i], map);
     map = null;
   }
 }
  /**
   * Delete the user folder with the provided name under the provided parent folder. The file layout
   * settings are consulted to determine if a flat layout or a usertree layout is used.
   *
   * @param parent the parent folder.
   * @param userName the user name.
   * @return true if the creation was successful.
   */
  public static boolean deleteMetaUserFolder(File parent, String userName) {
    String[] files = parent.list();
    if (files.length != 0) {
      throw new RuntimeException("Meta File Error, cannot delete, not empty.");
    }
    if (!parent.delete()) {
      throw new RuntimeException("Meta File Error, cannot delete folder.");
    }

    // consult layout preference
    String layout = getLayoutPreference();

    if ("flat".equals(layout)) { // $NON-NLS-1$
      // default layout is a flat list of user at the root
      return true;
    }

    // the user-tree layout organises projects by the user who created it: metastore/an/anthony
    File orgFolder = parent.getParentFile();
    files = orgFolder.list();
    if (files.length != 0) {
      return true;
    }
    if (!orgFolder.delete()) {
      throw new RuntimeException("Meta File Error, cannot delete folder.");
    }
    return true;
  }
Ejemplo n.º 12
0
  // TODO make this run through file names instead of doing manually?
  public void loadAssets() {
    File f = new File("images");
    String[] files = f.list();

    if (files != null) {
      for (String s : files) {
        System.out.println("loading image : " + s);
        loadImage(s);
      }
    }

    f = new File("sounds");
    files = f.list();

    if (files != null) {
      for (String s : files) {
        System.out.println("loading audio : " + s);
        loadAudio(s, true);
      }
    }

    f = new File("music");
    files = f.list();

    if (files != null) {
      for (String s : files) {
        System.out.println("loading music : " + s);
        loadAudio(s, false);
      }
    }
  }
  /**
   * this function determines the hazard curve based on the parameters
   *
   * @param imtLogFlag: Checks if the selected IMT is SA, PGA pr PGV, so that we can revert the the
   *     Log X values of the Hazard func values back to the original values, before writing to the
   *     file for each site.
   * @param hazFunction : it has X values set and result will be returned in this function
   * @param site : site parameter
   * @param imr :selected IMR object
   * @param eqkRupForecast : selected Earthquake rup forecast
   * @param mapParametersInfo : Parameters in String form used to generate the map
   * @return
   */
  public void getHazardMapCurves(
      boolean imtLogFlag,
      double[] xValues,
      SitesInGriddedRegion griddedSites,
      ScalarIntensityMeasureRelationshipAPI imr,
      EqkRupForecast eqkRupForecast,
      String mapParametersInfo) {

    // get the number of data sets presently in directory
    File mainDir = new File(this.DATASETS_PATH);

    if (!mainDir.isDirectory()) { // if main directory does not exist
      boolean success = (new File(DATASETS_PATH)).mkdir();
      newDir = DATASETS_PATH + "1";
    } else {
      if (mainDir.list() != null) { // if there are various data sets in directory
        int numDataSets = mainDir.list().length;
        newDir = DATASETS_PATH + (numDataSets + 1);
      } else { // if main directory is there but it is empty
        newDir = DATASETS_PATH + "1";
      }
    }
    // creating a new directory that stores all the HazardCurves for that region
    boolean success = (new File(newDir)).mkdir();
    calculate(imtLogFlag, xValues, griddedSites, imr, eqkRupForecast, mapParametersInfo, null);
  }
Ejemplo n.º 14
0
  @Test
  public void shouldSyncReposToDisk() throws ClassNotFoundException, IOException {
    SubsetSizeRepo subsetRepo = factory.createSubsetRepo("dev", LATEST_VERSION);
    SuiteTimeRepo suiteTimeRepo = factory.createSuiteTimeRepo("dev", LATEST_VERSION);
    SuiteResultRepo suiteResultRepo = factory.createSuiteResultRepo("dev", LATEST_VERSION);
    subsetRepo.add(new SubsetSizeEntry(10));
    suiteTimeRepo.update(new SuiteTimeEntry("foo.bar.Quux", 25));
    suiteResultRepo.update(new SuiteResultEntry("foo.bar.Baz", true));

    assertThat(
        "No files should exist as sync on this factory has never been called.",
        baseDir.list().length,
        is(0));

    factory.syncReposToDisk();

    assertThat(
        "Files should exist as sync on this factory has been called.",
        baseDir.list().length,
        is(3));

    assertContentIs(EntryRepoFactory.name("dev", LATEST_VERSION, SUBSET_SIZE), "10");
    assertContentIs(EntryRepoFactory.name("dev", LATEST_VERSION, SUITE_TIME), "foo.bar.Quux: 25");
    assertContentIs(
        EntryRepoFactory.name("dev", LATEST_VERSION, SUITE_RESULT), "foo.bar.Baz: true");
  }
Ejemplo n.º 15
0
  @Suites
  public static List<NamedParametrizedSuite> enumerateSuites() throws Exception {
    File dir = TestResourcesFixture.resourceNameToFile(MassExpansionTest.class, "/" + TESTS_DIR);

    String[] testSetDirs =
        dir.list(
            new FilenameFilter() {
              @Override
              public boolean accept(File dir, String name) {
                return new File(dir, name).isDirectory();
              }
            });

    String[] testSetZips =
        dir.list(
            new FilenameFilter() {
              @Override
              public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".zip");
              }
            });

    List<NamedParametrizedSuite> suites = new ArrayList<NamedParametrizedSuite>();

    for (String testDir : testSetDirs) suites.add(enumerateSuiteTestCases(new File(dir, testDir)));

    for (String testZip : testSetZips)
      suites.add(enumerateSuiteTestCasesFromZip(new File(dir, testZip)));

    Collections.sort(suites);

    return suites;
  }
Ejemplo n.º 16
0
  public static void deleteDirectory(File file) throws IOException {

    if (file.isDirectory()) {
      // directory is empty, then delete it
      if (file.list().length == 0) {
        file.delete();
      } else {
        // list all the directory contents
        String files[] = file.list();
        for (String temp : files) {
          // construct the file structure
          File fileDelete = new File(file, temp);
          // recursive delete
          deleteDirectory(fileDelete);
        }
        // check the directory again, if empty then delete it
        if (file.list().length == 0) {
          file.delete();
        }
      }

    } else {
      // if file, then delete it
      file.delete();
    }
  }
Ejemplo n.º 17
0
  @Test
  public void testWriterRollback() throws Exception {
    // verify staging directory is empty
    File staging = new File(new File(temporary, "data"), "staging");
    assertDirectory(staging);
    assertEquals(staging.list(), new String[] {});

    // create a shard in staging
    OrcStorageManager manager = createOrcStorageManager();

    List<Long> columnIds = ImmutableList.of(3L, 7L);
    List<Type> columnTypes = ImmutableList.<Type>of(BIGINT, createVarcharType(10));

    StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes);
    List<Page> pages = rowPagesBuilder(columnTypes).row(123L, "hello").row(456L, "bye").build();
    sink.appendPages(pages);

    sink.flush();

    // verify shard exists in staging
    String[] files = staging.list();
    assertEquals(files.length, 1);
    assertTrue(files[0].endsWith(".orc"));

    // rollback should cleanup staging files
    sink.rollback();

    assertEquals(staging.list(), new String[] {});
  }
Ejemplo n.º 18
0
 private void deleteRecursively(File f) {
   if (f.isDirectory()) {
     for (int i = f.list().length - 1; i >= 0; i--) {
       deleteRecursively(new File(f.getAbsolutePath() + File.separator + f.list()[i]));
     }
   }
   f.delete();
 }
Ejemplo n.º 19
0
 public static void main(String[] args) {
   File path = new File(".");
   String[] list;
   if (args.length == 0) list = path.list();
   else list = path.list(new DirFilter(args[0]));
   Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
   for (String dirItem : list) System.out.println(dirItem);
 }
Ejemplo n.º 20
0
  public static List<EnableappInfo> getInstalledAppsDisabled(Context context) {
    List<EnableappInfo> res = new ArrayList<EnableappInfo>();
    File fDisableSystem = new File(DirHelper.ENABLEAPP_DIR_SYSTEM);
    if (fDisableSystem.exists()) {
      for (String s : fDisableSystem.list()) {
        if (s.toLowerCase().endsWith(".apk")) {
          EnableappInfo newinfo = new EnableappInfo();
          newinfo.info = getAppInfoFromPackage(DirHelper.ENABLEAPP_DIR_SYSTEM + s);

          if (newinfo.info == null) {
            continue;
          }
          newinfo.type = 0;
          newinfo.enabled = false;
          newinfo.filePath = DirHelper.ENABLEAPP_DIR_SYSTEM + s;
          res.add(newinfo);
        }
      }
    }

    File fDisablePrivate = new File(DirHelper.ENABLEAPP_DIR_PRIVATE);
    if (fDisablePrivate.exists()) {
      for (String s : fDisablePrivate.list()) {
        if (s.toLowerCase().endsWith(".apk")) {
          EnableappInfo newinfo = new EnableappInfo();
          newinfo.info = getAppInfoFromPackage(DirHelper.ENABLEAPP_DIR_PRIVATE + s);

          if (newinfo.info == null) {
            continue;
          }
          newinfo.type = 3;
          newinfo.enabled = false;
          newinfo.filePath = DirHelper.ENABLEAPP_DIR_PRIVATE + s;
          res.add(newinfo);
        }
      }
    }

    File fDisableData = new File(DirHelper.ENABLEAPP_DIR_DATA);
    if (fDisableData.exists()) {
      for (String s : fDisableData.list()) {
        if (s.toLowerCase().endsWith(".apk")) {
          EnableappInfo newinfo = new EnableappInfo();
          newinfo.info = getAppInfoFromPackage(DirHelper.ENABLEAPP_DIR_DATA + s);

          if (newinfo.info == null) {
            continue;
          }
          newinfo.type = 1;
          newinfo.enabled = false;
          newinfo.filePath = DirHelper.ENABLEAPP_DIR_DATA + s;
          res.add(newinfo);
        }
      }
    }

    return res;
  }
Ejemplo n.º 21
0
 private void writeIntoFile(int numOfDir, int numOfFile) {
   String dirString = String.valueOf(numOfDir) + ".dir";
   String fileString = String.valueOf(numOfFile) + ".dat";
   File dbDir = tableDir.toPath().resolve(dirString).normalize().toFile();
   if (!dbDir.isDirectory()) {
     dbDir.mkdir();
   }
   File dbFile = dbDir.toPath().resolve(fileString).normalize().toFile();
   if (list[numOfDir][numOfFile].isEmpty()) {
     dbFile.delete();
     if (dbDir.list().length == 0) {
       dbDir.delete();
     }
     return;
   }
   RandomAccessFile db;
   try {
     db = new RandomAccessFile(dbFile, "rw");
     try {
       db.setLength(0);
       Iterator<Map.Entry<String, String>> it;
       it = list[numOfDir][numOfFile].entrySet().iterator();
       long[] pointers = new long[list[numOfDir][numOfFile].size()];
       int counter = 0;
       while (it.hasNext()) {
         Map.Entry<String, String> m = (Map.Entry<String, String>) it.next();
         String key = m.getKey();
         db.write(key.getBytes("UTF-8"));
         db.write("\0".getBytes("UTF-8"));
         pointers[counter] = db.getFilePointer();
         db.seek(pointers[counter] + 4);
         ++counter;
       }
       it = list[numOfDir][numOfFile].entrySet().iterator();
       counter = 0;
       while (it.hasNext()) {
         Map.Entry<String, String> m = (Map.Entry<String, String>) it.next();
         String value = m.getValue();
         int curPointer = (int) db.getFilePointer();
         db.seek(pointers[counter]);
         db.writeInt(curPointer);
         db.seek(curPointer);
         db.write(value.getBytes("UTF-8"));
         ++counter;
       }
     } catch (Exception e) {
       db.close();
       throw new Exception(e);
     }
     db.close();
     if (dbDir.list().length == 0) {
       dbDir.delete();
     }
   } catch (Exception e) {
     throw new IllegalArgumentException();
   }
 }
 public static void assertFilesEqual(File expected, File actual) {
   if (expected.isDirectory()) {
     assertThat(actual.list(), Matchers.arrayContainingInAnyOrder(expected.list()));
     for (String name : expected.list()) {
       assertFilesEqual(new File(expected, name), new File(actual, name));
     }
   } else {
     assertThat(getContent(actual), Matchers.equalTo(getContent(expected)));
   }
 }
Ejemplo n.º 23
0
  public void analyze() throws Exception {
    HashMap<String, ArrayList<String>> outputDataPaths = new HashMap<String, ArrayList<String>>();

    File outDir = new File(_outputPath);

    File reportDir = new File(_reportPath);
    if (!reportDir.exists()) reportDir.mkdirs();

    FilenameFilter filter =
        new FilenameFilter() {

          public boolean accept(File arg0, String arg1) {
            if (arg1.equals(".svn")) return false;
            else return true;
          }
        };

    // delete all in Statistics directory
    for (String s : reportDir.list(filter)) new File(_reportPath + "/" + s).delete();

    DataNode report = new DataNode("report");
    // list all Output|s directories
    for (String s : outDir.list(filter)) {
      String config = _outputPath + "/" + s + "/config.xml";
      if (new File(config).exists()) {
        List<DataNode> runs =
            processDirectorySet(
                new File(_outputPath + "/" + s).listFiles(), _outputPath, _reportPath, s);

        DataNode batch = new DataNode("batch");
        for (DataNode dn : runs) batch.putDataNode(dn);

        batch.putValue("id", s);

        String[] date = s.split("-");
        batch.putValue("date", date[0] + "-" + date[1]);
        batch.putDataNode(XmlHelper.readXml(new File(config)));

        report.putDataNode(batch);
      }
    }

    XmlHelper.writeXml(report, _reportPath + "/report.xml");

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer =
        tFactory.newTransformer(
            new javax.xml.transform.stream.StreamSource(
                getClass().getResourceAsStream("report.xsl")));

    transformer.transform(
        new javax.xml.transform.stream.StreamSource(_reportPath + "/report.xml"),
        new javax.xml.transform.stream.StreamResult(
            new FileOutputStream(_reportPath + "/report.html")));
  }
  @Test
  public void givenATextInputFileWhenVisitFileThenFileIsCopiedToTaskOutputDirectory() {
    FileVisitDetails fileDetails = mock(FileVisitDetails.class);
    when(fileDetails.getFile()).thenReturn(new File(inputDirectory, TEXT_INPUT_FILENAME));
    when(fileDetails.getName()).thenReturn(TEXT_INPUT_FILENAME);

    sourceVisitor.visitFile(fileDetails);

    assertEquals(1, outputDirectory.list().length);
    assertTrue(Arrays.asList(outputDirectory.list()).contains(TEXT_INPUT_FILENAME));
  }
Ejemplo n.º 25
0
  /**
   * Deploy applications for any directories or WAR files that are found in our "application root"
   * directory.
   */
  protected void deployApps() {

    File appBase = appBase();
    File configBase = configBase();
    // Deploy XML descriptors from configBase
    deployDescriptors(configBase, configBase.list());
    // Deploy WARs, and loop if additional descriptors are found
    deployWARs(appBase, appBase.list());
    // Deploy expanded folders
    deployDirectories(appBase, appBase.list());
  }
Ejemplo n.º 26
0
 @Override
 public int getChildCount(final Object parent) {
   File file = (File) parent;
   if (file.isDirectory()) {
     String[] fileList = file.list();
     if (fileList != null) {
       return file.list().length;
     }
   }
   return 0;
 }
  /**
   * Deletes a settings entry from the DB
   *
   * @return true if settings were deleted successfully, false otherwise
   */
  public synchronized boolean deleteSettings(String packageName) {
    boolean result = true;

    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction(); // make sure this ends up in a consistent state (DB and plain text files)
    try {
      //            Log.d(TAG, "deleteSettings - deleting database entry for " + packageName + " ("
      // + uid + ")");
      // try deleting contacts allowed entries; do not fail if deletion not possible
      Cursor c =
          db.query(
              TABLE_SETTINGS,
              new String[] {"_id"},
              "packageName=?",
              new String[] {packageName},
              null,
              null,
              null);
      if (c != null && c.getCount() > 0 && c.moveToFirst()) {
        int id = c.getInt(0);
        db.delete(TABLE_ALLOWED_CONTACTS, "settings_id=?", new String[] {Integer.toString(id)});
        c.close();
      }

      if (db.delete(TABLE_SETTINGS, "packageName=?", new String[] {packageName}) == 0) {
        Log.e(TAG, "deleteSettings - database entry for " + packageName + " not found");
        return false;
      }

      // delete settings from plain text file (for access from core libraries)
      //            File settingsUidDir = new File("/data/system/privacy/" + packageName + "/" + uid
      // + "/");
      File settingsPackageDir = new File("/data/system/privacy/" + packageName + "/");
      File systemLogsSettingFile =
          new File("/data/system/privacy/" + packageName + "/systemLogsSetting");
      // delete the setting files
      systemLogsSettingFile.delete();
      // delete the parent directories
      //            settingsUidDir.delete();
      if (settingsPackageDir.list() == null || settingsPackageDir.list().length == 0)
        settingsPackageDir.delete();
      // mark DB transaction successful (commit the changes)
      db.setTransactionSuccessful();
    } catch (Exception e) {
      result = false;
      Log.e(TAG, "deleteSettings - could not delete settings", e);
    } finally {
      db.endTransaction();
      if (db != null && db.isOpen()) db.close();
    }

    return result;
  }
Ejemplo n.º 28
0
 public void initFortunepath() {
   fortunepath = Environment.getExternalStorageDirectory().getPath();
   if (!fortunepath.endsWith("/")) {
     fortunepath += "/";
   }
   fortunepath += "cowsay/fortunes/";
   File f = new File(fortunepath);
   f.mkdirs();
   if (f.list() == null || f.list().length == 0) {
     copyFiles();
   }
 }
Ejemplo n.º 29
0
 private static void verifySingle(File ca) {
   if (ca.exists()) {
     if (ca.list().length > 0) {
       System.out.println(
           "looks OK: " + ca.getAbsolutePath() + " items: " + toStringList(ca.list()));
     } else {
       System.out.println("Warning!: " + ca.getAbsolutePath() + " is empty!");
     }
   } else {
     System.out.println("Error!: " + ca.getAbsolutePath() + " dont exists!");
   }
 }
Ejemplo n.º 30
0
  @Override
  public boolean onCreate() {
    // Log.v(TAG,"onCreate:: Oncreate started");

    providerUri =
        Uri.parse(
            "content://"
                + "edu.buffalo.cse.cse486586.simpledynamo.provider"
                + "/edu.buffalo.cse.cse486586.simpledynamo.SimpleDynamoProvider");
    newInserts = new HashMap<>();
    recoveryInProgress = false;
    /** Calculate the local port number */
    TelephonyManager tel =
        (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
    String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() - 4);
    localPort = String.valueOf((Integer.parseInt(portStr) * 2));

    ports = new HashSet<String>();
    dynamoNodes = new ArrayList<Node>();
    ports.add("11108");
    ports.add("11112");
    ports.add("11116");
    ports.add("11120");
    ports.add("11124");
    for (String port : ports) {
      Node node = new Node(port, convertPortNumToHashVal(port));
      dynamoNodes.add(node);
    }
    Collections.sort(dynamoNodes, new NodeHashValComparator());

    /*
     * Create a server socket as well as a thread (AsyncTask) that listens on the server
     * port.
     */

    try {
      ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
      new ServerTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serverSocket);
    } catch (IOException e) {
      Log.e(TAG, "Can't create a ServerSocket");
    }

    /** Start recovery */
    File filesDir = getContext().getFilesDir();
    if (filesDir.list() != null && filesDir.list().length > 0) {
      recoveryInProgress = true;
      // Log.v(TAG,"Started Recovery Task");
      new RecoverTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
    }

    return false;
  }