io.dropwizard.hibernate.UnitOfWork Java Examples

The following examples show how to use io.dropwizard.hibernate.UnitOfWork. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SubmissionResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@POST
@Path("/")
@Consumes(MULTIPART_FORM_DATA)
@UnitOfWork
public void createSubmission(@HeaderParam(AUTHORIZATION) AuthHeader authHeader, FormDataMultiPart parts) {
    String actorJid = actorChecker.check(authHeader);
    String containerJid = checkNotNull(parts.getField("containerJid"), "containerJid").getValue();
    String problemJid = checkNotNull(parts.getField("problemJid"), "problemJid").getValue();
    String gradingLanguage = checkNotNull(parts.getField("gradingLanguage"), "gradingLanguage").getValue();

    SubmissionData data = new SubmissionData.Builder()
            .problemJid(problemJid)
            .containerJid(containerJid)
            .gradingLanguage(gradingLanguage)
            .build();
    SubmissionSource source = submissionSourceBuilder.fromNewSubmission(parts);
    ProblemSubmissionConfig config = problemClient.getProgrammingProblemSubmissionConfig(data.getProblemJid());
    Submission submission = submissionClient.submit(data, source, config);

    submissionSourceBuilder.storeSubmissionSource(submission.getJid(), source);
}
 
Example #2
Source File: JobResource.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns all HTriggerInfo as a collection with the matches given job id.
 *
 * @param credentials auto fill by {@link RobeAuth} annotation for authentication.
 * @return all {@link HTriggerInfo} as a collection
 */
