Search in sources :

Example 31 with Files

use of java.nio.file.Files in project archiva by apache.

the class RepositoryScannerInstance method visitFile.

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    if (excludeMatcher.stream().noneMatch(m -> m.matches(file)) && includeMatcher.stream().allMatch(m -> m.matches(file))) {
        log.debug("Walk Step: {}, {}", file);
        stats.increaseFileCount();
        // consume files regardless - the predicate will check the timestamp
        Path repoPath = PathUtil.getPathFromUri(repository.getLocation());
        BaseFile basefile = new BaseFile(repoPath.toString(), file.toFile());
        // Timestamp finished points to the last successful scan, not this current one.
        if (Files.getLastModifiedTime(file).toMillis() >= changesSince) {
            stats.increaseNewFileCount();
        }
        consumerProcessFile.setBasefile(basefile);
        consumerWantsFile.setBasefile(basefile);
        Closure<RepositoryContentConsumer> processIfWanted = IfClosure.ifClosure(consumerWantsFile, consumerProcessFile);
        IterableUtils.forEach(this.knownConsumers, processIfWanted);
        if (consumerWantsFile.getWantedFileCount() <= 0) {
            // Nothing known processed this file.  It is invalid!
            IterableUtils.forEach(this.invalidConsumers, consumerProcessFile);
        }
    }
    return FileVisitResult.CONTINUE;
}
Also used : PathUtil(org.apache.archiva.common.utils.PathUtil) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) IfClosure(org.apache.commons.collections4.functors.IfClosure) Closure(org.apache.commons.collections4.Closure) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) IterableUtils(org.apache.commons.collections4.IterableUtils) RepositoryContentConsumer(org.apache.archiva.consumers.RepositoryContentConsumer) Map(java.util.Map) PathMatcher(java.nio.file.PathMatcher) ConsumerWantsFilePredicate(org.apache.archiva.consumers.functors.ConsumerWantsFilePredicate) SystemUtils(org.apache.commons.lang.SystemUtils) Path(java.nio.file.Path) TriggerBeginScanClosure(org.apache.archiva.repository.scanner.functors.TriggerBeginScanClosure) Logger(org.slf4j.Logger) FileVisitor(java.nio.file.FileVisitor) Files(java.nio.file.Files) ConsumerProcessFileClosure(org.apache.archiva.repository.scanner.functors.ConsumerProcessFileClosure) KnownRepositoryContentConsumer(org.apache.archiva.consumers.KnownRepositoryContentConsumer) IOException(java.io.IOException) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) ManagedRepository(org.apache.archiva.repository.ManagedRepository) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) BaseFile(org.apache.archiva.common.utils.BaseFile) InvalidRepositoryContentConsumer(org.apache.archiva.consumers.InvalidRepositoryContentConsumer) TriggerScanCompletedClosure(org.apache.archiva.repository.scanner.functors.TriggerScanCompletedClosure) FileSystems(java.nio.file.FileSystems) Path(java.nio.file.Path) BaseFile(org.apache.archiva.common.utils.BaseFile) RepositoryContentConsumer(org.apache.archiva.consumers.RepositoryContentConsumer) KnownRepositoryContentConsumer(org.apache.archiva.consumers.KnownRepositoryContentConsumer) InvalidRepositoryContentConsumer(org.apache.archiva.consumers.InvalidRepositoryContentConsumer)

Example 32 with Files

use of java.nio.file.Files in project Bytecoder by mirkosertic.

the class ModulePath method deriveModuleDescriptor.

/**
 * Treat the given JAR file as a module as follows:
 *
 * 1. The value of the Automatic-Module-Name attribute is the module name
 * 2. The version, and the module name when the  Automatic-Module-Name
 *    attribute is not present, is derived from the file ame of the JAR file
 * 3. All packages are derived from the .class files in the JAR file
 * 4. The contents of any META-INF/services configuration files are mapped
 *    to "provides" declarations
 * 5. The Main-Class attribute in the main attributes of the JAR manifest
 *    is mapped to the module descriptor mainClass if possible
 */
