Search in sources :

Example 16 with Repository

use of org.haiku.haikudepotserver.dataobjects.Repository in project haikudepotserver by haiku.

the class UserRatingOrchestrationServiceIT method createTestUserRatingData.

private UserRatingTestData createTestUserRatingData(ObjectContext context) {
    UserRatingTestData userRatingTestData = new UserRatingTestData();
    Repository repository = Repository.tryGetByCode(context, "testrepo").get();
    RepositorySource repositorySource = RepositorySource.tryGetByCode(context, "testreposrc_xyz").get();
    Architecture x86_64 = Architecture.tryGetByCode(context, "x86_64").get();
    Architecture x86_gcc2 = Architecture.tryGetByCode(context, "x86_gcc2").get();
    userRatingTestData.pkg = integrationTestSupportService.createPkg(context, "urtestpkg");
    pkgService.ensurePkgProminence(context, userRatingTestData.pkg, repository, Prominence.ORDERING_LAST);
    userRatingTestData.user1 = integrationTestSupportService.createBasicUser(context, "urtestuser1", "password");
    userRatingTestData.user2 = integrationTestSupportService.createBasicUser(context, "urtestuser2", "password");
    userRatingTestData.user3 = integrationTestSupportService.createBasicUser(context, "urtestuser3", "password");
    userRatingTestData.user4 = integrationTestSupportService.createBasicUser(context, "urtestuser4", "password");
    userRatingTestData.user5 = integrationTestSupportService.createBasicUser(context, "urtestuser5", "password");
    userRatingTestData.pkgVersion_0_0_9__x86_gcc2 = createTestUserRatingPkgVersion(context, repositorySource, userRatingTestData.pkg, x86_64, 0, 0, 9, null, false);
    userRatingTestData.pkgVersion_1_0_0__x86_gcc2 = createTestUserRatingPkgVersion(context, repositorySource, userRatingTestData.pkg, x86_64, 1, 0, 0, null, false);
    userRatingTestData.pkgVersion_1_0_1__x86_gcc2 = createTestUserRatingPkgVersion(context, repositorySource, userRatingTestData.pkg, x86_64, 1, 0, 1, null, false);
    userRatingTestData.pkgVersion_1_0_1_1__x86_gcc2 = createTestUserRatingPkgVersion(context, repositorySource, userRatingTestData.pkg, x86_64, 1, 0, 1, 1, false);
    userRatingTestData.pkgVersion_1_0_2__x86_gcc2 = createTestUserRatingPkgVersion(context, repositorySource, userRatingTestData.pkg, x86_64, 1, 0, 2, null, false);
    userRatingTestData.pkgVersion_1_0_2__x86_64 = createTestUserRatingPkgVersion(context, repositorySource, userRatingTestData.pkg, x86_gcc2, 1, 0, 2, null, false);
    return userRatingTestData;
}
Also used : Repository(org.haiku.haikudepotserver.dataobjects.Repository) Architecture(org.haiku.haikudepotserver.dataobjects.Architecture) RepositorySource(org.haiku.haikudepotserver.dataobjects.RepositorySource)

Example 17 with Repository

use of org.haiku.haikudepotserver.dataobjects.Repository in project haikudepotserver by haiku.

the class PkgCategoryCoverageExportSpreadsheetJobRunner method run.