@RobeService(group = "HJobInfo", description = "Returns all HTriggerInfo as a collection with the matches given job id.")
@PUT
@Path("{id}/unschedule")
@UnitOfWork(readOnly = true, cacheMode = GET, flushMode = FlushMode.MANUAL)
public boolean unschedule(@RobeAuth Credentials credentials, @PathParam("id") String id) {
    HJobInfo info = jobDao.findById(id);
    if (info == null) {
        throw new WebApplicationException(Response.status(404).build());
    }
    try {
        return JobManager.getInstance().unScheduleJob(info.getName(), info.getGroup());
    } catch (SchedulerException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example #3
Source File: SuperadminCreator.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@UnitOfWork
public void ensureSuperadminExists() {
    String initialPassword = config.orElse(SuperadminCreatorConfiguration.DEFAULT).getInitialPassword();

    Optional<User> maybeUser = userStore.getUserByUsername(SUPERADMIN_USERNAME);
    User user;
    if (maybeUser.isPresent()) {
        user = maybeUser.get();
        LOGGER.info("Superadmin user already exists");
    } else {
        user = userStore.createUser(new UserData.Builder()
                .username(SUPERADMIN_USERNAME)
                .password(initialPassword)
                .email(SUPERADMIN_INITIAL_EMAIL)
                .build());
        LOGGER.info("Created superadmin user");
    }
    superadminRoleStore.setSuperadmin(user.getJid());
}
 
Example #4
Source File: JobResource.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Return all HJobInfo as a collection
 *
 * @param credentials auto fill by {@link RobeAuth} annotation for authentication.
 * @return all {@link HJobInfo} as a collection
 */
@RobeService(group = "HJobInfo", description = "Returns all HJobInfo as a collection.")
@GET
@UnitOfWork(readOnly = true, cacheMode = GET, flushMode = FlushMode.MANUAL)
public Collection<JobInfoDTO> getAll(@RobeAuth Credentials credentials, @SearchParam SearchModel search) {
    List<JobInfoDTO> dtoList = new LinkedList<>();
    for (HJobInfo info : jobDao.findAllStrict(search)) {
        JobInfoDTO dto = new JobInfoDTO(info);
        try {
            if (!JobManager.getInstance().isScheduledJob(dto.getName(), dto.getGroup())) {
                dto.setStatus(JobInfoDTO.Status.UNSCHEDULED);
            } else {
                if (JobManager.getInstance().isPausedJob(dto.getName(), dto.getGroup())) {
                    dto.setStatus(JobInfoDTO.Status.PAUSED);
                } else {
                    dto.setStatus(JobInfoDTO.Status.ACTIVE);
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        dtoList.add(dto);
    }
    return dtoList;
}
 
Example #5
Source File: ChapterLessonResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ChapterLessonStatement getLessonStatement(
        Optional<AuthHeader> authHeader,
        String chapterJid,
        String lessonAlias) {

    String actorJid = actorChecker.check(authHeader);
    checkFound(chapterStore.getChapterByJid(chapterJid));

    ChapterLesson lesson = checkFound(lessonStore.getLessonByAlias(chapterJid, lessonAlias));
    String lessonJid = lesson.getLessonJid();
    LessonInfo lessonInfo = lessonClient.getLesson(lessonJid);
    LessonStatement statement = lessonClient.getLessonStatement(lesson.getLessonJid());

    return new ChapterLessonStatement.Builder()
            .defaultLanguage(lessonInfo.getDefaultLanguage())
            .languages(lessonInfo.getTitlesByLanguage().keySet())
            .lesson(lesson)
            .statement(statement)
            .build();
}
 
Example #6
Source File: ServiceResource.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Update {@link Service) resource and matches with the given id.
 * <p>
 * Status Code:
 * Not Found  404
 * Not Matches 412
 *
 * @param credentials Injected by {@link RobeAuth} annotation for authentication.
 * @param id          This is  the oid of {@link Service}
 * @param model       This is the one model of {@link Service}
 * @return Update {@link Service} resource and matches with the given id.
 */
@RobeService(group = "Service", description = "Update Service resource and matches with the given id.")
@Path("{id}")
@PUT
@UnitOfWork
public Service update(@RobeAuth Credentials credentials, @PathParam("id") String id, @Valid Service model) {
    if (!id.equals((model.getOid()))) {
        throw new WebApplicationException(Response.status(412).build());
    }
    Service entity = serviceDao.findById(id);
    if (entity == null) {
        throw new WebApplicationException(Response.status(404).build());
    }
    serviceDao.detach(entity);
    return serviceDao.update(model);
}
 
Example #7
Source File: SystemParameterResource.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Delete {@link SystemParameter) resource.
 *
 * @param credentials Injected by {@link RobeAuth} annotation for authentication.
 * @param id          This is  the oid of {@link SystemParameter}
 * @param model       This is the one model of {@link SystemParameter}
 * @return Delete {@link SystemParameter) resource.
 */
@RobeService(group = "SystemParameter", description = "Delete SystemParameter resource.")
@Path("{id}")
@DELETE
@UnitOfWork
public SystemParameter delete(@RobeAuth Credentials credentials, @PathParam("id") String id, @Valid SystemParameter model) {

    if (!id.equals(model.getOid())) {
        throw new WebApplicationException(Response.status(412).build());
    }
    SystemParameter entity = systemParameterDao.findById(id);
    if (entity == null) {
        throw new WebApplicationException(Response.status(404).build());
    }
    return systemParameterDao.delete(entity);
}
 
Example #8
Source File: PermissionResource.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Updates a {@link Permission} resource matches with the given id.
 * <p>
 * Status Code:
 * Not Found  404
 * Not Matches 412
 *
 * @param credentials Injected by @{@link RobeAuth} annotation for authentication.
 * @param id          This is  the oid of {@link Permission}
 * @param model       Data of {@link Permission}
 * @return Updates a @{@link Permission} resource matches with the given id.
 */
@RobeService(group = "Permission", description = "Updates a permission resource matches with the given id.")
@Path("{id}")
@PUT
@UnitOfWork
public Permission update(@RobeAuth Credentials credentials, @PathParam("id") String id, @Valid Permission model) {
    if (!id.equals((model.getOid()))) {
        throw new WebApplicationException(Response.status(412).build());
    }
    Permission entity = permissionDao.findById(id);
    if (entity == null) {
        throw new WebApplicationException(Response.status(404).build());
    }
    permissionDao.detach(entity);
    return permissionDao.update(model);
}
 
Example #9
Source File: FeedREST.java    From commafeed with Apache License 2.0 6 votes vote down vote up
@Path("/refresh")
@POST
@UnitOfWork
@ApiOperation(value = "Queue a feed for refresh", notes = "Manually add a feed to the refresh queue")
@Timed
public Response queueForRefresh(@ApiParam(hidden = true) @SecurityCheck User user,
		@ApiParam(value = "Feed id", required = true) IDRequest req) {

	Preconditions.checkNotNull(req);
	Preconditions.checkNotNull(req.getId());

	FeedSubscription sub = feedSubscriptionDAO.findById(user, req.getId());
	if (sub != null) {
		Feed feed = sub.getFeed();
		queues.add(feed, true);
		return Response.ok().build();
	}
	return Response.ok(Status.NOT_FOUND).build();
}
 
Example #10
Source File: JobResource.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns all HTriggerInfo as a collection with the matches given job id.
 *
 * @param credentials auto fill by {@link RobeAuth} annotation for authentication.
 * @return all {@link HTriggerInfo} as a collection
 */
@RobeService(group = "HJobInfo", description = "Returns all HTriggerInfo as a collection with the matches given job id.")
@GET
@Path("{id}/triggers")
@UnitOfWork
public List<TriggerInfoDTO> getJobTriggers(@RobeAuth Credentials credentials, @PathParam("id") String id) {
    List<TriggerInfoDTO> dtos = new LinkedList<>();
    for (HTriggerInfo info : triggerDao.findByJobOid(id)) {
        TriggerInfoDTO dto = new TriggerInfoDTO(info);
        try {
            if (!JobManager.getInstance().isScheduledTrigger(dto.getName(), dto.getGroup())) {
                dto.setStatus(JobInfoDTO.Status.UNSCHEDULED);
            } else {
                if (JobManager.getInstance().isPausedTrigger(dto.getName(), dto.getGroup())) {
                    dto.setStatus(JobInfoDTO.Status.PAUSED);
                } else {
                    dto.setStatus(JobInfoDTO.Status.ACTIVE);
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        dtos.add(dto);
    }
    return dtos;
}
 
Example #11
Source File: ContestManagerResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ContestManagersResponse getManagers(AuthHeader authHeader, String contestJid, Optional<Integer> page) {
    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));
    checkAllowed(managerRoleChecker.canView(actorJid, contest));

    Page<ContestManager> managers = managerStore.getManagers(contestJid, page);
    Set<String> userJids =
            managers.getPage().stream().map(ContestManager::getUserJid).collect(Collectors.toSet());
    Map<String, Profile> profilesMap = userJids.isEmpty()
            ? Collections.emptyMap()
            : profileService.getProfiles(userJids, contest.getBeginTime());
    boolean canManage = managerRoleChecker.canManage(actorJid);
    ContestManagerConfig config = new ContestManagerConfig.Builder()
            .canManage(canManage)
            .build();

    return new ContestManagersResponse.Builder()
            .data(managers)
            .profilesMap(profilesMap)
            .config(config)
            .build();
}
 
Example #12
Source File: ServerREST.java    From commafeed with Apache License 2.0 6 votes vote down vote up
@Path("/proxy")
@GET
@UnitOfWork
@ApiOperation(value = "proxy image")
@Produces("image/png")
@Timed
public Response getProxiedImage(@ApiParam(hidden = true) @SecurityCheck User user,
		@ApiParam(value = "image url", required = true) @QueryParam("u") String url) {
	if (!config.getApplicationSettings().getImageProxyEnabled()) {
		return Response.status(Status.FORBIDDEN).build();
	}

	url = FeedUtils.imageProxyDecoder(url);
	try {
		HttpResult result = httpGetter.getBinary(url, 20000);
		return Response.ok(result.getContent()).build();
	} catch (Exception e) {
		return Response.status(Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).build();
	}
}
 
Example #13
Source File: ChapterProblemResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ChapterProblemsResponse getProblems(Optional<AuthHeader> authHeader, String chapterJid) {
    String actorJid = actorChecker.check(authHeader);
    checkFound(chapterStore.getChapterByJid(chapterJid));

    List<ChapterProblem> problems = problemStore.getProblems(chapterJid);
    Set<String> problemJids = problems.stream().map(ChapterProblem::getProblemJid).collect(Collectors.toSet());
    Map<String, ProblemInfo> problemsMap = problemClient.getProblems(problemJids);
    Map<String, ProblemProgress> problemProgressesMap = statsStore.getProblemProgressesMap(actorJid, problemJids);

    return new ChapterProblemsResponse.Builder()
            .data(problems)
            .problemsMap(problemsMap)
            .problemProgressesMap(problemProgressesMap)
            .build();
}
 
Example #14
Source File: ContestSupervisorResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ContestSupervisorsResponse getSupervisors(AuthHeader authHeader, String contestJid, Optional<Integer> page) {
    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));
    checkAllowed(roleChecker.canSupervise(actorJid, contest));

    Page<ContestSupervisor> supervisors = supervisorStore.getSupervisors(contestJid, page);
    Set<String> userJids =
            supervisors.getPage().stream().map(ContestSupervisor::getUserJid).collect(Collectors.toSet());
    Map<String, Profile> profilesMap = userJids.isEmpty()
            ? Collections.emptyMap()
            : profileService.getProfiles(userJids, contest.getBeginTime());

    return new ContestSupervisorsResponse.Builder()
            .data(supervisors)
            .profilesMap(profilesMap)
            .build();
}
 
Example #15
Source File: TriggerResource.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RobeService(group = "HJobInfo", description = "Returns all HTriggerInfo as a collection with the matches given job id.")
@PUT
@Path("{id}/schedule")
@UnitOfWork(readOnly = true, cacheMode = GET, flushMode = FlushMode.MANUAL)
public boolean schedule(@RobeAuth Credentials credentials, @PathParam("id") String id) {
    HTriggerInfo info = triggerDao.findById(id);
    HJobInfo jobEntity = jobDao.findById(info.getJobOid());
    if (info == null || jobEntity == null) {
        throw new WebApplicationException(Response.status(404).build());
    }
    JobInfo job = new HibernateJobInfoProvider().getJob(jobEntity.getJobClass());

    try {
        if (info.getType().equals(TriggerInfo.Type.CRON) ||
                info.getType().equals(TriggerInfo.Type.SIMPLE)) {
            Trigger trigger = new HibernateJobInfoProvider().convert2Trigger(info, job);
            JobManager.getInstance().scheduleTrigger(trigger);
            return true;
        }
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #16
Source File: ContestContestantResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ContestContestantsResponse getContestants(AuthHeader authHeader, String contestJid, Optional<Integer> page) {
    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));
    checkAllowed(contestantRoleChecker.canSupervise(actorJid, contest));

    Page<ContestContestant> contestants = contestantStore.getContestants(contestJid, page);
    Set<String> userJids =
            contestants.getPage().stream().map(ContestContestant::getUserJid).collect(Collectors.toSet());
    Map<String, Profile> profilesMap = userJids.isEmpty()
            ? Collections.emptyMap()
            : profileService.getProfiles(userJids, contest.getBeginTime());

    boolean canManage = contestantRoleChecker.canManage(actorJid, contest);
    ContestContestantConfig config = new ContestContestantConfig.Builder()
            .canManage(canManage)
            .build();

    return new ContestContestantsResponse.Builder()
            .data(contestants)
            .profilesMap(profilesMap)
            .config(config)
            .build();
}
 
Example #17
Source File: FeedREST.java    From commafeed with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/subscribe")
@UnitOfWork
@ApiOperation(value = "Subscribe to a feed", notes = "Subscribe to a feed")
@Timed
public Response subscribeFromUrl(@ApiParam(hidden = true) @SecurityCheck User user,
		@ApiParam(value = "feed url", required = true) @QueryParam("url") String url) {

	try {
		Preconditions.checkNotNull(url);

		url = prependHttp(url);
		url = fetchFeedInternal(url).getUrl();

		FeedInfo info = fetchFeedInternal(url);
		feedSubscriptionService.subscribe(user, info.getUrl(), info.getTitle());
	} catch (Exception e) {
		log.info("Could not subscribe to url {} : {}", url, e.getMessage());
	}
	return Response.temporaryRedirect(URI.create(config.getApplicationSettings().getPublicUrl())).build();
}
 
Example #18
Source File: ContestFileResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ContestFilesResponse getFiles(AuthHeader authHeader, String contestJid) {
    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));

    checkAllowed(fileRoleChecker.canSupervise(actorJid, contest));

    boolean canManage = fileRoleChecker.canManage(actorJid, contest);
    ContestFileConfig config = new ContestFileConfig.Builder()
            .canManage(canManage)
            .build();

    List<ContestFile> files = Lists.transform(fileFs.listFilesInDirectory(Paths.get(contestJid)),
            f -> new ContestFile.Builder()
                    .name(f.getName())
                    .size(f.getSize())
                    .lastModifiedTime(f.getLastModifiedTime())
                    .build());
    return new ContestFilesResponse.Builder()
            .data(files)
            .config(config)
            .build();
}
 
Example #19
Source File: ContestClarificationResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
@UnitOfWork
public void answerClarification(
        AuthHeader authHeader,
        String contestJid,
        String clarificationJid,
        ContestClarificationAnswerData data) {

    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));
    checkAllowed(clarificationRoleChecker.canManage(actorJid, contest));

    checkFound(clarificationStore.answerClarification(
            contestJid,
            clarificationJid,
            data.getAnswer()));
}
 
