/**
  * Load fixtures and send it to the {@link SolrServer}.
  *
  * @param server The solr server.
  * @param core The core's name.
  * @param fixturesDir The fixtures directory.
  * @param async True for using a thread.
  */
 private static void populate(
     final SolrServer server, final String core, final File fixturesDir, final boolean async) {
   final Collection<File> xmlFiles = FileUtils.listFiles(fixturesDir, new String[] {"xml"}, true);
   if (xmlFiles.size() > 0) {
     Runnable post =
         new Runnable() {
           @Override
           public void run() {
             try {
               for (File xmlFile : xmlFiles) {
                 logger.info("[{}]: sending: {}...", core, xmlFile);
                 // Ensure it's in UTF-8 encoding
                 Reader reader = new InputStreamReader(new FileInputStream(xmlFile), "UTF-8");
                 String body = IOUtils.toString(reader);
                 SolrRequest request = new DirectXmlRequest("/update", body);
                 /** Post the document to the Index */
                 request.process(server);
                 IOUtils.closeQuietly(reader);
               }
               // Commit the changes
               server.commit();
             } catch (Exception ex) {
               logger.error("Unable to initialize data", ex);
             }
           }
         };
     if (async) {
       Thread thread = new Thread(post, core + "-postData");
       thread.setDaemon(true);
       thread.start();
     } else {
       post.run();
     }
   }
 }
  /**
   * Evaluate.
   *
   * @param goldenDirectory the golden directory
   * @param annotatedDirectory the annotated directory
   * @throws UIMAException the uIMA exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public void evaluate(File goldenDirectory, File annotatedDirectory)
      throws UIMAException, IOException {

    File[] goldens =
        FileUtils.listFiles(goldenDirectory, new String[] {"xmi"}, false).toArray(new File[] {});
    File[] annotated =
        FileUtils.listFiles(annotatedDirectory, new String[] {"xmi"}, false).toArray(new File[] {});

    for (int i = 0; i < goldens.length; i++) {
      String goldenFileName = goldens[i].getName();
      String annotatedFileName = annotated[i].getName();

      logger.info(
          "\n----------------\nComparing "
              + goldenFileName
              + " with "
              + annotatedFileName
              + "\n----------------\n");

      List<String> goldenSentences =
          Utils.extractCoveredTextAnnotations(goldens[i].getAbsolutePath(), Sentence.class);
      List<String> goldenConcern =
          Utils.extractCoveredTextAnnotations(goldens[i].getAbsolutePath(), DesignDecision.class);
      List<String> discoveredConcern =
          Utils.extractCoveredTextAnnotations(annotated[i].getAbsolutePath(), DesignDecision.class);

      goldenSentences.removeAll(discoveredConcern);
      goldenConcern.removeAll(discoveredConcern);

      logger.info("untraced concerns " + goldenConcern.size());
      logger.info("untraced sentences " + goldenSentences.size());
    }
  }
  private void testProcessLeftBelowFilesTooSoon() throws Exception {
    final HadoopWriterFactory factory = new NoWriteHadoopWriterFactory(null, config);

    FileUtils.touch(new File(lockDirectory.getPath() + "/some_file_which_should_be_sent_1"));
    FileUtils.touch(new File(lockDirectory.getPath() + "/some_file_which_should_be_sent_2"));
    FileUtils.touch(
        new File(quarantineDirectory.getPath() + "/some_other_file_which_should_be_sent"));

    Assert.assertEquals(
        FileUtils.listFiles(
                spoolDirectory, FileFilterUtils.trueFileFilter(), FileFilterUtils.trueFileFilter())
            .size(),
        3);
    Assert.assertTrue(spoolDirectory.exists());
    Assert.assertTrue(tmpDirectory.exists());
    Assert.assertTrue(lockDirectory.exists());
    Assert.assertTrue(quarantineDirectory.exists());

    // No sleep!
    factory.processLeftBelowFiles();

    // No file should have been sent
    Assert.assertEquals(
        FileUtils.listFiles(
                spoolDirectory, FileFilterUtils.trueFileFilter(), FileFilterUtils.trueFileFilter())
            .size(),
        3);
    Assert.assertTrue(spoolDirectory.exists());
    Assert.assertTrue(tmpDirectory.exists());
    Assert.assertTrue(lockDirectory.exists());
    Assert.assertTrue(quarantineDirectory.exists());

    // We could even test the mapping in HDFS here (with the keys)
    Assert.assertEquals(hdfs.values().size(), 0);
  }
Esempio n. 4
0
 public static void processFileC(Environment env, File testFiles) {
   try {
     env.stageFiles(testFiles);
     env.collateFiles(FileUtils.listFiles(env.getStagingDirectory(), null, true));
   } catch (IOException e) {
     e.printStackTrace();
   }
   env.ingestFiles(FileUtils.listFiles(env.getWorkingDirectory(), null, true));
 }
    @Override
    public Void doInBackground() {

      setProgress(0);

      MetaData metaData;
      final Loader loader = new Loader();
      final File file = loader.load();

      final Collection<File> files =
          FileUtils.listFiles(
              file, new RegexFileFilter("^(.*.mp3)"), DirectoryFileFilter.DIRECTORY);
      final List<Song> songList = new ArrayList<Song>();
      int onePercent = files.size() / 100;
      if (onePercent == 0) {
        onePercent = 1;
      }
      int progressSoFar = 0;
      for (final File singleFile : files) {
        metaData = new MetaData(singleFile);
        songList.add(new Song(metaData, singleFile));

        progress++;
        if (progress % onePercent == 0) {
          setProgress(Math.min(++progressSoFar, 99));
        }
      }

      songLibrary = new SongLibrary(songList);
      setProgress(100);
      pcs.firePropertyChange("libraryLoaded", 0, songLibrary);
      return null;
    }
Esempio n. 6
0
  @Test
  public void testPrintNotAllSourcesWithFilter() throws Exception {
    final File target = new File("./target/print-not-all/default");
    final SpoonAPI launcher = new Launcher();
    launcher.getEnvironment().setNoClasspath(true);
    launcher.addInputResource("./src/main/java");
    launcher.setSourceOutputDirectory(target);
    launcher.setOutputFilter(
        new AbstractFilter<CtType<?>>(CtType.class) {
          @Override
          public boolean matches(CtType<?> element) {
            return "spoon.Launcher".equals(element.getQualifiedName())
                || "spoon.template.AbstractTemplate".equals(element.getQualifiedName());
          }
        });
    launcher.run();

    List<File> list = new ArrayList<>(FileUtils.listFiles(target, new String[] {"java"}, true));
    final List<String> filesName =
        list.stream().map(File::getName).sorted().collect(Collectors.<String>toList());

    assertEquals(2, filesName.size());
    assertEquals("AbstractTemplate.java", filesName.get(0));
    assertEquals("Launcher.java", filesName.get(1));
  }
Esempio n. 7
0
 @SuppressWarnings("unchecked")
 private static void startPlugins() {
   logger.info("Loading available plugins");
   final Collection<File> botJars =
       FileUtils.listFiles(pluginsDirecotry, new String[] {"jar"}, false);
   for (File botJar : botJars) {
     try {
       JarFile jar = new JarFile(botJar);
       ZipEntry ze = jar.getEntry("plugin.yml");
       if (ze == null) throw new RuntimeException("Plugin has no plugin.yml file!");
       InputStream is = jar.getInputStream(ze);
       YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true);
       String mainClass = n.getString("mainClass");
       String name = n.getString("name");
       URLClassLoader loader =
           new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader());
       Plugin plugin = loader.loadClass(mainClass).asSubclass(Plugin.class).newInstance();
       plugin.start();
       PLUGIN_INFO.put(name, new PluginInfo(name, plugin, n));
       logger.info("Loaded plugin '{}'", name);
     } catch (Exception e) {
       logger.error("Failed to load plugin from {}", botJar.getName());
       e.printStackTrace();
     }
   }
   logger.info("Loaded {} plugin(s)", PLUGIN_INFO.size());
 }
Esempio n. 8
0
 @SuppressWarnings("unchecked")
 private static void loadBots() {
   logger.info("Loading available bots");
   final Collection<File> botJars =
       FileUtils.listFiles(botsDirecotry, new String[] {"jar"}, false);
   for (File botJar : botJars) {
     try {
       JarFile jar = new JarFile(botJar);
       ZipEntry entry = jar.getEntry("bot.yml");
       if (entry == null) throw new RuntimeException("Bot has no bot.yml file!");
       InputStream is = jar.getInputStream(entry);
       YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true);
       String mainClass = n.getString("mainClass");
       String type = n.getString("type");
       URLClassLoader loader =
           new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader());
       BOT_INFO.put(type, new BotClassInfo(loader.loadClass(mainClass).asSubclass(Bot.class), n));
       logger.info("Loaded bot '{}'", type);
     } catch (Exception e) {
       logger.error("Failed to load bot from {}", botJar.getName());
       e.printStackTrace();
     }
   }
   logger.info("Loaded {} bot(s)", BOT_INFO.size());
 }
Esempio n. 9
0
 public synchronized List<String> listSpecs() {
   List<String> specs = new ArrayList<String>();
   for (File f : org.apache.commons.io.FileUtils.listFiles(home, new String[] {"spec"}, false)) {
     specs.add(f.getName().substring(0, f.getName().lastIndexOf('.')));
   }
   return specs;
 }
Esempio n. 10
0
 private File[] getScriptFiles() {
   final String starts = this.prefix + "_";
   if (AppConstants.SCRIPT_DIR.exists() == false) {
     return new File[0];
   }
   File[] array =
       FileUtils.listFiles(
               AppConstants.SCRIPT_DIR,
               new AbstractFileFilter() {
                 @Override
                 public boolean accept(File file) {
                   String name = file.getName();
                   return name.endsWith(".js") && name.startsWith(starts);
                 }
               },
               FileFilterUtils.trueFileFilter())
           .toArray(new File[0]);
   Arrays.sort(
       array,
       new Comparator<File>() {
         @Override
         public int compare(File arg0, File arg1) {
           return arg0.getPath().compareTo(arg1.getPath());
         }
       });
   return array;
 }
Esempio n. 11
0
  File[] getArtifactFilesOfType(
      String artifactsPathFromRoot, String jobArtifactPath, final String fileExtension) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(
          "getArtifactFilesOfType("
              + artifactsPathFromRoot
              + ", "
              + jobArtifactPath
              + ", "
              + fileExtension
              + ")");
    }

    File jobArtifactFile =
        new File(artifactBaseDir, artifactsPathFromRoot + File.separator + jobArtifactPath);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Artifact directory calculated to be " + jobArtifactFile.getAbsolutePath());
    }

    if (!jobArtifactFile.exists() || !jobArtifactFile.isDirectory()) {
      return new File[0];
    }

    Collection collection =
        FileUtils.listFiles(
            jobArtifactFile,
            new SuffixFileFilter(fileExtension, IOCase.INSENSITIVE),
            TrueFileFilter.INSTANCE);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("" + collection.size() + " artifact files found.");
    }
    return (File[]) collection.toArray(new File[0]);
  }
Esempio n. 12
0
  /**
   * @param path
   * @param keyword keyword which should be contained in the desired file names
   * @param ext
   * @param include if the keyword should be exist in the file name
   * @return
   */
  public static List<File> findFilesByKeyword(
      String path, String keyword, boolean include, String ext) {
    ArrayList<File> rst = new ArrayList<File>();
    String[] ptns = keyword.split(",");
    Collection<File> files =
        FileUtils.listFiles(new File(path), new String[] {PathUtil.getExtName(ext)}, true);
    for (File file : files) {
      for (String p : ptns) {
        if (include) {
          if (file.getName().contains(p.trim())) {
            rst.add(file);
          }
        } else {
          if (!file.getName().contains(p.trim())) {
            rst.add(file);
          }
        }
      }
    }

    if (log.isDebugEnabled()) {
      System.out.println(rst.size() + " files found=============");
      for (File file : rst) {
        System.out.println(file.getAbsolutePath());
      }
    }
    return rst;
  }