@Override
public void run(JobService jobService, PkgCategoryCoverageExportSpreadsheetJobSpecification specification) throws IOException {
    Preconditions.checkArgument(null != jobService);
    Preconditions.checkArgument(null != specification);
    final ObjectContext context = serverRuntime.newContext();
    // this will register the outbound data against the job.
    JobDataWithByteSink jobDataWithByteSink = jobService.storeGeneratedData(specification.getGuid(), "download", MediaType.CSV_UTF_8.toString());
    try (OutputStream outputStream = jobDataWithByteSink.getByteSink().openBufferedStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        CSVWriter writer = new CSVWriter(outputStreamWriter, ',')) {
        // headers
        final List<String> pkgCategoryCodes = getPkgCategoryCodes();
        String[] headings = getHeadingRow(pkgCategoryCodes);
        long startMs = System.currentTimeMillis();
        writer.writeNext(headings);
        // stream out the packages.
        LOGGER.info("will produce category coverage spreadsheet report");
        long count = pkgService.eachPkg(context, false, pkg -> {
            PkgSupplement pkgSupplement = pkg.getPkgSupplement();
            List<String> cols = new ArrayList<>();
            Optional<PkgVersionLocalization> locOptional = Optional.empty();
            if (null != pkg) {
                locOptional = PkgVersionLocalization.getAnyPkgVersionLocalizationForPkg(context, pkg);
            }
            cols.add(pkg.getName());
            cols.add(repositoryService.getRepositoriesForPkg(context, pkg).stream().map(Repository::getCode).collect(Collectors.joining(";")));
            cols.add(locOptional.isPresent() ? locOptional.get().getSummary().orElse("") : "");
            cols.add(pkgSupplement.getPkgPkgCategories().isEmpty() ? AbstractJobRunner.MARKER : "");
            for (String pkgCategoryCode : pkgCategoryCodes) {
                cols.add(pkgSupplement.getPkgPkgCategory(pkgCategoryCode).isPresent() ? AbstractJobRunner.MARKER : "");
            }
            // no action
            cols.add("");
            writer.writeNext(cols.toArray(new String[cols.size()]));
            // keep going!
            return true;
        });
        LOGGER.info("did produce category coverage spreadsheet report for {} packages in {}ms", count, System.currentTimeMillis() - startMs);
    }
}
Also used : PkgVersionLocalization(org.haiku.haikudepotserver.dataobjects.PkgVersionLocalization) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) CSVWriter(com.opencsv.CSVWriter) JobDataWithByteSink(org.haiku.haikudepotserver.job.model.JobDataWithByteSink) PkgSupplement(org.haiku.haikudepotserver.dataobjects.PkgSupplement) Repository(org.haiku.haikudepotserver.dataobjects.Repository) OutputStreamWriter(java.io.OutputStreamWriter) ObjectContext(org.apache.cayenne.ObjectContext)

Example 18 with Repository

use of org.haiku.haikudepotserver.dataobjects.Repository in project haikudepotserver by haiku.

the class RepositoryHpkrIngressServiceIT method testImportThenCheck.

