Search in sources :

Example 26 with ManagedRepositoryContent

use of org.apache.archiva.repository.ManagedRepositoryContent in project archiva by apache.

the class ArchivaDavResourceFactoryTest method testRequestArtifactMetadataTwoPartsRepoHasDefaultLayout.

@Test
public void testRequestArtifactMetadataTwoPartsRepoHasDefaultLayout() throws Exception {
    // should not fetch metadata
    DavResourceLocator locator = new ArchivaDavResourceLocator("", "/repository/" + INTERNAL_REPO + "/eclipse/maven-metadata.xml", INTERNAL_REPO, new ArchivaDavLocatorFactory());
    ManagedRepositoryContent internalRepo = createManagedRepositoryContent(INTERNAL_REPO);
    // use actual object (this performs the isMetadata, isDefault and isSupportFile check!)
    RepositoryRequest repoRequest = new RepositoryRequest();
    resourceFactory.setRepositoryRequest(repoRequest);
    try {
        archivaConfigurationControl.reset();
        expect(archivaConfiguration.getConfiguration()).andReturn(config).times(2);
        expect(repoFactory.getManagedRepositoryContent(INTERNAL_REPO)).andReturn(internalRepo);
        expect(request.getMethod()).andReturn("GET").times(3);
        expect(request.getRemoteAddr()).andReturn("http://localhost:8080").times(3);
        expect(request.getDavSession()).andReturn(new ArchivaDavSession()).times(2);
        expect(request.getContextPath()).andReturn("").times(2);
        archivaConfigurationControl.replay();
        repoContentFactoryControl.replay();
        requestControl.replay();
        resourceFactory.createResource(locator, request, response);
        archivaConfigurationControl.verify();
        repoContentFactoryControl.verify();
        requestControl.verify();
        fail("A 404 error should have been thrown!");
    } catch (DavException e) {
        assertEquals(404, e.getErrorCode());
    }
}
Also used : DavException(org.apache.jackrabbit.webdav.DavException) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) RepositoryRequest(org.apache.archiva.repository.content.maven2.RepositoryRequest) DavResourceLocator(org.apache.jackrabbit.webdav.DavResourceLocator) Test(org.junit.Test)

Example 27 with ManagedRepositoryContent

use of org.apache.archiva.repository.ManagedRepositoryContent in project archiva by apache.

the class DefaultFileUploadService method saveFile.

