use of org.haiku.haikudepotserver.dataobjects.Pkg in project haikudepotserver by haiku.
the class UserRatingJobApiImpl method queueUserRatingSpreadsheetJob.
@Override
public QueueUserRatingSpreadsheetJobResult queueUserRatingSpreadsheetJob(QueueUserRatingSpreadsheetJobRequest request) {
Preconditions.checkArgument(null != request);
Preconditions.checkArgument(Strings.isNullOrEmpty(request.pkgName) || Strings.isNullOrEmpty(request.userNickname), "the user nickname or pkg name can be supplied, but not both");
final ObjectContext context = serverRuntime.newContext();
User user = obtainAuthenticatedUser(context);
UserRatingSpreadsheetJobSpecification spec = new UserRatingSpreadsheetJobSpecification();
if (!Strings.isNullOrEmpty(request.repositoryCode)) {
spec.setRepositoryCode(getRepository(context, request.repositoryCode).getCode());
}
if (!Strings.isNullOrEmpty(request.userNickname)) {
Optional<User> requestUserOptional = User.tryGetByNickname(context, request.userNickname);
if (requestUserOptional.isEmpty()) {
throw new AccessDeniedException("attempt to produce user rating report for user [" + request.userNickname + "], but that user does not exist -- not allowed");
}
if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), requestUserOptional.get(), Permission.BULK_USERRATINGSPREADSHEETREPORT_USER)) {
throw new AccessDeniedException("attempt to access a user rating report for user [" + request.userNickname + "], but this was disallowed");
}
spec.setUserNickname(request.userNickname);
} else {
if (!Strings.isNullOrEmpty(request.pkgName)) {
Optional<Pkg> requestPkgOptional = Pkg.tryGetByName(context, request.pkgName);
if (requestPkgOptional.isEmpty()) {
throw new AccessDeniedException("attempt to produce user rating report for pkg [" + request.pkgName + "], but that pkg does not exist -- not allowed");
}
if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), requestPkgOptional.get(), Permission.BULK_USERRATINGSPREADSHEETREPORT_PKG)) {
throw new AccessDeniedException("attempt to access a user rating report for pkg [" + request.pkgName + "], but this was disallowed");
}
spec.setPkgName(request.pkgName);
} else {
if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), null, Permission.BULK_USERRATINGSPREADSHEETREPORT_ALL)) {
throw new AccessDeniedException("attempt to access a user rating report, but was unauthorized");
}
}
}
spec.setOwnerUserNickname(user.getNickname());
return new QueueUserRatingSpreadsheetJobResult(jobService.submit(spec, JobSnapshot.COALESCE_STATUSES_QUEUED_STARTED));
}
use of org.haiku.haikudepotserver.dataobjects.Pkg in project haikudepotserver by haiku.
the class PkgDownloadController method download.
@RequestMapping(value = { "/" + SEGMENT_PKGDOWNLOAD + PATH }, method = RequestMethod.GET)
public void download(HttpServletResponse response, @PathVariable(value = KEY_PKGNAME) String pkgName, @PathVariable(value = KEY_REPOSITORYCODE) String repositoryCode, @PathVariable(value = KEY_MAJOR) String major, @PathVariable(value = KEY_MINOR) String minor, @PathVariable(value = KEY_MICRO) String micro, @PathVariable(value = KEY_PRERELEASE) String prerelease, @PathVariable(value = KEY_REVISION) String revisionStr, @PathVariable(value = KEY_ARCHITECTURECODE) String architectureCode) throws IOException, RequestObjectNotFound {
Preconditions.checkArgument(null != response, "the response is required");
ObjectContext context = serverRuntime.newContext();
Pkg pkg = Pkg.tryGetByName(context, pkgName).orElseThrow(() -> {
LOGGER.info("unable to find the package; {}", pkgName);
return new RequestObjectNotFound();
});
Repository repository = Repository.tryGetByCode(context, repositoryCode).orElseThrow(() -> {
LOGGER.info("unable to find the repository; {}", repositoryCode);
return new RequestObjectNotFound();
});
Architecture architecture = Architecture.tryGetByCode(context, architectureCode).orElseThrow(() -> {
LOGGER.info("unable to find the architecture; {}", architectureCode);
return new RequestObjectNotFound();
});
revisionStr = hyphenToNull(revisionStr);
VersionCoordinates versionCoordinates = new VersionCoordinates(hyphenToNull(major), hyphenToNull(minor), hyphenToNull(micro), hyphenToNull(prerelease), null == revisionStr ? null : Integer.parseInt(revisionStr));
PkgVersion pkgVersion = PkgVersion.getForPkg(context, pkg, repository, architecture, versionCoordinates).orElseThrow(() -> {
LOGGER.info("unable to find the pkg version; {}, {}", pkgName, versionCoordinates);
return new RequestObjectNotFound();
});
Optional<URL> urlOptional = pkgVersion.tryGetHpkgURL(ExposureType.EXTERNAL_FACING);
if (urlOptional.isEmpty()) {
LOGGER.info("unable to allow download of the hpkg data as no url was able to be generated");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else {
URL url = urlOptional.get();
if (ImmutableSet.of("http", "https").contains(url.getProtocol())) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader(HttpHeaders.LOCATION, url.toString());
response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString());
PrintWriter writer = response.getWriter();
writer.print(url.toString());
writer.flush();
} else {
response.setContentType(MediaType.OCTET_STREAM.toString());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=\"%s\"", pkgVersion.getHpkgFilename()));
try (InputStream inputStream = url.openStream()) {
LOGGER.info("downloaded package version; {} - {}", pkg.getName(), pkgVersion);
ByteStreams.copy(inputStream, response.getOutputStream());
} catch (IOException ioe) {
// logged without a stack trace because it happens fairly often that a robot will initiate the download and then drop it.
LOGGER.error("unable to relay data to output stream from '{}'; {} -- {}", url.toString(), ioe.getClass().getSimpleName(), ioe.getMessage());
}
}
}
}
use of org.haiku.haikudepotserver.dataobjects.Pkg in project haikudepotserver by haiku.
the class PkgIconController method handleHeadOrGetPkgIcon.
private void handleHeadOrGetPkgIcon(RequestMethod requestMethod, HttpServletResponse response, Integer size, String format, String pkgName, Boolean fallback) throws IOException {
if (null == format) {
throw new MissingOrBadFormat();
}
if (Strings.isNullOrEmpty(pkgName) || !Pkg.PATTERN_NAME.matcher(pkgName).matches()) {
throw new MissingPkgName();
}
ObjectContext context = serverRuntime.newContext();
// cached
Optional<Pkg> pkg = Pkg.tryGetByName(context, pkgName);
if (!pkg.isPresent()) {
LOGGER.debug("request for icon for package '{}', but no such package was able to be found", pkgName);
throw new PkgNotFound();
}
PkgSupplement pkgSupplement = pkg.get().getPkgSupplement();
switch(format) {
case org.haiku.haikudepotserver.dataobjects.MediaType.EXTENSION_HAIKUVECTORICONFILE:
Optional<PkgIcon> hvifPkgIcon = pkg.get().getPkgSupplement().getPkgIcon(org.haiku.haikudepotserver.dataobjects.MediaType.getByExtension(context, format).get(), null);
if (hvifPkgIcon.isPresent()) {
byte[] data = hvifPkgIcon.get().getPkgIconImage().getData();
response.setContentType(org.haiku.haikudepotserver.dataobjects.MediaType.MEDIATYPE_HAIKUVECTORICONFILE);
outputToResponse(response, pkgSupplement, data, requestMethod == RequestMethod.GET);
} else {
throw new PkgIconNotFound();
}
break;
case org.haiku.haikudepotserver.dataobjects.MediaType.EXTENSION_PNG:
if (null == size) {
throw new IllegalArgumentException("the size must be provided when requesting a PNG");
}
size = normalizeSize(size);
Optional<byte[]> pngImageData = renderedPkgIconRepository.render(size, context, pkg.get().getPkgSupplement());
if (!pngImageData.isPresent()) {
if ((null == fallback) || !fallback) {
throw new PkgIconNotFound();
}
handleGenericHeadOrGet(requestMethod, response, size, true);
} else {
byte[] data = pngImageData.get();
response.setContentType(MediaType.PNG.toString());
outputToResponse(response, pkgSupplement, data, requestMethod == RequestMethod.GET);
}
break;
default:
throw new IllegalStateException("unexpected format; " + format);
}
}
use of org.haiku.haikudepotserver.dataobjects.Pkg in project haikudepotserver by haiku.
the class PkgScreenshotController method handleAdd.
/**
* <p>This handler will take-up an HTTP POST that provides a new screenshot for the package.</p>
*/
@RequestMapping(value = "/{" + KEY_PKGNAME + "}/add", method = RequestMethod.POST)
public void handleAdd(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = KEY_FORMAT) String format, @PathVariable(value = KEY_PKGNAME) String pkgName) throws IOException {
if (Strings.isNullOrEmpty(pkgName) || !Pkg.PATTERN_NAME.matcher(pkgName).matches()) {
throw new MissingPkgName();
}
if (Strings.isNullOrEmpty(format) || !"png".equals(format)) {
throw new MissingOrBadFormat();
}
ObjectContext context = serverRuntime.newContext();
Pkg pkg = Pkg.tryGetByName(context, pkgName).orElseThrow(PkgNotFound::new);
// check the authorization
Optional<User> user = tryObtainAuthenticatedUser(context);
if (!permissionEvaluator.hasPermission(SecurityContextHolder.getContext().getAuthentication(), pkg, Permission.PKG_EDITSCREENSHOT)) {
LOGGER.warn("attempt to add a pkg screenshot, but there is no user present or that user is not able to edit the pkg");
throw new PkgAuthorizationFailure();
}
String screenshotCode;
try {
screenshotCode = pkgScreenshotService.storePkgScreenshotImage(request.getInputStream(), context, pkg.getPkgSupplement(), null).getCode();
} catch (SizeLimitReachedException sizeLimit) {
LOGGER.warn("attempt to load in a screenshot larger than the size limit");
throw new MissingOrBadFormat();
} catch (BadPkgScreenshotException badIcon) {
throw new MissingOrBadFormat();
}
context.commitChanges();
// trigger optimization of the screenshot image.
jobService.submit(new PkgScreenshotOptimizationJobSpecification(screenshotCode), JobSnapshot.COALESCE_STATUSES_QUEUED_STARTED);
response.setHeader(HEADER_SCREENSHOTCODE, screenshotCode);
response.setStatus(HttpServletResponse.SC_OK);
}
use of org.haiku.haikudepotserver.dataobjects.Pkg in project haikudepotserver by haiku.
the class AuthorizationApiIT method createSearchAuthorizationRuleTestData.
private void createSearchAuthorizationRuleTestData() {
ObjectContext context = serverRuntime.newContext();
User user1 = integrationTestSupportService.createBasicUser(context, "testuser1", "fakepassword");
User user2 = integrationTestSupportService.createBasicUser(context, "testuser2", "fakepassword");
User user3 = integrationTestSupportService.createBasicUser(context, "testuser3", "fakepassword");
Pkg pkg1 = Pkg.tryGetByName(context, "pkg1").get();
Pkg pkg2 = Pkg.tryGetByName(context, "pkg2").get();
org.haiku.haikudepotserver.dataobjects.Permission permission = org.haiku.haikudepotserver.dataobjects.Permission.getByCode(context, Permission.PKG_EDITICON.name().toLowerCase()).get();
PermissionUserPkg pup_u1p1 = context.newObject(PermissionUserPkg.class);
pup_u1p1.setPkg(pkg1);
pup_u1p1.setUser(user1);
pup_u1p1.setPermission(permission);
PermissionUserPkg pup_u2p1 = context.newObject(PermissionUserPkg.class);
pup_u2p1.setPkg(pkg1);
pup_u2p1.setUser(user2);
pup_u2p1.setPermission(permission);
PermissionUserPkg pup_u3p1 = context.newObject(PermissionUserPkg.class);
pup_u3p1.setPkg(pkg1);
pup_u3p1.setUser(user3);
pup_u3p1.setPermission(permission);
PermissionUserPkg pup_u2p2 = context.newObject(PermissionUserPkg.class);
pup_u2p2.setPkg(pkg2);
pup_u2p2.setUser(user2);
pup_u2p2.setPermission(permission);
context.commitChanges();
}
Aggregations