Esempio n. 13
0
  @Test
  public void testAlreadyExistingMuleConfigWithApikitRouter() throws Exception {
    List<File> ramls = Arrays.asList(getFile("scaffolder-existing/simple.raml"));
    File xmlFile = getFile("scaffolder-existing/mule-config-no-api-flows.xml");
    List<File> xmls = Arrays.asList(xmlFile);
    File muleXmlOut = folder.newFolder("mule-xml-out");

    Scaffolder scaffolder = createScaffolder(ramls, xmls, muleXmlOut);
    scaffolder.run();

    assertTrue(xmlFile.exists());
    String s = IOUtils.toString(new FileInputStream(xmlFile));
    assertEquals(
        1,
        countOccurences(
            s,
            "http:listener-config name=\"HTTP_Listener_Configuration\" host=\"localhost\" port=\"${serverPort}\""));
    assertEquals(
        1,
        countOccurences(
            s, "http:listener config-ref=\"HTTP_Listener_Configuration\" path=\"/api/*\""));
    assertEquals(1, countOccurences(s, "<apikit:router config-ref=\"apikit-config\" />"));
    assertEquals(0, countOccurences(s, "http:inbound-endpoint"));
    assertEquals(1, countOccurences(s, "get:/pet"));
    assertEquals(1, countOccurences(s, "post:/pet"));
    assertEquals(1, countOccurences(s, "get:/:"));
    Collection<File> newXmlConfigs = FileUtils.listFiles(muleXmlOut, new String[] {"xml"}, true);
    assertEquals(0, newXmlConfigs.size());
  }
  /**
   * Find the Java File object based off of a starting directory.
   *
   * @param filename the filename to search for
   * @param startingDirectory the directory to start searching at
   * @return the File discovered
   * @throws FileNotFoundException will throw an exception if no file is found matching the criteria
   */
  public static File findAbsoluteFile(final String filename, final String startingDirectory)
      throws FileNotFoundException {
    File returnFile = null;
    try {
      File startingDirFile = new File(startingDirectory);
      Collection<File> files =
          FileUtils.listFiles(
              startingDirFile, FileFilterUtils.nameFileFilter(filename), TrueFileFilter.INSTANCE);

      if (files.size() == 0) {
        throw new FileNotFoundException(
            "file '" + filename + "' not found in directory '" + startingDirectory);
      } else if (files.size() > 1) {
        throw new FileNotFoundException(
            "multiple files with filename '"
                + filename
                + "' found in directory '"
                + startingDirectory);
      } else {
        for (File f : files) {
          returnFile = f;
        }
      }
    } catch (FileNotFoundException fnfe) {
      throw fnfe;
    } catch (Exception e) {
      throw new FileNotFoundException(
          "'" + filename + "' not found in directory '" + startingDirectory + "'");
    }
    return returnFile;
  }