protected void saveFile(String repositoryId, FileMetadata fileMetadata, boolean generatePom, String groupId, String artifactId, String version, String packaging) throws ArchivaRestServiceException {
    try {
        ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository(repositoryId);
        ArtifactReference artifactReference = new ArtifactReference();
        artifactReference.setArtifactId(artifactId);
        artifactReference.setGroupId(groupId);
        artifactReference.setVersion(version);
        artifactReference.setClassifier(fileMetadata.getClassifier());
        artifactReference.setType(StringUtils.isEmpty(fileMetadata.getPackaging()) ? packaging : fileMetadata.getPackaging());
        ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent(repositoryId);
        String artifactPath = repository.toPath(artifactReference);
        int lastIndex = artifactPath.lastIndexOf('/');
        String path = artifactPath.substring(0, lastIndex);
        Path targetPath = Paths.get(repoConfig.getLocation(), path);
        log.debug("artifactPath: {} found targetPath: {}", artifactPath, targetPath);
        Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
        int newBuildNumber = -1;
        String timestamp = null;
        Path versionMetadataFile = targetPath.resolve(MetadataTools.MAVEN_METADATA);
        ArchivaRepositoryMetadata versionMetadata = getMetadata(versionMetadataFile);
        if (VersionUtil.isSnapshot(version)) {
            TimeZone timezone = TimeZone.getTimeZone("UTC");
            DateFormat fmt = new SimpleDateFormat("yyyyMMdd.HHmmss");
            fmt.setTimeZone(timezone);
            timestamp = fmt.format(lastUpdatedTimestamp);
            if (versionMetadata.getSnapshotVersion() != null) {
                newBuildNumber = versionMetadata.getSnapshotVersion().getBuildNumber() + 1;
            } else {
                newBuildNumber = 1;
            }
        }
        if (!Files.exists(targetPath)) {
            Files.createDirectories(targetPath);
        }
        String filename = artifactPath.substring(lastIndex + 1);
        if (VersionUtil.isSnapshot(version)) {
            filename = filename.replaceAll(VersionUtil.SNAPSHOT, timestamp + "-" + newBuildNumber);
        }
        boolean fixChecksums = !(archivaAdministration.getKnownContentConsumers().contains("create-missing-checksums"));
        try {
            Path targetFile = targetPath.resolve(filename);
            if (Files.exists(targetFile) && !VersionUtil.isSnapshot(version) && repoConfig.isBlockRedeployments()) {
                throw new ArchivaRestServiceException("Overwriting released artifacts in repository '" + repoConfig.getId() + "' is not allowed.", Response.Status.BAD_REQUEST.getStatusCode(), null);
            } else {
                copyFile(Paths.get(fileMetadata.getServerFileName()), targetPath, filename, fixChecksums);
                triggerAuditEvent(repository.getId(), path + "/" + filename, AuditEvent.UPLOAD_FILE);
                queueRepositoryTask(repository.getId(), targetFile);
            }
        } catch (IOException ie) {
            log.error("IOException copying file: {}", ie.getMessage(), ie);
            throw new ArchivaRestServiceException("Overwriting released artifacts in repository '" + repoConfig.getId() + "' is not allowed.", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ie);
        }
        if (generatePom) {
            String pomFilename = filename;
            if (StringUtils.isNotEmpty(fileMetadata.getClassifier())) {
                pomFilename = StringUtils.remove(pomFilename, "-" + fileMetadata.getClassifier());
            }
            pomFilename = FilenameUtils.removeExtension(pomFilename) + ".pom";
            try {
                Path generatedPomFile = createPom(targetPath, pomFilename, fileMetadata, groupId, artifactId, version, packaging);
                triggerAuditEvent(repoConfig.getId(), path + "/" + pomFilename, AuditEvent.UPLOAD_FILE);
                if (fixChecksums) {
                    fixChecksums(generatedPomFile);
                }
                queueRepositoryTask(repoConfig.getId(), generatedPomFile);
            } catch (IOException ie) {
                throw new ArchivaRestServiceException("Error encountered while writing pom file: " + ie.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ie);
            }
        }
        // explicitly update only if metadata-updater consumer is not enabled!
        if (!archivaAdministration.getKnownContentConsumers().contains("metadata-updater")) {
            updateProjectMetadata(targetPath.toAbsolutePath().toString(), lastUpdatedTimestamp, timestamp, newBuildNumber, fixChecksums, fileMetadata, groupId, artifactId, version, packaging);
            if (VersionUtil.isSnapshot(version)) {
                updateVersionMetadata(versionMetadata, versionMetadataFile, lastUpdatedTimestamp, timestamp, newBuildNumber, fixChecksums, fileMetadata, groupId, artifactId, version, packaging);
            }
        }
    } catch (RepositoryNotFoundException re) {
        throw new ArchivaRestServiceException("Target repository cannot be found: " + re.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), re);
    } catch (RepositoryException rep) {
        throw new ArchivaRestServiceException("Repository exception: " + rep.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rep);
    } catch (RepositoryAdminException e) {
        throw new ArchivaRestServiceException("RepositoryAdmin exception: " + e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    } catch (IOException e) {
        throw new ArchivaRestServiceException("Repository exception " + e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    }
}
Also used : Path(java.nio.file.Path) ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) RepositoryException(org.apache.archiva.repository.RepositoryException) IOException(java.io.IOException) RepositoryNotFoundException(org.apache.archiva.repository.RepositoryNotFoundException) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) Date(java.util.Date) TimeZone(java.util.TimeZone) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) ArchivaRepositoryMetadata(org.apache.archiva.model.ArchivaRepositoryMetadata) ArtifactReference(org.apache.archiva.model.ArtifactReference) SimpleDateFormat(java.text.SimpleDateFormat)

Example 28 with ManagedRepositoryContent

use of org.apache.archiva.repository.ManagedRepositoryContent in project archiva by apache.

the class DefaultFileUploadService method savePomFile.

