Search in sources :

Example 16 with PathMatcher

use of java.nio.file.PathMatcher in project jetty.project by eclipse.

the class BaseHome method getPaths.

/**
     * Get a List of {@link Path}s from a provided pattern.
     * <p>
     * Resolution Steps:
     * <ol>
     * <li>If the pattern starts with "regex:" or "glob:" then a standard {@link PathMatcher} is built using
     * {@link java.nio.file.FileSystem#getPathMatcher(String)} as a file search.</li>
     * <li>If pattern starts with a known filesystem root (using information from {@link java.nio.file.FileSystem#getRootDirectories()}) then this is assumed to
     * be a absolute file system pattern.</li>
     * <li>All other patterns are treated as relative to BaseHome information:
     * <ol>
     * <li>Search ${jetty.home} first</li>
     * <li>Search ${jetty.base} for overrides</li>
     * </ol>
     * </li>
     * </ol>
     * <p>
     * Pattern examples:
     * <dl>
     * <dt><code>lib/logging/*.jar</code></dt>
     * <dd>Relative pattern, not recursive, search <code>${jetty.home}</code> then <code>${jetty.base}</code> for lib/logging/*.jar content</dd>
     * 
     * <dt><code>lib/**&#47;*-dev.jar</code></dt>
     * <dd>Relative pattern, recursive search <code>${jetty.home}</code> then <code>${jetty.base}</code> for files under <code>lib</code> ending in
     * <code>-dev.jar</code></dd>
     * 
     * <dt><code>etc/jetty.xml</code></dt>
     * <dd>Relative pattern, no glob, search for <code>${jetty.home}/etc/jetty.xml</code> then <code>${jetty.base}/etc/jetty.xml</code></dd>
     * 
     * <dt><code>glob:/opt/app/common/*-corp.jar</code></dt>
     * <dd>PathMapper pattern, glob, search <code>/opt/app/common/</code> for <code>*-corp.jar</code></dd>
     * 
     * </dl>
     * 
     * <p>
     * Notes:
     * <ul>
     * <li>FileSystem case sensitivity is implementation specific (eg: linux is case-sensitive, windows is case-insensitive).<br>
     * See {@link java.nio.file.FileSystem#getPathMatcher(String)} for more details</li>
     * <li>Pattern slashes are implementation neutral (use '/' always and you'll be fine)</li>
     * <li>Recursive searching is limited to 30 levels deep (not configurable)</li>
     * <li>File System loops are detected and skipped</li>
     * </ul>
     * 
     * @param pattern
     *            the pattern to search.
     * @return the collection of paths found
     * @throws IOException
     *             if error during search operation
     */
public List<Path> getPaths(String pattern) throws IOException {
    StartLog.debug("getPaths('%s')", pattern);
    List<Path> hits = new ArrayList<>();
    if (PathMatchers.isAbsolute(pattern)) {
        // Perform absolute path pattern search
        // The root to start search from
        Path root = PathMatchers.getSearchRoot(pattern);
        // The matcher for file hits
        PathMatcher matcher = PathMatchers.getMatcher(pattern);
        if (FS.isValidDirectory(root)) {
            PathFinder finder = new PathFinder();
            finder.setIncludeDirsInResults(true);
            finder.setFileMatcher(matcher);
            finder.setBase(root);
            Files.walkFileTree(root, SEARCH_VISIT_OPTIONS, MAX_SEARCH_DEPTH, finder);
            hits.addAll(finder.getHits());
        }
    } else {
        // Perform relative path pattern search
        Path relativePath = PathMatchers.getSearchRoot(pattern);
        PathMatcher matcher = PathMatchers.getMatcher(pattern);
        PathFinder finder = new PathFinder();
        finder.setIncludeDirsInResults(true);
        finder.setFileMatcher(matcher);
        // walk config sources backwards ...
        ListIterator<ConfigSource> iter = sources.reverseListIterator();
        while (iter.hasPrevious()) {
            ConfigSource source = iter.previous();
            if (source instanceof DirConfigSource) {
                DirConfigSource dirsource = (DirConfigSource) source;
                Path dir = dirsource.getDir();
                Path deepDir = dir.resolve(relativePath);
                if (FS.isValidDirectory(deepDir)) {
                    finder.setBase(dir);
                    Files.walkFileTree(deepDir, SEARCH_VISIT_OPTIONS, MAX_SEARCH_DEPTH, finder);
                }
            }
        }
        hits.addAll(finder.getHits());
    }
    Collections.sort(hits, new NaturalSort.Paths());
    return hits;
}
Also used : Path(java.nio.file.Path) DirConfigSource(org.eclipse.jetty.start.config.DirConfigSource) JettyHomeConfigSource(org.eclipse.jetty.start.config.JettyHomeConfigSource) ConfigSource(org.eclipse.jetty.start.config.ConfigSource) JettyBaseConfigSource(org.eclipse.jetty.start.config.JettyBaseConfigSource) CommandLineConfigSource(org.eclipse.jetty.start.config.CommandLineConfigSource) PathMatcher(java.nio.file.PathMatcher) ArrayList(java.util.ArrayList) DirConfigSource(org.eclipse.jetty.start.config.DirConfigSource)