Example #20
Source File: UserAvatarResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@GET
@UnitOfWork(readOnly = true)
public Response renderAvatar(
        @HeaderParam(IF_MODIFIED_SINCE) Optional<String> ifModifiedSince,
        @PathParam("userJid") String userJid) {

    Optional<String> avatarUrl = userStore.getUserAvatarUrl(userJid);
    if (avatarUrl.isPresent()) {
        return buildImageResponse(avatarUrl.get(), ifModifiedSince);
    }
    return buildImageResponse(
            UserAvatarResource.class.getClassLoader().getResourceAsStream(DEFAULT_AVATAR),
            "png",
            new Date(1532822400),
            ifModifiedSince);
}
 
Example #21
Source File: CategoryREST.java    From commafeed with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/get")
@UnitOfWork
@ApiOperation(value = "Get root category", notes = "Get all categories and subscriptions of the user", response = Category.class)
@Timed
public Response getRootCategory(@ApiParam(hidden = true) @SecurityCheck User user) {
	Category root = cache.getUserRootCategory(user);
	if (root == null) {
		log.debug("tree cache miss for {}", user.getId());
		List<FeedCategory> categories = feedCategoryDAO.findAll(user);
		List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(user);
		Map<Long, UnreadCount> unreadCount = feedSubscriptionService.getUnreadCount(user);

		root = buildCategory(null, categories, subscriptions, unreadCount);
		root.setId("all");
		root.setName("All");
		cache.setUserRootCategory(user, root);
	}

	return Response.ok(root).build();
}
 