Esempio n. 15
0
  public void run(String[] args)
      throws ParseException, TransformationException, IOException, AnalysisException {
    Options options = new Options();
    options.addOption("input", true, "input path");
    options.addOption("output", true, "output path");
    options.addOption("ext", true, "extension");
    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(options, args);
    String inDir = line.getOptionValue("input");
    String outDir = line.getOptionValue("output");
    String extension = line.getOptionValue("ext");

    File dir = new File(inDir);

    for (File f : FileUtils.listFiles(dir, new String[] {extension}, true)) {
      TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
      List<BxPage> pages = tvReader.read(new FileReader(f));
      BxDocument doc = new BxDocument().setPages(pages);
      doc.setFilename(f.getName());

      BxDocument rewritten = transform(doc);

      File f2 = new File(outDir + doc.getFilename());
      BxDocumentToTrueVizWriter wrt = new BxDocumentToTrueVizWriter();
      boolean created = f2.createNewFile();
      if (!created) {
        throw new IOException("Cannot create file: ");
      }
      FileWriter fw = new FileWriter(f2);
      wrt.write(fw, Lists.newArrayList(rewritten));
      fw.flush();
      fw.close();
    }
  }
Esempio n. 16
0
 private Collection<File> listFiles(String[] dirs, String[] extensions) {
   List<File> files = new ArrayList<>();
   for (String dir : dirs) {
     files.addAll(FileUtils.listFiles(new File(rootDir, dir), extensions, true));
   }
   return files;
 }
  /** Tests that the variables are degribed to csv and that the csv contains the actual values */
  @Test
  public void testDegribVariables() {
    variable.setName(VARIABLE_NAME);
    variable.setMessages(messages);
    variable.setOutputName(OUTPUT_VARIABLE_NAME);
    variables = new ArrayList<DegribVariable>();
    variables.add(variable);
    degrib.setVariables(variables);

    try {
      degrib.degribVariables();
    } catch (IOException e1) {
      System.out.println("Error running degrib executable");
      e1.printStackTrace();
    }
    String[] extensions = {"csv"};
    Collection<File> result = FileUtils.listFiles(outputDirectory, extensions, false);
    int actualCount = result.size();

    assertEquals(messages.size(), actualCount);
    for (Integer m : messages) {
      System.out.println(m);
      String currentFile = outputDirectory.getPath() + "/" + OUTPUT_VARIABLE_NAME + m + ".csv";
      System.out.println(currentFile);
      try {
        assertTrue(
            FileUtils.directoryContains(
                outputDirectory, new File(outputDirectory, OUTPUT_VARIABLE_NAME + m + ".csv")));
      } catch (IOException e) {
        System.out.println("Error accessing directory");
      }
    }
  }