Example 17 with PathMatcher

use of java.nio.file.PathMatcher in project jetty.project by eclipse.

the class BaseHome method getPaths.

/**
     * Search specified Path with pattern and return hits
     * 
     * @param dir
     *            the path to a directory to start search from
     * @param searchDepth
     *            the number of directories deep to perform the search
     * @param pattern
     *            the raw pattern to use for the search (must be relative)
     * @return the list of Paths found
     * @throws IOException
     *             if unable to search the path
     */
public List<Path> getPaths(Path dir, int searchDepth, String pattern) throws IOException {
    if (PathMatchers.isAbsolute(pattern)) {
        throw new RuntimeException("Pattern cannot be absolute: " + pattern);
    }
    List<Path> hits = new ArrayList<>();
    if (FS.isValidDirectory(dir)) {
        PathMatcher matcher = PathMatchers.getMatcher(pattern);
        PathFinder finder = new PathFinder();
        finder.setFileMatcher(matcher);
        finder.setBase(dir);
        finder.setIncludeDirsInResults(true);
        Files.walkFileTree(dir, SEARCH_VISIT_OPTIONS, searchDepth, finder);
        hits.addAll(finder.getHits());
        Collections.sort(hits, new NaturalSort.Paths());
    }
    return hits;
}
Also used : Path(java.nio.file.Path) PathMatcher(java.nio.file.PathMatcher) ArrayList(java.util.ArrayList)

Example 18 with PathMatcher

use of java.nio.file.PathMatcher in project che by eclipse.

the class ProjectServiceTest method setUp.