Example #22
Source File: ChapterResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ChaptersResponse getChapters(AuthHeader authHeader) {
    String actorJid = actorChecker.check(authHeader);
    checkAllowed(roleChecker.isAdmin(actorJid));

    List<Chapter> chapters = chapterStore.getChapters();
    return new ChaptersResponse.Builder()
            .data(chapters)
            .build();
}
 
Example #23
Source File: ContestSupervisorResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork
public ContestSupervisorsUpsertResponse upsertSupervisors(
        AuthHeader authHeader,
        String contestJid,
        ContestSupervisorUpsertData data) {

    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));
    checkAllowed(roleChecker.canManage(actorJid, contest));

    checkArgument(data.getUsernames().size() <= 100, "Cannot add more than 100 users.");

    Map<String, String> usernameToJidMap = userSearchService.translateUsernamesToJids(data.getUsernames());

    Set<String> userJids = ImmutableSet.copyOf(usernameToJidMap.values());
    Set<String> upsertedSupervisorUsernames = Sets.newHashSet();
    usernameToJidMap.forEach((username, userJid) -> {
        supervisorStore.upsertSupervisor(contest.getJid(), userJid, data.getManagementPermissions());
        upsertedSupervisorUsernames.add(username);
    });

    Map<String, Profile> userJidToProfileMap = profileService.getProfiles(userJids);
    Map<String, Profile> upsertedSupervisorProfilesMap = upsertedSupervisorUsernames
            .stream()
            .collect(Collectors.toMap(u -> u, u -> userJidToProfileMap.get(usernameToJidMap.get(u))));

    return new ContestSupervisorsUpsertResponse.Builder()
            .upsertedSupervisorProfilesMap(upsertedSupervisorProfilesMap)
            .build();
}
 