private ModuleDescriptor deriveModuleDescriptor(JarFile jf) throws IOException {
    // Read Automatic-Module-Name attribute if present
    Manifest man = jf.getManifest();
    Attributes attrs = null;
    String moduleName = null;
    if (man != null) {
        attrs = man.getMainAttributes();
        if (attrs != null) {
            moduleName = attrs.getValue(AUTOMATIC_MODULE_NAME);
        }
    }
    // Derive the version, and the module name if needed, from JAR file name
    String fn = jf.getName();
    int i = fn.lastIndexOf(File.separator);
    if (i != -1)
        fn = fn.substring(i + 1);
    // drop ".jar"
    String name = fn.substring(0, fn.length() - 4);
    String vs = null;
    // find first occurrence of -${NUMBER}. or -${NUMBER}$
    Matcher matcher = Patterns.DASH_VERSION.matcher(name);
    if (matcher.find()) {
        int start = matcher.start();
        // attempt to parse the tail as a version string
        try {
            String tail = name.substring(start + 1);
            ModuleDescriptor.Version.parse(tail);
            vs = tail;
        } catch (IllegalArgumentException ignore) {
        }
        name = name.substring(0, start);
    }
    // Create builder, using the name derived from file name when
    // Automatic-Module-Name not present
    Builder builder;
    if (moduleName != null) {
        try {
            builder = ModuleDescriptor.newAutomaticModule(moduleName);
        } catch (IllegalArgumentException e) {
            throw new FindException(AUTOMATIC_MODULE_NAME + ": " + e.getMessage());
        }
    } else {
        builder = ModuleDescriptor.newAutomaticModule(cleanModuleName(name));
    }
    // module version if present
    if (vs != null)
        builder.version(vs);
    // scan the names of the entries in the JAR file
    Map<Boolean, Set<String>> map = VersionedStream.stream(jf).filter(e -> !e.isDirectory()).map(JarEntry::getName).filter(e -> (e.endsWith(".class") ^ e.startsWith(SERVICES_PREFIX))).collect(Collectors.partitioningBy(e -> e.startsWith(SERVICES_PREFIX), Collectors.toSet()));
    Set<String> classFiles = map.get(Boolean.FALSE);
    Set<String> configFiles = map.get(Boolean.TRUE);
    // the packages containing class files
    Set<String> packages = classFiles.stream().map(this::toPackageName).flatMap(Optional::stream).distinct().collect(Collectors.toSet());
    // all packages are exported and open
    builder.packages(packages);
    // map names of service configuration files to service names
    Set<String> serviceNames = configFiles.stream().map(this::toServiceName).flatMap(Optional::stream).collect(Collectors.toSet());
    // parse each service configuration file
    for (String sn : serviceNames) {
        JarEntry entry = jf.getJarEntry(SERVICES_PREFIX + sn);
        List<String> providerClasses = new ArrayList<>();
        try (InputStream in = jf.getInputStream(entry)) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String cn;
            while ((cn = nextLine(reader)) != null) {
                if (cn.length() > 0) {
                    String pn = packageName(cn);
                    if (!packages.contains(pn)) {
                        String msg = "Provider class " + cn + " not in module";
                        throw new InvalidModuleDescriptorException(msg);
                    }
                    providerClasses.add(cn);
                }
            }
        }
        if (!providerClasses.isEmpty())
            builder.provides(sn, providerClasses);
    }
    // Main-Class attribute if it exists
    if (attrs != null) {
        String mainClass = attrs.getValue(Attributes.Name.MAIN_CLASS);
        if (mainClass != null) {
            mainClass = mainClass.replace("/", ".");
            if (Checks.isClassName(mainClass)) {
                String pn = packageName(mainClass);
                if (packages.contains(pn)) {
                    builder.mainClass(mainClass);
                }
            }
        }
    }
    return builder.build();
}
Also used : Builder(java.lang.module.ModuleDescriptor.Builder) Manifest(java.util.jar.Manifest) NoSuchFileException(java.nio.file.NoSuchFileException) BufferedInputStream(java.io.BufferedInputStream) VersionedStream(jdk.internal.util.jar.VersionedStream) ModuleDescriptor(java.lang.module.ModuleDescriptor) ModuleReference(java.lang.module.ModuleReference) HashMap(java.util.HashMap) JarFile(java.util.jar.JarFile) ArrayList(java.util.ArrayList) Section(jdk.internal.jmod.JmodFile.Section) DirectoryStream(java.nio.file.DirectoryStream) JarEntry(java.util.jar.JarEntry) Matcher(java.util.regex.Matcher) ModuleFinder(java.lang.module.ModuleFinder) Map(java.util.Map) ZipFile(java.util.zip.ZipFile) URI(java.net.URI) Path(java.nio.file.Path) FindException(java.lang.module.FindException) PerfCounter(jdk.internal.perf.PerfCounter) ZipException(java.util.zip.ZipException) Files(java.nio.file.Files) Set(java.util.Set) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) InputStreamReader(java.io.InputStreamReader) Attributes(java.util.jar.Attributes) Collectors(java.util.stream.Collectors) File(java.io.File) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) JmodFile(jdk.internal.jmod.JmodFile) Paths(java.nio.file.Paths) InvalidModuleDescriptorException(java.lang.module.InvalidModuleDescriptorException) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) InputStream(java.io.InputStream) Set(java.util.Set) Optional(java.util.Optional) InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Builder(java.lang.module.ModuleDescriptor.Builder) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Attributes(java.util.jar.Attributes) ArrayList(java.util.ArrayList) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) InvalidModuleDescriptorException(java.lang.module.InvalidModuleDescriptorException) FindException(java.lang.module.FindException) BufferedReader(java.io.BufferedReader)