@BeforeMethod
public void setUp() throws Exception {
    WorkspaceProjectsSyncer workspaceHolder = new WsAgentTestBase.TestWorkspaceHolder();
    File root = new File(FS_PATH);
    if (root.exists()) {
        IoUtil.deleteRecursive(root);
    }
    root.mkdir();
    File indexDir = new File(INDEX_PATH);
    if (indexDir.exists()) {
        IoUtil.deleteRecursive(indexDir);
    }
    indexDir.mkdir();
    Set<PathMatcher> filters = new HashSet<>();
    filters.add(path -> {
        for (java.nio.file.Path pathElement : path) {
            if (pathElement == null || EXCLUDE_SEARCH_PATH.equals(pathElement.toString())) {
                return true;
            }
        }
        return false;
    });
    FSLuceneSearcherProvider sProvider = new FSLuceneSearcherProvider(indexDir, filters);
    vfsProvider = new LocalVirtualFileSystemProvider(root, sProvider);
    final EventService eventService = new EventService();
    // PTs for test
    ProjectTypeDef chuck = new ProjectTypeDef("chuck_project_type", "chuck_project_type", true, false) {

        {
            addConstantDefinition("x", "attr description", new AttributeValue(Arrays.asList("a", "b")));
        }
    };
    Set<ProjectTypeDef> projectTypes = new HashSet<>();
    final LocalProjectType myProjectType = new LocalProjectType("my_project_type", "my project type");
    projectTypes.add(myProjectType);
    projectTypes.add(new LocalProjectType("module_type", "module type"));
    projectTypes.add(chuck);
    ptRegistry = new ProjectTypeRegistry(projectTypes);
    phRegistry = new ProjectHandlerRegistry(new HashSet<>());
    importerRegistry = new ProjectImporterRegistry(Collections.<ProjectImporter>emptySet());
    projectServiceLinksInjector = new ProjectServiceLinksInjector();
    projectRegistry = new ProjectRegistry(workspaceHolder, vfsProvider, ptRegistry, phRegistry, eventService);
    projectRegistry.initProjects();
    FileWatcherNotificationHandler fileWatcherNotificationHandler = new DefaultFileWatcherNotificationHandler(vfsProvider);
    FileTreeWatcher fileTreeWatcher = new FileTreeWatcher(root, new HashSet<>(), fileWatcherNotificationHandler);
    pm = new ProjectManager(vfsProvider, ptRegistry, projectRegistry, phRegistry, importerRegistry, fileWatcherNotificationHandler, fileTreeWatcher, workspaceHolder, fileWatcherManager);
    pm.initWatcher();
    HttpJsonRequest httpJsonRequest = mock(HttpJsonRequest.class, new SelfReturningAnswer());
    //List<ProjectConfigDto> modules = new ArrayList<>();
    projects = new ArrayList<>();
    addMockedProjectConfigDto(myProjectType, "my_project");
    when(httpJsonRequestFactory.fromLink(any())).thenReturn(httpJsonRequest);
    when(httpJsonRequest.request()).thenReturn(httpJsonResponse);
    when(httpJsonResponse.asDto(WorkspaceDto.class)).thenReturn(usersWorkspaceMock);
    when(usersWorkspaceMock.getConfig()).thenReturn(workspaceConfigMock);
    when(workspaceConfigMock.getProjects()).thenReturn(projects);
    //        verify(httpJsonRequestFactory).fromLink(eq(DtoFactory.newDto(Link.class)
    //                                                             .withHref(apiEndpoint + "/workspace/" + workspace + "/project")
    //                                                             .withMethod(PUT)));
    DependencySupplierImpl dependencies = new DependencySupplierImpl();
    dependencies.addInstance(ProjectTypeRegistry.class, ptRegistry);
    dependencies.addInstance(UserDao.class, userDao);
    dependencies.addInstance(ProjectManager.class, pm);
    dependencies.addInstance(ProjectImporterRegistry.class, importerRegistry);
    dependencies.addInstance(ProjectHandlerRegistry.class, phRegistry);
    dependencies.addInstance(EventService.class, eventService);
    dependencies.addInstance(ProjectServiceLinksInjector.class, projectServiceLinksInjector);
    ResourceBinder resources = new ResourceBinderImpl();
    ProviderBinder providers = ProviderBinder.getInstance();
    EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), dependencies, new RequestHandlerImpl(new RequestDispatcher(resources), providers), null);
    launcher = new ResourceLauncher(processor);
    processor.addApplication(new Application() {

        @Override
        public Set<Class<?>> getClasses() {
            return java.util.Collections.<Class<?>>singleton(ProjectService.class);
        }

        @Override
        public Set<Object> getSingletons() {
            return new HashSet<>(Arrays.asList(new ApiExceptionMapper()));
        }
    });
    ApplicationContext.setCurrent(anApplicationContext().withProviders(providers).build());
    env = org.eclipse.che.commons.env.EnvironmentContext.getCurrent();
}
Also used : ProjectTypeRegistry(org.eclipse.che.api.project.server.type.ProjectTypeRegistry) DependencySupplierImpl(org.everrest.core.tools.DependencySupplierImpl) AttributeValue(org.eclipse.che.api.project.server.type.AttributeValue) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) FileWatcherNotificationHandler(org.eclipse.che.api.vfs.impl.file.FileWatcherNotificationHandler) DefaultFileWatcherNotificationHandler(org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler) ProjectImporterRegistry(org.eclipse.che.api.project.server.importer.ProjectImporterRegistry) ProjectTypeDef(org.eclipse.che.api.project.server.type.ProjectTypeDef) ResourceLauncher(org.everrest.core.tools.ResourceLauncher) EverrestConfiguration(org.everrest.core.impl.EverrestConfiguration) EverrestProcessor(org.everrest.core.impl.EverrestProcessor) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) ProjectHandlerRegistry(org.eclipse.che.api.project.server.handlers.ProjectHandlerRegistry) HttpJsonRequest(org.eclipse.che.api.core.rest.HttpJsonRequest) ApiExceptionMapper(org.eclipse.che.api.core.rest.ApiExceptionMapper) LocalVirtualFileSystemProvider(org.eclipse.che.api.vfs.impl.file.LocalVirtualFileSystemProvider) EventService(org.eclipse.che.api.core.notification.EventService) RequestDispatcher(org.everrest.core.impl.RequestDispatcher) ProjectImporter(org.eclipse.che.api.project.server.importer.ProjectImporter) ProviderBinder(org.everrest.core.impl.ProviderBinder) PathMatcher(java.nio.file.PathMatcher) DefaultFileWatcherNotificationHandler(org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler) SelfReturningAnswer(org.eclipse.che.commons.test.mockito.answer.SelfReturningAnswer) RequestHandlerImpl(org.everrest.core.impl.RequestHandlerImpl) ResourceBinderImpl(org.everrest.core.impl.ResourceBinderImpl) ResourceBinder(org.everrest.core.ResourceBinder) FileTreeWatcher(org.eclipse.che.api.vfs.impl.file.FileTreeWatcher) VirtualFile(org.eclipse.che.api.vfs.VirtualFile) File(java.io.File) Application(javax.ws.rs.core.Application) FSLuceneSearcherProvider(org.eclipse.che.api.vfs.search.impl.FSLuceneSearcherProvider) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 19 with PathMatcher

