Search in sources :

Example 21 with LayoutException

use of org.apache.archiva.repository.content.LayoutException in project archiva by apache.

the class ArchivaDavResourceFactory method processRepositoryGroup.

private DavResource processRepositoryGroup(final DavServletRequest request, ArchivaDavResourceLocator archivaLocator, String activePrincipal, List<String> resourcesInAbsolutePath, RepositoryGroup repoGroup) throws DavException {
    DavResource resource = null;
    List<DavException> storedExceptions = new ArrayList<>();
    String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/");
    String rootPath = StringUtils.substringBeforeLast(pathInfo, "/");
    String mergedIndexPath = "/";
    if (repoGroup.supportsFeature(IndexCreationFeature.class)) {
        mergedIndexPath = repoGroup.getFeature(IndexCreationFeature.class).getIndexPath().getPath();
    }
    if (StringUtils.endsWith(rootPath, mergedIndexPath)) {
        // we are in the case of index file request
        String requestedFileName = StringUtils.substringAfterLast(pathInfo, "/");
        StorageAsset temporaryIndexDirectory = buildMergedIndexDirectory(activePrincipal, request, repoGroup);
        StorageAsset asset = temporaryIndexDirectory.resolve(requestedFileName);
        try {
            resource = new ArchivaDavResource(asset, requestedFileName, repoGroup, request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler);
        } catch (LayoutException e) {
            log.error("Bad layout: {}", e.getMessage(), e);
            throw new DavException(500, e);
        }
    } else {
        for (ManagedRepository repository : repoGroup.getRepositories()) {
            String repositoryId = repository.getId();
            ManagedRepositoryContent managedRepositoryContent;
            ManagedRepository managedRepository = repositoryRegistry.getManagedRepository(repositoryId);
            if (managedRepository == null) {
                throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find repository with id " + repositoryId);
            }
            managedRepositoryContent = managedRepository.getContent();
            if (managedRepositoryContent == null) {
                log.error("Inconsistency detected. Repository content not found for '{}'", repositoryId);
                throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find repository content with id " + repositoryId);
            }
            try {
                DavResource updatedResource = processRepository(request, archivaLocator, activePrincipal, managedRepositoryContent, managedRepository);
                if (resource == null) {
                    resource = updatedResource;
                }
                String logicalResource = getLogicalResource(archivaLocator, null, false);
                if (logicalResource.endsWith("/")) {
                    logicalResource = logicalResource.substring(1);
                }
                resourcesInAbsolutePath.add(managedRepositoryContent.getRepository().getRoot().resolve(logicalResource).getFilePath().toAbsolutePath().toString());
            } catch (DavException e) {
                storedExceptions.add(e);
            }
        }
    }
    if (resource == null) {
        if (!storedExceptions.isEmpty()) {
            // MRM-1232
            for (DavException e : storedExceptions) {
                if (401 == e.getErrorCode()) {
                    throw e;
                }
            }
            throw new DavException(HttpServletResponse.SC_NOT_FOUND);
        } else {
            throw new DavException(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    return resource;
}
Also used : IndexCreationFeature(org.apache.archiva.repository.features.IndexCreationFeature) DavResource(org.apache.jackrabbit.webdav.DavResource) ManagedRepository(org.apache.archiva.repository.ManagedRepository) DavException(org.apache.jackrabbit.webdav.DavException) LayoutException(org.apache.archiva.repository.content.LayoutException) StorageAsset(org.apache.archiva.repository.storage.StorageAsset) ArrayList(java.util.ArrayList) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent)

Example 22 with LayoutException

use of org.apache.archiva.repository.content.LayoutException in project archiva by apache.

the class ArchivaDavResourceFactory method fetchContentFromProxies.

private boolean fetchContentFromProxies(ManagedRepository managedRepository, DavServletRequest request, LogicalResource resource) throws DavException {
    String path = resource.getPath();
    if (!proxyRegistry.hasHandler(managedRepository.getType())) {
        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "No proxy handler found for repository type " + managedRepository.getType());
    }
    RepositoryRequestInfo repositoryRequestInfo = managedRepository.getRequestInfo();
    RepositoryProxyHandler proxyHandler = proxyRegistry.getHandler(managedRepository.getType()).get(0);
    if (repositoryRequestInfo.isSupportFile(path)) {
        StorageAsset proxiedFile = proxyHandler.fetchFromProxies(managedRepository, path);
        return (proxiedFile != null);
    }
    // Is it a Metadata resource?
    if ("default".equals(repositoryRequestInfo.getLayout(path)) && repositoryRequestInfo.isMetadata(path)) {
        return proxyHandler.fetchMetadataFromProxies(managedRepository, path).isModified();
    }
    // Is it an Archetype Catalog?
    if (repositoryRequestInfo.isArchetypeCatalog(path)) {
        // FIXME we must implement a merge of remote archetype catalog from remote servers.
        StorageAsset proxiedFile = proxyHandler.fetchFromProxies(managedRepository, path);
        return (proxiedFile != null);
    }
    // Not any of the above? Then it's gotta be an artifact reference.
    try {
        // Get the artifact reference in a layout neutral way.
        // ArtifactReference artifact = repositoryRequestInfo.toArtifactReference( path );
        ItemSelector selector = repositoryRequestInfo.toItemSelector(path);
        if (selector != null) {
            String repositoryLayout = managedRepository.getLayout();
            RepositoryStorage repositoryStorage = this.applicationContext.getBean("repositoryStorage#" + repositoryLayout, RepositoryStorage.class);
            selector = repositoryStorage.applyServerSideRelocation(managedRepository, selector);
            StorageAsset proxiedFile = proxyHandler.fetchFromProxies(managedRepository, selector);
            resource.setPath(managedRepository.getContent().toPath(selector));
            log.debug("Proxied artifact '{}:{}:{}:{}'", selector.getNamespace(), selector.getArtifactId(), selector.getVersion(), selector.getArtifactVersion());
            return (proxiedFile != null);
        }
    } catch (LayoutException e) {
    /* eat it */
    } catch (ProxyDownloadException e) {
        log.error(e.getMessage(), e);
        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource.");
    }
    return false;
}
Also used : RepositoryStorage(org.apache.archiva.metadata.repository.storage.RepositoryStorage) ItemSelector(org.apache.archiva.repository.content.ItemSelector) DavException(org.apache.jackrabbit.webdav.DavException) LayoutException(org.apache.archiva.repository.content.LayoutException) StorageAsset(org.apache.archiva.repository.storage.StorageAsset) ProxyDownloadException(org.apache.archiva.policies.ProxyDownloadException) RepositoryRequestInfo(org.apache.archiva.repository.RepositoryRequestInfo) RepositoryProxyHandler(org.apache.archiva.proxy.model.RepositoryProxyHandler)

Example 23 with LayoutException

use of org.apache.archiva.repository.content.LayoutException in project archiva by apache.

the class ArchivaDavResourceFactory method createResource.

@Override
public DavResource createResource(final DavResourceLocator locator, final DavSession davSession) throws DavException {
    ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator(locator);
    ManagedRepositoryContent managedRepositoryContent;
    ManagedRepository repo = repositoryRegistry.getManagedRepository(archivaLocator.getRepositoryId());
    if (repo == null) {
        throw new DavException(HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " + archivaLocator.getRepositoryId());
    }
    managedRepositoryContent = repo.getContent();
    if (managedRepositoryContent == null) {
        log.error("Inconsistency detected. Repository content not found for '{}'", archivaLocator.getRepositoryId());
        throw new DavException(HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " + archivaLocator.getRepositoryId());
    }
    DavResource resource = null;
    String logicalResource = getLogicalResource(archivaLocator, repo, false);
    if (logicalResource.startsWith("/")) {
        logicalResource = logicalResource.substring(1);
    }
    StorageAsset resourceAsset = repo.getAsset(logicalResource);
    try {
        resource = new ArchivaDavResource(resourceAsset, logicalResource, repo, davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler);
    } catch (LayoutException e) {
        log.error("Incompatible layout: {}", e.getMessage(), e);
        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    }
    resource.addLockManager(lockManager);
    return resource;
}
Also used : ManagedRepository(org.apache.archiva.repository.ManagedRepository) DavResource(org.apache.jackrabbit.webdav.DavResource) DavException(org.apache.jackrabbit.webdav.DavException) LayoutException(org.apache.archiva.repository.content.LayoutException) StorageAsset(org.apache.archiva.repository.storage.StorageAsset) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent)

Example 24 with LayoutException

use of org.apache.archiva.repository.content.LayoutException in project archiva by apache.

the class ArchivaDavResourceFactory method getResourceFromGroup.

private DavResource getResourceFromGroup(DavServletRequest request, ArchivaDavResourceLocator locator, RepositoryGroup repositoryGroup) throws DavException {
    final String id = repositoryGroup.getId();
    final List<ManagedRepository> repositories = repositoryGroup.getRepositories();
    if (repositories == null || repositories.isEmpty()) {
        try {
            return new ArchivaDavResource(repositoryGroup.getAsset("/"), "groups/" + id, null, request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler);
        } catch (LayoutException e) {
            log.error("Bad repository layout: {}", e.getMessage(), e);
            throw new DavException(500, e);
        }
    }
    List<StorageAsset> mergedRepositoryContents = new ArrayList<>();
    ManagedRepository firstRepo = repositories.get(0);
    String path = getLogicalResource(locator, firstRepo, false);
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    LogicalResource logicalResource = new LogicalResource(path);
    // flow:
    // if the current user logged in has permission to any of the repositories, allow user to
    // browse the repo group but displaying only the repositories which the user has permission to access.
    // otherwise, prompt for authentication.
    String activePrincipal = getActivePrincipal(request);
    boolean allow = isAllowedToContinue(request, repositories, activePrincipal);
    // remove last /
    String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/");
    String mergedIndexPath = "/";
    if (repositoryGroup.supportsFeature(IndexCreationFeature.class)) {
        IndexCreationFeature indexCreationFeature = repositoryGroup.getFeature(IndexCreationFeature.class);
        mergedIndexPath = indexCreationFeature.getIndexPath().getPath();
    }
    if (allow) {
        if (StringUtils.endsWith(pathInfo, mergedIndexPath)) {
            StorageAsset mergedRepoDirPath = buildMergedIndexDirectory(activePrincipal, request, repositoryGroup);
            mergedRepositoryContents.add(mergedRepoDirPath);
        } else {
            if (StringUtils.equalsIgnoreCase(pathInfo, "/" + id)) {
                Path tmpDirectory = Paths.get(SystemUtils.getJavaIoTmpDir().toString(), id, mergedIndexPath);
                if (!Files.exists(tmpDirectory)) {
                    synchronized (tmpDirectory.toAbsolutePath().toString()) {
                        if (!Files.exists(tmpDirectory)) {
                            try {
                                Files.createDirectories(tmpDirectory);
                            } catch (IOException e) {
                                throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create direcotory " + tmpDirectory);
                            }
                        }
                    }
                }
                try {
                    FilesystemStorage storage = new FilesystemStorage(tmpDirectory.getParent(), new DefaultFileLockManager());
                    mergedRepositoryContents.add(storage.getRoot());
                } catch (IOException e) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create storage for " + tmpDirectory);
                }
            }
            for (ManagedRepository repo : repositories) {
                ManagedRepositoryContent managedRepository = null;
                if (repo == null) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid managed repository <" + repo.getId() + ">");
                }
                managedRepository = repo.getContent();
                if (managedRepository == null) {
                    log.error("Inconsistency detected. Repository content not found for '{}'", repo.getId());
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid managed repository <" + repo.getId() + ">");
                }
                // Path resourceFile = Paths.get( managedRepository.getRepoRoot(), logicalResource.getPath() );
                StorageAsset resourceFile = repo.getAsset(logicalResource.getPath());
                if (resourceFile.exists() && managedRepository.getRepository().supportsFeature(IndexCreationFeature.class)) {
                    // in case of group displaying index directory doesn't have sense !!
                    IndexCreationFeature idf = managedRepository.getRepository().getFeature(IndexCreationFeature.class);
                    StorageAsset repoIndexDirectory = idf.getLocalIndexPath();
                    if (!StringUtils.equals(FilenameUtils.normalize(repoIndexDirectory.getPath()), FilenameUtils.normalize(logicalResource.getPath()))) {
                        // for prompted authentication
                        if (httpAuth.getSecuritySession(request.getSession(true)) != null) {
                            try {
                                if (isAuthorized(request, repo.getId())) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repo.getId(), activePrincipal);
                                }
                            } catch (DavException e) {
                                // TODO: review exception handling
                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository, activePrincipal, e.getMessage());
                            }
                        } else {
                            // for the current user logged in
                            try {
                                if (servletAuth.isAuthorized(activePrincipal, repo.getId(), WebdavMethodUtil.getMethodPermission(request.getMethod()))) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repo.getId(), activePrincipal);
                                }
                            } catch (UnauthorizedException e) {
                                // TODO: review exception handling
                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository, activePrincipal, e.getMessage());
                            }
                        }
                    }
                }
            }
        }
    } else {
        throw new UnauthorizedDavException(locator.getRepositoryId(), "User not authorized.");
    }
    ArchivaVirtualDavResource resource = new ArchivaVirtualDavResource(mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this);
    // compatibility with MRM-440 to ensure browsing the repository group works ok
    if (resource.isCollection() && !request.getRequestURI().endsWith("/")) {
        throw new BrowserRedirectException(resource.getHref());
    }
    return resource;
}
Also used : Path(java.nio.file.Path) ManagedRepository(org.apache.archiva.repository.ManagedRepository) DavException(org.apache.jackrabbit.webdav.DavException) FilesystemStorage(org.apache.archiva.repository.storage.fs.FilesystemStorage) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IndexCreationFeature(org.apache.archiva.repository.features.IndexCreationFeature) LayoutException(org.apache.archiva.repository.content.LayoutException) StorageAsset(org.apache.archiva.repository.storage.StorageAsset) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException) DefaultFileLockManager(org.apache.archiva.common.filelock.DefaultFileLockManager)