Example 33 with Files

use of java.nio.file.Files in project n4js by eclipse.

the class AbstractFileChecker method containsFileWithName.

protected boolean containsFileWithName(Path path, String fileName) {
    final File file = path.toFile();
    final File[] files = file.listFiles();
    return files != null && Stream.of(files).anyMatch(f -> fileName.equals(f.getName()));
}
Also used : Arrays(java.util.Arrays) Files(java.nio.file.Files) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) Set(java.util.Set) IOException(java.io.IOException) Multimap(com.google.common.collect.Multimap) Collectors(java.util.stream.Collectors) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) Stream(java.util.stream.Stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Pattern(java.util.regex.Pattern) Path(java.nio.file.Path) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) Joiner(com.google.common.base.Joiner) File(java.io.File)

Example 34 with Files

use of java.nio.file.Files in project n4js by eclipse.

the class AbstractFileChecker method readListOfThirdPartyFiles.

// ################################################################################################################
/**
 * <pre>
 * #
 * # List of files and folders with third-party copyright.
 * #
 * #
 * # This file is processed automatically by FileChecker.java to ensure the below information is kept up-to-date.
 * #
 * # Format:
 * # every non-empty line in this file either starts with '#' and is then a comment (to be ignored) or must
 * # contain the relative path to a file with third-party copyright. If a path ends in "/**" it must point to
 * # a folder and its contents are declared to be third-party files. All paths must be relative to the folder
 * # containing this file.
 * #
 * </pre>
 */