use of java.nio.file.PathMatcher in project che by eclipse.

the class FileWatcherByPathMatcher method accept.

@Override
public void accept(Path path) {
    if (!exists(path)) {
        if (pathWatchRegistrations.containsKey(path)) {
            pathWatchRegistrations.remove(path).forEach(watcher::unwatch);
        }
        paths.values().forEach(it -> it.remove(path));
        paths.entrySet().removeIf(it -> it.getValue().isEmpty());
    }
    for (PathMatcher matcher : matchers.keySet()) {
        if (matcher.matches(path)) {
            for (int operationId : matchers.get(matcher)) {
                paths.putIfAbsent(operationId, newConcurrentHashSet());
                if (paths.get(operationId).contains(path)) {
                    return;
                }
                paths.get(operationId).add(path);
                Operation operation = operations.get(operationId);
                int pathWatcherOperationId = watcher.watch(path, operation.create, operation.modify, operation.delete);
                pathWatchRegistrations.putIfAbsent(path, newConcurrentHashSet());
                pathWatchRegistrations.get(path).add(pathWatcherOperationId);
            }
        }
    }
}
Also used : PathMatcher(java.nio.file.PathMatcher)

Example 20 with PathMatcher

use of java.nio.file.PathMatcher in project che by eclipse.

the class JavaDebuggerTest method initProjectApi.