protected void savePomFile(String repositoryId, FileMetadata fileMetadata, String groupId, String artifactId, String version, String packaging) throws ArchivaRestServiceException {
    try {
        boolean fixChecksums = !(archivaAdministration.getKnownContentConsumers().contains("create-missing-checksums"));
        ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository(repositoryId);
        ArtifactReference artifactReference = new ArtifactReference();
        artifactReference.setArtifactId(artifactId);
        artifactReference.setGroupId(groupId);
        artifactReference.setVersion(version);
        artifactReference.setClassifier(fileMetadata.getClassifier());
        artifactReference.setType(packaging);
        ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent(repositoryId);
        String artifactPath = repository.toPath(artifactReference);
        int lastIndex = artifactPath.lastIndexOf('/');
        String path = artifactPath.substring(0, lastIndex);
        Path targetPath = Paths.get(repoConfig.getLocation(), path);
        String pomFilename = artifactPath.substring(lastIndex + 1);
        if (StringUtils.isNotEmpty(fileMetadata.getClassifier())) {
            pomFilename = StringUtils.remove(pomFilename, "-" + fileMetadata.getClassifier());
        }
        pomFilename = FilenameUtils.removeExtension(pomFilename) + ".pom";
        copyFile(Paths.get(fileMetadata.getServerFileName()), targetPath, pomFilename, fixChecksums);
        triggerAuditEvent(repoConfig.getId(), path + "/" + pomFilename, AuditEvent.UPLOAD_FILE);
        queueRepositoryTask(repoConfig.getId(), targetPath.resolve(pomFilename));
    } catch (IOException ie) {
        throw new ArchivaRestServiceException("Error encountered while uploading pom file: " + ie.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ie);
    } catch (RepositoryException rep) {
        throw new ArchivaRestServiceException("Repository exception: " + rep.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rep);
    } catch (RepositoryAdminException e) {
        throw new ArchivaRestServiceException("RepositoryAdmin exception: " + e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    }
}
Also used : Path(java.nio.file.Path) ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) RepositoryException(org.apache.archiva.repository.RepositoryException) IOException(java.io.IOException) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) ArtifactReference(org.apache.archiva.model.ArtifactReference)

Example 29 with ManagedRepositoryContent

use of org.apache.archiva.repository.ManagedRepositoryContent in project archiva by apache.

the class AbstractProxyTestCase method createRepository.

protected ManagedRepositoryContent createRepository(String id, String name, String path, String layout) throws Exception {
    MavenManagedRepository repo = new MavenManagedRepository(id, name, Paths.get(path).getParent());
    repo.setLocation(new URI(path));
    repo.setLayout(layout);
    RepositoryContentProvider provider = applicationContext.getBean("repositoryContentProvider#maven", RepositoryContentProvider.class);
    ManagedRepositoryContent repoContent = provider.createManagedContent(repo);
    return repoContent;
}
Also used : RepositoryContentProvider(org.apache.archiva.repository.RepositoryContentProvider) MavenManagedRepository(org.apache.archiva.repository.maven2.MavenManagedRepository) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) URI(java.net.URI)

Example 30 with ManagedRepositoryContent

use of org.apache.archiva.repository.ManagedRepositoryContent in project archiva by apache.

the class HttpProxyTransferTest method setUp.

