Ejemplo n.º 1
0
 Iterator<Path> getSupportSapComNotesZip() throws IOException {
   DirectoryStream<Path> ex =
       Files.newDirectoryStream(
           supportSapComNotes,
           "notes_[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]--[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9].zip");
   return ex.iterator();
 }
Ejemplo n.º 2
0
  /** DirectoryStream tests. DirectoryStream is not recursive */
  @Test
  public void testDirectoryStream() throws IOException {
    Path rootDir = createDemonstrationDirectoryStructure();
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootDir);
    List<Path> paths = iterableToList(dirStream);
    // closing is required
    dirStream.close();

    // stream is not recursive!
    assertEquals(3, paths.size());
    assertTrue(paths.contains(rootDir.resolve("childDir")));
    assertTrue(paths.contains(rootDir.resolve("firstFile.txt")));
    assertTrue(paths.contains(rootDir.resolve("secondFile.txt")));

    // attempt to do something with closed directory stream
    try {
      dirStream.iterator();
      fail("IllegalStateException expected!");
    } catch (IllegalStateException e) {
    }

    // directory stream iterator doesnt support remove()
    try (DirectoryStream<Path> tmpStream = Files.newDirectoryStream(rootDir)) {
      tmpStream.iterator().remove();
      fail("UnsupportedOperationException expected!");
    } catch (UnsupportedOperationException e) {
    }
  }
Ejemplo n.º 3
0
  /**
   * Reads input files from input directory and sorts them in ascending order.
   *
   * @param inputDirPath input directory
   * @return sorted list of input files
   */
  private static List<Path> getInputFiles(final Path inputDirPath) {
    final List<Path> result = new ArrayList<>(10);

    try (final DirectoryStream<Path> files = Files.newDirectoryStream(inputDirPath)) {
      final Iterator<Path> filesIterator = files.iterator();

      while (filesIterator.hasNext()) {
        final Path file = filesIterator.next();

        if (!Files.isDirectory(file)) {
          result.add(file);
        }
      }
    } catch (final IOException ex) {
      throw new RuntimeException("Failed to read content of input directory", ex);
    }

    Collections.sort(
        result,
        new Comparator<Path>() {
          @Override
          public int compare(final Path o1, final Path o2) {
            return o1.getFileName().toString().compareTo(o2.getFileName().toString());
          }
        });

    return result;
  }
Ejemplo n.º 4
0
  public List<T> collect() {
    List<T> list = new ArrayList<>();

    for (Pair<String, String> p : map.keySet()) {

      String folder = p.first;
      String pattern = p.second;
      Function<String, ? extends T> func = map.get(p);

      DirectoryStream<Path> dirStream;
      try {
        dirStream = Files.newDirectoryStream(Paths.get(folder), pattern);
        logger.info(String.format("Load files from folder %s with pattern %s.", folder, pattern));

        // sort the files
        List<String> files = new ArrayList<>();
        dirStream.forEach(s -> files.add(s.toString()));
        Collections.sort(files);

        for (String s : files) {
          logger.info(String.format("Loading file %s.", s));
          list.add(func.apply(s));
        }

      } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(String.format("Could not load files from patern: %s", pattern));
      }
    }

    return list;
  }