@BeforeClass
protected void initProjectApi() throws Exception {
    TestWorkspaceHolder workspaceHolder = new TestWorkspaceHolder(new ArrayList<>());
    File root = new File("target/test-classes/workspace");
    assertTrue(root.exists());
    File indexDir = new File("target/fs_index");
    assertTrue(indexDir.mkdirs());
    Set<PathMatcher> filters = new HashSet<>();
    filters.add(path -> true);
    FSLuceneSearcherProvider sProvider = new FSLuceneSearcherProvider(indexDir, filters);
    EventService eventService = new EventService();
    LocalVirtualFileSystemProvider vfsProvider = new LocalVirtualFileSystemProvider(root, sProvider);
    ProjectTypeRegistry projectTypeRegistry = new ProjectTypeRegistry(new HashSet<>());
    projectTypeRegistry.registerProjectType(new JavaProjectType(new JavaValueProviderFactory()));
    ProjectHandlerRegistry projectHandlerRegistry = new ProjectHandlerRegistry(new HashSet<>());
    ProjectRegistry projectRegistry = new ProjectRegistry(workspaceHolder, vfsProvider, projectTypeRegistry, projectHandlerRegistry, eventService);
    projectRegistry.initProjects();
    ProjectImporterRegistry importerRegistry = new ProjectImporterRegistry(new HashSet<>());
    FileWatcherNotificationHandler fileWatcherNotificationHandler = new DefaultFileWatcherNotificationHandler(vfsProvider);
    FileTreeWatcher fileTreeWatcher = new FileTreeWatcher(root, new HashSet<>(), fileWatcherNotificationHandler);
    ProjectManager projectManager = new ProjectManager(vfsProvider, projectTypeRegistry, projectRegistry, projectHandlerRegistry, importerRegistry, fileWatcherNotificationHandler, fileTreeWatcher, workspaceHolder, mock(FileWatcherManager.class));
    ResourcesPlugin resourcesPlugin = new ResourcesPlugin("target/index", root.getAbsolutePath(), () -> projectRegistry, () -> projectManager);
    resourcesPlugin.start();
    JavaPlugin javaPlugin = new JavaPlugin(root.getAbsolutePath() + "/.settings", resourcesPlugin, projectRegistry);
    javaPlugin.start();
    projectRegistry.setProjectType("test", "java", false);
    JavaModelManager.getDeltaState().initializeRoots(true);
    events = new ArrayBlockingQueue<>(10);
    Map<String, String> connectionProperties = ImmutableMap.of("host", "localhost", "port", System.getProperty("debug.port"));
    JavaDebuggerFactory factory = new JavaDebuggerFactory();
    debugger = factory.create(connectionProperties, events::add);
}
Also used : ProjectTypeRegistry(org.eclipse.che.api.project.server.type.ProjectTypeRegistry) FileWatcherNotificationHandler(org.eclipse.che.api.vfs.impl.file.FileWatcherNotificationHandler) DefaultFileWatcherNotificationHandler(org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler) ProjectImporterRegistry(org.eclipse.che.api.project.server.importer.ProjectImporterRegistry) JavaPlugin(org.eclipse.jdt.internal.ui.JavaPlugin) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) ProjectRegistry(org.eclipse.che.api.project.server.ProjectRegistry) JavaProjectType(org.eclipse.che.plugin.java.server.projecttype.JavaProjectType) HashSet(java.util.HashSet) ProjectHandlerRegistry(org.eclipse.che.api.project.server.handlers.ProjectHandlerRegistry) JavaValueProviderFactory(org.eclipse.che.plugin.java.server.projecttype.JavaValueProviderFactory) LocalVirtualFileSystemProvider(org.eclipse.che.api.vfs.impl.file.LocalVirtualFileSystemProvider) EventService(org.eclipse.che.api.core.notification.EventService) ProjectManager(org.eclipse.che.api.project.server.ProjectManager) FileWatcherManager(org.eclipse.che.api.vfs.watcher.FileWatcherManager) PathMatcher(java.nio.file.PathMatcher) DefaultFileWatcherNotificationHandler(org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler) FileTreeWatcher(org.eclipse.che.api.vfs.impl.file.FileTreeWatcher) File(java.io.File) FSLuceneSearcherProvider(org.eclipse.che.api.vfs.search.impl.FSLuceneSearcherProvider) BeforeClass(org.testng.annotations.BeforeClass)

Aggregations

PathMatcher (java.nio.file.PathMatcher)31 Path (java.nio.file.Path)15 File (java.io.File)9 HashSet (java.util.HashSet)5 ProjectHandlerRegistry (org.eclipse.che.api.project.server.handlers.ProjectHandlerRegistry)5 ProjectImporterRegistry (org.eclipse.che.api.project.server.importer.ProjectImporterRegistry)5 ProjectTypeRegistry (org.eclipse.che.api.project.server.type.ProjectTypeRegistry)5 DefaultFileWatcherNotificationHandler (org.eclipse.che.api.vfs.impl.file.DefaultFileWatcherNotificationHandler)5 FileTreeWatcher (org.eclipse.che.api.vfs.impl.file.FileTreeWatcher)5 LocalVirtualFileSystemProvider (org.eclipse.che.api.vfs.impl.file.LocalVirtualFileSystemProvider)5 FSLuceneSearcherProvider (org.eclipse.che.api.vfs.search.impl.FSLuceneSearcherProvider)5 Test (org.junit.Test)5 IOException (java.io.IOException)4 FileSystem (java.nio.file.FileSystem)4 ArrayList (java.util.ArrayList)4 EventService (org.eclipse.che.api.core.notification.EventService)4 FileVisitResult (java.nio.file.FileVisitResult)3 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)3 Set (java.util.Set)3 ProjectManager (org.eclipse.che.api.project.server.ProjectManager)3