Example #24
Source File: ItemSubmissionResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork
public void regradeSubmissions(
        AuthHeader authHeader,
        Optional<String> containerJid,
        Optional<String> userJid,
        Optional<String> problemJid) {

    String actorJid = actorChecker.check(authHeader);
    checkAllowed(submissionRoleChecker.canManage(actorJid));
    itemSubmissionRegrader.regradeSubmissions(containerJid, userJid, problemJid);
}
 
Example #25
Source File: WorldResource.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@GET
@Path("/query")
@UnitOfWork(readOnly = true) // Needed only for Hibernate - not for Mongo or JDBI
public Object query(@QueryParam("queries") String queries) {
	int totalQueries = Helper.getQueries(queries); // Optional check is done inside
	return worldDAO.findById(Helper.getRandomInts(totalQueries));
}
 
Example #26
Source File: ContestWebResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ContestWebConfig getWebConfig(Optional<AuthHeader> authHeader, String contestJid) {
    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));
    checkAllowed(contestRoleChecker.canView(actorJid, contest));
    return webConfigFetcher.fetchConfig(actorJid, contest);
}
 
Example #27
Source File: ContestContestantResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork
public void registerMyselfAsContestant(AuthHeader authHeader, String contestJid) {
    String actorJid = actorChecker.check(authHeader);
    Contest contest = checkFound(contestStore.getContestByJid(contestJid));
    Profile profile = profileService.getProfiles(ImmutableSet.of(actorJid)).get(actorJid);
    checkAllowed(contestantRoleChecker.canRegister(actorJid, profile.getRating(), contest));

    contestantStore.upsertContestant(contestJid, actorJid);
}
 