Ejemplo n.º 5
0
  static {
    Path tempDataDir = null;

    // create data directory for shell
    try {
      tempDataDir = Files.createTempDirectory("VdbBuilderDataDir");
      tempDataDir.toFile().deleteOnExit();
      System.setProperty(SystemConstants.VDB_BUILDER_DATA_DIR, tempDataDir.toString());
      LOGGER.debug("AbstractCommandTest:_shellDataDirectory = {0}", tempDataDir);

      final Path commandsDir = Paths.get(tempDataDir.toString() + "/commands");
      commandsDir.toFile().deleteOnExit();
      Files.createDirectory(commandsDir);

      System.setProperty("komodo.shell.commandsDir", commandsDir.toString());
      LOGGER.debug("AbstractCommandTest: commands directory is {0}", commandsDir);

      { // find relational command provider jar and copy over to commands directory so it can be
        // discovered
        final String relativeTargetPath = "target";
        final Path targetDir = Paths.get(relativeTargetPath);
        LOGGER.debug("AbstractCommandTest: Looking for jar here: {0}", targetDir);

        try (final DirectoryStream<Path> stream =
            Files.newDirectoryStream(targetDir, "*-with-dependencies.jar")) {
          final Iterator<Path> itr = stream.iterator();

          if (itr.hasNext()) {
            final Path path = itr.next();
            final String pathString = path.toString();
            LOGGER.debug("AbstractCommandTest: found jar {0}", pathString);

            if (itr.hasNext()) {
              Assert.fail(
                  "*** Found more than one relational command provider jar ***"); //$NON-NLS-1$
            }

            // copy
            Path filePath = Paths.get(commandsDir.toString() + '/' + path.getFileName());
            Files.copy(path, filePath);
            filePath.toFile().deleteOnExit();
            LOGGER.debug(
                "AbstractCommandTest: copying jar to {0}",
                (commandsDir.toString() + '/' + path.getFileName()));
          } else {
            Assert.fail("*** Failed to find relational command provider jar ***"); // $NON-NLS-1$
          }
        } catch (final IOException e) {
          Assert.fail("Failed to copy jar to commands directory: " + e.getMessage()); // $NON-NLS-1$
        }
      }
    } catch (final Exception e) {
      Assert.fail(e.getLocalizedMessage());
    }

    SHELL_DATA_DIRECTORY = tempDataDir;
  }
Ejemplo n.º 6
0
  public Path[] getListInstalledPlugins() throws IOException {
    if (!Files.exists(environment.pluginsFile())) {
      return new Path[0];
    }

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(environment.pluginsFile())) {
      return Iterators.toArray(stream.iterator(), Path.class);
    }
  }
Ejemplo n.º 7
0
 /**
  * helper method equivalent to File#listFiles() grabs children only, does not walk recursively
  *
  * @param p
  * @return
  */
 public static List<Path> listPaths(Path p) throws IOException {
   List<Path> list = new ArrayList<>();
   try (DirectoryStream<Path> ds = Files.newDirectoryStream(p)) {
     Iterator<Path> it = ds.iterator();
     while (it.hasNext()) {
       list.add(it.next());
     }
   }
   return list;
 }
Ejemplo n.º 8
0
 private static List<Path> filesInDirectory(String resource)
     throws IOException, URISyntaxException {
   List<Path> files = new ArrayList<>();
   try (DirectoryStream<Path> directoryStream =
       Files.newDirectoryStream(
           Paths.get(RandomKnapsackTest.class.getResource(resource).toURI()))) {
     directoryStream.forEach(files::add);
   }
   return files;
 }
Ejemplo n.º 9
0
 /**
  * Counts immediate children only, does not work recursively
  *
  * @param p
  * @return
  * @throws IOException
  */
 public static int countChildren(Path p) throws IOException {
   int i = 0;
   try (DirectoryStream<Path> ds = Files.newDirectoryStream(p)) {
     Iterator<Path> it = ds.iterator();
     while (it.hasNext()) {
       i++;
       it.next();
     }
   }
   return i;
 }
Ejemplo n.º 10
0
  private static ImmutableSortedSet<Path> listFiles(Path root) throws IOException {
    if (!Files.isDirectory(root)) {
      return ImmutableSortedSet.of();
    }

    ImmutableSortedSet.Builder<Path> toReturn = ImmutableSortedSet.naturalOrder();

    try (DirectoryStream<Path> directory = Files.newDirectoryStream(root)) {
      toReturn.addAll(directory.iterator());
    }

    return toReturn.build();
  }
Ejemplo n.º 11
0
  private static Map<String, Vertabrae> extract_files(Path dir) throws IOException {
    Map<String, Vertabrae> file_names = new TreeMap<>();

    DirectoryStream<Path> directory_stream = java.nio.file.Files.newDirectoryStream(dir, "*.md");

    for (Path from_file : directory_stream) {

      Vertabrae vertabrae = new Vertabrae(from_file);

      file_names.put(vertabrae.file_name(), vertabrae);
      System.out.println("[SPINE] Vertabrae file name: " + vertabrae.file_name());
    }
    directory_stream.close();
    return file_names;
  }
