use of org.apache.archiva.repository.ManagedRepository 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);
}
Path resourceFile = Paths.get(managedRepositoryContent.getRepoRoot(), logicalResource);
resource = new ArchivaDavResource(resourceFile.toAbsolutePath().toString(), logicalResource, repo, davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
resource.addLockManager(lockManager);
return resource;
}
use of org.apache.archiva.repository.ManagedRepository in project archiva by apache.
the class ArchivaDavResourceFactory method createResource.
@Override
public DavResource createResource(final DavResourceLocator locator, final DavServletRequest request, final DavServletResponse response) throws DavException {
ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator(locator);
RepositoryGroupConfiguration repoGroupConfig = archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get(archivaLocator.getRepositoryId());
String activePrincipal = getActivePrincipal(request);
List<String> resourcesInAbsolutePath = new ArrayList<>();
boolean readMethod = WebdavMethodUtil.isReadMethod(request.getMethod());
DavResource resource;
if (repoGroupConfig != null) {
if (!readMethod) {
throw new DavException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Write method not allowed for repository groups.");
}
log.debug("Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal);
// handle browse requests for virtual repos
if (getLogicalResource(archivaLocator, null, true).endsWith("/")) {
DavResource davResource = getResourceFromGroup(request, repoGroupConfig.getRepositories(), archivaLocator, repoGroupConfig);
setHeaders(response, locator, davResource, true);
return davResource;
} else {
// make a copy to avoid potential concurrent modifications (eg. by configuration)
// TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
// infrequent
List<String> repositories = new ArrayList<>(repoGroupConfig.getRepositories());
resource = processRepositoryGroup(request, archivaLocator, repositories, activePrincipal, resourcesInAbsolutePath, repoGroupConfig);
}
} else {
try {
RemoteRepository remoteRepository = remoteRepositoryAdmin.getRemoteRepository(archivaLocator.getRepositoryId());
if (remoteRepository != null) {
String logicalResource = getLogicalResource(archivaLocator, null, false);
IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext(remoteRepository);
Path resourceFile = StringUtils.equals(logicalResource, "/") ? Paths.get(indexingContext.getIndexDirectoryFile().getParent()) : Paths.get(indexingContext.getIndexDirectoryFile().getParent(), logicalResource);
resource = new //
ArchivaDavResource(//
resourceFile.toAbsolutePath().toString(), //
locator.getResourcePath(), //
null, //
request.getRemoteAddr(), //
activePrincipal, //
request.getDavSession(), //
archivaLocator, //
this, //
mimeTypes, //
auditListeners, //
scheduler, fileLockManager);
setHeaders(response, locator, resource, false);
return resource;
}
} catch (RepositoryAdminException e) {
log.debug("RepositoryException remote repository with d'{}' not found, msg: {}", archivaLocator.getRepositoryId(), e.getMessage());
}
ManagedRepository repo = repositoryRegistry.getManagedRepository(archivaLocator.getRepositoryId());
if (repo == null) {
throw new DavException(HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " + archivaLocator.getRepositoryId());
}
ManagedRepositoryContent 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());
}
log.debug("Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal);
resource = processRepository(request, archivaLocator, activePrincipal, managedRepositoryContent, repo);
String logicalResource = getLogicalResource(archivaLocator, null, false);
resourcesInAbsolutePath.add(Paths.get(managedRepositoryContent.getRepoRoot(), logicalResource).toAbsolutePath().toString());
}
String requestedResource = request.getRequestURI();
// merge metadata only when requested via the repo group
if ((repositoryRequest.isMetadata(requestedResource) || repositoryRequest.isMetadataSupportFile(requestedResource)) && repoGroupConfig != null) {
// this should only be at the project level not version level!
if (isProjectReference(requestedResource)) {
ArchivaDavResource res = (ArchivaDavResource) resource;
String filePath = StringUtils.substringBeforeLast(res.getLocalResource().toAbsolutePath().toString().replace('\\', '/'), "/");
filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
// for MRM-872 handle checksums of the merged metadata files
if (repositoryRequest.isSupportFile(requestedResource)) {
Path metadataChecksum = Paths.get(filePath + "." + StringUtils.substringAfterLast(requestedResource, "."));
if (Files.exists(metadataChecksum)) {
LogicalResource logicalResource = new LogicalResource(getLogicalResource(archivaLocator, null, false));
resource = new ArchivaDavResource(metadataChecksum.toAbsolutePath().toString(), logicalResource.getPath(), null, request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
}
} else {
if (resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1) {
// merge the metadata of all repos under group
ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
for (String resourceAbsPath : resourcesInAbsolutePath) {
try {
Path metadataFile = Paths.get(resourceAbsPath);
ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read(metadataFile);
mergedMetadata = RepositoryMetadataMerge.merge(mergedMetadata, repoMetadata);
} catch (XMLException e) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while reading metadata file.");
} catch (RepositoryMetadataException r) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while merging metadata file.");
}
}
try {
Path resourceFile = writeMergedMetadataToFile(mergedMetadata, filePath);
LogicalResource logicalResource = new LogicalResource(getLogicalResource(archivaLocator, null, false));
resource = new ArchivaDavResource(resourceFile.toAbsolutePath().toString(), logicalResource.getPath(), null, request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
} catch (RepositoryMetadataException r) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while writing metadata file.");
} catch (IOException ie) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while generating checksum files.");
} catch (DigesterException de) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while generating checksum files." + de.getMessage());
}
}
}
}
}
setHeaders(response, locator, resource, false);
// compatibility with MRM-440 to ensure browsing the repository works ok
if (resource.isCollection() && !request.getRequestURI().endsWith("/")) {
throw new BrowserRedirectException(resource.getHref());
}
resource.addLockManager(lockManager);
return resource;
}
use of org.apache.archiva.repository.ManagedRepository in project archiva by apache.
the class ArchivaDavResourceFactory method getResourceFromGroup.
private DavResource getResourceFromGroup(DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator, RepositoryGroupConfiguration repositoryGroupConfiguration) throws DavException {
if (repositoryGroupConfiguration.getRepositories() == null || repositoryGroupConfiguration.getRepositories().isEmpty()) {
Path file = Paths.get(System.getProperty("appserver.base"), "groups/" + repositoryGroupConfiguration.getId());
return new ArchivaDavResource(file.toString(), "groups/" + repositoryGroupConfiguration.getId(), null, request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
}
List<Path> mergedRepositoryContents = new ArrayList<>();
// multiple repo types so we guess they are all the same type
// so use the first one
// FIXME add a method with group in the repository storage
String firstRepoId = repositoryGroupConfiguration.getRepositories().get(0);
String path = getLogicalResource(locator, repositoryRegistry.getManagedRepository(firstRepoId), 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(), "/");
if (allow) {
if (StringUtils.endsWith(pathInfo, repositoryGroupConfiguration.getMergedIndexPath())) {
Path mergedRepoDir = buildMergedIndexDirectory(repositories, activePrincipal, request, repositoryGroupConfiguration);
mergedRepositoryContents.add(mergedRepoDir);
} else {
if (StringUtils.equalsIgnoreCase(pathInfo, "/" + repositoryGroupConfiguration.getId())) {
Path tmpDirectory = Paths.get(SystemUtils.getJavaIoTmpDir().toString(), repositoryGroupConfiguration.getId(), repositoryGroupConfiguration.getMergedIndexPath());
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);
}
}
}
}
mergedRepositoryContents.add(tmpDirectory.getParent());
}
for (String repository : repositories) {
ManagedRepositoryContent managedRepository = null;
ManagedRepository repo = repositoryRegistry.getManagedRepository(repository);
if (repo == null) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid managed repository <" + repository + ">");
}
managedRepository = repo.getContent();
if (managedRepository == null) {
log.error("Inconsistency detected. Repository content not found for '{}'", repository);
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid managed repository <" + repository + ">");
}
Path resourceFile = Paths.get(managedRepository.getRepoRoot(), logicalResource.getPath());
if (Files.exists(resourceFile)) {
// in case of group displaying index directory doesn't have sense !!
IndexCreationFeature idf = managedRepository.getRepository().getFeature(IndexCreationFeature.class).get();
String repoIndexDirectory = idf.getIndexPath().toString();
if (StringUtils.isNotEmpty(repoIndexDirectory)) {
if (!Paths.get(repoIndexDirectory).isAbsolute()) {
repoIndexDirectory = Paths.get(managedRepository.getRepository().getLocation()).resolve(StringUtils.isEmpty(repoIndexDirectory) ? ".indexer" : repoIndexDirectory).toAbsolutePath().toString();
}
}
if (StringUtils.isEmpty(repoIndexDirectory)) {
repoIndexDirectory = Paths.get(managedRepository.getRepository().getLocation()).resolve(".indexer").toAbsolutePath().toString();
}
if (!StringUtils.equals(FilenameUtils.normalize(repoIndexDirectory), FilenameUtils.normalize(resourceFile.toAbsolutePath().toString()))) {
// for prompted authentication
if (httpAuth.getSecuritySession(request.getSession(true)) != null) {
try {
if (isAuthorized(request, repository)) {
mergedRepositoryContents.add(resourceFile);
log.debug("Repository '{}' accessed by '{}'", repository, 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, repository, WebdavMethodUtil.getMethodPermission(request.getMethod()))) {
mergedRepositoryContents.add(resourceFile);
log.debug("Repository '{}' accessed by '{}'", repository, 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;
}
use of org.apache.archiva.repository.ManagedRepository in project archiva by apache.
the class MavenIndexManager method createContext.
@Override
public ArchivaIndexingContext createContext(Repository repository) throws IndexCreationFailedException {
log.debug("Creating context for repo {}, type: {}", repository.getId(), repository.getType());
if (repository.getType() != RepositoryType.MAVEN) {
throw new UnsupportedRepositoryTypeException(repository.getType());
}
IndexingContext mvnCtx = null;
try {
if (repository instanceof RemoteRepository) {
mvnCtx = createRemoteContext((RemoteRepository) repository);
} else if (repository instanceof ManagedRepository) {
mvnCtx = createManagedContext((ManagedRepository) repository);
}
} catch (IOException e) {
log.error("IOException during context creation " + e.getMessage(), e);
throw new IndexCreationFailedException("Could not create index context for repository " + repository.getId() + (StringUtils.isNotEmpty(e.getMessage()) ? ": " + e.getMessage() : ""), e);
}
MavenIndexContext context = new MavenIndexContext(repository, mvnCtx);
return context;
}
use of org.apache.archiva.repository.ManagedRepository in project archiva by apache.
the class DefaultRepositoryProxyConnectors method initConnectorsAndNetworkProxies.
@SuppressWarnings("unchecked")
private void initConnectorsAndNetworkProxies() {
ProxyConnectorOrderComparator proxyOrderSorter = new ProxyConnectorOrderComparator();
this.proxyConnectorMap.clear();
Configuration configuration = archivaConfiguration.getConfiguration();
List<ProxyConnectorRuleConfiguration> allProxyConnectorRuleConfigurations = configuration.getProxyConnectorRuleConfigurations();
List<ProxyConnectorConfiguration> proxyConfigs = configuration.getProxyConnectors();
for (ProxyConnectorConfiguration proxyConfig : proxyConfigs) {
String key = proxyConfig.getSourceRepoId();
// Create connector object.
ProxyConnector connector = new ProxyConnector();
ManagedRepository repo = repositoryRegistry.getManagedRepository(proxyConfig.getSourceRepoId());
if (repo == null) {
log.error("Cannot find source repository after config change " + proxyConfig.getSourceRepoId());
continue;
}
connector.setSourceRepository(repo.getContent());
RemoteRepository rRepo = repositoryRegistry.getRemoteRepository(proxyConfig.getTargetRepoId());
if (rRepo == null) {
log.error("Cannot find target repository after config change " + proxyConfig.getSourceRepoId());
continue;
}
connector.setTargetRepository(rRepo.getContent());
connector.setProxyId(proxyConfig.getProxyId());
connector.setPolicies(proxyConfig.getPolicies());
connector.setOrder(proxyConfig.getOrder());
connector.setDisabled(proxyConfig.isDisabled());
// Copy any blacklist patterns.
List<String> blacklist = new ArrayList<>(0);
if (CollectionUtils.isNotEmpty(proxyConfig.getBlackListPatterns())) {
blacklist.addAll(proxyConfig.getBlackListPatterns());
}
connector.setBlacklist(blacklist);
// Copy any whitelist patterns.
List<String> whitelist = new ArrayList<>(0);
if (CollectionUtils.isNotEmpty(proxyConfig.getWhiteListPatterns())) {
whitelist.addAll(proxyConfig.getWhiteListPatterns());
}
connector.setWhitelist(whitelist);
List<ProxyConnectorRuleConfiguration> proxyConnectorRuleConfigurations = findProxyConnectorRules(connector.getSourceRepository().getId(), connector.getTargetRepository().getId(), allProxyConnectorRuleConfigurations);
if (!proxyConnectorRuleConfigurations.isEmpty()) {
for (ProxyConnectorRuleConfiguration proxyConnectorRuleConfiguration : proxyConnectorRuleConfigurations) {
if (StringUtils.equals(proxyConnectorRuleConfiguration.getRuleType(), ProxyConnectorRuleType.BLACK_LIST.getRuleType())) {
connector.getBlacklist().add(proxyConnectorRuleConfiguration.getPattern());
}
if (StringUtils.equals(proxyConnectorRuleConfiguration.getRuleType(), ProxyConnectorRuleType.WHITE_LIST.getRuleType())) {
connector.getWhitelist().add(proxyConnectorRuleConfiguration.getPattern());
}
}
}
// Get other connectors
List<ProxyConnector> connectors = this.proxyConnectorMap.get(key);
if (connectors == null) {
// Create if we are the first.
connectors = new ArrayList<>(1);
}
// Add the connector.
connectors.add(connector);
// Ensure the list is sorted.
Collections.sort(connectors, proxyOrderSorter);
// Set the key to the list of connectors.
this.proxyConnectorMap.put(key, connectors);
}
this.networkProxyMap.clear();
List<NetworkProxyConfiguration> networkProxies = archivaConfiguration.getConfiguration().getNetworkProxies();
for (NetworkProxyConfiguration networkProxyConfig : networkProxies) {
String key = networkProxyConfig.getId();
ProxyInfo proxy = new ProxyInfo();
proxy.setType(networkProxyConfig.getProtocol());
proxy.setHost(networkProxyConfig.getHost());
proxy.setPort(networkProxyConfig.getPort());
proxy.setUserName(networkProxyConfig.getUsername());
proxy.setPassword(networkProxyConfig.getPassword());
this.networkProxyMap.put(key, proxy);
}
}
Aggregations