Esempio n. 18
0
  protected static Set<X509Certificate> listerCertificats(
      String aCertificatesDirectory, String typeCert, String provider, boolean recursive)
      throws IOException, GeneralSecurityException {
    List<X509Certificate> lstCert = new ArrayList<X509Certificate>();
    // Set<X509Certificate> lstCert = new HashSet<X509Certificate>();
    // recherche des certificats dans le répertoire (*.cer ou *.CER)

    IOFileFilter fileFilter = new WildcardFileFilter(FILTRE_CERTIFICAT_X509, IOCase.INSENSITIVE);

    IOFileFilter dirFilter = recursive ? TrueFileFilter.INSTANCE : null;
    Collection<File> lstFichiers =
        FileUtils.listFiles(new File(aCertificatesDirectory), fileFilter, dirFilter);

    if (lstFichiers != null) {
      // boucle sur les certificats trouvés
      for (File fichier : lstFichiers) {
        InputStream certStream = new FileInputStream(fichier);
        // remarque: un fichier .cer peut contenir plus d'un certificat
        Collection<X509Certificate> trustedCerts =
            chargerCertificatsX509(certStream, typeCert, provider);
        IOUtils.closeQuietly(certStream);
        lstCert.addAll(trustedCerts);
      }
    }
    Set<X509Certificate> trustedCertificates = new HashSet<X509Certificate>(lstCert);
    return trustedCertificates;
  }
  public static void reconstructTurtle(File partFolder, File reconstructed) throws IOException {
    Path tmpOut = Files.createTempFile(partFolder.toPath(), "reconstr", ".tmp");
    FileOutputStream dstOut = new FileOutputStream(tmpOut.toFile());
    FileChannel dstOutChannel = dstOut.getChannel();
    try {
      if (!Files.isDirectory(partFolder.toPath()))
        throw new IOException("Not a directory: " + partFolder);
      File[] fileList =
          FileUtils.listFiles(partFolder, new PrefixFileFilter("part"), TrueFileFilter.TRUE)
              .toArray(new File[0]);
      Arrays.sort(fileList);
      RandomAccessFile inputFile;

      inputFile = new RandomAccessFile(fileList[0], "r");
      inputFile.getChannel().transferTo(0, inputFile.length(), dstOutChannel);
      inputFile.close();
      for (int i = 1; i < fileList.length; i++) {
        inputFile = new RandomAccessFile(fileList[i], "r");
        long lastPrefix = findTurtlePrefixEnd(inputFile);
        inputFile
            .getChannel()
            .transferTo(lastPrefix, inputFile.length() - lastPrefix, dstOutChannel);
        inputFile.close();
      }
    } finally {
      dstOut.close();
    }
    Files.move(
        tmpOut,
        reconstructed.toPath(),
        StandardCopyOption.ATOMIC_MOVE,
        StandardCopyOption.REPLACE_EXISTING);
    FileUtils.deleteQuietly(tmpOut.toFile());
    FileUtils.deleteQuietly(partFolder);
  }