Example #28
Source File: ArchiveResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork
public Archive updateArchive(AuthHeader authHeader, String archiveJid, ArchiveUpdateData data) {
    String actorJid = actorChecker.check(authHeader);
    checkAllowed(roleChecker.isAdmin(actorJid));

    return checkFound(archiveStore.updateArchive(archiveJid, data));
}
 
Example #29
Source File: ChapterResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork
public Chapter updateChapter(AuthHeader authHeader, String chapterJid, ChapterUpdateData data) {
    String actorJid = actorChecker.check(authHeader);
    checkAllowed(roleChecker.isAdmin(actorJid));

    return checkFound(chapterStore.updateChapter(chapterJid, data));
}
 
Example #30
Source File: ContestHistoryResource.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
@UnitOfWork(readOnly = true)
public ContestHistoryResponse getPublicHistory(String username) {
    Map<String, String> userJidMap = userSearchService.translateUsernamesToJids(ImmutableSet.of(username));
    if (!userJidMap.containsKey(username)) {
        throw new NotFoundException();
    }
    String userJid = userJidMap.get(username);

    List<Contest> contests = contestStore.getPubliclyParticipatedContests(userJid);
    Map<String, UserRating> ratingsMap = userRatingService.getRatingHistory(userJid)
            .stream()
            .collect(Collectors.toMap(UserRatingEvent::getEventJid, UserRatingEvent::getRating));
    Map<String, Integer> ranksMap = contestantStore.getContestantFinalRanks(userJid);

    List<ContestHistoryEvent> events = contests
            .stream()
            .map(contest -> new ContestHistoryEvent.Builder()
                    .contestJid(contest.getJid())
                    .rating(Optional.ofNullable(ratingsMap.get(contest.getJid())))
                    .rank(ranksMap.get(contest.getJid()))
                    .build())
            .collect(Collectors.toList());

    Map<String, ContestInfo> contestsMap = contests
            .stream()
            .collect(Collectors.toMap(Contest::getJid, contest -> new ContestInfo.Builder()
                    .name(contest.getName())
                    .slug(contest.getSlug())
                    .beginTime(contest.getBeginTime())
                    .build()));

    return new ContestHistoryResponse.Builder()
            .data(events)
            .contestsMap(contestsMap)
            .build();
}