@Test
public void testImportThenCheck() throws Exception {
    File temporaryDir;
    File temporaryRepoFile = null;
    File temporaryRepoInfoFile = null;
    try {
        temporaryDir = Files.createTempDir();
        temporaryRepoFile = new File(temporaryDir, "repo");
        temporaryRepoInfoFile = new File(temporaryDir, "repo.info");
        // get the test hpkr data and copy it into a temporary file that can be used as a source
        // for a repository.
        Files.write(getResourceData("sample-repo.info"), temporaryRepoInfoFile);
        Files.write(getResourceData("sample-repo.hpkr"), temporaryRepoFile);
        // first setup a fake repository to import that points at the local test HPKR file.
        {
            ObjectContext context = serverRuntime.newContext();
            Repository repository = context.newObject(Repository.class);
            repository.setCode("test");
            repository.setName("Test Repository");
            RepositorySource repositorySource = context.newObject(RepositorySource.class);
            repositorySource.setCode("testsrc_xyz");
            repositorySource.setIdentifier("file://" + temporaryDir.getAbsolutePath());
            repository.addToManyTarget(Repository.REPOSITORY_SOURCES.getName(), repositorySource, true);
            RepositorySourceMirror repositorySourceMirror = context.newObject(RepositorySourceMirror.class);
            repositorySourceMirror.setBaseUrl("file://" + temporaryDir.getAbsolutePath());
            repositorySourceMirror.setIsPrimary(true);
            repositorySourceMirror.setCode("testsrc_xyz_mirror");
            repositorySourceMirror.setCountry(Country.getByCode(context, Country.CODE_NZ));
            repositorySource.addToManyTarget(RepositorySource.REPOSITORY_SOURCE_MIRRORS.getName(), repositorySourceMirror, true);
            context.commitChanges();
        }
        // setup another repository that is not related to the import test to check some stuff...
        {
            ObjectContext context = serverRuntime.newContext();
            Repository repository = context.newObject(Repository.class);
            repository.setCode("test2");
            repository.setName("Test 2");
            RepositorySource repositorySource = context.newObject(RepositorySource.class);
            repositorySource.setCode("testsrc2_xyz");
            // just after epoc second.
            repositorySource.setLastImportTimestamp(new java.sql.Timestamp(12345L));
            repository.addToManyTarget(Repository.REPOSITORY_SOURCES.getName(), repositorySource, true);
            RepositorySourceMirror repositorySourceMirror = context.newObject(RepositorySourceMirror.class);
            repositorySourceMirror.setBaseUrl("file://does-not-exist/path");
            repositorySourceMirror.setIsPrimary(true);
            repositorySourceMirror.setCode("testsrc2_xyz_mirror");
            repositorySourceMirror.setCountry(Country.getByCode(context, Country.CODE_NZ));
            repositorySource.addToManyTarget(RepositorySource.REPOSITORY_SOURCE_MIRRORS.getName(), repositorySourceMirror, true);
            context.commitChanges();
        }
        // add a package version from this repository that is known not to be in that example and then
        // latterly check that the package version is no longer active.
        {
            ObjectContext context = serverRuntime.newContext();
            Pkg pkg = integrationTestSupportService.createPkg(context, "taranaki");
            pkgService.ensurePkgProminence(context, pkg, Repository.tryGetByCode(context, "test").get());
            pkgService.ensurePkgProminence(context, pkg, Repository.tryGetByCode(context, "test2").get());
            // this one should get deactivated
            {
                PkgVersion pkgVersion = context.newObject(PkgVersion.class);
                pkgVersion.setPkg(pkg);
                pkgVersion.setMajor("1");
                pkgVersion.setMinor("2");
                pkgVersion.setArchitecture(Architecture.tryGetByCode(context, "x86_64").get());
                pkgVersion.setIsLatest(true);
                pkgVersion.setRepositorySource(RepositorySource.tryGetByCode(context, "testsrc_xyz").get());
            }
            // this one should remain
            {
                PkgVersion pkgVersion = context.newObject(PkgVersion.class);
                pkgVersion.setPkg(pkg);
                pkgVersion.setMajor("1");
                pkgVersion.setMinor("3");
                pkgVersion.setArchitecture(Architecture.tryGetByCode(context, "x86_64").get());
                pkgVersion.setIsLatest(true);
                pkgVersion.setRepositorySource(RepositorySource.tryGetByCode(context, "testsrc2_xyz").get());
            }
            context.commitChanges();
        }
        // add an inactive package version from this repository that is known to be in the repository.  This
        // package should be activated and re-used.
        ObjectId originalFfmpegPkgOid;
        {
            ObjectContext context = serverRuntime.newContext();
            Pkg pkg = integrationTestSupportService.createPkg(context, "ffmpeg");
            pkgService.ensurePkgProminence(context, pkg, Repository.tryGetByCode(context, "test").get());
            pkgService.ensurePkgProminence(context, pkg, Repository.tryGetByCode(context, "test2").get());
            PkgVersion pkgVersion = context.newObject(PkgVersion.class);
            pkgVersion.setPkg(pkg);
            pkgVersion.setMajor("3");
            pkgVersion.setMinor("3");
            pkgVersion.setMicro("2");
            pkgVersion.setRevision(1);
            pkgVersion.setArchitecture(Architecture.tryGetByCode(context, "x86_64").get());
            pkgVersion.setIsLatest(true);
            // to be sure!
            pkgVersion.setActive(false);
            pkgVersion.setRepositorySource(RepositorySource.tryGetByCode(context, "testsrc_xyz").get());
            PkgVersionUrl pkgVersionUrl = context.newObject(PkgVersionUrl.class);
            pkgVersionUrl.setPkgUrlType(PkgUrlType.getByCode(context, org.haiku.pkg.model.PkgUrlType.HOMEPAGE.name().toLowerCase()).get());
            pkgVersionUrl.setUrl("http://noop");
            pkgVersion.addToManyTarget(PkgVersion.PKG_VERSION_URLS.getName(), pkgVersionUrl, true);
            PkgVersionCopyright pkgVersionCopyright = context.newObject(PkgVersionCopyright.class);
            pkgVersionCopyright.setBody("Norfolk pine");
            pkgVersion.addToManyTarget(PkgVersion.PKG_VERSION_COPYRIGHTS.getName(), pkgVersionCopyright, true);
            PkgVersionLicense pkgVersionLicense = context.newObject(PkgVersionLicense.class);
            pkgVersionLicense.setBody("Punga");
            pkgVersion.addToManyTarget(PkgVersion.PKG_VERSION_LICENSES.getName(), pkgVersionLicense, true);
            context.commitChanges();
            originalFfmpegPkgOid = pkgVersion.getObjectId();
        }
        // do the import.
        String guid = jobService.submit(new RepositoryHpkrIngressJobSpecification("test"), JobSnapshot.COALESCE_STATUSES_NONE);
        // wait for it to finish.
        {
            long startMs = System.currentTimeMillis();
            while (Jobs.isQueuedOrStarted(jobService.tryGetJob(guid).get()) && (System.currentTimeMillis() - startMs) < DELAY_PROCESSSUBMITTEDTESTJOB) {
                Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
            }
            if (Jobs.isQueuedOrStarted(jobService.tryGetJob(guid).get())) {
                throw new IllegalStateException("test processing of the sample repo has taken > " + DELAY_PROCESSSUBMITTEDTESTJOB + "ms");
            }
        }
        // check that the sample url is loaded into the repository source.
        {
            ObjectContext context = serverRuntime.newContext();
            RepositorySource repositorySource = RepositorySource.tryGetByCode(context, "testsrc_xyz").get();
            Assertions.assertThat(repositorySource.getIdentifier()).isEqualTo("f0c086e5-e096-429c-b38d-57beabd764e9");
            // ^^ as defined in the repo info file.
            Assertions.assertThat(repositorySource.getArchitecture().getCode()).isEqualTo("x86_gcc2");
        // ^^ as defined in the repo info file.
        }
        // now pull out some known packages and make sure they are imported correctly.
        // TODO - this is a fairly simplistic test; do some more checks.
        {
            ObjectContext context = serverRuntime.newContext();
            verifyPackage(context, "apr");
            verifyPackage(context, "schroedinger");
            // this one is not in the import and so should be inactive afterwards.
            List<PkgVersion> pkgVersions = ObjectSelect.query(PkgVersion.class).where(PkgVersion.PKG.dot(Pkg.NAME).eq("taranaki")).select(context);
            Assertions.assertThat(pkgVersions.size()).isEqualTo(2);
            for (PkgVersion pkgVersion : pkgVersions) {
                boolean isTestRepository = pkgVersion.getRepositorySource().getRepository().getCode().equals("test");
                Assertions.assertThat(pkgVersion.getActive()).isEqualTo(!isTestRepository);
            }
            // check that the ffmpeg package was re-used and populated; as an example.
            {
                PkgVersion pkgVersion = PkgVersion.get(context, originalFfmpegPkgOid);
                Assertions.assertThat(pkgVersion.getActive()).isTrue();
                Assertions.assertThat(pkgVersion.getIsLatest()).isTrue();
                Assertions.assertThat(PkgVersion.getForPkg(context, pkgVersion.getPkg(), Repository.tryGetByCode(context, "test").get(), true).size()).isEqualTo(// include inactive
                1);
                PkgVersionLocalization localization = pkgVersion.getPkgVersionLocalization(NaturalLanguage.getByCode(context, NaturalLanguage.CODE_ENGLISH)).get();
                Assertions.assertThat(localization.getDescription().get()).startsWith("FFmpeg is a complete, cro");
                Assertions.assertThat(localization.getSummary().get()).startsWith("Audio and video rec");
                // the former rubbish copyright is removed
                List<String> copyrights = pkgVersion.getCopyrights();
                Assertions.assertThat(copyrights.size()).isEqualTo(2);
                Assertions.assertThat(ImmutableSet.copyOf(copyrights)).containsOnly("2000-2003 Fabrice Bellard", "2003-2017 the FFmpeg developers");
                // the former rubbish license is removed
                List<String> licenses = pkgVersion.getLicenses();
                Assertions.assertThat(licenses.size()).isEqualTo(2);
                Assertions.assertThat(ImmutableSet.copyOf(licenses)).containsOnly("GNU LGPL v2.1", "GNU GPL v2");
                Optional<PkgVersionUrl> pkgVersionUrlOptional = pkgVersion.getPkgVersionUrlForType(PkgUrlType.getByCode(context, org.haiku.pkg.model.PkgUrlType.HOMEPAGE.name().toLowerCase()).get());
                Assertions.assertThat(pkgVersionUrlOptional.isPresent()).isTrue();
                Assertions.assertThat(pkgVersionUrlOptional.get().getUrl()).isEqualTo("https://ffmpeg.org/");
            }
        }
    } finally {
        if (null != temporaryRepoFile) {
            if (!temporaryRepoFile.delete()) {
                LOGGER.warn("unable to delete the temporary 'repo' file");
            }
        }
        if (null != temporaryRepoInfoFile) {
            if (!temporaryRepoInfoFile.delete()) {
                LOGGER.warn("unable to delete the temporary 'repo.info' file");
            }
        }
    }
}
Also used : PkgVersionLocalization(org.haiku.haikudepotserver.dataobjects.PkgVersionLocalization) PkgVersionLicense(org.haiku.haikudepotserver.dataobjects.PkgVersionLicense) RepositoryHpkrIngressJobSpecification(org.haiku.haikudepotserver.repository.model.RepositoryHpkrIngressJobSpecification) ObjectId(org.apache.cayenne.ObjectId) Pkg(org.haiku.haikudepotserver.dataobjects.Pkg) Repository(org.haiku.haikudepotserver.dataobjects.Repository) RepositorySourceMirror(org.haiku.haikudepotserver.dataobjects.RepositorySourceMirror) PkgVersionUrl(org.haiku.haikudepotserver.dataobjects.PkgVersionUrl) PkgVersionCopyright(org.haiku.haikudepotserver.dataobjects.PkgVersionCopyright) RepositorySource(org.haiku.haikudepotserver.dataobjects.RepositorySource) PkgVersion(org.haiku.haikudepotserver.dataobjects.PkgVersion) List(java.util.List) ObjectContext(org.apache.cayenne.ObjectContext) File(java.io.File) AbstractIntegrationTest(org.haiku.haikudepotserver.AbstractIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 19 with Repository

use of org.haiku.haikudepotserver.dataobjects.Repository in project haikudepotserver by haiku.

the class RepositoryAuthenticationProvider method tryAuthenticateUsernamePassword.

private Optional<Authentication> tryAuthenticateUsernamePassword(String username, String passwordClear) {
    if (StringUtils.isBlank(username) || StringUtils.isBlank(passwordClear)) {
        return Optional.empty();
    }
    ObjectContext context = serverRuntime.newContext();
    Repository repository = Optional.of(username).flatMap(rc -> Repository.tryGetByCode(context, username)).orElse(null);
    if (null == repository) {
        String msg = "unable to find the repository [" + username + "]";
        LOGGER.info(msg);
        throw new UsernameNotFoundException(msg);
    }
    if (null == repository.getPasswordHash() || null == repository.getPasswordSalt()) {
        LOGGER.info("repository [{}] has no password hash / salt", repository);
        return Optional.empty();
    }
    if (!repositoryService.matchPassword(repository, passwordClear)) {
        throw new BadCredentialsException("authentication against repository [" + repository + "] failed");
    }
    RepositoryAuthentication result = new RepositoryAuthentication(repository.getCode());
    result.setAuthenticated(true);
    return Optional.of(result);
}
Also used : ObjectContext(org.apache.cayenne.ObjectContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Logger(org.slf4j.Logger) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) RepositoryAuthenticationDetails(org.haiku.haikudepotserver.security.model.RepositoryAuthenticationDetails) StringUtils(org.apache.commons.lang3.StringUtils) RepositoryService(org.haiku.haikudepotserver.repository.model.RepositoryService) Repository(org.haiku.haikudepotserver.dataobjects.Repository) Optional(java.util.Optional) AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Authentication(org.springframework.security.core.Authentication) ServerRuntime(org.apache.cayenne.configuration.server.ServerRuntime) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Repository(org.haiku.haikudepotserver.dataobjects.Repository) ObjectContext(org.apache.cayenne.ObjectContext) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 20 with Repository

use of org.haiku.haikudepotserver.dataobjects.Repository in project haikudepotserver by haiku.

the class PermissionEvaluator method hasPermission.

@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permissionObject) {
    Preconditions.checkArgument(null != permissionObject, "the permission is not provided");
    ObjectContext context = serverRuntime.newContext();
    Permission permission = toPermission(permissionObject);
    if (userAuthorizationService.check(context, Optional.ofNullable(authentication).filter(a -> a instanceof UserAuthentication).filter(Authentication::isAuthenticated).map(a -> (ObjectId) authentication.getPrincipal()).map(userOid -> User.getByObjectId(context, userOid)).orElse(null), (DataObject) targetDomainObject, permission)) {
        return true;
    }
    if (permission == Permission.REPOSITORY_IMPORT && targetDomainObject instanceof Repository && Optional.of(targetDomainObject).map(po -> (Repository) po).filter(r -> checkRepositoryImport(authentication, r)).isPresent()) {
        return true;
    }
    return false;
}
Also used : ObjectContext(org.apache.cayenne.ObjectContext) Permission(org.haiku.haikudepotserver.security.model.Permission) TargetType(org.haiku.haikudepotserver.security.model.TargetType) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) StringUtils(org.apache.commons.lang3.StringUtils) Serializable(java.io.Serializable) Component(org.springframework.stereotype.Component) ObjectId(org.apache.cayenne.ObjectId) Repository(org.haiku.haikudepotserver.dataobjects.Repository) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) User(org.haiku.haikudepotserver.dataobjects.User) DataObject(org.apache.cayenne.DataObject) Authentication(org.springframework.security.core.Authentication) ServerRuntime(org.apache.cayenne.configuration.server.ServerRuntime) UserAuthorizationService(org.haiku.haikudepotserver.security.model.UserAuthorizationService) Repository(org.haiku.haikudepotserver.dataobjects.Repository) ObjectId(org.apache.cayenne.ObjectId) Authentication(org.springframework.security.core.Authentication) Permission(org.haiku.haikudepotserver.security.model.Permission) ObjectContext(org.apache.cayenne.ObjectContext)