Example 25 with LayoutException

use of org.apache.archiva.repository.content.LayoutException in project archiva by apache.

the class DaysOldRepositoryPurge method process.

@Override
public void process(String path) throws RepositoryPurgeException {
    try {
        ContentItem item = repository.toItem(path);
        Artifact artifactItem = repository.getLayout(BaseRepositoryContentLayout.class).adaptItem(Artifact.class, item);
        if (!artifactItem.exists()) {
            return;
        }
        // ArtifactReference artifact = repository.toArtifactReference( path );
        Calendar olderThanThisDate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        olderThanThisDate.add(Calendar.DATE, -retentionPeriod);
        ArchivaItemSelector selector = ArchivaItemSelector.builder().withNamespace(artifactItem.getVersion().getProject().getNamespace().getId()).withProjectId(artifactItem.getVersion().getProject().getId()).withVersion(artifactItem.getVersion().getId()).withClassifier("*").includeRelatedArtifacts().build();
        List<String> artifactVersions;
        try (Stream<? extends Artifact> stream = repository.getLayout(BaseRepositoryContentLayout.class).newArtifactStream(selector)) {
            artifactVersions = stream.map(a -> a.getArtifactVersion()).filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
        }
        Collections.sort(artifactVersions, VersionComparator.getInstance());
        if (retentionCount > artifactVersions.size()) {
            // Done. nothing to do here. skip it.
            return;
        }
        int countToPurge = artifactVersions.size() - retentionCount;
        ArchivaItemSelector.Builder artifactSelectorBuilder = ArchivaItemSelector.builder().withNamespace(artifactItem.getVersion().getProject().getNamespace().getId()).withProjectId(artifactItem.getVersion().getProject().getId()).withVersion(artifactItem.getVersion().getId()).withArtifactId(artifactItem.getId()).withClassifier("*").includeRelatedArtifacts();
        Set<Artifact> artifactsToDelete = new HashSet<>();
        for (String version : artifactVersions) {
            if (countToPurge-- <= 0) {
                break;
            }
            ArchivaItemSelector artifactSelector = artifactSelectorBuilder.withArtifactVersion(version).build();
            try {
                // Is this a generic snapshot "1.0-SNAPSHOT" ?
                if (VersionUtil.isGenericSnapshot(version)) {
                    List<? extends Artifact> artifactList = repository.getLayout(BaseRepositoryContentLayout.class).getArtifacts(artifactSelector);
                    if (artifactList.size() > 0 && artifactList.get(0).getAsset().getModificationTime().toEpochMilli() < olderThanThisDate.getTimeInMillis()) {
                        artifactsToDelete.addAll(artifactList);
                    }
                } else // Is this a timestamp snapshot "1.0-20070822.123456-42" ?
                if (VersionUtil.isUniqueSnapshot(version)) {
                    Calendar timestampCal = uniqueSnapshotToCalendar(version);
                    if (timestampCal.getTimeInMillis() < olderThanThisDate.getTimeInMillis()) {
                        artifactsToDelete.addAll(repository.getLayout(BaseRepositoryContentLayout.class).getArtifacts(artifactSelector));
                    }
                }
            } catch (IllegalArgumentException e) {
                log.error("Bad selector for artifact: {}", e.getMessage(), e);
            // continue
            }
        }
        purge(artifactsToDelete);
    } catch (LayoutException e) {
        log.debug("Not processing file that is not an artifact: {}", e.getMessage());
    } catch (ContentAccessException e) {
        e.printStackTrace();
    }
}
Also used : ArchivaItemSelector(org.apache.archiva.repository.content.base.ArchivaItemSelector) Calendar(java.util.Calendar) Artifact(org.apache.archiva.repository.content.Artifact) LayoutException(org.apache.archiva.repository.content.LayoutException) BaseRepositoryContentLayout(org.apache.archiva.repository.content.BaseRepositoryContentLayout) ContentItem(org.apache.archiva.repository.content.ContentItem) HashSet(java.util.HashSet) ContentAccessException(org.apache.archiva.repository.content.ContentAccessException)