Ejemplo n.º 12
0
  public void testDirectoryIteratorException() throws IOException {
    Path dir = testFolder.resolve("dir2");
    Path trigger = dir.resolve("DirectoryIteratorException");
    Files.createFile(trigger);
    FaultyFileSystem.FaultyFSProvider fsp = FaultyFileSystem.FaultyFSProvider.getInstance();
    FaultyFileSystem fs = (FaultyFileSystem) fsp.newFileSystem(dir, null);

    try {
      fsp.setFaultyMode(false);
      Path fakeRoot = fs.getRoot();
      try {
        try (Stream<Path> s = Files.list(fakeRoot)) {
          s.forEach(
              path -> assertEquals(path.getFileName().toString(), "DirectoryIteratorException"));
        }
      } catch (UncheckedIOException uioe) {
        fail("Unexpected exception.");
      }

      fsp.setFaultyMode(true);
      try {
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(fakeRoot)) {
          Iterator<Path> itor = ds.iterator();
          while (itor.hasNext()) {
            itor.next();
          }
        }
        fail("Shoule throw DirectoryIteratorException");
      } catch (DirectoryIteratorException die) {
      }

      try {
        try (Stream<Path> s = Files.list(fakeRoot)) {
          s.forEach(path -> fail("should not get here"));
        }
      } catch (UncheckedIOException uioe) {
        assertTrue(uioe.getCause() instanceof FaultyFileSystem.FaultyException);
      } catch (DirectoryIteratorException die) {
        fail("Should have been converted into UncheckedIOException.");
      }
    } finally {
      // Cleanup
      if (fs != null) {
        fs.close();
      }
      Files.delete(trigger);
    }
  }
Ejemplo n.º 13
0
  public static void main(String[] args) throws IOException {
    // open file but do not close it. Its existance will be checked by
    // the calling script.
    Paths.get(args[0]).newByteChannel(READ, WRITE, DELETE_ON_CLOSE);

    // check temporary file has been deleted after closing it
    Path file = File.createTempFile("blah", "tmp").toPath();
    file.newByteChannel(READ, WRITE, DELETE_ON_CLOSE).close();
    if (file.exists()) throw new RuntimeException("Temporary file was not deleted");

    Path dir = TestUtil.createTemporaryDirectory();
    try {
      // check that DELETE_ON_CLOSE fails when file is a sym link
      if (TestUtil.supportsLinks(dir)) {
        file = dir.resolve("foo").createFile();
        Path link = dir.resolve("link").createSymbolicLink(file);
        try {
          link.newByteChannel(READ, WRITE, DELETE_ON_CLOSE);
          throw new RuntimeException("IOException expected");
        } catch (IOException ignore) {
        }
      }

      // check that DELETE_ON_CLOSE works with files created via open
      // directories
      DirectoryStream stream = dir.newDirectoryStream();
      try {
        if (stream instanceof SecureDirectoryStream) {
          SecureDirectoryStream secure = (SecureDirectoryStream) stream;
          file = Paths.get("foo");

          Set<OpenOption> opts = new HashSet<OpenOption>();
          opts.add(WRITE);
          opts.add(DELETE_ON_CLOSE);
          secure.newByteChannel(file, opts).close();

          if (dir.resolve(file).exists()) throw new RuntimeException("File not deleted");
        }
      } finally {
        stream.close();
      }
    } finally {
      TestUtil.removeAll(dir);
    }
  }
Ejemplo n.º 14
0
 private static void checkCompiledScripts(
     final DirectoryStream<Path> stream, final int numberOfScripts) throws IOException {
   int n = numberOfScripts;
   for (@SuppressWarnings("unused") final Path file : stream) {
     n--;
   }
   stream.close();
   assertEquals(n, 0);
 }