Esempio n. 20
0
  /**
   * Search for the adb.exe in the folder that is specified in the ANDROID_HOME environment variable
   *
   * @return
   */
  private static File findAdbFile() throws IOException {
    final String androidHome = System.getenv("ANDROID_HOME");
    if (androidHome == null || androidHome.isEmpty()) {
      throw new IOException("ANDROID_HOME environment variable is not set");
    }

    final File root = new File(androidHome);
    if (!root.exists()) {
      throw new IOException("Android home: " + root.getAbsolutePath() + " does not exist");
    }

    try {
      boolean recursive = true;
      Collection<File> files = FileUtils.listFiles(root, null, recursive);
      for (Iterator<File> iterator = files.iterator(); iterator.hasNext(); ) {
        File file = (File) iterator.next();
        // TODO: Eran - I think should be using equals as compareTo is more sortedDataStructure
        // oriented.
        if (file.getName().equals("adb") || file.getName().equals("adb.exe")) {
          return file.getParentFile();
        }
      }
    } catch (Exception e) {
      throw new IOException("Failed to find adb.exe in " + root.getAbsolutePath());
    }
    throw new IOException("Failed to find adb.exe in " + root.getAbsolutePath());
  }
Esempio n. 21
0
 @Parameters
 public static List<Object[]> creoleFiles() throws IOException {
   if (!pCreoleInRoot.isDirectory())
     throw new IllegalStateException("Dir missing: " + pCreoleInRoot.getAbsolutePath());
   if (!nCreoleInRoot.isDirectory())
     throw new IllegalStateException("Dir missing: " + nCreoleInRoot.getAbsolutePath());
   if (pWorkOutRoot.exists()) FileUtils.deleteDirectory(pWorkOutRoot);
   pWorkOutRoot.mkdir();
   if (nWorkOutRoot.exists()) FileUtils.deleteDirectory(nWorkOutRoot);
   nWorkOutRoot.mkdir();
   List<Object[]> params = new ArrayList<Object[]>();
   File eFile;
   for (File f : FileUtils.listFiles(pCreoleInRoot, new String[] {"creole"}, true)) {
     eFile = new File(f.getParentFile(), f.getName().replaceFirst("\\..*", "") + ".html");
     params.add(
         new Object[] {
           f,
           eFile,
           (eFile.isFile()
               ? new File(
                   pWorkOutRoot,
                   f.getParentFile().equals(pCreoleInRoot)
                       ? eFile.getName()
                       : (f.getParent().substring(pCreoleInRootPath.length())
                           + FSEP
                           + eFile.getName()))
               : null),
           Boolean.TRUE
         });
   }
   String name;
   for (File f : FileUtils.listFiles(nCreoleInRoot, new String[] {"creole"}, true)) {
     name = f.getName().replaceFirst("\\..*", "") + ".html";
     params.add(
         new Object[] {
           f,
           null,
           new File(
               nWorkOutRoot,
               f.getParentFile().equals(nCreoleInRoot)
                   ? name
                   : (f.getParent().substring(nCreoleInRootPath.length()) + FSEP + name)),
           Boolean.FALSE
         });
   }
   return params;
 }