@Before
public void setUp() throws Exception {
    proxyHandler = applicationContext.getBean("repositoryProxyConnectors#test", RepositoryProxyConnectors.class);
    config = applicationContext.getBean("archivaConfiguration#mock", ArchivaConfiguration.class);
    // clear from previous tests - TODO the spring context should be initialised per test instead, or the config
    // made a complete mock
    config.getConfiguration().getProxyConnectors().clear();
    // Setup source repository (using default layout)
    String repoPath = "target/test-repository/managed/" + getClass().getSimpleName();
    Path destRepoDir = Paths.get(repoPath);
    // Cleanout destination dirs.
    if (Files.exists(destRepoDir)) {
        FileUtils.deleteDirectory(destRepoDir.toFile());
    }
    // Make the destination dir.
    Files.createDirectories(destRepoDir);
    MavenManagedRepository repo = new MavenManagedRepository(MANAGED_ID, "Default Managed Repository", Paths.get(repoPath).getParent());
    repo.setLocation(new URI(repoPath));
    repo.setLayout("default");
    RepositoryContentProvider provider = applicationContext.getBean("repositoryContentProvider#maven", RepositoryContentProvider.class);
    ManagedRepositoryContent repoContent = provider.createManagedContent(repo);
    managedDefaultRepository = repoContent;
    ((DefaultManagedRepositoryAdmin) applicationContext.getBean(ManagedRepositoryAdmin.class)).setArchivaConfiguration(config);
    RepositoryRegistry managedRepositoryAdmin = applicationContext.getBean(RepositoryRegistry.class);
    if (managedRepositoryAdmin.getManagedRepository(repo.getId()) == null) {
        managedRepositoryAdmin.putRepository(repo);
    }
    // config.getConfiguration().addManagedRepository( repo );
    Handler handler = new AbstractHandler() {

        @Override
        public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print("get-default-layout-1.0.jar\n\n");
            assertNotNull(request.getHeader("Proxy-Connection"));
            ((Request) request).setHandled(true);
        }

        public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print("get-default-layout-1.0.jar\n\n");
            assertNotNull(request.getHeader("Proxy-Connection"));
            ((Request) request).setHandled(true);
        }
    };
    server = new Server();
    ServerConnector serverConnector = new ServerConnector(server, new HttpConnectionFactory());
    server.addConnector(serverConnector);
    server.setHandler(handler);
    server.start();
    int port = serverConnector.getLocalPort();
    NetworkProxyConfiguration proxyConfig = new NetworkProxyConfiguration();
    proxyConfig.setHost("localhost");
    proxyConfig.setPort(port);
    proxyConfig.setProtocol("http");
    proxyConfig.setId(PROXY_ID);
    config.getConfiguration().addNetworkProxy(proxyConfig);
    // Setup target (proxied to) repository.
    RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
    repoConfig.setId(PROXIED_ID);
    repoConfig.setName("Proxied Repository 1");
    repoConfig.setLayout("default");
    repoConfig.setUrl("http://www.example.com/");
    config.getConfiguration().addRemoteRepository(repoConfig);
}
Also used : Path(java.nio.file.Path) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) MavenManagedRepository(org.apache.archiva.repository.maven2.MavenManagedRepository) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) Handler(org.eclipse.jetty.server.Handler) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) RepositoryProxyConnectors(org.apache.archiva.proxy.model.RepositoryProxyConnectors) URI(java.net.URI) ArchivaConfiguration(org.apache.archiva.configuration.ArchivaConfiguration) DefaultManagedRepositoryAdmin(org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServerConnector(org.eclipse.jetty.server.ServerConnector) RepositoryContentProvider(org.apache.archiva.repository.RepositoryContentProvider) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) ManagedRepositoryAdmin(org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin) DefaultManagedRepositoryAdmin(org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin) NetworkProxyConfiguration(org.apache.archiva.configuration.NetworkProxyConfiguration) RepositoryRegistry(org.apache.archiva.repository.RepositoryRegistry) RemoteRepositoryConfiguration(org.apache.archiva.configuration.RemoteRepositoryConfiguration) Before(org.junit.Before)

Aggregations

ManagedRepositoryContent (org.apache.archiva.repository.ManagedRepositoryContent)41 Path (java.nio.file.Path)16 Test (org.junit.Test)13 RepositoryException (org.apache.archiva.repository.RepositoryException)12 ArchivaRestServiceException (org.apache.archiva.rest.api.services.ArchivaRestServiceException)11 DavException (org.apache.jackrabbit.webdav.DavException)10 ArrayList (java.util.ArrayList)9 MetadataRepositoryException (org.apache.archiva.metadata.repository.MetadataRepositoryException)9 IOException (java.io.IOException)8 ArtifactReference (org.apache.archiva.model.ArtifactReference)8 VersionedReference (org.apache.archiva.model.VersionedReference)7 RepositoryAdminException (org.apache.archiva.admin.model.RepositoryAdminException)6 LayoutException (org.apache.archiva.repository.LayoutException)6 RepositoryContentProvider (org.apache.archiva.repository.RepositoryContentProvider)6 DavResourceLocator (org.apache.jackrabbit.webdav.DavResourceLocator)6 ManagedRepository (org.apache.archiva.admin.model.beans.ManagedRepository)5 MetadataRepository (org.apache.archiva.metadata.repository.MetadataRepository)5 ArchivaRepositoryMetadata (org.apache.archiva.model.ArchivaRepositoryMetadata)5 ManagedRepository (org.apache.archiva.repository.ManagedRepository)5 MavenManagedRepository (org.apache.archiva.repository.maven2.MavenManagedRepository)5