Ejemplo n.º 15
0
  /**
   * Globbing is specifying DirectoryStream result with something like simplified regular
   * expressions.
   */
  @Test
  public void testDirectoryStreamGlobbing() throws IOException {
    Path rootDir = createDemonstrationDirectoryStructure();
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootDir, "*.txt");
    List<Path> paths = iterableToList(dirStream);
    // closing is required
    dirStream.close();
    assertEquals(2, paths.size());
    assertTrue(paths.contains(rootDir.resolve("firstFile.txt")));
    assertTrue(paths.contains(rootDir.resolve("secondFile.txt")));

    // only dir
    dirStream = Files.newDirectoryStream(rootDir, "*Dir");
    paths = iterableToList(dirStream);
    dirStream.close();
    assertEquals(1, paths.size());
    assertTrue(paths.contains(rootDir.resolve("childDir")));

    // PathMatcher is used in loop
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*File*");
    dirStream = Files.newDirectoryStream(rootDir);
    int matchedFilenane = 0;
    int matchedPath = 0;
    for (Path p : dirStream) {
      if (matcher.matches(p.getFileName())) {
        matchedFilenane++;
      }

      if (matcher.matches(p)) {
        matchedPath++;
      }
    }
    dirStream.close();
    assertEquals(2, matchedFilenane);
    // don't work with whole path just with filename
    assertEquals(0, matchedPath);

    // path matcher with unrecognized prefix
    try {
      FileSystems.getDefault().getPathMatcher("gldob:*.txt");
      fail("UnsupportedOperationException expected!");
    } catch (UnsupportedOperationException e) {
    }
  }
Ejemplo n.º 16
0
    private int getNumberOfItems(Path quellOrdner) {
      int retValue = 0;

      try {
        DirectoryStream<Path> qstream = Files.newDirectoryStream(quellOrdner);
        for (Path qfile : qstream) {
          if (Files.isDirectory(qfile)) {
            getNumberOfItems(Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()));
          }
          i++;
        }
        qstream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

      retValue = i;
      return retValue;
    }
Ejemplo n.º 17
0
  /**
   * TEst how to determine if system support SecureDirectoryStream Dont understand what can be do
   * with such stream.
   *
   * @throws IOException
   */
  @Test
  public void testSecureDirectoryStream() throws IOException {
    Path rootDir = createDemonstrationDirectoryStructure();
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootDir);

    // in my system SecureDirectoryStream is not supported
    assertFalse(dirStream instanceof SecureDirectoryStream);

    // in doc is written that, SecureDirectoryStream can be obtained by casting
    // standard DirectoryStream to SecureDirectoryStrea. If cast fails, it means,
    // SecureDirectoryStream is not supported in the system
    try {
      System.out.println((SecureDirectoryStream<Path>) dirStream);
      fail("ClassCastException expected!");
    } catch (ClassCastException e) {
    }

    dirStream.close();
  }
Ejemplo n.º 18
0
  /**
   * DirectoryStream.Filter is suitable for filtering based on other file attributes than file name
   * (size, hidden..)
   */
  @Test
  public void testDirectoryStreamFilter() throws IOException {
    Path rootDir = createDemonstrationDirectoryStructure();

    // filter accepts only directories
    DirectoryStream.Filter<Path> filter =
        new DirectoryStream.Filter<Path>() {
          @Override
          public boolean accept(Path entry) throws IOException {
            return Files.isDirectory(entry);
          }
        };

    DirectoryStream<Path> dirStream = Files.newDirectoryStream(rootDir, filter);
    List<Path> filteredPaths = iterableToList(dirStream);
    dirStream.close();

    // just single entry fulfill criteria
    assertEquals(1, filteredPaths.size());
    assertEquals(Paths.get("childDir"), filteredPaths.get(0).getFileName());
  }
Ejemplo n.º 19
0
 /** Scans the hunspell directory and loads all found dictionaries */
 private void scanAndLoadDictionaries() throws IOException {
   if (Files.isDirectory(hunspellDir)) {
     try (DirectoryStream<Path> stream = Files.newDirectoryStream(hunspellDir)) {
       for (Path file : stream) {
         if (Files.isDirectory(file)) {
           try (DirectoryStream<Path> inner =
               Files.newDirectoryStream(hunspellDir.resolve(file), "*.dic")) {
             if (inner.iterator().hasNext()) { // just making sure it's indeed a dictionary dir
               try {
                 getDictionary(file.getFileName().toString());
               } catch (Throwable e) {
                 // The cache loader throws unchecked exception (see #loadDictionary()),
                 // here we simply report the exception and continue loading the dictionaries
                 logger.error("exception while loading dictionary {}", e, file.getFileName());
               }
             }
           }
         }
       }
     }
   }
 }