Aggregations

Repository (org.haiku.haikudepotserver.dataobjects.Repository)30 ObjectContext (org.apache.cayenne.ObjectContext)26 List (java.util.List)9 RepositorySource (org.haiku.haikudepotserver.dataobjects.RepositorySource)9 AccessDeniedException (org.springframework.security.access.AccessDeniedException)9 Optional (java.util.Optional)8 Architecture (org.haiku.haikudepotserver.dataobjects.Architecture)8 ServerRuntime (org.apache.cayenne.configuration.server.ServerRuntime)7 AbstractIntegrationTest (org.haiku.haikudepotserver.AbstractIntegrationTest)7 RepositoryHpkrIngressJobSpecification (org.haiku.haikudepotserver.repository.model.RepositoryHpkrIngressJobSpecification)7 Test (org.junit.jupiter.api.Test)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 Preconditions (com.google.common.base.Preconditions)6 UpdateRepositoryRequest (org.haiku.haikudepotserver.api1.model.repository.UpdateRepositoryRequest)6 Pkg (org.haiku.haikudepotserver.dataobjects.Pkg)6 Component (org.springframework.stereotype.Component)6 ObjectId (org.apache.cayenne.ObjectId)5 StringUtils (org.apache.commons.lang3.StringUtils)5 OutputStream (java.io.OutputStream)4