Esempio n. 22
0
  /** Gets the generated jtl file path, if it was any generated */
  protected String getJtlFilePath(Project project, String innerProjectJMeterReportsPath) {
    String baseDirPath = project.getFileSystem().getBasedir().getAbsolutePath();
    File reportDir = new File(baseDirPath + innerProjectJMeterReportsPath);

    if (reportDir.exists()) {
      for (File file :
          (Collection<File>) FileUtils.listFiles(reportDir, new String[] {"jtl"}, true)) {
        return file.getAbsolutePath();
      }

      for (File file :
          (Collection<File>) FileUtils.listFiles(reportDir, new String[] {"xml"}, true)) {
        return file.getAbsolutePath();
      }
    }
    return null;
  }
 @After
 public void cleanUp() {
   String[] extensions = {"csv", "txt"};
   Collection<File> toDelete = FileUtils.listFiles(outputDirectory, extensions, false);
   for (File file : toDelete) {
     FileUtils.deleteQuietly(file);
   }
 }
Esempio n. 24
0
  public Collection<File> getXMLs() {

    String[] extensions = {"xml"};

    Collection<File> files = FileUtils.listFiles(getSource(), extensions, true);

    return files;
  }
Esempio n. 25
0
 @SuppressWarnings("unchecked")
 private static void unzipSQLScripts() throws IOException {
   File zipScriptPath = new File(DBTool.getWorkingDirectory(), getZipPath());
   for (File file :
       (Collection<File>) FileUtils.listFiles(zipScriptPath, new String[] {"zip"}, false)) {
     ZipUtils.unzipArchive(file, SCRIPT_INSTALL_DIR);
   }
 }