Ejemplo n.º 20
0
  public void openDirection(Path innerDirection) {

    DirectoryStream<Path> listOfFiles;
    try {
      listOfFiles = Files.newDirectoryStream(innerDirection);
    } catch (IOException ioexc) {
      throw new DatabaseException(pathToTable + ": can't make a list of files");
    }

    for (Path innerFile : listOfFiles) {
      if (!Files.exists(innerFile)) {
        throw new DatabaseException(innerFile + ": isn't a file");
      }
      openFile(innerFile);
    }

    try {
      listOfFiles.close();
    } catch (IOException ioexc) {
      throw new DatabaseException(
          "can't close list of directories of " + innerDirection.toString());
    }
  }
Ejemplo n.º 21
0
  public void openTable() {

    DirectoryStream<Path> listOfDirs;

    try {
      listOfDirs = Files.newDirectoryStream(pathToTable);
    } catch (IOException ioexc) {
      throw new DatabaseException(pathToTable + ": can't make a list of directories");
    }

    for (Path innerDirection : listOfDirs) {
      if (!Files.isDirectory(innerDirection)) {
        throw new DatabaseException(innerDirection + ": isn't a directiion");
      }

      openDirection(innerDirection);
    }

    try {
      listOfDirs.close();
    } catch (IOException ioexc) {
      throw new DatabaseException("can't close list of directories of " + pathToTable.toString());
    }
  }
Ejemplo n.º 22
0
 /** Returns true if the directory is empty */
 private static boolean dirEmpty(final Path path) throws IOException {
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
     return stream.iterator().hasNext() == false;
   }
 }