Aggregations

LayoutException (org.apache.archiva.repository.content.LayoutException)29 ManagedRepositoryContent (org.apache.archiva.repository.ManagedRepositoryContent)14 StorageAsset (org.apache.archiva.repository.storage.StorageAsset)14 BaseRepositoryContentLayout (org.apache.archiva.repository.content.BaseRepositoryContentLayout)13 Artifact (org.apache.archiva.repository.content.Artifact)12 ArchivaItemSelector (org.apache.archiva.repository.content.base.ArchivaItemSelector)12 IOException (java.io.IOException)9 ManagedRepository (org.apache.archiva.repository.ManagedRepository)8 ContentItem (org.apache.archiva.repository.content.ContentItem)8 ItemSelector (org.apache.archiva.repository.content.ItemSelector)8 ContentAccessException (org.apache.archiva.repository.content.ContentAccessException)6 Version (org.apache.archiva.repository.content.Version)6 DavException (org.apache.jackrabbit.webdav.DavException)6 ArrayList (java.util.ArrayList)5 ArchivaRepositoryMetadata (org.apache.archiva.model.ArchivaRepositoryMetadata)4 ItemNotFoundException (org.apache.archiva.repository.content.ItemNotFoundException)4 Project (org.apache.archiva.repository.content.Project)4 DavResource (org.apache.jackrabbit.webdav.DavResource)4 Path (java.nio.file.Path)3 HashSet (java.util.HashSet)3