Esempio n. 26
0
 @SuppressWarnings("unchecked")
 private List<File> listClassFiles() {
   List<File> files =
       new ArrayList<File>(
           (Collection<File>) FileUtils.listFiles(file, new String[] {"class"}, true));
   Collections.sort(files);
   return files;
 }
 private static WebArchive addWebResourcesTo(WebArchive archive) {
   final File webAppDirectory = new File(WEBAPP_SRC);
   for (File file : FileUtils.listFiles(webAppDirectory, null, true)) {
     if (!file.isDirectory()) {
       archive.addAsWebResource(file, file.getPath().substring(WEBAPP_SRC.length()));
     }
   }
   return archive;
 }
Esempio n. 28
0
 /**
  * Iteratively finds all jar files in a given directory and scans them, producing {@link
  * VictimsRecord}. The string values of the resulting records will be written to the specified
  * output stream.
  *
  * @param dir
  * @param os
  * @throws IOException
  */
 private static void scanDir(File dir, VictimsOutputStream vos) throws IOException {
   Collection<File> files =
       FileUtils.listFiles(
           dir, new RegexFileFilter("^(.*?)\\.jar"), DirectoryFileFilter.DIRECTORY);
   Iterator<File> fi = files.iterator();
   while (fi.hasNext()) {
     scanFile(fi.next(), vos);
   }
 }
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case GitActivity.REQUEST_CLONE:
          // if we get here with a RESULT_OK then it's probably OK :)
          settings.edit().putBoolean("repository_initialized", true).apply();
          break;
        case PgpHandler.REQUEST_CODE_ENCRYPT:
          Git git = new Git(PasswordRepository.getRepository(new File("")));
          GitAsyncTask tasks = new GitAsyncTask(this, false, false, CommitCommand.class);
          tasks.execute(
              git.add().addFilepattern("."),
              git.commit()
                  .setMessage(
                      this.getResources().getString(R.string.add_commit_text)
                          + data.getExtras().getString("NAME")
                          + this.getResources().getString(R.string.from_store)));
          refreshListAdapter();
          break;
        case GitActivity.REQUEST_INIT:
          initializeRepositoryInfo();
          break;
        case GitActivity.REQUEST_PULL:
          updateListAdapter();
          break;
        case HOME:
          checkLocalRepository();
          break;
        case NEW_REPO_BUTTON:
          initializeRepositoryInfo();
          break;
        case CLONE_REPO_BUTTON:
          // duplicate code
          if (settings.getBoolean("git_external", false)
              && settings.getString("git_external_repo", null) != null) {
            String externalRepoPath = settings.getString("git_external_repo", null);
            File dir = externalRepoPath != null ? new File(externalRepoPath) : null;

            if (dir != null
                && dir.exists()
                && dir.isDirectory()
                && !FileUtils.listFiles(dir, null, true).isEmpty()
                && !PasswordRepository.getPasswords(
                        dir, PasswordRepository.getRepositoryDirectory(this))
                    .isEmpty()) {
              PasswordRepository.closeRepository();
              checkLocalRepository();
              return; // if not empty, just show me the passwords!
            }
          }
          Intent intent = new Intent(activity, GitActivity.class);
          intent.putExtra("Operation", GitActivity.REQUEST_CLONE);
          startActivityForResult(intent, GitActivity.REQUEST_CLONE);
          break;
      }
    }
  }