Ejemplo n.º 23
0
  protected List<PluginInfo<T>> scan(
      LogSource logger,
      String hosterpath,
      final List<? extends LazyPlugin<T>> pluginCache,
      final AtomicLong lastFolderModification)
      throws Exception {
    DirectoryStream<Path> stream = null;
    final ArrayList<PluginInfo<T>> ret = new ArrayList<PluginInfo<T>>();
    final long timeStamp = System.currentTimeMillis();
    try {
      long lastModified = lastFolderModification != null ? lastFolderModification.get() : -1;
      final Path folder =
          Application.getRootByClass(jd.SecondLevelLaunch.class, hosterpath).toPath();
      final long lastFolderModified =
          Files.readAttributes(folder, BasicFileAttributes.class).lastModifiedTime().toMillis();
      if (lastModified > 0
          && lastFolderModified == lastModified
          && pluginCache != null
          && pluginCache.size() > 0) {
        for (final LazyPlugin<T> lazyPlugin : pluginCache) {
          final PluginInfo<T> pluginInfo = new PluginInfo<T>(lazyPlugin.getLazyPluginClass(), null);
          pluginInfo.setLazyPlugin(lazyPlugin);
          ret.add(pluginInfo);
        }
        return ret;
      }
      PluginClassLoaderChild cl = null;
      MessageDigest md = null;
      final String pkg = hosterpath.replace("/", ".");
      final byte[] mdCache = new byte[32767];
      final HashMap<String, List<LazyPlugin<T>>> lazyPluginClassMap;
      if (pluginCache != null && pluginCache.size() > 0) {
        lazyPluginClassMap = new HashMap<String, List<LazyPlugin<T>>>();
        for (final LazyPlugin<T> lazyPlugin : pluginCache) {
          List<LazyPlugin<T>> list =
              lazyPluginClassMap.get(lazyPlugin.getLazyPluginClass().getClassName());
          if (list == null) {
            list = new ArrayList<LazyPlugin<T>>();
            lazyPluginClassMap.put(lazyPlugin.getLazyPluginClass().getClassName(), list);
          }
          list.add(lazyPlugin);
        }
      } else {
        lazyPluginClassMap = null;
      }
      if (lastFolderModification != null) {
        lastFolderModification.set(lastFolderModified);
      }
      stream = Files.newDirectoryStream(folder, "*.class");
      for (final Path path : stream) {
        try {
          final String pathFileName = path.getFileName().toString();
          final String className = pathFileName.substring(0, pathFileName.length() - 6);
          if (className.indexOf("$") < 0 && !PluginController.IGNORELIST.contains(className)) {
            byte[] sha256 = null;
            final BasicFileAttributes pathAttr =
                Files.readAttributes(path, BasicFileAttributes.class);
            if (lazyPluginClassMap != null) {
              final List<LazyPlugin<T>> lazyPlugins = lazyPluginClassMap.get(className);
              if (lazyPlugins != null && lazyPlugins.size() > 0) {
                final LazyPluginClass lazyPluginClass = lazyPlugins.get(0).getLazyPluginClass();
                if (lazyPluginClass != null
                    && (lazyPluginClass.getLastModified() == pathAttr.lastModifiedTime().toMillis()
                        || ((md = MessageDigest.getInstance("SHA-256")) != null
                            && (sha256 =
                                    PluginController.getFileHashBytes(path.toFile(), md, mdCache))
                                != null
                            && Arrays.equals(sha256, lazyPluginClass.getSha256())))) {
                  for (final LazyPlugin<T> lazyPlugin : lazyPlugins) {
                    // logger.finer("Cached: " + className + "|" + lazyPlugin.getDisplayName() + "|"
                    // +
                    // lazyPluginClass.getRevision());
                    final PluginInfo<T> pluginInfo = new PluginInfo<T>(lazyPluginClass, null);
                    pluginInfo.setLazyPlugin(lazyPlugin);
                    ret.add(pluginInfo);
                  }
                  continue;
                }
              }
            }
            Class<T> pluginClass = null;
            long[] infos = null;
            try {
              if (cl == null) {
                cl = PluginClassLoader.getInstance().getChild();
              }
              if (md == null) {
                md = MessageDigest.getInstance("SHA-256");
              }
              pluginClass = (Class<T>) cl.loadClass(pkg + "." + className);
              if (!Modifier.isAbstract(pluginClass.getModifiers())
                  && Plugin.class.isAssignableFrom(pluginClass)) {
                infos = getPluginController().getInfos(pluginClass);
                if (infos == null) {
                  continue;
                }
              } else {
                continue;
              }
            } catch (final Throwable e) {
              logger.finer("Failed: " + className);
              logger.log(e);
              continue;
            }
            if (sha256 == null) {
              sha256 = PluginController.getFileHashBytes(path.toFile(), md, mdCache);
            }
            //
            final LazyPluginClass lazyPluginClass =
                new LazyPluginClass(
                    className,
                    sha256,
                    pathAttr.lastModifiedTime().toMillis(),
                    (int) infos[0],
                    infos[1]);
            final PluginInfo<T> pluginInfo = new PluginInfo<T>(lazyPluginClass, pluginClass);
            // logger.finer("Scaned: " + className + "|" + lazyPluginClass.getRevision());
            ret.add(pluginInfo);
          }

        } catch (Throwable e) {
          logger.finer("Failed: " + path);
          logger.log(e);
        }
      }
      return ret;
    } finally {
      logger.info(
          "@PluginController(NIO): scan took "
              + (System.currentTimeMillis() - timeStamp)
              + "ms for "
              + ret.size());
      if (stream != null) {
        stream.close();
      }
    }
  }
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {

    initMojo();
    getLog().info("Scanning: " + magentoPath);
    getLog().info("");
    if (mVersion != null) {
      getLog().info("Version: Magento " + mVersion.toString());
    }

    // parse sql properties from local.xml
    final Path localXmlPath = Paths.get(magentoPath + "/app/etc/local.xml");
    Document localXml = null;
    if (Files.exists(localXmlPath)) {
      localXml = MagentoXmlUtil.readXmlFile(localXmlPath.toAbsolutePath().toString());
    } else {
      throw new MojoExecutionException(
          "Could not read or parse /app/etc/local.xml."
              + " Use -DmagentoPath= to set Magento dir.");
    }
    final Map<String, String> dbSettings = MagentoXmlUtil.getDbValues(localXml);
    final String jdbcUrl =
        MagentoSqlUtil.getJdbcUrl(
            dbSettings.get("host"), dbSettings.get("port"), dbSettings.get("dbname"));

    // fetch installdate
    final String magentoInstallDate = MagentoXmlUtil.getMagentoInstallData(localXml);
    getLog().info("Installed: " + magentoInstallDate);
    getLog().info("");

    // read baseUrl
    MagentoCoreConfig baseUrl = null;
    try {
      baseUrl = new MagentoCoreConfig("web/unsecure/base_url");
    } catch (Exception e) {
      throw new MojoExecutionException("Error creating config entry. " + e.getMessage(), e);
    }

    String sqlError = SQL_CONNECTION_VALID;
    try {
      baseUrl =
          MagentoSqlUtil.getCoreConfigData(
              baseUrl, dbSettings.get("user"), dbSettings.get("password"), jdbcUrl, getLog());
      getLog().info("URL: " + baseUrl.getValue());
      getLog().info("");
    } catch (MojoExecutionException e) {
      sqlError = e.getMessage();
    }

    getLog()
        .info(
            "Database: "
                + dbSettings.get("dbname")
                + " via "
                + dbSettings.get("user")
                + "@"
                + dbSettings.get("host")
                + ":"
                + dbSettings.get("port"));
    getLog().info("Connection: " + sqlError);
    getLog().info("");

    if (!skipSize) {
      MutableLong rootSizeTotal = new MutableLong();
      try {
        FileSizeVisitor fs = new FileSizeVisitor(rootSizeTotal);
        Files.walkFileTree(Paths.get(magentoPath), fs);
      } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
      }
      getLog()
          .info(
              "Magento files total: "
                  + String.format("%,8d", rootSizeTotal.toLong()).trim()
                  + " bytes");
      if (SQL_CONNECTION_VALID.equals(sqlError)) {
        try {
          final Map<String, Integer> dbDetails =
              MagentoSqlUtil.getDbSize(
                  dbSettings.get("dbname"),
                  dbSettings.get("user"),
                  dbSettings.get("password"),
                  jdbcUrl,
                  getLog());
          final List<MysqlTable> logTableDetails =
              MagentoSqlUtil.getLogTablesSize(
                  dbSettings.get("dbname"),
                  dbSettings.get("user"),
                  dbSettings.get("password"),
                  jdbcUrl,
                  getLog());
          getLog()
              .info(
                  "Database total: "
                      + String.format("%,8d", dbDetails.get("totalRows")).trim()
                      + " entries / "
                      + String.format("%,8d", dbDetails.get("totalSize")).trim()
                      + "mb");
          int logSizeTotal = 0;
          int logRowsTotal = 0;
          for (MysqlTable t : logTableDetails) {
            logSizeTotal += t.getTableSizeInMb();
            logRowsTotal += t.getTableRows();
            if (showDetails) {
              getLog()
                  .info(
                      " "
                          + t.getTableName()
                          + ": "
                          + t.getFormatedTableEntries()
                          + " entries / "
                          + t.getFormatedTableSizeInMb()
                          + "mb");
            }
          }
          getLog()
              .info(
                  "Log tables total: "
                      + String.format("%,8d", logRowsTotal).trim()
                      + " entries / "
                      + String.format("%,8d", logSizeTotal).trim()
                      + "mb");
        } catch (MojoExecutionException e) {
          getLog().info("Error: " + e.getMessage());
        }
      }
      getLog().info("");
    }
    // parse modules
    final Path modulesXmlPath = Paths.get(magentoPath + "/app/etc/modules");
    if (!Files.exists(modulesXmlPath)) {
      throw new MojoExecutionException("Could not find /app/etc/modules directory.");
    }

    DirectoryStream<Path> files = null;
    final ArrayList<MagentoModule> localModules = new ArrayList<MagentoModule>();
    final ArrayList<MagentoModule> communityModules = new ArrayList<MagentoModule>();
    try {
      files = Files.newDirectoryStream(modulesXmlPath);
      for (Path path : files) {
        if (!path.getFileName().toString().startsWith("Mage")) {
          MagentoModule m = new MagentoModule(path);
          if (m.getCodePool().equals("local")) {
            localModules.add(m);
          } else {
            communityModules.add(m);
          }
        }
      }
    } catch (IOException e) {
      throw new MojoExecutionException("Could not read modules directory. " + e.getMessage(), e);
    } finally {
      try {
        files.close();
      } catch (IOException e) {
        throw new MojoExecutionException("Error closing directory stream. " + e.getMessage(), e);
      }
    }

    // print module sorted module list
    final MagentoModuleComperator mmc = new MagentoModuleComperator();
    Collections.sort(localModules, mmc);
    Collections.sort(communityModules, mmc);

    getLog().info("Installed modules in..");

    getLog().info("..local: ");
    for (MagentoModule m : localModules) {
      getLog()
          .info(
              m.getNamespace()
                  + "_"
                  + m.getName()
                  + " version: "
                  + m.getVersion()
                  + " active: "
                  + m.isActive());
    }
    if (localModules.size() == 0) {
      getLog().info("--none--");
    }
    getLog().info("");

    getLog().info("..community: ");
    for (MagentoModule m : communityModules) {
      getLog()
          .info(
              m.getNamespace()
                  + "_"
                  + m.getName()
                  + " version: "
                  + m.getVersion()
                  + " active: "
                  + m.isActive());
    }
    if (communityModules.size() == 0) {
      getLog().info("--none--");
    }
    getLog().info("");

    // check local overlays for content
    getLog().info("Overlay status..");
    int fileCount = -1;
    final File localMage = new File(magentoPath + "/app/code/local/Mage");
    if (localMage.exists()) {
      fileCount = localMage.list().length;
      if (fileCount > 0) {
        getLog().info("local/Mage: " + localMage.list().length + " file(s)");
      }
    }
    final File localVarien = new File(magentoPath + "/app/code/local/Varien");

    if (localVarien.exists()) {
      fileCount = localVarien.list().length;
      if (fileCount > 0) {
        getLog().info("local/Varien: " + localVarien.list().length + " file(s)");
      }
    }

    if (fileCount == -1) {
      getLog().info("..not in use.");
    }
  }