private static Set<Path> readListOfThirdPartyFiles(Path rootPath) throws IOException {
    System.out.println("Reading list of third-party files from \"" + FILE_NAME__THIRD_PARTY + "\" ...");
    final Path thirdPartyList = rootPath.resolve(FILE_NAME__THIRD_PARTY);
    if (!thirdPartyList.toFile().exists()) {
        // note: providing a third-party.txt file is optional, so no error here:
        System.out.println("    no such file found, assuming 0 third-party files.");
        return Collections.emptySet();
    }
    final List<String> lines = Files.readAllLines(thirdPartyList, StandardCharsets.UTF_8);
    // trim all lines
    lines.replaceAll((l) -> l.trim());
    // remove empty lines and comments
    lines.removeIf((l) -> l.length() == 0 || l.startsWith("#"));
    // make sure all paths are relative
    if (lines.stream().anyMatch((l) -> l.startsWith("/") || l.startsWith("\\")))
        throw new IOException("paths in " + FILE_NAME__THIRD_PARTY + " must be relative, i.e. not start with '/'");
    // make sure all files/folders exist & are of correct type
    final List<Path> paths = lines.stream().map((l) -> rootPath.resolve(l)).collect(Collectors.toList());
    int files = 0;
    int folders = 0;
    // replace folders by their contained files
    for (int i = 0; i < paths.size(); i++) {
        final Path p = paths.get(i);
        if (p.endsWith("**")) {
            final Path parent = p.getParent();
            final List<Path> allFiles = getAllContainedFiles(parent);
            if (allFiles.isEmpty()) {
            // throw new IOException("folder is empty: " + parent);
            }
            paths.remove(i);
            paths.addAll(i, allFiles);
            i += allFiles.size() - 1;
        }
    }
    // check for duplicates
    final Set<Path> duplicates = collectDuplicates(paths);
    if (!duplicates.isEmpty()) {
        throw new IOException("the following files are declared more than once in " + FILE_NAME__THIRD_PARTY + " (maybe because they are contained in a folder declared with \"/**\"):\n    " + Joiner.on("\n    ").join(duplicates));
    }
    // report to user
    System.out.println("    " + files + " files and " + folders + " folders (for a total of " + paths.size() + " files) declared as third-party artifacts.");
    // order does not matter, so don't need LinkedHashSet
    return new HashSet<>(paths);
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) Files(java.nio.file.Files) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) Set(java.util.Set) IOException(java.io.IOException) Multimap(com.google.common.collect.Multimap) Collectors(java.util.stream.Collectors) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) Stream(java.util.stream.Stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Pattern(java.util.regex.Pattern) Path(java.nio.file.Path) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) Joiner(com.google.common.base.Joiner) IOException(java.io.IOException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 35 with Files

use of java.nio.file.Files in project fakereplace by fakereplace.

the class WildflyAutoUpdate method runUpdate.

public static synchronized Result runUpdate(ModuleClassLoader classLoader) {
    String moduleName = classLoader.getModule().getIdentifier().getName();
    if (moduleName.startsWith(DEPLOYMENT)) {
        moduleName = moduleName.substring(DEPLOYMENT.length());
    }
    String sourcePaths = System.getProperty(FAKEREPLACE_SOURCE_PATHS + moduleName);
    if (sourcePaths == null) {
        return Result.NO_CHANGE;
    }
    List<Path> paths = Arrays.stream(sourcePaths.split(",")).map((s) -> Paths.get(s)).collect(Collectors.toList());
    try {
        for (Path base : paths) {
            final Map<String, Long> timestamps = new HashMap<>();
            scan(base, base, timestamps);
            List<String> toUpdate = new ArrayList<>();
            List<String> added = new ArrayList<>();
            List<String> replace = new ArrayList<>();
            for (Map.Entry<String, Long> entry : timestamps.entrySet()) {
                String name = entry.getKey();
                if (name.endsWith(".java")) {
                    String baseName = name.substring(0, name.length() - 5);
                    Long last = replacedTimestamps.get(baseName);
                    if (last != null) {
                        if (last < entry.getValue()) {
                            toUpdate.add(baseName);
                            replacedTimestamps.put(baseName, entry.getValue());
                            replace.add(baseName);
                        }
                    } else {
                        URL res = classLoader.getResource(baseName + ".class");
                        if (res != null) {
                            URLConnection con = res.openConnection();
                            long lm = con.getLastModified();
                            if (lm < entry.getValue()) {
                                toUpdate.add(baseName);
                                replacedTimestamps.put(baseName, entry.getValue());
                                replace.add(baseName);
                            }
                        } else {
                            toUpdate.add(baseName);
                            replacedTimestamps.put(baseName, entry.getValue());
                            added.add(baseName);
                        }
                    }
                }
            }
            if (!toUpdate.isEmpty()) {
                System.out.println("Fakereplace detected the following source files have been changed: " + toUpdate);
                ClassLoaderCompiler compiler = new ClassLoaderCompiler(classLoader, base, toUpdate);
                compiler.compile();
                Map<String, byte[]> byteMap = REPLACED_CLASSES.computeIfAbsent(classLoader, k -> new HashMap<>());
                AddedClass[] addedClass = new AddedClass[added.size()];
                for (int i = 0; i < added.size(); ++i) {
                    String className = added.get(i);
                    addedClass[i] = new AddedClass(className, compiler.getOutput().get(className).toByteArray(), classLoader);
                    byteMap.put(className, compiler.getOutput().get(className).toByteArray());
                }
                ClassDefinition[] classDefinition = new ClassDefinition[replace.size()];
                for (int i = 0; i < replace.size(); ++i) {
                    String className = replace.get(i);
                    classDefinition[i] = new ClassDefinition(classLoader.loadClass(className.replace("/", ".")), compiler.getOutput().get(className).toByteArray());
                    byteMap.put(className, compiler.getOutput().get(className).toByteArray());
                }
                try {
                    Fakereplace.redefine(classDefinition, addedClass);
                } catch (Exception e) {
                    System.err.println("Hot replace failed, redeploy required" + e.getMessage());
                    return Result.REDEPLOY_REQUIRED;
                }
                return Result.RELOAD;
            }
        }
        return Result.NO_CHANGE;
    } catch (Exception e) {
        System.err.println("Check for updated classes failed");
        e.printStackTrace();
    } finally {
        // something in the compiler clears the TCCL, fix it up
        Thread.currentThread().setContextClassLoader(classLoader);
    }
    return Result.NO_CHANGE;
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) Files(java.nio.file.Files) URL(java.net.URL) IOException(java.io.IOException) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) ClassDefinition(java.lang.instrument.ClassDefinition) List(java.util.List) Fakereplace(org.fakereplace.core.Fakereplace) Paths(java.nio.file.Paths) URLConnection(java.net.URLConnection) Map(java.util.Map) ModuleClassLoader(org.jboss.modules.ModuleClassLoader) Path(java.nio.file.Path) WeakHashMap(java.util.WeakHashMap) AddedClass(org.fakereplace.replacement.AddedClass) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) ArrayList(java.util.ArrayList) AddedClass(org.fakereplace.replacement.AddedClass) ClassDefinition(java.lang.instrument.ClassDefinition) URL(java.net.URL) URLConnection(java.net.URLConnection) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap)

Aggregations

Files (java.nio.file.Files)247 IOException (java.io.IOException)213 Path (java.nio.file.Path)199 List (java.util.List)177 Collectors (java.util.stream.Collectors)157 Paths (java.nio.file.Paths)135 File (java.io.File)130 ArrayList (java.util.ArrayList)117 Map (java.util.Map)111 Set (java.util.Set)97 Collections (java.util.Collections)89 Arrays (java.util.Arrays)81 Stream (java.util.stream.Stream)78 HashMap (java.util.HashMap)75 HashSet (java.util.HashSet)58 InputStream (java.io.InputStream)56 Collection (java.util.Collection)55 Logger (org.slf4j.Logger)54 Pattern (java.util.regex.Pattern)53 Optional (java.util.Optional)51