Esempio n. 30
0
 /**
  * Process and compare the files which a located in different folders.
  *
  * @param sourceFolder folder where the source files are located.
  * @param targetFolder folder where the target files are located.
  * @param fileFilter filter used to select files to process.
  * @param toTargetFileName {@link Transformer} used to identify the target file name based on
  *     source file name.
  * @param preProcessor {@link ResourcePreProcessor} used to process the source files.
  * @throws IOException
  */
 private static void compareFromDifferentFolders(
     final File sourceFolder,
     final File targetFolder,
     final IOFileFilter fileFilter,
     final Transformer<String> toTargetFileName,
     final ResourcePreProcessor preProcessor)
     throws IOException {
   LOG.debug("sourceFolder: {}", sourceFolder);
   LOG.debug("targetFolder: {}", targetFolder);
   final Collection<File> files =
       FileUtils.listFiles(sourceFolder, fileFilter, FalseFileFilter.INSTANCE);
   int processedNumber = 0;
   // TODO use WroUtil#runInParallel for running tests faster
   for (final File file : files) {
     File targetFile = null;
     try {
       targetFile = new File(targetFolder, toTargetFileName.transform(file.getName()));
       final InputStream targetFileStream = new FileInputStream(targetFile);
       LOG.debug("=========== processing: {} ===========", file.getName());
       // ResourceType doesn't matter here
       compare(
           new FileInputStream(file),
           targetFileStream,
           new ResourcePostProcessor() {
             public void process(final Reader reader, final Writer writer) throws IOException {
               // ResourceType doesn't matter here
               ResourceType resourceType = ResourceType.JS;
               try {
                 resourceType = ResourceType.get(FilenameUtils.getExtension(file.getPath()));
               } catch (final IllegalArgumentException e) {
                 LOG.warn(
                     "unkown resource type for file: {}, assuming resource type is: {}",
                     file.getPath(),
                     resourceType);
               }
               try {
                 preProcessor.process(
                     Resource.create("file:" + file.getPath(), resourceType), reader, writer);
               } catch (IOException e) {
                 LOG.error("processing failed...", e);
                 throw new WroRuntimeException("Processing failed...", e);
               }
             }
           });
       processedNumber++;
     } catch (final IOException e) {
       LOG.warn(
           "Skip comparison because couldn't find the TARGET file "
               + targetFile.getPath()
               + "\n. Original exception: "
               + e.getCause());
     } catch (final Exception e) {
       throw new WroRuntimeException("A problem during transformation occured", e);
     }
   }
   logSuccess(processedNumber);
 }