Ejemplo n.º 25
0
 public static boolean isEmptyDir(Path path) throws IOException {
   try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
     Iterator<Path> files = ds.iterator();
     return !files.hasNext();
   }
 }
Ejemplo n.º 26
0
    public void cnpStart(Path quellOrdner, Path zielOrdner) {
      try {
        DirectoryStream<Path> qstream = Files.newDirectoryStream(quellOrdner);
        for (Path qfile : qstream) {
          Path target = Paths.get(zielOrdner.toString() + "/" + qfile.getFileName());
          if (abbruch) break;
          if (Files.isDirectory(qfile) && !Files.exists(target)) {
            Files.createDirectory(target);
            textArea.append("Verzeichnis: " + qfile + " wurde erstellt" + System.lineSeparator());
            cnpStart(
                Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()),
                Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()));
          } else if (Files.isDirectory(qfile) && Files.exists(target)) {
            textArea.append("Wechsle in Verzeichnis: " + qfile + System.lineSeparator());
            cnpStart(
                Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()),
                Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()));
          }
          // Wenn die Datei noch nicht existiert
          else if (!Files.exists(target)) {
            textArea.append(
                "Datei " + target.toString() + " wurde erstellt" + System.lineSeparator());
            Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING);

          }
          // Wenn Datei im Zielverzeichnis schon existiert
          else if (Files.exists(target)) {
            if (cAUeSchr) {
              textArea.append(
                  "Datei "
                      + target.toString()
                      + " wird absolut überschrieben"
                      + System.lineSeparator());
              Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING);
            } else if (cUeSchr) {
              if (checkAlter(
                  Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()),
                  Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()))) {
                textArea.append(
                    target.toString()
                        + " wird mit neuer Datei überschrieben"
                        + System.lineSeparator());
                Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING);
              } else {
                textArea.append(
                    target.toString() + " alte Datei bleibt bestehen" + System.lineSeparator());
              }
            } else
              textArea.append(
                  target.toString() + " alte Datei bleibt bestehen" + System.lineSeparator());
          }
          pbCounter++;
          progressBar.setValue(pbCounter);
        }

        qstream.close();
      } catch (IOException e) {

        e.printStackTrace();
      }
    }