diff --git a/server/src/main/java/org/eclipse/openvsx/ExtensionValidator.java b/server/src/main/java/org/eclipse/openvsx/ExtensionValidator.java index ff1b4f868..4b86af490 100644 --- a/server/src/main/java/org/eclipse/openvsx/ExtensionValidator.java +++ b/server/src/main/java/org/eclipse/openvsx/ExtensionValidator.java @@ -62,33 +62,33 @@ public Optional validateNamespace(String namespace) { public List validateNamespaceDetails(NamespaceDetailsJson json) { var issues = new ArrayList(); - checkCharacters(json.displayName, "displayName", issues); - checkFieldSize(json.displayName, 32, "displayName", issues); - checkCharacters(json.description, "description", issues); - checkFieldSize(json.description, DEFAULT_STRING_SIZE, "description", issues); - checkURL(json.website, "website", issues); - checkURL(json.supportLink, "supportLink", issues); - - var githubLink = json.socialLinks.get("github"); + checkCharacters(json.getDisplayName(), "displayName", issues); + checkFieldSize(json.getDisplayName(), 32, "displayName", issues); + checkCharacters(json.getDescription(), "description", issues); + checkFieldSize(json.getDescription(), DEFAULT_STRING_SIZE, "description", issues); + checkURL(json.getWebsite(), "website", issues); + checkURL(json.getSupportLink(), "supportLink", issues); + + var githubLink = json.getSocialLinks().get("github"); if(githubLink != null && !githubLink.matches("https:\\/\\/github\\.com\\/[^\\/]+")) { issues.add(new Issue("Invalid GitHub URL")); } - var linkedinLink = json.socialLinks.get("linkedin"); + var linkedinLink = json.getSocialLinks().get("linkedin"); if(linkedinLink != null && !linkedinLink.matches("https:\\/\\/www\\.linkedin\\.com\\/(company|in)\\/[^\\/]+")) { issues.add(new Issue("Invalid LinkedIn URL")); } - var twitterLink = json.socialLinks.get("twitter"); + var twitterLink = json.getSocialLinks().get("twitter"); if(twitterLink != null && !twitterLink.matches("https:\\/\\/twitter\\.com\\/[^\\/]+")) { issues.add(new Issue("Invalid Twitter URL")); } - if(json.logoBytes != null) { - try (var in = new ByteArrayInputStream(json.logoBytes)) { + if(json.getLogoBytes() != null) { + try (var in = new ByteArrayInputStream(json.getLogoBytes())) { var tika = new Tika(); - var detectedType = tika.detect(in, json.logo); + var detectedType = tika.detect(in, json.getLogo()); var logoType = MimeTypes.getDefaultMimeTypes().getRegisteredMimeType(detectedType); if(logoType != null) { - json.logo = "logo-" + json.name + "-" + System.currentTimeMillis() + logoType.getExtension(); + json.setLogo("logo-" + json.getName() + "-" + System.currentTimeMillis() + logoType.getExtension()); if(!logoType.getType().equals(MediaType.image("png")) && !logoType.getType().equals(MediaType.image("jpg"))) { issues.add(new Issue("Namespace logo should be of png or jpg type")); } diff --git a/server/src/main/java/org/eclipse/openvsx/LocalRegistryService.java b/server/src/main/java/org/eclipse/openvsx/LocalRegistryService.java index 5db35190c..cd5d3a09d 100644 --- a/server/src/main/java/org/eclipse/openvsx/LocalRegistryService.java +++ b/server/src/main/java/org/eclipse/openvsx/LocalRegistryService.java @@ -99,15 +99,16 @@ public NamespaceJson getNamespace(String namespaceName) { if (namespace == null) throw new NotFoundException(); var json = new NamespaceJson(); - json.name = namespace.getName(); - json.extensions = new LinkedHashMap<>(); + json.setName(namespace.getName()); + var extensions = new LinkedHashMap(); var serverUrl = UrlUtil.getBaseUrl(); for (var name : repositories.findActiveExtensionNames(namespace)) { String url = createApiUrl(serverUrl, "api", namespace.getName(), name); - json.extensions.put(name, url); + extensions.put(name, url); } - json.verified = repositories.hasMemberships(namespace, NamespaceMembership.ROLE_OWNER); - json.access = "restricted"; + json.setExtensions(extensions); + json.setVerified(repositories.hasMemberships(namespace, NamespaceMembership.ROLE_OWNER)); + json.setAccess("restricted"); return json; } @@ -122,7 +123,7 @@ public ExtensionJson getExtension(String namespace, String extensionName, String public ExtensionJson getExtension(String namespace, String extensionName, String targetPlatform, String version) { var extVersion = findExtensionVersion(namespace, extensionName, targetPlatform, version); var json = toExtensionVersionJson(extVersion, targetPlatform, true); - json.downloads = getDownloads(extVersion.getExtension(), targetPlatform, extVersion.getVersion()); + json.setDownloads(getDownloads(extVersion.getExtension(), targetPlatform, extVersion.getVersion())); return json; } @@ -132,17 +133,17 @@ public VersionsJson getVersions(String namespace, String extension, String targe var page = repositories.findActiveVersionStringsSorted(namespace, extension, targetPlatform, pageRequest); var json = new VersionsJson(); - json.offset = (int) page.getPageable().getOffset(); - json.totalSize = (int) page.getTotalElements(); + json.setOffset((int) page.getPageable().getOffset()); + json.setTotalSize((int) page.getTotalElements()); var namespaceLowerCase = namespace.toLowerCase(); var extensionLowerCase = extension.toLowerCase(); - json.versions = page.get() + json.setVersions(page.get() .collect(Collectors.toMap( version -> version, version -> UrlUtil.createApiVersionUrl(UrlUtil.getBaseUrl(), namespaceLowerCase, extensionLowerCase, targetPlatform, version), (v1, v2) -> v1, LinkedHashMap::new - )); + ))); return json; } @@ -157,23 +158,24 @@ public VersionReferencesJson getVersionReferences(String namespace, String exten var fileUrls = storageUtil.getFileUrls(page.getContent(), UrlUtil.getBaseUrl(), withFileTypes(DOWNLOAD)); var json = new VersionReferencesJson(); - json.offset = (int) page.getPageable().getOffset(); - json.totalSize = (int) page.getTotalElements(); - json.versions = page.get() + json.setOffset((int) page.getPageable().getOffset()); + json.setTotalSize((int) page.getTotalElements()); + json.setVersions(page.get() .map(extVersion -> { var versionRef = new VersionReferenceJson(); - versionRef.version = extVersion.getVersion(); - versionRef.targetPlatform = extVersion.getTargetPlatform(); - versionRef.engines = extVersion.getEnginesMap(); - versionRef.url = UrlUtil.createApiVersionUrl(UrlUtil.getBaseUrl(), extVersion); - versionRef.files = fileUrls.get(extVersion.getId()); - if(versionRef.files.containsKey(DOWNLOAD_SIG)) { - versionRef.files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); + versionRef.setVersion(extVersion.getVersion()); + versionRef.setTargetPlatform(extVersion.getTargetPlatform()); + versionRef.setEngines(extVersion.getEnginesMap()); + versionRef.setUrl(UrlUtil.createApiVersionUrl(UrlUtil.getBaseUrl(), extVersion)); + var files = fileUrls.get(extVersion.getId()); + if(files.containsKey(DOWNLOAD_SIG)) { + files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); } + versionRef.setFiles(files); return versionRef; }) - .collect(Collectors.toList()); + .toList()); return json; } @@ -235,30 +237,30 @@ public ReviewListJson getReviews(String namespaceName, String extensionName) { throw new NotFoundException(); var list = new ReviewListJson(); var serverUrl = UrlUtil.getBaseUrl(); - list.postUrl = createApiUrl(serverUrl, "api", extension.getNamespace().getName(), extension.getName(), "review"); - list.deleteUrl = createApiUrl(serverUrl, "api", extension.getNamespace().getName(), extension.getName(), "review", "delete"); - list.reviews = repositories.findActiveReviews(extension) + list.setPostUrl(createApiUrl(serverUrl, "api", extension.getNamespace().getName(), extension.getName(), "review")); + list.setDeleteUrl(createApiUrl(serverUrl, "api", extension.getNamespace().getName(), extension.getName(), "review", "delete")); + list.setReviews(repositories.findActiveReviews(extension) .map(extReview -> extReview.toReviewJson()) - .toList(); + .toList()); return list; } @Override public SearchResultJson search(ISearchService.Options options) { var json = new SearchResultJson(); - var size = options.requestedSize; + var size = options.requestedSize(); if (size <= 0 || !search.isEnabled()) { - json.extensions = Collections.emptyList(); + json.setExtensions(Collections.emptyList()); return json; } var searchHits = search.search(options); if(searchHits.hasSearchHits()) { - json.extensions = toSearchEntries(searchHits, options); - json.offset = options.requestedOffset; - json.totalSize = (int) searchHits.getTotalHits(); + json.setExtensions(toSearchEntries(searchHits, options)); + json.setOffset(options.requestedOffset()); + json.setTotalSize((int) searchHits.getTotalHits()); } else { - json.extensions = Collections.emptyList(); + json.setExtensions(Collections.emptyList()); } return json; @@ -266,22 +268,42 @@ public SearchResultJson search(ISearchService.Options options) { @Override public QueryResultJson query(QueryRequest request) { - if (!StringUtils.isEmpty(request.extensionId)) { - var extensionId = NamingUtil.fromExtensionId(request.extensionId); + if (!StringUtils.isEmpty(request.extensionId())) { + var extensionId = NamingUtil.fromExtensionId(request.extensionId()); if(extensionId == null) throw new ErrorResultException("The 'extensionId' parameter must have the format 'namespace.extension'."); - if (!StringUtils.isEmpty(request.namespaceName) && !request.namespaceName.equals(extensionId.namespace())) + if (!StringUtils.isEmpty(request.namespaceName()) && !request.namespaceName().equals(extensionId.namespace())) throw new ErrorResultException("Conflicting parameters 'extensionId' and 'namespaceName'"); - if (!StringUtils.isEmpty(request.extensionName) && !request.extensionName.equals(extensionId.extension())) + if (!StringUtils.isEmpty(request.extensionName()) && !request.extensionName().equals(extensionId.extension())) throw new ErrorResultException("Conflicting parameters 'extensionId' and 'extensionName'"); - request.namespaceName = extensionId.namespace(); - request.extensionName = extensionId.extension(); - request.extensionId = null; - } - - if(!TargetPlatform.isValid(request.targetPlatform)) { - request.targetPlatform = null; + request = new QueryRequest( + extensionId.namespace(), + extensionId.extension(), + request.extensionVersion(), + null, + request.extensionUuid(), + request.namespaceUuid(), + request.includeAllVersions(), + request.targetPlatform(), + request.size(), + request.offset() + ); + } + + if(!TargetPlatform.isValid(request.targetPlatform())) { + request = new QueryRequest( + request.namespaceName(), + request.extensionName(), + request.extensionVersion(), + request.extensionId(), + request.extensionUuid(), + request.namespaceUuid(), + request.includeAllVersions(), + null, + request.size(), + request.offset() + ); } var extensionVersionsPage = repositories.findActiveVersions(request); @@ -291,17 +313,18 @@ public QueryResultJson query(QueryRequest request) { .collect(Collectors.toSet()); var reviewCounts = getReviewCounts(extensionVersions); - var versionStrings = getVersionStrings(extensionIds, request.targetPlatform); + var versionStrings = getVersionStrings(extensionIds, request.targetPlatform()); var latestVersions = getLatestVersions(extensionVersions); var latestPreReleases = getLatestVersions(extensionVersions, true); var previewsByExtensionId = getPreviews(extensionIds); var fileResourcesByExtensionVersionId = getFileResources(extensionVersions); var membershipsByNamespaceId = getMemberships(extensionVersions); + var targetPlatform = request.targetPlatform(); var result = new QueryResultJson(); - result.offset = (int) extensionVersionsPage.getPageable().getOffset(); - result.totalSize = (int) extensionVersionsPage.getTotalElements(); - result.extensions = extensionVersions.stream() + result.setOffset((int) extensionVersionsPage.getPageable().getOffset()); + result.setTotalSize((int) extensionVersionsPage.getTotalElements()); + result.setExtensions(extensionVersions.stream() .map(ev -> { var latest = latestVersions.get(getLatestVersionKey(ev)); var latestPreRelease = latestPreReleases.get(getLatestVersionKey(ev)); @@ -309,47 +332,80 @@ public QueryResultJson query(QueryRequest request) { var preview = previewsByExtensionId.get(ev.getExtension().getId()); var versions = versionStrings.get(ev.getExtension().getId()); var fileResources = fileResourcesByExtensionVersionId.getOrDefault(ev.getId(), Collections.emptyList()); - return toExtensionVersionJson(ev, latest, latestPreRelease, reviewCount, preview, versions, request.targetPlatform, fileResources, membershipsByNamespaceId); + return toExtensionVersionJson(ev, latest, latestPreRelease, reviewCount, preview, versions, targetPlatform, fileResources, membershipsByNamespaceId); }) - .collect(Collectors.toList()); + .toList()); return result; } @Override public QueryResultJson queryV2(QueryRequestV2 request) { - if (!StringUtils.isEmpty(request.extensionId)) { - var extensionId = NamingUtil.fromExtensionId(request.extensionId); + if (!StringUtils.isEmpty(request.extensionId())) { + var extensionId = NamingUtil.fromExtensionId(request.extensionId()); if (extensionId == null) throw new ErrorResultException("The 'extensionId' parameter must have the format 'namespace.extension'."); - if (!StringUtils.isEmpty(request.namespaceName) && !request.namespaceName.equals(extensionId.namespace())) + if (!StringUtils.isEmpty(request.namespaceName()) && !request.namespaceName().equals(extensionId.namespace())) throw new ErrorResultException("Conflicting parameters 'extensionId' and 'namespaceName'"); - if (!StringUtils.isEmpty(request.extensionName) && !request.extensionName.equals(extensionId.extension())) + if (!StringUtils.isEmpty(request.extensionName()) && !request.extensionName().equals(extensionId.extension())) throw new ErrorResultException("Conflicting parameters 'extensionId' and 'extensionName'"); - request.namespaceName = extensionId.namespace(); - request.extensionName = extensionId.extension(); - request.extensionId = null; - } - - if(!TargetPlatform.isValid(request.targetPlatform)) { - request.targetPlatform = null; + request = new QueryRequestV2( + extensionId.namespace(), + extensionId.extension(), + request.extensionVersion(), + null, + request.extensionUuid(), + request.namespaceUuid(), + request.includeAllVersions(), + request.targetPlatform(), + request.size(), + request.offset() + ); + } + + if(!TargetPlatform.isValid(request.targetPlatform())) { + request = new QueryRequestV2( + request.namespaceName(), + request.extensionName(), + request.extensionVersion(), + request.extensionId(), + request.extensionUuid(), + request.namespaceUuid(), + request.includeAllVersions(), + null, + request.size(), + request.offset() + ); } // Revert to default includeAllVersions value when extensionVersion is set - if(!StringUtils.isEmpty(request.extensionVersion) && request.includeAllVersions.equals("true")) { - request.includeAllVersions = "links"; - } - - var queryRequest = new QueryRequest(); - queryRequest.namespaceName = request.namespaceName; - queryRequest.extensionName = request.extensionName; - queryRequest.extensionVersion = request.extensionVersion; - queryRequest.extensionUuid = request.extensionUuid; - queryRequest.namespaceUuid = request.namespaceUuid; - queryRequest.includeAllVersions = request.includeAllVersions.equals("true"); - queryRequest.targetPlatform = request.targetPlatform; - queryRequest.size = request.size; - queryRequest.offset = request.offset; + if(!StringUtils.isEmpty(request.extensionVersion()) && request.includeAllVersions().equals("true")) { + request = new QueryRequestV2( + request.namespaceName(), + request.extensionName(), + request.extensionVersion(), + request.extensionId(), + request.extensionUuid(), + request.namespaceUuid(), + "links", + request.targetPlatform(), + request.size(), + request.offset() + ); + } + + var queryRequest = new QueryRequest( + request.namespaceName(), + request.extensionName(), + request.extensionVersion(), + null, + request.extensionUuid(), + request.namespaceUuid(), + request.includeAllVersions().equals("true"), + request.targetPlatform(), + request.size(), + request.offset() + ); var extensionVersionsPage = repositories.findActiveVersions(queryRequest); var extensionVersions = extensionVersionsPage.getContent(); @@ -358,8 +414,8 @@ public QueryResultJson queryV2(QueryRequestV2 request) { .collect(Collectors.toSet()); var reviewCounts = getReviewCounts(extensionVersions); - var addAllVersions = request.includeAllVersions.equals("links"); - var versionStrings = addAllVersions ? getVersionStrings(extensionIds, request.targetPlatform) : null; + var addAllVersions = request.includeAllVersions().equals("links"); + var versionStrings = addAllVersions ? getVersionStrings(extensionIds, request.targetPlatform()) : null; var latestGlobalVersions = addAllVersions ? getLatestGlobalVersions(extensionVersions) : null; var latestGlobalPreReleases = addAllVersions ? getLatestGlobalVersions(extensionVersions, true) : null; @@ -368,11 +424,12 @@ public QueryResultJson queryV2(QueryRequestV2 request) { var previewsByExtensionId = getPreviews(extensionIds); var fileResourcesByExtensionVersionId = getFileResources(extensionVersions); var membershipsByNamespaceId = getMemberships(extensionVersions); + var targetPlatform = request.targetPlatform(); var result = new QueryResultJson(); - result.offset = (int) extensionVersionsPage.getPageable().getOffset(); - result.totalSize = (int) extensionVersionsPage.getTotalElements(); - result.extensions = extensionVersions.stream() + result.setOffset((int) extensionVersionsPage.getPageable().getOffset()); + result.setTotalSize((int) extensionVersionsPage.getTotalElements()); + result.setExtensions(extensionVersions.stream() .map(ev -> { var latest = latestVersions.get(getLatestVersionKey(ev)); var latestPreRelease = latestPreReleases.get(getLatestVersionKey(ev)); @@ -383,9 +440,9 @@ public QueryResultJson queryV2(QueryRequestV2 request) { var globalLatestPreRelease = addAllVersions ? latestGlobalPreReleases.get(ev.getExtension().getId()) : null; var versions = addAllVersions ? versionStrings.get(ev.getExtension().getId()) : null; - return toExtensionVersionJsonV2(ev, latest, latestPreRelease, globalLatest, globalLatestPreRelease, reviewCount, preview, versions, request.targetPlatform, fileResources, membershipsByNamespaceId); + return toExtensionVersionJsonV2(ev, latest, latestPreRelease, globalLatest, globalLatestPreRelease, reviewCount, preview, versions, targetPlatform, fileResources, membershipsByNamespaceId); }) - .collect(Collectors.toList()); + .toList()); return result; } @@ -399,27 +456,30 @@ public NamespaceDetailsJson getNamespaceDetails(String namespaceName) { throw new NotFoundException(); } - var json = namespace.toNamespaceDetailsJson(); - json.verified = repositories.hasMemberships(namespace, NamespaceMembership.ROLE_OWNER); - json.logo = namespace.getLogoStorageType() != null + var logo = namespace.getLogoStorageType() != null ? storageUtil.getNamespaceLogoLocation(namespace).toString() : null; + var json = namespace.toNamespaceDetailsJson(); + json.setVerified(repositories.hasMemberships(namespace, NamespaceMembership.ROLE_OWNER)); + json.setLogo(logo); + var serverUrl = UrlUtil.getBaseUrl(); var extVersions = repositories.findLatestVersions(namespace); var fileUrls = storageUtil.getFileUrls(extVersions, serverUrl, withFileTypes(DOWNLOAD, ICON)); - json.extensions = extVersions.stream() + json.setExtensions(extVersions.stream() .map(extVersion -> { var entry = extVersion.toSearchEntryJson(); - entry.url = createApiUrl(serverUrl, "api", entry.namespace, entry.name); - entry.files = fileUrls.get(extVersion.getId()); - if(entry.files.containsKey(DOWNLOAD_SIG)) { - entry.files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); + entry.setUrl(createApiUrl(serverUrl, "api", entry.getNamespace(), entry.getName())); + var files = fileUrls.get(extVersion.getId()); + if(files.containsKey(DOWNLOAD_SIG)) { + files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); } + entry.setFiles(files); return entry; }) - .collect(Collectors.toList()); + .toList()); return json; } @@ -546,20 +606,20 @@ public ResultJson createNamespace(NamespaceJson json, String tokenValue) { @Transactional(rollbackOn = ErrorResultException.class) public ResultJson createNamespace(NamespaceJson json, UserData user) { - var namespaceIssue = validator.validateNamespace(json.name); + var namespaceIssue = validator.validateNamespace(json.getName()); if (namespaceIssue.isPresent()) { throw new ErrorResultException(namespaceIssue.get().toString()); } eclipse.checkPublisherAgreement(user); - var namespaceName = repositories.findNamespaceName(json.name); + var namespaceName = repositories.findNamespaceName(json.getName()); if (namespaceName != null) { throw new ErrorResultException("Namespace already exists: " + namespaceName); } // Create the requested namespace var namespace = new Namespace(); - namespace.setName(json.name); + namespace.setName(json.getName()); entityManager.persist(namespace); // Assign the requesting user as contributor @@ -593,8 +653,8 @@ public ResultJson verifyToken(String namespaceName, String tokenValue) { public ExtensionJson publish(InputStream content, UserData user) throws ErrorResultException { var token = users.createAccessToken(user, "One time use publish token"); - var json = publish(content, token.value); - users.deleteAccessToken(user, token.id); + var json = publish(content, token.getValue()); + users.deleteAccessToken(user, token.getId()); return json; } @@ -609,7 +669,7 @@ public ExtensionJson publish(InputStream content, String tokenValue) throws Erro var extVersion = extensions.publishVersion(content, token); var json = toExtensionVersionJson(extVersion, null, true); - json.success = "It can take a couple minutes before the extension version is available"; + json.setSuccess("It can take a couple minutes before the extension version is available"); if(repositories.hasSameVersion(extVersion)) { var existingRelease = extVersion.isPreRelease() ? "stable release" : "pre-release"; @@ -618,8 +678,8 @@ public ExtensionJson publish(InputStream content, String tokenValue) throws Erro var semver = extVersion.getSemanticVersion(); var newVersion = String.join(".", String.valueOf(semver.getMajor()), String.valueOf(semver.getMinor() + 1), "0"); - json.warning = "A " + existingRelease + " already exists for " + NamingUtil.toLogFormat(extension.getNamespace().getName(), extension.getName(), extVersion.getVersion()) + ".\n" + - "To prevent update conflicts, we recommend that this " + thisRelease + " uses " + newVersion + " as its version instead."; + json.setWarning("A " + existingRelease + " already exists for " + NamingUtil.toLogFormat(extension.getNamespace().getName(), extension.getName(), extVersion.getVersion()) + ".\n" + + "To prevent update conflicts, we recommend that this " + thisRelease + " uses " + newVersion + " as its version instead."); } return json; @@ -645,9 +705,9 @@ public ResultJson postReview(ReviewJson review, String namespace, String extensi extReview.setActive(true); extReview.setTimestamp(TimeUtil.getCurrentUTC()); extReview.setUser(user); - extReview.setTitle(review.title); - extReview.setComment(review.comment); - extReview.setRating(review.rating); + extReview.setTitle(review.getTitle()); + extReview.setComment(review.getComment()); + extReview.setRating(review.getRating()); entityManager.persist(extReview); extension.setAverageRating(repositories.getAverageReviewRating(extension)); extension.setReviewCount(repositories.countActiveReviews(extension)); @@ -686,7 +746,7 @@ public ResultJson deleteReview(String namespace, String extensionName) { private LinkedHashMap getLatestVersions(SearchHits searchHits) { var ids = searchHits.stream() - .map(searchHit -> searchHit.getContent().id) + .map(searchHit -> searchHit.getContent().getId()) .distinct() .collect(Collectors.toList()); @@ -723,8 +783,8 @@ private List toSearchEntries(SearchHits search var searchEntries = latestVersions.entrySet().stream() .map(e -> { var entry = e.getValue().toSearchEntryJson(); - entry.url = createApiUrl(serverUrl, "api", entry.namespace, entry.name); - entry.verified = isVerified(e.getValue(), membershipsByNamespaceId); + entry.setUrl(createApiUrl(serverUrl, "api", entry.getNamespace(), entry.getName())); + entry.setVerified(isVerified(e.getValue(), membershipsByNamespaceId)); return new AbstractMap.SimpleEntry<>(e.getKey(), entry); }) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); @@ -732,20 +792,22 @@ private List toSearchEntries(SearchHits search var fileUrls = storageUtil.getFileUrls(latestVersions.values(), serverUrl, withFileTypes(DOWNLOAD, ICON)); searchEntries.forEach((extensionId, searchEntry) -> { var extVersion = latestVersions.get(extensionId); - searchEntry.files = fileUrls.get(extVersion.getId()); - if(searchEntry.files.containsKey(DOWNLOAD_SIG)) { - searchEntry.files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); + var files = fileUrls.get(extVersion.getId()); + if(files.containsKey(DOWNLOAD_SIG)) { + files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); } + + searchEntry.setFiles(files); }); - if (options.includeAllVersions) { + if (options.includeAllVersions()) { var activeVersions = repositories.findActiveVersionReferencesSorted(latestVersions.keySet()); var activeVersionsByExtensionId = activeVersions.stream().collect(Collectors.groupingBy(ev -> ev.getExtension().getId())); var versionFileUrls = storageUtil.getFileUrls(activeVersions, serverUrl, withFileTypes(DOWNLOAD)); for(var extensionId : latestVersions.keySet()) { var extVersions = activeVersionsByExtensionId.get(extensionId); var searchEntry = searchEntries.get(extensionId); - searchEntry.allVersions = getAllVersionReferences(extVersions, versionFileUrls, serverUrl); - searchEntry.allVersionsUrl = UrlUtil.createAllVersionsUrl(searchEntry.namespace, searchEntry.name, options.targetPlatform, "version-references"); + searchEntry.setAllVersions(getAllVersionReferences(extVersions, versionFileUrls, serverUrl)); + searchEntry.setAllVersionsUrl(UrlUtil.createAllVersionsUrl(searchEntry.getNamespace(), searchEntry.getName(), options.targetPlatform(), "version-references")); } } @@ -761,15 +823,16 @@ private List getAllVersionReferences( ) { return extVersions.stream().map(extVersion -> { var ref = new VersionReferenceJson(); - ref.version = extVersion.getVersion(); - ref.targetPlatform = extVersion.getTargetPlatform(); - ref.engines = extVersion.getEnginesMap(); - ref.url = UrlUtil.createApiVersionUrl(serverUrl, extVersion); - ref.files = versionFileUrls.get(extVersion.getId()); - if(ref.files.containsKey(DOWNLOAD_SIG)) { - ref.files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); + ref.setVersion(extVersion.getVersion()); + ref.setTargetPlatform(extVersion.getTargetPlatform()); + ref.setEngines(extVersion.getEnginesMap()); + ref.setUrl(UrlUtil.createApiVersionUrl(serverUrl, extVersion)); + var files = versionFileUrls.get(extVersion.getId()); + if(files.containsKey(DOWNLOAD_SIG)) { + files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); } + ref.setFiles(files); return ref; }).collect(Collectors.toList()); } @@ -784,27 +847,33 @@ public ExtensionJson toExtensionVersionJson(ExtensionVersion extVersion, String var replacementId = extension.getReplacement().getId(); var replacement = repositories.findLatestReplacement(replacementId, targetPlatform, false, onlyActive); if(replacement != null) { - json.replacement = new ExtensionReplacementJson(); - json.replacement.url = UrlUtil.createApiUrl(webuiUrl, "extension", replacement.getExtension().getNamespace().getName(), replacement.getExtension().getName()); - json.replacement.displayName = StringUtils.isNotEmpty(replacement.getDisplayName()) + var displayName = StringUtils.isNotEmpty(replacement.getDisplayName()) ? replacement.getDisplayName() : replacement.getExtension().getName(); + + var replacementJson = new ExtensionReplacementJson(); + replacementJson.setUrl(UrlUtil.createApiUrl(webuiUrl, "extension", replacement.getExtension().getNamespace().getName(), replacement.getExtension().getName())); + replacementJson.setDisplayName(displayName); + json.setReplacement(replacementJson); } } - json.preview = latest != null && latest.isPreview(); - json.versionAlias = new ArrayList<>(2); + json.setPreview(latest != null && latest.isPreview()); + json.setVersionAlias(new ArrayList<>(2)); + var versionAlias = new ArrayList(); if (latest != null && extVersion.getVersion().equals(latest.getVersion())) - json.versionAlias.add(VersionAlias.LATEST); + versionAlias.add(VersionAlias.LATEST); if (latestPreRelease != null && extVersion.getVersion().equals(latestPreRelease.getVersion())) - json.versionAlias.add(VersionAlias.PRE_RELEASE); - json.verified = isVerified(extVersion); - json.namespaceAccess = "restricted"; - json.unrelatedPublisher = !json.verified; - json.reviewCount = Optional.ofNullable(extension.getReviewCount()).orElse(0L); + versionAlias.add(VersionAlias.PRE_RELEASE); + + json.setVersionAlias(versionAlias); + json.setVerified(isVerified(extVersion)); + json.setNamespaceAccess("restricted"); + json.setUnrelatedPublisher(!json.getVerified()); + json.setReviewCount(Optional.ofNullable(extension.getReviewCount()).orElse(0L)); var serverUrl = UrlUtil.getBaseUrl(); - json.namespaceUrl = createApiUrl(serverUrl, "api", json.namespace); - json.reviewsUrl = createApiUrl(serverUrl, "api", json.namespace, json.name, "reviews"); + json.setNamespaceUrl(createApiUrl(serverUrl, "api", json.getNamespace())); + json.setReviewsUrl(createApiUrl(serverUrl, "api", json.getNamespace(), json.getName(), "reviews")); var allVersions = new ArrayList(); if (latest != null) @@ -812,28 +881,29 @@ public ExtensionJson toExtensionVersionJson(ExtensionVersion extVersion, String if (latestPreRelease != null) allVersions.add(VersionAlias.PRE_RELEASE); - var versionBaseUrl = UrlUtil.createApiVersionBaseUrl(serverUrl, json.namespace, json.name, targetPlatform); + var versionBaseUrl = UrlUtil.createApiVersionBaseUrl(serverUrl, json.getNamespace(), json.getName(), targetPlatform); allVersions.addAll(repositories.findVersionStringsSorted(extension, targetPlatform, onlyActive)); - json.allVersionsUrl = UrlUtil.createAllVersionsUrl(json.namespace, json.name, targetPlatform, "versions"); - json.allVersions = Maps.newLinkedHashMapWithExpectedSize(allVersions.size()); + json.setAllVersionsUrl(UrlUtil.createAllVersionsUrl(json.getNamespace(), json.getName(), targetPlatform, "versions")); + var allVersionsJson = Maps.newLinkedHashMapWithExpectedSize(allVersions.size()); for (var version : allVersions) { - json.allVersions.put(version, createApiUrl(versionBaseUrl, version)); + allVersionsJson.put(version, createApiUrl(versionBaseUrl, version)); } + json.setAllVersions(allVersionsJson); var fileUrls = storageUtil.getFileUrls(List.of(extVersion), serverUrl, withFileTypes(DOWNLOAD, MANIFEST, ICON, README, LICENSE, CHANGELOG, VSIXMANIFEST)); - json.files = fileUrls.get(extVersion.getId()); - if (json.files.containsKey(DOWNLOAD_SIG)) { - json.files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); + json.setFiles(fileUrls.get(extVersion.getId())); + if (json.getFiles().containsKey(DOWNLOAD_SIG)) { + json.getFiles().put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); } - if (json.dependencies != null) { - json.dependencies.forEach(ref -> { - ref.url = createApiUrl(serverUrl, "api", ref.namespace, ref.extension); - }); + if (json.getDependencies() != null) { + json.setDependencies(json.getDependencies().stream() + .peek(ref -> ref.setUrl(createApiUrl(serverUrl, "api", ref.getNamespace(), ref.getExtension()))) + .toList()); } - if (json.bundledExtensions != null) { - json.bundledExtensions.forEach(ref -> { - ref.url = createApiUrl(serverUrl, "api", ref.namespace, ref.extension); - }); + if (json.getBundledExtensions() != null) { + json.setBundledExtensions(json.getBundledExtensions().stream() + .peek(ref -> ref.setUrl(createApiUrl(serverUrl, "api", ref.getNamespace(), ref.getExtension()))) + .toList()); } return json; } @@ -850,36 +920,40 @@ public ExtensionJson toExtensionVersionJson( Map> membershipsByNamespaceId ) { var json = extVersion.toExtensionJson(); - json.preview = preview; - json.verified = isVerified(extVersion, membershipsByNamespaceId); - json.namespaceAccess = "restricted"; - json.unrelatedPublisher = !json.verified; - json.reviewCount = reviewCount; + json.setPreview(preview); + json.setVerified(isVerified(extVersion, membershipsByNamespaceId)); + json.setNamespaceAccess("restricted"); + json.setUnrelatedPublisher(!json.getVerified()); + json.setReviewCount(reviewCount); var serverUrl = UrlUtil.getBaseUrl(); - json.namespaceUrl = createApiUrl(serverUrl, "api", json.namespace); - json.reviewsUrl = createApiUrl(serverUrl, "api", json.namespace, json.name, "reviews"); + json.setNamespaceUrl(createApiUrl(serverUrl, "api", json.getNamespace())); + json.setReviewsUrl(createApiUrl(serverUrl, "api", json.getNamespace(), json.getName(), "reviews")); var extension = extVersion.getExtension(); if(extension.getReplacement() != null) { var replacementId = extension.getReplacement().getId(); var replacement = repositories.findLatestReplacement(replacementId, targetPlatformParam, false, true); if(replacement != null) { - json.replacement = new ExtensionReplacementJson(); - json.replacement.url = UrlUtil.createApiUrl(serverUrl, "api", replacement.getExtension().getNamespace().getName(), replacement.getExtension().getName()); - json.replacement.displayName = StringUtils.isNotEmpty(replacement.getDisplayName()) + var displayName = StringUtils.isNotEmpty(replacement.getDisplayName()) ? replacement.getDisplayName() : replacement.getExtension().getName(); + + var replacementJson = new ExtensionReplacementJson(); + replacementJson.setUrl(UrlUtil.createApiUrl(serverUrl, "api", replacement.getExtension().getNamespace().getName(), replacement.getExtension().getName())); + replacementJson.setDisplayName(displayName); + json.setReplacement(replacementJson); } } - json.versionAlias = new ArrayList<>(2); + var versionAlias = new ArrayList(2); if (extVersion.equals(latest)) { - json.versionAlias.add(VersionAlias.LATEST); + versionAlias.add(VersionAlias.LATEST); } if (extVersion.equals(latestPreRelease)) { - json.versionAlias.add(VersionAlias.PRE_RELEASE); + versionAlias.add(VersionAlias.PRE_RELEASE); } + json.setVersionAlias(versionAlias); var allVersions = new ArrayList(); if(latest != null) { allVersions.add(VersionAlias.LATEST); @@ -891,32 +965,34 @@ public ExtensionJson toExtensionVersionJson( allVersions.addAll(versions); } - json.allVersionsUrl = UrlUtil.createAllVersionsUrl(json.namespace, json.name, targetPlatformParam, "versions"); - json.allVersions = Maps.newLinkedHashMapWithExpectedSize(allVersions.size()); - var versionBaseUrl = UrlUtil.createApiVersionBaseUrl(serverUrl, json.namespace, json.name, targetPlatformParam); + json.setAllVersionsUrl(UrlUtil.createAllVersionsUrl(json.getNamespace(), json.getName(), targetPlatformParam, "versions")); + var allVersionsJson = Maps.newLinkedHashMapWithExpectedSize(allVersions.size()); + var versionBaseUrl = UrlUtil.createApiVersionBaseUrl(serverUrl, json.getNamespace(), json.getName(), targetPlatformParam); for(var version : allVersions) { - json.allVersions.put(version, createApiUrl(versionBaseUrl, version)); + allVersionsJson.put(version, createApiUrl(versionBaseUrl, version)); } - json.files = Maps.newLinkedHashMapWithExpectedSize(8); - var fileBaseUrl = UrlUtil.createApiFileBaseUrl(serverUrl, json.namespace, json.name, json.targetPlatform, json.version); + json.setAllVersions(allVersionsJson); + var files = Maps.newLinkedHashMapWithExpectedSize(8); + var fileBaseUrl = UrlUtil.createApiFileBaseUrl(serverUrl, json.getNamespace(), json.getName(), json.getTargetPlatform(), json.getVersion()); for (var resource : resources) { var fileUrl = UrlUtil.createApiFileUrl(fileBaseUrl, resource.getName()); - json.files.put(resource.getType(), fileUrl); + files.put(resource.getType(), fileUrl); } - if(json.files.containsKey(DOWNLOAD_SIG)) { - json.files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); + if(files.containsKey(DOWNLOAD_SIG)) { + files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); } - if (json.dependencies != null) { - json.dependencies.forEach(ref -> { - ref.url = createApiUrl(serverUrl, "api", ref.namespace, ref.extension); - }); + json.setFiles(files); + if (json.getDependencies() != null) { + json.setDependencies(json.getDependencies().stream() + .peek(ref -> ref.setUrl(createApiUrl(serverUrl, "api", ref.getNamespace(), ref.getExtension()))) + .toList()); } - if (json.bundledExtensions != null) { - json.bundledExtensions.forEach(ref -> { - ref.url = createApiUrl(serverUrl, "api", ref.namespace, ref.extension); - }); + if (json.getBundledExtensions() != null) { + json.setBundledExtensions(json.getBundledExtensions().stream() + .peek(ref -> ref.setUrl(createApiUrl(serverUrl, "api", ref.getNamespace(), ref.getExtension()))) + .toList()); } return json; } @@ -935,37 +1011,42 @@ public ExtensionJson toExtensionVersionJsonV2( Map> membershipsByNamespaceId ) { var json = extVersion.toExtensionJson(); - json.preview = preview; - json.verified = isVerified(extVersion, membershipsByNamespaceId); - json.namespaceAccess = "restricted"; - json.unrelatedPublisher = !json.verified; - json.reviewCount = reviewCount; + json.setPreview(preview); + json.setVerified(isVerified(extVersion, membershipsByNamespaceId)); + json.setNamespaceAccess("restricted"); + json.setUnrelatedPublisher(!json.getVerified()); + json.setReviewCount(reviewCount); var serverUrl = UrlUtil.getBaseUrl(); - json.namespaceUrl = createApiUrl(serverUrl, "api", json.namespace); - json.reviewsUrl = createApiUrl(serverUrl, "api", json.namespace, json.name, "reviews"); - json.url = createApiVersionUrl(serverUrl, json); + json.setNamespaceUrl(createApiUrl(serverUrl, "api", json.getNamespace())); + json.setReviewsUrl(createApiUrl(serverUrl, "api", json.getNamespace(), json.getName(), "reviews")); + json.setUrl(createApiVersionUrl(serverUrl, json)); var extension = extVersion.getExtension(); if(extension.getReplacement() != null) { var replacementId = extension.getReplacement().getId(); var replacement = repositories.findLatestReplacement(replacementId, targetPlatformParam, false, true); if(replacement != null) { - json.replacement = new ExtensionReplacementJson(); - json.replacement.url = UrlUtil.createApiUrl(serverUrl, "api", replacement.getExtension().getNamespace().getName(), replacement.getExtension().getName()); - json.replacement.displayName = StringUtils.isNotEmpty(replacement.getDisplayName()) + var displayName = StringUtils.isNotEmpty(replacement.getDisplayName()) ? replacement.getDisplayName() : replacement.getExtension().getName(); + + var replacementJson = new ExtensionReplacementJson(); + replacementJson.setUrl(UrlUtil.createApiUrl(serverUrl, "api", replacement.getExtension().getNamespace().getName(), replacement.getExtension().getName())); + replacementJson.setDisplayName(displayName); + + json.setReplacement(replacementJson); } } - json.versionAlias = new ArrayList<>(2); + var versionAlias = new ArrayList(2); if (extVersion.equals(latest)) { - json.versionAlias.add(VersionAlias.LATEST); + versionAlias.add(VersionAlias.LATEST); } if (extVersion.equals(latestPreRelease)) { - json.versionAlias.add(VersionAlias.PRE_RELEASE); + versionAlias.add(VersionAlias.PRE_RELEASE); } + json.setVersionAlias(versionAlias); var allVersions = new ArrayList(); if(globalLatest != null) { allVersions.add(VersionAlias.LATEST); @@ -977,34 +1058,36 @@ public ExtensionJson toExtensionVersionJsonV2( allVersions.addAll(versions); } - json.allVersionsUrl = UrlUtil.createAllVersionsUrl(json.namespace, json.name, targetPlatformParam, "versions"); + json.setAllVersionsUrl(UrlUtil.createAllVersionsUrl(json.getNamespace(), json.getName(), targetPlatformParam, "versions")); if(!allVersions.isEmpty()) { - json.allVersions = Maps.newLinkedHashMapWithExpectedSize(allVersions.size()); - var versionBaseUrl = UrlUtil.createApiVersionBaseUrl(serverUrl, json.namespace, json.name, targetPlatformParam); + var allVersionsJson = Maps.newLinkedHashMapWithExpectedSize(allVersions.size()); + var versionBaseUrl = UrlUtil.createApiVersionBaseUrl(serverUrl, json.getNamespace(), json.getName(), targetPlatformParam); for(var version : allVersions) { - json.allVersions.put(version, createApiUrl(versionBaseUrl, version)); + allVersionsJson.put(version, createApiUrl(versionBaseUrl, version)); } + json.setAllVersions(allVersionsJson); } - json.files = Maps.newLinkedHashMapWithExpectedSize(8); - var fileBaseUrl = UrlUtil.createApiFileBaseUrl(serverUrl, json.namespace, json.name, json.targetPlatform, json.version); + var files = Maps.newLinkedHashMapWithExpectedSize(8); + var fileBaseUrl = UrlUtil.createApiFileBaseUrl(serverUrl, json.getNamespace(), json.getName(), json.getTargetPlatform(), json.getVersion()); for (var resource : resources) { var fileUrl = UrlUtil.createApiFileUrl(fileBaseUrl, resource.getName()); - json.files.put(resource.getType(), fileUrl); + files.put(resource.getType(), fileUrl); } - if(json.files.containsKey(DOWNLOAD_SIG)) { - json.files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); + if(files.containsKey(DOWNLOAD_SIG)) { + files.put(PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVersion)); } - if (json.dependencies != null) { - json.dependencies.forEach(ref -> { - ref.url = createApiUrl(serverUrl, "api", ref.namespace, ref.extension); - }); + json.setFiles(files); + if (json.getDependencies() != null) { + json.setDependencies(json.getDependencies().stream() + .peek(ref -> ref.setUrl(createApiUrl(serverUrl, "api", ref.getNamespace(), ref.getExtension()))) + .toList()); } - if (json.bundledExtensions != null) { - json.bundledExtensions.forEach(ref -> { - ref.url = createApiUrl(serverUrl, "api", ref.namespace, ref.extension); - }); + if (json.getBundledExtensions() != null) { + json.setBundledExtensions(json.getBundledExtensions().stream() + .peek(ref -> ref.setUrl(createApiUrl(serverUrl, "api", ref.getNamespace(), ref.getExtension()))) + .toList()); } return json; } @@ -1054,7 +1137,7 @@ public RegistryVersionJson getRegistryVersion() { throw new NotFoundException(); } var registryVersion = new RegistryVersionJson(); - registryVersion.version = this.registryVersion; + registryVersion.setVersion(this.registryVersion); return registryVersion; } } diff --git a/server/src/main/java/org/eclipse/openvsx/RegistryAPI.java b/server/src/main/java/org/eclipse/openvsx/RegistryAPI.java index a4b4dfb95..1122d25f2 100644 --- a/server/src/main/java/org/eclipse/openvsx/RegistryAPI.java +++ b/server/src/main/java/org/eclipse/openvsx/RegistryAPI.java @@ -994,24 +994,25 @@ public ResponseEntity search( return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); } - var options = new ISearchService.Options(query, category, targetPlatform, size, offset, sortOrder, sortBy, includeAllVersions); - var result = new SearchResultJson(); - result.extensions = new ArrayList<>(size); + var options = new ISearchService.Options(query, category, targetPlatform, size, offset, sortOrder, sortBy, includeAllVersions, null); + var resultOffset = 0; + var resultSize = 0; + var resultExtensions = new ArrayList(size); for (var registry : getRegistries()) { - if (result.extensions.size() >= size) { - return ResponseEntity.ok(result); + if (resultExtensions.size() >= size) { + break; } try { var subResult = registry.search(options); - if(result.extensions.isEmpty() && subResult.extensions != null) { - result.extensions.addAll(subResult.extensions); - } else if (subResult.extensions != null && !subResult.extensions.isEmpty()) { - int limit = size - result.extensions.size(); - var subResultSize = mergeSearchResults(result, subResult.extensions, limit); - result.offset += subResult.offset; - offset = Math.max(offset - subResult.offset - subResultSize, 0); + if(resultExtensions.isEmpty() && subResult.getExtensions() != null) { + resultExtensions.addAll(subResult.getExtensions()); + } else if (subResult.getExtensions() != null && !subResult.getExtensions().isEmpty()) { + int limit = size - resultExtensions.size(); + var subResultSize = mergeSearchResults(resultExtensions, subResult.getExtensions(), limit); + resultOffset += subResult.getOffset(); + offset = Math.max(offset - subResult.getOffset() - subResultSize, 0); } - result.totalSize += subResult.totalSize; + resultSize += subResult.getTotalSize(); } catch (NotFoundException exc) { // Try the next registry } catch (ErrorResultException exc) { @@ -1019,19 +1020,23 @@ public ResponseEntity search( } } + var result = new SearchResultJson(); + result.setOffset(resultOffset); + result.setTotalSize(resultSize); + result.setExtensions(resultExtensions); return ResponseEntity.ok() .cacheControl(CacheControl.noCache().cachePublic()) .body(result); } - private int mergeSearchResults(SearchResultJson result, List entries, int limit) { - var previousResult = Iterables.limit(result.extensions, result.extensions.size()); + private int mergeSearchResults(List extensions, List entries, int limit) { + var previousResult = Iterables.limit(extensions, extensions.size()); var entriesIter = entries.iterator(); int mergedEntries = 0; - while (entriesIter.hasNext() && result.extensions.size() < limit) { + while (entriesIter.hasNext() && extensions.size() < limit) { var next = entriesIter.next(); - if (!Iterables.any(previousResult, ext -> ext.namespace.equals(next.namespace) && ext.name.equals(next.name))) { - result.extensions.add(next); + if (!Iterables.any(previousResult, ext -> ext.getNamespace().equals(next.getNamespace()) && ext.getName().equals(next.getName()))) { + extensions.add(next); mergedEntries++; } } @@ -1112,39 +1117,45 @@ public ResponseEntity getQueryV2( return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); } - var request = new QueryRequestV2(); - request.namespaceName = namespaceName; - request.extensionName = extensionName; - request.extensionVersion = extensionVersion; - request.extensionId = extensionId; - request.extensionUuid = extensionUuid; - request.namespaceUuid = namespaceUuid; - request.includeAllVersions = includeAllVersions; - request.targetPlatform = targetPlatform; - request.size = size; - request.offset = offset; + var request = new QueryRequestV2( + namespaceName, + extensionName, + extensionVersion, + extensionId, + extensionUuid, + namespaceUuid, + includeAllVersions, + targetPlatform, + size, + offset + ); - var result = new QueryResultJson(); - result.offset = request.offset; - result.extensions = new ArrayList<>(size); + var resultSize = 0; + var resultOffset = request.offset(); + var resultExtensions = new ArrayList(size); for (var registry : getRegistries()) { try { var subResult = registry.queryV2(request); - if(result.extensions.isEmpty() && subResult.extensions != null) { - result.extensions.addAll(subResult.extensions); - } else if (subResult.extensions != null && !subResult.extensions.isEmpty()) { - int limit = size - result.extensions.size(); - var subResultSize = mergeQueryResults(result, subResult.extensions, limit); - result.offset += subResult.offset; - offset = Math.max(offset - subResult.offset - subResultSize, 0); + if(resultExtensions.isEmpty() && subResult.getExtensions() != null) { + resultExtensions.addAll(subResult.getExtensions()); + } else if (subResult.getExtensions() != null && !subResult.getExtensions().isEmpty()) { + int limit = size - resultExtensions.size(); + var subResultSize = mergeQueryResults(resultExtensions, subResult.getExtensions(), limit); + resultOffset += subResult.getOffset(); + offset = Math.max(offset - subResult.getOffset() - subResultSize, 0); } - result.totalSize += subResult.totalSize; + resultSize += subResult.getTotalSize(); } catch (NotFoundException exc) { // Try the next registry } catch (ErrorResultException exc) { return exc.toResponseEntity(QueryResultJson.class); } } + + var result = new QueryResultJson(); + result.setOffset(resultOffset); + result.setTotalSize(resultSize); + result.setExtensions(resultExtensions); return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES).cachePublic()) .body(result); @@ -1238,52 +1249,58 @@ public ResponseEntity getQuery( return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); } - var request = new QueryRequest(); - request.namespaceName = namespaceName; - request.extensionName = extensionName; - request.extensionVersion = extensionVersion; - request.extensionId = extensionId; - request.extensionUuid = extensionUuid; - request.namespaceUuid = namespaceUuid; - request.includeAllVersions = includeAllVersions; - request.targetPlatform = targetPlatform; - request.size = size; - request.offset = offset; + var request = new QueryRequest( + namespaceName, + extensionName, + extensionVersion, + extensionId, + extensionUuid, + namespaceUuid, + includeAllVersions, + targetPlatform, + size, + offset + ); - var result = new QueryResultJson(); - result.offset = request.offset; - result.extensions = new ArrayList<>(size); + var resultSize = 0; + var resultOffset = request.offset(); + var resultExtensions = new ArrayList(size); for (var registry : getRegistries()) { try { var subResult = registry.query(request); - if(result.extensions.isEmpty() && subResult.extensions != null) { - result.extensions.addAll(subResult.extensions); - } else if (subResult.extensions != null && !subResult.extensions.isEmpty()) { - int limit = size - result.extensions.size(); - var subResultSize = mergeQueryResults(result, subResult.extensions, limit); - result.offset += subResult.offset; - offset = Math.max(offset - subResult.offset - subResultSize, 0); + if(resultExtensions.isEmpty() && subResult.getExtensions() != null) { + resultExtensions.addAll(subResult.getExtensions()); + } else if (subResult.getExtensions() != null && !subResult.getExtensions().isEmpty()) { + int limit = size - resultExtensions.size(); + var subResultSize = mergeQueryResults(resultExtensions, subResult.getExtensions(), limit); + resultOffset += subResult.getOffset(); + offset = Math.max(offset - subResult.getOffset() - subResultSize, 0); } - result.totalSize += subResult.totalSize; + resultSize += subResult.getTotalSize(); } catch (NotFoundException exc) { // Try the next registry } catch (ErrorResultException exc) { return exc.toResponseEntity(QueryResultJson.class); } } + + var result = new QueryResultJson(); + result.setTotalSize(resultSize); + result.setOffset(resultOffset); + result.setExtensions(resultExtensions); return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES).cachePublic()) .body(result); } - private int mergeQueryResults(QueryResultJson result, List entries, int limit) { - var previousResult = Iterables.limit(result.extensions, result.extensions.size()); + private int mergeQueryResults(List extensions, List entries, int limit) { + var previousResult = Iterables.limit(extensions, extensions.size()); var entriesIter = entries.iterator(); int mergedEntries = 0; - while (entriesIter.hasNext() && result.extensions.size() < limit) { + while (entriesIter.hasNext() && extensions.size() < limit) { var next = entriesIter.next(); - if (!Iterables.any(previousResult, ext -> ext.namespace.equals(next.namespace) && ext.name.equals(next.name))) { - result.extensions.add(next); + if (!Iterables.any(previousResult, ext -> ext.getNamespace().equals(next.getNamespace()) && ext.getName().equals(next.getName()))) { + extensions.add(next); mergedEntries++; } } @@ -1387,13 +1404,13 @@ public ResponseEntity createNamespace( if (namespace == null) { return ResponseEntity.ok(ResultJson.error("No JSON input.")); } - if (StringUtils.isEmpty(namespace.name)) { + if (StringUtils.isEmpty(namespace.getName())) { return ResponseEntity.ok(ResultJson.error("Missing required property 'name'.")); } try { var json = local.createNamespace(namespace, token); var serverUrl = UrlUtil.getBaseUrl(); - var url = UrlUtil.createApiUrl(serverUrl, "api", namespace.name); + var url = UrlUtil.createApiUrl(serverUrl, "api", namespace.getName()); return ResponseEntity.status(HttpStatus.CREATED) .location(URI.create(url)) .body(json); @@ -1470,13 +1487,13 @@ public ResponseEntity createNamespace( if (namespace == null) { return ResponseEntity.ok(ResultJson.error("No JSON input.")); } - if (StringUtils.isEmpty(namespace.name)) { + if (StringUtils.isEmpty(namespace.getName())) { return ResponseEntity.ok(ResultJson.error("Missing required property 'name'.")); } try { var json = local.createNamespace(namespace, user); var serverUrl = UrlUtil.getBaseUrl(); - var url = UrlUtil.createApiUrl(serverUrl, "api", namespace.name); + var url = UrlUtil.createApiUrl(serverUrl, "api", namespace.getName()); return ResponseEntity.status(HttpStatus.CREATED) .location(URI.create(url)) .body(json); @@ -1613,7 +1630,7 @@ public ResponseEntity publish(InputStream content) { var json = local.publish(content, user); var serverUrl = UrlUtil.getBaseUrl(); - var url = UrlUtil.createApiUrl(serverUrl, "api", json.namespace, json.name, json.version); + var url = UrlUtil.createApiUrl(serverUrl, "api", json.getNamespace(), json.getName(), json.getVersion()); return ResponseEntity.status(HttpStatus.CREATED) .location(URI.create(url)) .body(json); @@ -1638,20 +1655,20 @@ public ResponseEntity postReview( var json = ResultJson.error("No JSON input."); return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); } - if (review.rating < 0 || review.rating > 5) { + if (review.getRating() < 0 || review.getRating() > 5) { var json = ResultJson.error("The rating must be an integer number between 0 and 5."); return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); } - if (review.title != null && review.title.length() > REVIEW_TITLE_SIZE) { + if (review.getTitle() != null && review.getTitle().length() > REVIEW_TITLE_SIZE) { var json = ResultJson.error("The title must not be longer than " + REVIEW_TITLE_SIZE + " characters."); return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); } - if (review.comment != null && review.comment.length() > REVIEW_COMMENT_SIZE) { + if (review.getComment() != null && review.getComment().length() > REVIEW_COMMENT_SIZE) { var json = ResultJson.error("The review must not be longer than " + REVIEW_COMMENT_SIZE + " characters."); return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); } var json = local.postReview(review, namespace, extension); - if (json.error == null) { + if (json.getError() == null) { return new ResponseEntity<>(json, HttpStatus.CREATED); } else { return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); @@ -1665,7 +1682,7 @@ public ResponseEntity postReview( @Operation(hidden = true) public ResponseEntity deleteReview(@PathVariable String namespace, @PathVariable String extension) { var json = local.deleteReview(namespace, extension); - if (json.error == null) { + if (json.getError() == null) { return ResponseEntity.ok(json); } else { return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST); diff --git a/server/src/main/java/org/eclipse/openvsx/UpstreamProxyService.java b/server/src/main/java/org/eclipse/openvsx/UpstreamProxyService.java index 271dfb1dc..7fa7153b4 100644 --- a/server/src/main/java/org/eclipse/openvsx/UpstreamProxyService.java +++ b/server/src/main/java/org/eclipse/openvsx/UpstreamProxyService.java @@ -35,63 +35,94 @@ public class UpstreamProxyService { protected final Logger logger = LoggerFactory.getLogger(UpstreamProxyService.class); public NamespaceJson rewriteUrls(NamespaceJson json) { - rewriteUrlMap(json.extensions); - if(!StringUtils.isEmpty(json.membersUrl)) { - json.membersUrl = rewriteUrl(json.membersUrl); + rewriteUrlMap(json.getExtensions()); + if(!StringUtils.isEmpty(json.getMembersUrl())) { + json.setMembersUrl(rewriteUrl(json.getMembersUrl())); } - if(!StringUtils.isEmpty(json.roleUrl)) { - json.roleUrl = rewriteUrl(json.roleUrl); + if(!StringUtils.isEmpty(json.getRoleUrl())) { + json.setRoleUrl(rewriteUrl(json.getRoleUrl())); } return json; } public ExtensionJson rewriteUrls(ExtensionJson json) { - json.namespaceUrl = rewriteUrl(json.namespaceUrl); - json.reviewsUrl = rewriteUrl(json.reviewsUrl); - rewriteUrlMap(json.files); - rewriteUrlMap(json.allVersions); - json.dependencies = rewriteUrlList(json.dependencies, this::rewriteUrls); - json.bundledExtensions = rewriteUrlList(json.bundledExtensions, this::rewriteUrls); - rewriteUrlMap(json.downloads); + json.setNamespaceUrl(rewriteUrl(json.getNamespaceUrl())); + json.setReviewsUrl(rewriteUrl(json.getReviewsUrl())); + rewriteUrlMap(json.getFiles()); + rewriteUrlMap(json.getAllVersions()); + json.setDependencies(rewriteUrlList(json.getDependencies(), this::rewriteUrls)); + json.setBundledExtensions(rewriteUrlList(json.getBundledExtensions(), this::rewriteUrls)); + rewriteUrlMap(json.getDownloads()); return json; } public SearchResultJson rewriteUrls(SearchResultJson json) { - json.extensions = rewriteUrlList(json.extensions, this::rewriteUrls); + json.setExtensions(rewriteUrlList(json.getExtensions(), this::rewriteUrls)); return json; } public QueryResultJson rewriteUrls(QueryResultJson json) { - json.extensions = rewriteUrlList(json.extensions, this::rewriteUrls); + json.setExtensions(rewriteUrlList(json.getExtensions(), this::rewriteUrls)); return json; } public ExtensionQueryResult rewriteUrls(ExtensionQueryResult json) { - for(var result : json.results) { - for(var extension : result.extensions) { - for(var version : extension.versions) { - version.assetUri = rewriteUrl(version.assetUri); - version.fallbackAssetUri = rewriteUrl(version.fallbackAssetUri); - for (var file : version.files) { - file.source = rewriteUrl(file.source); - } - } - } - } - return json; + return new ExtensionQueryResult(json.results().stream() + .map(result -> new ExtensionQueryResult.ResultItem(rewriteExtensionUrls(result.extensions()), result.resultMetadata())) + .toList()); + } + + private List rewriteExtensionUrls(List extensions) { + return extensions.stream() + .map(extension -> new ExtensionQueryResult.Extension( + extension.extensionId(), + extension.extensionName(), + extension.displayName(), + extension.shortDescription(), + extension.publisher(), + rewriteVersionUrls(extension.versions()), + extension.statistics(), + extension.tags(), + extension.releaseDate(), + extension.publishedDate(), + extension.lastUpdated(), + extension.categories(), + extension.flags() + )) + .toList(); + } + + private List rewriteVersionUrls(List versions) { + return versions.stream() + .map(version -> new ExtensionQueryResult.ExtensionVersion( + version.version(), + version.lastUpdated(), + rewriteUrl(version.assetUri()), + rewriteUrl(version.fallbackAssetUri()), + rewriteFileUrls(version.files()), + version.properties(), + version.targetPlatform() + )) + .toList(); + } + + private List rewriteFileUrls(List files) { + return files.stream() + .map(file -> new ExtensionQueryResult.ExtensionFile( + file.assetType(), + rewriteUrl(file.source()) + )) + .toList(); } public VersionsJson rewriteUrls(VersionsJson json) { - rewriteUrlMap(json.versions); + rewriteUrlMap(json.getVersions()); return json; } public VersionReferencesJson rewriteUrls(VersionReferencesJson json) { - json.versions = json.versions.stream() - .map(this::rewriteUrls) - .collect(Collectors.toList()); - + json.setVersions(json.getVersions().stream().map(this::rewriteUrls).toList()); return json; } @@ -111,22 +142,21 @@ public URI rewriteUrl(URI location) { } private SearchEntryJson rewriteUrls(SearchEntryJson json) { - json.url = rewriteUrl(json.url); - rewriteUrlMap(json.files); - json.allVersions = rewriteUrlList(json.allVersions, this::rewriteUrls); + json.setUrl(rewriteUrl(json.getUrl())); + rewriteUrlMap(json.getFiles()); + json.setAllVersions(rewriteUrlList(json.getAllVersions(), this::rewriteUrls)); return json; } private VersionReferenceJson rewriteUrls(VersionReferenceJson json) { - json.url = rewriteUrl(json.url); - rewriteUrlMap(json.files); - + json.setUrl(rewriteUrl(json.getUrl())); + rewriteUrlMap(json.getFiles()); return json; } private ExtensionReferenceJson rewriteUrls(ExtensionReferenceJson json) { - json.url = rewriteUrl(json.url); + json.setUrl(rewriteUrl(json.getUrl())); return json; } diff --git a/server/src/main/java/org/eclipse/openvsx/UpstreamRegistryService.java b/server/src/main/java/org/eclipse/openvsx/UpstreamRegistryService.java index be086dedf..1ef7645b8 100644 --- a/server/src/main/java/org/eclipse/openvsx/UpstreamRegistryService.java +++ b/server/src/main/java/org/eclipse/openvsx/UpstreamRegistryService.java @@ -266,14 +266,14 @@ public ReviewListJson getReviews(String namespace, String extension) { public SearchResultJson search(ISearchService.Options options) { var urlTemplate = urlConfigService.getUpstreamUrl() + "/api/-/search"; var uriVariables = new HashMap(); - uriVariables.put("size", Integer.toString(options.requestedSize)); - uriVariables.put("offset", Integer.toString(options.requestedOffset)); - uriVariables.put("includeAllVersions", Boolean.toString(options.includeAllVersions)); - uriVariables.put("query", options.queryString); - uriVariables.put("category", options.category); - uriVariables.put("sortOrder", options.sortOrder); - uriVariables.put("sortBy", options.sortBy); - uriVariables.put("targetPlatform", options.targetPlatform); + uriVariables.put("size", Integer.toString(options.requestedSize())); + uriVariables.put("offset", Integer.toString(options.requestedOffset())); + uriVariables.put("includeAllVersions", Boolean.toString(options.includeAllVersions())); + uriVariables.put("query", options.queryString()); + uriVariables.put("category", options.category()); + uriVariables.put("sortOrder", options.sortOrder()); + uriVariables.put("sortBy", options.sortBy()); + uriVariables.put("targetPlatform", options.targetPlatform()); var queryString = uriVariables.entrySet().stream() .filter(entry -> !StringUtils.isEmpty(entry.getValue())) @@ -300,17 +300,16 @@ public SearchResultJson search(ISearchService.Options options) { public QueryResultJson query(QueryRequest request) { var urlTemplate = urlConfigService.getUpstreamUrl() + "/api/-/query"; var queryParams = new HashMap(); - queryParams.put("namespaceName", request.namespaceName); - queryParams.put("extensionName", request.extensionName); - queryParams.put("extensionVersion", request.extensionVersion); - queryParams.put("extensionId", request.extensionId); - queryParams.put("extensionUuid", request.extensionUuid); - queryParams.put("namespaceUuid", request.namespaceUuid); - queryParams.put("includeAllVersions", String.valueOf(request.includeAllVersions)); - queryParams.put("targetPlatform", request.targetPlatform); - queryParams.put("size", String.valueOf(request.size)); - queryParams.put("offset", String.valueOf(request.offset)); - + queryParams.put("namespaceName", request.namespaceName()); + queryParams.put("extensionName", request.extensionName()); + queryParams.put("extensionVersion", request.extensionVersion()); + queryParams.put("extensionId", request.extensionId()); + queryParams.put("extensionUuid", request.extensionUuid()); + queryParams.put("namespaceUuid", request.namespaceUuid()); + queryParams.put("includeAllVersions", String.valueOf(request.includeAllVersions())); + queryParams.put("targetPlatform", request.targetPlatform()); + queryParams.put("size", String.valueOf(request.size())); + queryParams.put("offset", String.valueOf(request.offset())); var queryString = queryParams.entrySet().stream() .filter(entry -> !StringUtils.isEmpty(entry.getValue())) @@ -337,16 +336,16 @@ public QueryResultJson query(QueryRequest request) { public QueryResultJson queryV2(QueryRequestV2 request) { var urlTemplate = urlConfigService.getUpstreamUrl() + "/api/v2/-/query"; var queryParams = new HashMap(); - queryParams.put("namespaceName", request.namespaceName); - queryParams.put("extensionName", request.extensionName); - queryParams.put("extensionVersion", request.extensionVersion); - queryParams.put("extensionId", request.extensionId); - queryParams.put("extensionUuid", request.extensionUuid); - queryParams.put("namespaceUuid", request.namespaceUuid); - queryParams.put("includeAllVersions", String.valueOf(request.includeAllVersions)); - queryParams.put("targetPlatform", request.targetPlatform); - queryParams.put("size", String.valueOf(request.size)); - queryParams.put("offset", String.valueOf(request.offset)); + queryParams.put("namespaceName", request.namespaceName()); + queryParams.put("extensionName", request.extensionName()); + queryParams.put("extensionVersion", request.extensionVersion()); + queryParams.put("extensionId", request.extensionId()); + queryParams.put("extensionUuid", request.extensionUuid()); + queryParams.put("namespaceUuid", request.namespaceUuid()); + queryParams.put("includeAllVersions", String.valueOf(request.includeAllVersions())); + queryParams.put("targetPlatform", request.targetPlatform()); + queryParams.put("size", String.valueOf(request.size())); + queryParams.put("offset", String.valueOf(request.offset())); var queryString = queryParams.entrySet().stream() .filter(entry -> !StringUtils.isEmpty(entry.getValue())) @@ -421,9 +420,10 @@ private void handleError(Throwable exc) throws RuntimeException { } private void makeDownloadsCompatible(ExtensionJson json) { - if (json.downloads == null && json.files.containsKey("download")) { - json.downloads = new HashMap<>(); - json.downloads.put(TargetPlatform.NAME_UNIVERSAL, json.files.get("download")); + if (json.getDownloads() == null && json.getFiles().containsKey("download")) { + var downloads = new HashMap(); + downloads.put(TargetPlatform.NAME_UNIVERSAL, json.getFiles().get("download")); + json.setDownloads(downloads); } } diff --git a/server/src/main/java/org/eclipse/openvsx/UserAPI.java b/server/src/main/java/org/eclipse/openvsx/UserAPI.java index 5e53dc616..dfff7d1c1 100644 --- a/server/src/main/java/org/eclipse/openvsx/UserAPI.java +++ b/server/src/main/java/org/eclipse/openvsx/UserAPI.java @@ -86,11 +86,9 @@ public ErrorJson getAuthError(HttpServletRequest request) { var authException = request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); if (!(authException instanceof AuthenticationException)) throw new ResponseStatusException(HttpStatus.NOT_FOUND); - var json = new ErrorJson(); - json.message = ((AuthenticationException) authException).getMessage(); - if (authException instanceof CodedAuthException) - json.code = ((CodedAuthException) authException).getCode(); - return json; + + var code = authException instanceof CodedAuthException ? ((CodedAuthException) authException).getCode() : null; + return new ErrorJson(((AuthenticationException) authException).getMessage(), code); } /** @@ -109,9 +107,9 @@ public UserJson getUserData() { } var json = user.toUserJson(); var serverUrl = UrlUtil.getBaseUrl(); - json.role = user.getRole(); - json.tokensUrl = createApiUrl(serverUrl, "user", "tokens"); - json.createTokenUrl = createApiUrl(serverUrl, "user", "token", "create"); + json.setRole(user.getRole()); + json.setTokensUrl(createApiUrl(serverUrl, "user", "tokens")); + json.setCreateTokenUrl(createApiUrl(serverUrl, "user", "token", "create")); eclipse.enrichUserJson(json, user); return json; } @@ -122,13 +120,9 @@ public UserJson getUserData() { ) public CsrfTokenJson getCsrfToken(HttpServletRequest request) { var csrfToken = (CsrfToken) request.getAttribute("_csrf"); - if (csrfToken == null) { - return CsrfTokenJson.error("Token is not available."); - } - var json = new CsrfTokenJson(); - json.value = csrfToken.getToken(); - json.header = csrfToken.getHeaderName(); - return json; + return csrfToken != null + ? new CsrfTokenJson(csrfToken.getToken(), csrfToken.getHeaderName()) + : CsrfTokenJson.error("Token is not available."); } @GetMapping( @@ -144,7 +138,7 @@ public List getAccessTokens() { return repositories.findActiveAccessTokens(user) .map(token -> { var json = token.toAccessTokenJson(); - json.deleteTokenUrl = createApiUrl(serverUrl, "user", "token", "delete", Long.toString(token.getId())); + json.setDeleteTokenUrl(createApiUrl(serverUrl, "user", "token", "delete", Long.toString(token.getId()))); return json; }) .toList(); @@ -200,9 +194,9 @@ public List getOwnExtensions() { return extVersions.stream() .map(latest -> { var json = latest.toExtensionJson(); - json.preview = latest.isPreview(); - json.active = latest.getExtension().isActive(); - json.files = fileUrls.get(latest.getId()); + json.setPreview(latest.isPreview()); + json.setActive(latest.getExtension().isActive()); + json.setFiles(fileUrls.get(latest.getId())); return json; }) .toList(); @@ -220,20 +214,21 @@ public List getOwnNamespaces() { return repositories.findMemberships(user).map(membership -> { var namespace = membership.getNamespace(); - var json = new NamespaceJson(); - json.name = namespace.getName(); - json.extensions = new LinkedHashMap<>(); + var extensions = new LinkedHashMap(); var serverUrl = UrlUtil.getBaseUrl(); repositories.findActiveExtensionsForUrls(namespace).forEach(extension -> { String url = createApiUrl(serverUrl, "api", namespace.getName(), extension.getName()); - json.extensions.put(extension.getName(), url); + extensions.put(extension.getName(), url); }); + var json = new NamespaceJson(); + json.setName(namespace.getName()); + json.setExtensions(extensions); var isOwner = membership.getRole().equals(NamespaceMembership.ROLE_OWNER); - json.verified = isOwner || repositories.hasMemberships(namespace, NamespaceMembership.ROLE_OWNER); + json.setVerified(isOwner || repositories.hasMemberships(namespace, NamespaceMembership.ROLE_OWNER)); if(isOwner) { - json.membersUrl = createApiUrl(serverUrl, "user", "namespace", namespace.getName(), "members"); - json.roleUrl = createApiUrl(serverUrl, "user", "namespace", namespace.getName(), "role"); + json.setMembersUrl(createApiUrl(serverUrl, "user", "namespace", namespace.getName(), "members")); + json.setRoleUrl(createApiUrl(serverUrl, "user", "namespace", namespace.getName(), "role")); } return json; @@ -250,7 +245,7 @@ public ResponseEntity updateNamespaceDetails(@RequestBody NamespaceD .cacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES).cachePublic()) .body(users.updateNamespaceDetails(details)); } catch (NotFoundException exc) { - var json = NamespaceDetailsJson.error("Namespace not found: " + details.name); + var json = NamespaceDetailsJson.error("Namespace not found: " + details.getName()); return new ResponseEntity<>(json, HttpStatus.NOT_FOUND); } catch (ErrorResultException exc) { return exc.toResponseEntity(ResultJson.class); @@ -270,7 +265,7 @@ public ResponseEntity getNamespaceMembers(@PathVari var memberships = repositories.findMembershipsForOwner(user, name); if (!memberships.isEmpty()) { var membershipList = new NamespaceMembershipListJson(); - membershipList.namespaceMemberships = memberships.stream().map(NamespaceMembership::toJson).toList(); + membershipList.setNamespaceMemberships(memberships.stream().map(NamespaceMembership::toJson).toList()); return new ResponseEntity<>(membershipList, HttpStatus.OK); } else { return new ResponseEntity<>(NamespaceMembershipListJson.error("You don't have the permission to see this."), HttpStatus.FORBIDDEN); diff --git a/server/src/main/java/org/eclipse/openvsx/UserService.java b/server/src/main/java/org/eclipse/openvsx/UserService.java index 70fa4687b..680d30807 100644 --- a/server/src/main/java/org/eclipse/openvsx/UserService.java +++ b/server/src/main/java/org/eclipse/openvsx/UserService.java @@ -199,7 +199,7 @@ public ResultJson addNamespaceMember(Namespace namespace, UserData user, String @Transactional(rollbackOn = { ErrorResultException.class, NotFoundException.class }) @CacheEvict(value = { CACHE_NAMESPACE_DETAILS_JSON }, key="#details.name") public ResultJson updateNamespaceDetails(NamespaceDetailsJson details) { - var namespace = repositories.findNamespace(details.name); + var namespace = repositories.findNamespace(details.getName()); if (namespace == null) { throw new NotFoundException(); } @@ -213,34 +213,34 @@ public ResultJson updateNamespaceDetails(NamespaceDetailsJson details) { throw new ErrorResultException(message); } - if(!Objects.equals(details.displayName, namespace.getDisplayName())) { - namespace.setDisplayName(details.displayName); + if(!Objects.equals(details.getDisplayName(), namespace.getDisplayName())) { + namespace.setDisplayName(details.getDisplayName()); } - if(!Objects.equals(details.description, namespace.getDescription())) { - namespace.setDescription(details.description); + if(!Objects.equals(details.getDescription(), namespace.getDescription())) { + namespace.setDescription(details.getDescription()); } - if(!Objects.equals(details.website, namespace.getWebsite())) { - namespace.setWebsite(details.website); + if(!Objects.equals(details.getWebsite(), namespace.getWebsite())) { + namespace.setWebsite(details.getWebsite()); } - if(!Objects.equals(details.supportLink, namespace.getSupportLink())) { - namespace.setSupportLink(details.supportLink); + if(!Objects.equals(details.getSupportLink(), namespace.getSupportLink())) { + namespace.setSupportLink(details.getSupportLink()); } - if(!Objects.equals(details.socialLinks, namespace.getSocialLinks())) { - namespace.setSocialLinks(details.socialLinks); + if(!Objects.equals(details.getSocialLinks(), namespace.getSocialLinks())) { + namespace.setSocialLinks(details.getSocialLinks()); } var logo = namespace.getLogoStorageType() != null ? storageUtil.getNamespaceLogoLocation(namespace).toString() : null; - if(!Objects.equals(details.logo, logo)) { - if (details.logoBytes != null && details.logoBytes.length > 0) { + if(!Objects.equals(details.getLogo(), logo)) { + if (details.getLogoBytes() != null && details.getLogoBytes().length > 0) { if (namespace.getLogoStorageType() != null) { storageUtil.removeNamespaceLogo(namespace); } - namespace.setLogoName(details.logo); - namespace.setLogoBytes(details.logoBytes); + namespace.setLogoName(details.getLogo()); + namespace.setLogoBytes(details.getLogoBytes()); storeNamespaceLogo(namespace); } else if (namespace.getLogoStorageType() != null) { storageUtil.removeNamespaceLogo(namespace); @@ -250,7 +250,7 @@ public ResultJson updateNamespaceDetails(NamespaceDetailsJson details) { } } - return ResultJson.success("Updated details for namespace " + details.name); + return ResultJson.success("Updated details for namespace " + details.getName()); } private void storeNamespaceLogo(Namespace namespace) { @@ -273,8 +273,8 @@ public AccessTokenJson createAccessToken(UserData user, String description) { entityManager.persist(token); var json = token.toAccessTokenJson(); // Include the token value after creation so the user can copy it - json.value = token.getValue(); - json.deleteTokenUrl = createApiUrl(UrlUtil.getBaseUrl(), "user", "token", "delete", Long.toString(token.getId())); + json.setValue(token.getValue()); + json.setDeleteTokenUrl(createApiUrl(UrlUtil.getBaseUrl(), "user", "token", "delete", Long.toString(token.getId()))); return json; } diff --git a/server/src/main/java/org/eclipse/openvsx/adapter/DefaultExtensionQueryRequestHandler.java b/server/src/main/java/org/eclipse/openvsx/adapter/DefaultExtensionQueryRequestHandler.java index 169a85902..699b5e972 100644 --- a/server/src/main/java/org/eclipse/openvsx/adapter/DefaultExtensionQueryRequestHandler.java +++ b/server/src/main/java/org/eclipse/openvsx/adapter/DefaultExtensionQueryRequestHandler.java @@ -38,7 +38,7 @@ public ExtensionQueryResult getResult(ExtensionQueryParam param, int pageSize, i var service = services.next(); if(extensions.isEmpty()) { var subResult = service.extensionQuery(param, defaultPageSize); - var subExtensions = subResult.results.get(0).extensions; + var subExtensions = subResult.results().get(0).extensions(); if(subExtensions != null) { extensions.addAll(subExtensions); } @@ -47,7 +47,7 @@ public ExtensionQueryResult getResult(ExtensionQueryParam param, int pageSize, i } else { var extensionCount = extensions.size(); var subResult = service.extensionQuery(param, defaultPageSize); - var subExtensions = subResult.results.get(0).extensions; + var subExtensions = subResult.results().get(0).extensions(); var subExtensionsCount = subExtensions != null ? subExtensions.size() : 0; if (subExtensionsCount > 0) { int limit = pageSize - extensionCount; @@ -95,15 +95,15 @@ private void mergeExtensionQueryResults(List ext } private long getTotalCount(ExtensionQueryResult subResult) { - return subResult.results.get(0).resultMetadata.stream() - .filter(metadata -> metadata.metadataType.equals("ResultCount")) + return subResult.results().get(0).resultMetadata().stream() + .filter(metadata -> metadata.metadataType().equals("ResultCount")) .findFirst() - .map(metadata -> metadata.metadataItems) + .map(metadata -> metadata.metadataItems()) .orElseGet(Collections::emptyList) .stream() - .filter(item -> item.name.equals("TotalCount")) + .filter(item -> item.name().equals("TotalCount")) .findFirst() - .map(item -> item.count) + .map(item -> item.count()) .orElse(0L); } } diff --git a/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryParam.java b/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryParam.java index 9ce9c6492..bab4186b3 100644 --- a/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryParam.java +++ b/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryParam.java @@ -13,7 +13,7 @@ import java.util.List; import java.util.stream.Collectors; -public class ExtensionQueryParam { +public record ExtensionQueryParam(List filters, int flags) { public static final int FLAG_INCLUDE_VERSIONS = 0x1; public static final int FLAG_INCLUDE_FILES = 0x2; @@ -27,15 +27,7 @@ public class ExtensionQueryParam { public static final int FLAG_INCLUDE_LATEST_VERSION_ONLY = 0x200; public static final int FLAG_UNPUBLISHED = 0x1000; - public List filters; - public int flags; - - public static class Filter { - public List criteria; - public int pageNumber; - public int pageSize; - public int sortBy; - public int sortOrder; + public record Filter(List criteria, int pageNumber, int pageSize, int sortBy, int sortOrder) { public String findCriterion(int type) { if (criteria == null || criteria.isEmpty()) @@ -57,7 +49,7 @@ public List findCriteria(int type) { } } - public static class Criterion { + public static record Criterion(int filterType, String value) { public static final int FILTER_TAG = 1; public static final int FILTER_EXTENSION_ID = 4; public static final int FILTER_CATEGORY = 5; @@ -66,9 +58,5 @@ public static class Criterion { public static final int FILTER_FEATURED = 9; public static final int FILTER_SEARCH_TEXT = 10; public static final int FILTER_EXCLUDE_WITH_FLAGS = 12; - - public int filterType; - public String value; } - } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryResult.java b/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryResult.java index 09fc6c7bd..5ee915365 100644 --- a/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryResult.java +++ b/server/src/main/java/org/eclipse/openvsx/adapter/ExtensionQueryResult.java @@ -13,70 +13,47 @@ // Keep interfaces in sync with // https://github.com/microsoft/vscode/blob/de0724b414e2f95f6cc484b03bccbc96686c2cfd/src/vs/platform/extensionManagement/common/extensionGalleryService.ts#L34-L81 -public class ExtensionQueryResult { - - public List results; - - public static class ResultItem { - public List extensions; - public List resultMetadata; - } - - public static class Extension { +public record ExtensionQueryResult(List results) { + + public record ResultItem(List extensions, List resultMetadata) {} + + public record Extension( + String extensionId, + String extensionName, + String displayName, + String shortDescription, + Publisher publisher, + List versions, + List statistics, + List tags, + String releaseDate, + String publishedDate, + String lastUpdated, + List categories, + String flags + ) { public static final String FLAG_PREVIEW = "preview"; - - public String extensionId; - public String extensionName; - public String displayName; - public String shortDescription; - public Publisher publisher; - public List versions; - public List statistics; - public List tags; - public String releaseDate; - public String publishedDate; - public String lastUpdated; - public List categories; - public String flags; } - public static class Publisher { - public String displayName; - public String publisherId; - public String publisherName; - public String domain; - public Boolean isDomainVerified; - } - - public static class ExtensionVersion { - public String version; - public String lastUpdated; - public String assetUri; - public String fallbackAssetUri; - public List files; - public List properties; - public String targetPlatform; - - public void addFile(String assetType, String source) { - if (source != null) { - var file = new ExtensionFile(); - file.assetType = assetType; - file.source = source; - files.add(file); - } - } - - public void addProperty(String key, String value) { - if (value != null) { - var repositoryProp = new Property(); - repositoryProp.key = key; - repositoryProp.value = value; - properties.add(repositoryProp); - } - } - } - - public static class ExtensionFile { + public record Publisher( + String displayName, + String publisherId, + String publisherName, + String domain, + Boolean isDomainVerified + ) {} + + public record ExtensionVersion( + String version, + String lastUpdated, + String assetUri, + String fallbackAssetUri, + List files, + List properties, + String targetPlatform + ) {} + + public record ExtensionFile(String assetType, String source) { public static final String FILE_ICON = "Microsoft.VisualStudio.Services.Icons.Default"; public static final String FILE_DETAILS = "Microsoft.VisualStudio.Services.Content.Details"; public static final String FILE_CHANGELOG = "Microsoft.VisualStudio.Services.Content.Changelog"; @@ -87,12 +64,9 @@ public static class ExtensionFile { public static final String FILE_VSIXMANIFEST = "Microsoft.VisualStudio.Services.VsixManifest"; public static final String FILE_SIGNATURE = "Microsoft.VisualStudio.Services.VsixSignature"; public static final String FILE_PUBLIC_KEY = "Microsoft.VisualStudio.Services.PublicKey"; - - public String assetType; - public String source; } - public static class Property { + public record Property(String key, String value) { public static final String PROP_REPOSITORY = "Microsoft.VisualStudio.Services.Links.Source"; public static final String PROP_SPONSOR_LINK = "Microsoft.VisualStudio.Code.SponsorLink"; public static final String PROP_DEPENDENCY = "Microsoft.VisualStudio.Code.ExtensionDependencies"; @@ -103,28 +77,15 @@ public static class Property { public static final String PROP_BRANDING_THEME = "Microsoft.VisualStudio.Services.Branding.Theme"; public static final String PROP_WEB_EXTENSION = "Microsoft.VisualStudio.Code.WebExtension"; public static final String PROP_PRE_RELEASE = "Microsoft.VisualStudio.Code.PreRelease"; - - public String key; - public String value; } - public static class Statistic { + public record Statistic(String statisticName, double value) { public static final String STAT_INSTALL = "install"; public static final String STAT_AVERAGE_RATING = "averagerating"; public static final String STAT_RATING_COUNT = "ratingcount"; - - public String statisticName; - public double value; - } - - public static class ResultMetadata { - public String metadataType; - public List metadataItems; } - public static class ResultMetadataItem { - public String name; - public long count; - } + public record ResultMetadata(String metadataType, List metadataItems) {} + public record ResultMetadataItem(String name, long count) {} } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/adapter/LocalVSCodeService.java b/server/src/main/java/org/eclipse/openvsx/adapter/LocalVSCodeService.java index 3325f2403..e3646b81a 100644 --- a/server/src/main/java/org/eclipse/openvsx/adapter/LocalVSCodeService.java +++ b/server/src/main/java/org/eclipse/openvsx/adapter/LocalVSCodeService.java @@ -82,7 +82,7 @@ public ExtensionQueryResult extensionQuery(ExtensionQueryParam param, int defaul String sortBy; Set extensionIds; Set extensionNames; - if (param.filters == null || param.filters.isEmpty()) { + if (param.filters() == null || param.filters().isEmpty()) { pageNumber = 0; pageSize = defaultPageSize; sortBy = "relevance"; @@ -91,7 +91,7 @@ public ExtensionQueryResult extensionQuery(ExtensionQueryParam param, int defaul extensionIds = Collections.emptySet(); extensionNames = Collections.emptySet(); } else { - var filter = param.filters.get(0); + var filter = param.filters().get(0); extensionIds = new HashSet<>(filter.findCriteria(FILTER_EXTENSION_ID)); extensionNames = new HashSet<>(filter.findCriteria(FILTER_EXTENSION_NAME)); @@ -103,10 +103,10 @@ public ExtensionQueryResult extensionQuery(ExtensionQueryParam param, int defaul var targetCriterion = filter.findCriterion(FILTER_TARGET); targetPlatform = TargetPlatform.isValid(targetCriterion) ? targetCriterion : null; - pageNumber = Math.max(0, filter.pageNumber - 1); - pageSize = filter.pageSize > 0 ? filter.pageSize : defaultPageSize; - sortOrder = getSortOrder(filter.sortOrder); - sortBy = getSortBy(filter.sortBy); + pageNumber = Math.max(0, filter.pageNumber() - 1); + pageSize = filter.pageSize() > 0 ? filter.pageSize() : defaultPageSize; + sortOrder = getSortOrder(filter.sortOrder()); + sortBy = getSortBy(filter.sortBy()); } Long totalCount = null; @@ -127,12 +127,12 @@ public ExtensionQueryResult extensionQuery(ExtensionQueryParam param, int defaul try { var pageOffset = pageNumber * pageSize; var searchOptions = new SearchUtilService.Options(queryString, category, targetPlatform, pageSize, - pageOffset, sortOrder, sortBy, false, BuiltInExtensionUtil.getBuiltInNamespace()); + pageOffset, sortOrder, sortBy, false, new String[]{BuiltInExtensionUtil.getBuiltInNamespace()}); var searchResult = search.search(searchOptions); totalCount = searchResult.getTotalHits(); var ids = searchResult.getSearchHits().stream() - .map(hit -> hit.getContent().id) + .map(hit -> hit.getContent().getId()) .collect(Collectors.toList()); var extensionsMap = repositories.findActiveExtensionsById(ids).stream() @@ -151,7 +151,7 @@ public ExtensionQueryResult extensionQuery(ExtensionQueryParam param, int defaul totalCount = (long) extensionsList.size(); } - var flags = param.flags; + var flags = param.flags(); var extensionsMap = extensionsList.stream().collect(Collectors.toMap(e -> e.getId(), e -> e)); List allActiveExtensionVersions = repositories.findActiveExtensionVersions(extensionsMap.keySet(), targetPlatform); @@ -211,11 +211,11 @@ public ExtensionQueryResult extensionQuery(ExtensionQueryParam param, int defaul var extensionQueryResults = new ArrayList(); for(var extension : extensionsList) { var latest = latestVersions.get(extension.getId()); - var queryExt = toQueryExtension(extension, latest, flags); - queryExt.versions = extensionVersionsMap.getOrDefault(extension.getId(), Collections.emptyList()).stream() + var versions = extensionVersionsMap.getOrDefault(extension.getId(), Collections.emptyList()).stream() .map(extVer -> toQueryVersion(extVer, fileResources, flags)) .collect(Collectors.toList()); + var queryExt = toQueryExtension(extension, latest, versions, flags); extensionQueryResults.add(queryExt); } @@ -239,20 +239,10 @@ public ExtensionQueryResult toQueryResult(List e } public ExtensionQueryResult toQueryResult(List extensions, long totalCount) { - var resultItem = new ExtensionQueryResult.ResultItem(); - resultItem.extensions = extensions; - - var countMetadataItem = new ExtensionQueryResult.ResultMetadataItem(); - countMetadataItem.name = "TotalCount"; - countMetadataItem.count = totalCount; - var countMetadata = new ExtensionQueryResult.ResultMetadata(); - countMetadata.metadataType = "ResultCount"; - countMetadata.metadataItems = List.of(countMetadataItem); - resultItem.resultMetadata = List.of(countMetadata); - - var result = new ExtensionQueryResult(); - result.results = List.of(resultItem); - return result; + var countMetadataItem = new ExtensionQueryResult.ResultMetadataItem("TotalCount", totalCount); + var countMetadata = new ExtensionQueryResult.ResultMetadata("ResultCount", List.of(countMetadataItem)); + var resultItem = new ExtensionQueryResult.ResultItem(extensions, List.of(countMetadata)); + return new ExtensionQueryResult(List.of(resultItem)); } private String getSortBy(int sortBy) { @@ -473,44 +463,50 @@ private ResponseEntity browseDirectory( .body(json.getBytes(StandardCharsets.UTF_8)); } - private ExtensionQueryResult.Extension toQueryExtension(Extension extension, ExtensionVersion latest, int flags) { + private ExtensionQueryResult.Extension toQueryExtension(Extension extension, ExtensionVersion latest, List versions, int flags) { + var statistics = getQueryExtensionStatistics(extension, flags); var namespace = extension.getNamespace(); + var publisher = new ExtensionQueryResult.Publisher( + !StringUtils.isEmpty(namespace.getDisplayName()) ? namespace.getDisplayName() : namespace.getName(), + namespace.getPublicId(), + namespace.getName(), + null, + null + ); - var queryExt = new ExtensionQueryResult.Extension(); - queryExt.extensionId = extension.getPublicId(); - queryExt.extensionName = extension.getName(); - queryExt.displayName = latest.getDisplayName(); - queryExt.shortDescription = latest.getDescription(); - queryExt.publisher = new ExtensionQueryResult.Publisher(); - queryExt.publisher.publisherId = namespace.getPublicId(); - queryExt.publisher.publisherName = namespace.getName(); - queryExt.publisher.displayName = !StringUtils.isEmpty(namespace.getDisplayName()) ? namespace.getDisplayName() : namespace.getName(); - queryExt.tags = latest.getTags(); - queryExt.releaseDate = TimeUtil.toUTCString(extension.getPublishedDate()); - queryExt.publishedDate = TimeUtil.toUTCString(extension.getPublishedDate()); - queryExt.lastUpdated = TimeUtil.toUTCString(extension.getLastUpdatedDate()); - queryExt.categories = latest.getCategories(); - queryExt.flags = latest.isPreview() ? FLAG_PREVIEW : ""; + return new ExtensionQueryResult.Extension( + extension.getPublicId(), + extension.getName(), + latest.getDisplayName(), + latest.getDescription(), + publisher, + versions, + statistics, + latest.getTags(), + TimeUtil.toUTCString(extension.getPublishedDate()), + TimeUtil.toUTCString(extension.getPublishedDate()), + TimeUtil.toUTCString(extension.getLastUpdatedDate()), + latest.getCategories(), + latest.isPreview() ? FLAG_PREVIEW : "" + ); + } + private List getQueryExtensionStatistics(Extension extension, int flags) { + var statistics = new ArrayList(); if (test(flags, FLAG_INCLUDE_STATISTICS)) { - queryExt.statistics = Lists.newArrayList(); - var installStat = new ExtensionQueryResult.Statistic(); - installStat.statisticName = STAT_INSTALL; - installStat.value = extension.getDownloadCount(); - queryExt.statistics.add(installStat); + var installStat = new ExtensionQueryResult.Statistic(STAT_INSTALL, extension.getDownloadCount()); + statistics.add(installStat); if (extension.getAverageRating() != null) { - var avgRatingStat = new ExtensionQueryResult.Statistic(); - avgRatingStat.statisticName = STAT_AVERAGE_RATING; - avgRatingStat.value = extension.getAverageRating(); - queryExt.statistics.add(avgRatingStat); + var avgRatingStat = new ExtensionQueryResult.Statistic(STAT_AVERAGE_RATING, extension.getAverageRating()); + statistics.add(avgRatingStat); } - var ratingCountStat = new ExtensionQueryResult.Statistic(); - ratingCountStat.statisticName = STAT_RATING_COUNT; - ratingCountStat.value = Optional.ofNullable(extension.getReviewCount()).orElse(0L); - queryExt.statistics.add(ratingCountStat); + var ratingCountStat = new ExtensionQueryResult.Statistic( + STAT_RATING_COUNT, + Optional.ofNullable(extension.getReviewCount()).orElse(0L) + ); + statistics.add(ratingCountStat); } - - return queryExt; + return statistics; } private ExtensionQueryResult.ExtensionVersion toQueryVersion( @@ -518,63 +514,79 @@ private ExtensionQueryResult.ExtensionVersion toQueryVersion( Map> fileResources, int flags ) { - var queryVer = new ExtensionQueryResult.ExtensionVersion(); - queryVer.version = extVer.getVersion(); - queryVer.lastUpdated = TimeUtil.toUTCString(extVer.getTimestamp()); - queryVer.targetPlatform = extVer.getTargetPlatform(); var serverUrl = UrlUtil.getBaseUrl(); var namespaceName = extVer.getExtension().getNamespace().getName(); var extensionName = extVer.getExtension().getName(); + String assetUri = null; if (test(flags, FLAG_INCLUDE_ASSET_URI)) { - queryVer.assetUri = UrlUtil.createApiUrl(serverUrl, "vscode", "asset", namespaceName, extensionName, extVer.getVersion()); - queryVer.fallbackAssetUri = queryVer.assetUri; + assetUri = UrlUtil.createApiUrl(serverUrl, "vscode", "asset", namespaceName, extensionName, extVer.getVersion()); } + + List properties = null; if (test(flags, FLAG_INCLUDE_VERSION_PROPERTIES)) { - queryVer.properties = Lists.newArrayList(); - queryVer.addProperty(PROP_BRANDING_COLOR, extVer.getGalleryColor()); - queryVer.addProperty(PROP_BRANDING_THEME, extVer.getGalleryTheme()); - queryVer.addProperty(PROP_REPOSITORY, extVer.getRepository()); - queryVer.addProperty(PROP_SPONSOR_LINK, extVer.getSponsorLink()); - queryVer.addProperty(PROP_ENGINE, getVscodeEngine(extVer)); - var dependencies = extVer.getDependencies().stream() - .collect(Collectors.joining(",")); - queryVer.addProperty(PROP_DEPENDENCY, dependencies); - var bundledExtensions = extVer.getBundledExtensions().stream() - .collect(Collectors.joining(",")); - queryVer.addProperty(PROP_EXTENSION_PACK, bundledExtensions); - var localizedLanguages = extVer.getLocalizedLanguages().stream() - .collect(Collectors.joining(",")); - queryVer.addProperty(PROP_LOCALIZED_LANGUAGES, localizedLanguages); + properties = Lists.newArrayList(); + addQueryExtensionVersionProperty(properties, PROP_BRANDING_COLOR, extVer.getGalleryColor()); + addQueryExtensionVersionProperty(properties, PROP_BRANDING_THEME, extVer.getGalleryTheme()); + addQueryExtensionVersionProperty(properties, PROP_REPOSITORY, extVer.getRepository()); + addQueryExtensionVersionProperty(properties, PROP_SPONSOR_LINK, extVer.getSponsorLink()); + addQueryExtensionVersionProperty(properties, PROP_ENGINE, getVscodeEngine(extVer)); + var dependencies = String.join(",", extVer.getDependencies()); + addQueryExtensionVersionProperty(properties, PROP_DEPENDENCY, dependencies); + var bundledExtensions = String.join(",", extVer.getBundledExtensions()); + addQueryExtensionVersionProperty(properties, PROP_EXTENSION_PACK, bundledExtensions); + var localizedLanguages = String.join(",", extVer.getLocalizedLanguages()); + addQueryExtensionVersionProperty(properties, PROP_LOCALIZED_LANGUAGES, localizedLanguages); if (extVer.isPreRelease()) { - queryVer.addProperty(PROP_PRE_RELEASE, "true"); + addQueryExtensionVersionProperty(properties, PROP_PRE_RELEASE, "true"); } if (isWebExtension(extVer)) { - queryVer.addProperty(PROP_WEB_EXTENSION, "true"); + addQueryExtensionVersionProperty(properties, PROP_WEB_EXTENSION, "true"); } } + List files = null; if(fileResources.containsKey(extVer.getId())) { var resourcesByType = fileResources.get(extVer.getId()).stream() .collect(Collectors.groupingBy(FileResource::getType)); var fileBaseUrl = UrlUtil.createApiFileBaseUrl(serverUrl, namespaceName, extensionName, extVer.getTargetPlatform(), extVer.getVersion()); - queryVer.files = Lists.newArrayList(); - queryVer.addFile(FILE_MANIFEST, createFileUrl(resourcesByType.get(MANIFEST), fileBaseUrl)); - queryVer.addFile(FILE_DETAILS, createFileUrl(resourcesByType.get(README), fileBaseUrl)); - queryVer.addFile(FILE_LICENSE, createFileUrl(resourcesByType.get(LICENSE), fileBaseUrl)); - queryVer.addFile(FILE_ICON, createFileUrl(resourcesByType.get(ICON), fileBaseUrl)); - queryVer.addFile(FILE_VSIX, createFileUrl(resourcesByType.get(DOWNLOAD), fileBaseUrl)); - queryVer.addFile(FILE_CHANGELOG, createFileUrl(resourcesByType.get(CHANGELOG), fileBaseUrl)); - queryVer.addFile(FILE_VSIXMANIFEST, createFileUrl(resourcesByType.get(VSIXMANIFEST), fileBaseUrl)); - queryVer.addFile(FILE_SIGNATURE, createFileUrl(resourcesByType.get(DOWNLOAD_SIG), fileBaseUrl)); + files = Lists.newArrayList(); + addQueryExtensionVersionFile(files, FILE_MANIFEST, createFileUrl(resourcesByType.get(MANIFEST), fileBaseUrl)); + addQueryExtensionVersionFile(files, FILE_DETAILS, createFileUrl(resourcesByType.get(README), fileBaseUrl)); + addQueryExtensionVersionFile(files, FILE_LICENSE, createFileUrl(resourcesByType.get(LICENSE), fileBaseUrl)); + addQueryExtensionVersionFile(files, FILE_ICON, createFileUrl(resourcesByType.get(ICON), fileBaseUrl)); + addQueryExtensionVersionFile(files, FILE_VSIX, createFileUrl(resourcesByType.get(DOWNLOAD), fileBaseUrl)); + addQueryExtensionVersionFile(files, FILE_CHANGELOG, createFileUrl(resourcesByType.get(CHANGELOG), fileBaseUrl)); + addQueryExtensionVersionFile(files, FILE_VSIXMANIFEST, createFileUrl(resourcesByType.get(VSIXMANIFEST), fileBaseUrl)); + addQueryExtensionVersionFile(files, FILE_SIGNATURE, createFileUrl(resourcesByType.get(DOWNLOAD_SIG), fileBaseUrl)); if(resourcesByType.containsKey(DOWNLOAD_SIG)) { - queryVer.addFile(FILE_PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVer)); + addQueryExtensionVersionFile(files, FILE_PUBLIC_KEY, UrlUtil.getPublicKeyUrl(extVer)); } } - return queryVer; + return new ExtensionQueryResult.ExtensionVersion( + extVer.getVersion(), + TimeUtil.toUTCString(extVer.getTimestamp()), + assetUri, + assetUri, + files, + properties, + extVer.getTargetPlatform() + ); + } + + public void addQueryExtensionVersionFile(List files, String assetType, String source) { + if (source != null) { + files.add(new ExtensionQueryResult.ExtensionFile(assetType, source)); + } + } + + public void addQueryExtensionVersionProperty(List properties, String key, String value) { + if (value != null) { + properties.add(new ExtensionQueryResult.Property(key, value)); + } } private String getVscodeEngine(ExtensionVersion extVer) { diff --git a/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeAPI.java b/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeAPI.java index 18e8d5169..31f6ec4b7 100644 --- a/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeAPI.java +++ b/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeAPI.java @@ -58,8 +58,8 @@ private Iterable getVSCodeServices() { @CrossOrigin public ExtensionQueryResult extensionQuery(@RequestBody ExtensionQueryParam param) { var size = 0; - if(param.filters != null && !param.filters.isEmpty()) { - size = param.filters.get(0).pageSize; + if(param.filters() != null && !param.filters().isEmpty()) { + size = param.filters().get(0).pageSize(); } if(size <= 0) { size = DEFAULT_PAGE_SIZE; diff --git a/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeIdService.java b/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeIdService.java index c42d4a7a0..bee49831c 100644 --- a/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeIdService.java +++ b/server/src/main/java/org/eclipse/openvsx/adapter/VSCodeIdService.java @@ -31,6 +31,8 @@ import org.springframework.web.client.RestTemplate; import java.time.ZoneId; +import java.util.ArrayList; +import java.util.List; import java.util.UUID; @Component @@ -84,11 +86,9 @@ public PublicIds getUpstreamPublicIds(Extension extension) { String namespacePublicId = null; var upstream = getUpstreamExtension(extension); if (upstream != null) { - if (upstream.extensionId != null) { - extensionPublicId = upstream.extensionId; - } - if (upstream.publisher != null && upstream.publisher.publisherId != null) { - namespacePublicId = upstream.publisher.publisherId; + extensionPublicId = upstream.extensionId(); + if (upstream.publisher() != null) { + namespacePublicId = upstream.publisher().publisherId(); } } @@ -108,10 +108,10 @@ private ExtensionQueryResult.Extension getUpstreamExtension(Extension extension) headers.set(HttpHeaders.ACCEPT, "application/json;api-version=" + API_VERSION); var result = vsCodeIdRestTemplate.postForObject(requestUrl, new HttpEntity<>(requestData, headers), ExtensionQueryResult.class); - if (result.results != null && result.results.size() > 0) { - var item = result.results.get(0); - if (item.extensions != null && item.extensions.size() > 0) { - return item.extensions.get(0); + if (result.results() != null && result.results().size() > 0) { + var item = result.results().get(0); + if (item.extensions() != null && item.extensions().size() > 0) { + return item.extensions().get(0); } } @@ -119,20 +119,20 @@ private ExtensionQueryResult.Extension getUpstreamExtension(Extension extension) } private ExtensionQueryParam createRequestData(Extension extension) { - var request = new ExtensionQueryParam(); - var filter = new ExtensionQueryParam.Filter(); - filter.criteria = Lists.newArrayList(); - var targetCriterion = new ExtensionQueryParam.Criterion(); - targetCriterion.filterType = ExtensionQueryParam.Criterion.FILTER_TARGET; - targetCriterion.value = "Microsoft.VisualStudio.Code"; - filter.criteria.add(targetCriterion); - var nameCriterion = new ExtensionQueryParam.Criterion(); - nameCriterion.filterType = ExtensionQueryParam.Criterion.FILTER_EXTENSION_NAME; - nameCriterion.value = NamingUtil.toExtensionId(extension); - filter.criteria.add(nameCriterion); - filter.pageNumber = 1; - filter.pageSize = 1; - request.filters = Lists.newArrayList(filter); - return request; + var criteria = List.of( + new ExtensionQueryParam.Criterion( + ExtensionQueryParam.Criterion.FILTER_TARGET, + "Microsoft.VisualStudio.Code" + ), + new ExtensionQueryParam.Criterion( + ExtensionQueryParam.Criterion.FILTER_EXTENSION_NAME, + NamingUtil.toExtensionId(extension) + ) + ); + + return new ExtensionQueryParam( + List.of(new ExtensionQueryParam.Filter(criteria, 1, 1, 0, 0)), + 0 + ); } } diff --git a/server/src/main/java/org/eclipse/openvsx/admin/AdminAPI.java b/server/src/main/java/org/eclipse/openvsx/admin/AdminAPI.java index ad85ff142..8c20e05c9 100644 --- a/server/src/main/java/org/eclipse/openvsx/admin/AdminAPI.java +++ b/server/src/main/java/org/eclipse/openvsx/admin/AdminAPI.java @@ -108,9 +108,9 @@ public ResponseEntity getStats() { admins.checkAdminUser(); var json = new StatsJson(); - json.userCount = repositories.countUsers(); - json.extensionCount = repositories.countExtensions(); - json.namespaceCount = repositories.countNamespaces(); + json.setUserCount(repositories.countUsers()); + json.setExtensionCount(repositories.countExtensions()); + json.setNamespaceCount(repositories.countNamespaces()); return ResponseEntity.ok(json); } catch (ErrorResultException exc) { return exc.toResponseEntity(StatsJson.class); @@ -181,8 +181,8 @@ public ResponseEntity getExtension(@PathVariable String namespace var latest = repositories.findLatestVersion(namespaceName, extensionName, null, false, false); if (latest != null) { json = local.toExtensionVersionJson(latest, null, false); - json.allTargetPlatformVersions = repositories.findTargetPlatformsGroupedByVersion(latest.getExtension()); - json.active = latest.getExtension().isActive(); + json.setAllTargetPlatformVersions(repositories.findTargetPlatformsGroupedByVersion(latest.getExtension())); + json.setActive(latest.getExtension().isActive()); } else { var extension = repositories.findExtension(extensionName, namespaceName); if (extension == null) { @@ -191,12 +191,12 @@ public ResponseEntity getExtension(@PathVariable String namespace } json = new ExtensionJson(); - json.namespace = extension.getNamespace().getName(); - json.name = extension.getName(); - json.allVersions = Collections.emptyMap(); - json.allTargetPlatformVersions = Collections.emptyList(); - json.deprecated = extension.isDeprecated(); - json.active = extension.isActive(); + json.setNamespace(extension.getNamespace().getName()); + json.setName(extension.getName()); + json.setAllVersions(Collections.emptyMap()); + json.setAllTargetPlatformVersions(Collections.emptyList()); + json.setDeprecated(extension.isDeprecated()); + json.setActive(extension.isActive()); } return ResponseEntity.ok(json); } catch (ErrorResultException exc) { @@ -219,12 +219,12 @@ public ResponseEntity deleteExtension(@PathVariable String namespace } else { var results = new ArrayList(); for(var targetVersion : targetVersions) { - results.add(admins.deleteExtension(namespaceName, extensionName, targetVersion.targetPlatform, targetVersion.version, adminUser)); + results.add(admins.deleteExtension(namespaceName, extensionName, targetVersion.targetPlatform(), targetVersion.version(), adminUser)); } result = new ResultJson(); - result.error = results.stream().map(r -> r.error).filter(Objects::nonNull).collect(Collectors.joining("\n")); - result.success = results.stream().map(r -> r.success).filter(Objects::nonNull).collect(Collectors.joining("\n")); + result.setError(results.stream().map(ResultJson::getError).filter(Objects::nonNull).collect(Collectors.joining("\n"))); + result.setSuccess(results.stream().map(ResultJson::getSuccess).filter(Objects::nonNull).collect(Collectors.joining("\n"))); } return ResponseEntity.ok(result); @@ -243,8 +243,8 @@ public ResponseEntity getNamespace(@PathVariable String namespace var namespace = local.getNamespace(namespaceName); var serverUrl = UrlUtil.getBaseUrl(); - namespace.membersUrl = UrlUtil.createApiUrl(serverUrl, "admin", "namespace", namespace.name, "members"); - namespace.roleUrl = UrlUtil.createApiUrl(serverUrl, "admin", "namespace", namespace.name, "change-member"); + namespace.setMembersUrl(UrlUtil.createApiUrl(serverUrl, "admin", "namespace", namespace.getName(), "members")); + namespace.setRoleUrl(UrlUtil.createApiUrl(serverUrl, "admin", "namespace", namespace.getName(), "change-member")); return ResponseEntity.ok(namespace); } catch (NotFoundException exc) { var json = NamespaceJson.error("Namespace not found: " + namespaceName); @@ -264,7 +264,7 @@ public ResponseEntity createNamespace(@RequestBody NamespaceJson nam admins.checkAdminUser(); var json = admins.createNamespace(namespace); var serverUrl = UrlUtil.getBaseUrl(); - var url = UrlUtil.createApiUrl(serverUrl, "admin", "namespace", namespace.name); + var url = UrlUtil.createApiUrl(serverUrl, "admin", "namespace", namespace.getName()); return ResponseEntity.status(HttpStatus.CREATED) .location(URI.create(url)) .body(json); @@ -282,7 +282,7 @@ public ResponseEntity changeNamespace(@RequestBody ChangeNamespaceJs try { admins.checkAdminUser(); admins.changeNamespace(json); - return ResponseEntity.ok(ResultJson.success("Scheduled namespace change from '" + json.oldNamespace + "' to '" + json.newNamespace + "'.\nIt can take 15 minutes to a couple hours for the change to become visible.")); + return ResponseEntity.ok(ResultJson.success("Scheduled namespace change from '" + json.oldNamespace() + "' to '" + json.newNamespace() + "'.\nIt can take 15 minutes to a couple hours for the change to become visible.")); } catch (ErrorResultException exc) { return exc.toResponseEntity(); } @@ -297,7 +297,7 @@ public ResponseEntity getNamespaceMembers(@PathVari admins.checkAdminUser(); var memberships = repositories.findMemberships(namespaceName); var membershipList = new NamespaceMembershipListJson(); - membershipList.namespaceMemberships = memberships.stream().map(NamespaceMembership::toJson).toList(); + membershipList.setNamespaceMemberships(memberships.stream().map(NamespaceMembership::toJson).toList()); return ResponseEntity.ok(membershipList); } catch (ErrorResultException exc) { return exc.toResponseEntity(NamespaceMembershipListJson.class); diff --git a/server/src/main/java/org/eclipse/openvsx/admin/AdminService.java b/server/src/main/java/org/eclipse/openvsx/admin/AdminService.java index 5ec9845e4..15783f46b 100644 --- a/server/src/main/java/org/eclipse/openvsx/admin/AdminService.java +++ b/server/src/main/java/org/eclipse/openvsx/admin/AdminService.java @@ -189,37 +189,37 @@ public ResultJson editNamespaceMember(String namespaceName, String userName, Str @Transactional(rollbackOn = ErrorResultException.class) public ResultJson createNamespace(NamespaceJson json) { - var namespaceIssue = validator.validateNamespace(json.name); + var namespaceIssue = validator.validateNamespace(json.getName()); if (namespaceIssue.isPresent()) { throw new ErrorResultException(namespaceIssue.get().toString()); } - var namespaceName = repositories.findNamespaceName(json.name); + var namespaceName = repositories.findNamespaceName(json.getName()); if (namespaceName != null) { throw new ErrorResultException("Namespace already exists: " + namespaceName); } var namespace = new Namespace(); - namespace.setName(json.name); + namespace.setName(json.getName()); entityManager.persist(namespace); return ResultJson.success("Created namespace " + namespace.getName()); } public void changeNamespace(ChangeNamespaceJson json) { - if (StringUtils.isEmpty(json.oldNamespace)) { + if (StringUtils.isEmpty(json.oldNamespace())) { throw new ErrorResultException("Old namespace must have a value"); } - if (StringUtils.isEmpty(json.newNamespace)) { + if (StringUtils.isEmpty(json.newNamespace())) { throw new ErrorResultException("New namespace must have a value"); } - var oldNamespace = repositories.findNamespace(json.oldNamespace); + var oldNamespace = repositories.findNamespace(json.oldNamespace()); if (oldNamespace == null) { - throw new ErrorResultException("Old namespace doesn't exists: " + json.oldNamespace); + throw new ErrorResultException("Old namespace doesn't exists: " + json.oldNamespace()); } - var newNamespace = repositories.findNamespace(json.newNamespace); - if (newNamespace != null && !json.mergeIfNewNamespaceAlreadyExists) { - throw new ErrorResultException("New namespace already exists: " + json.newNamespace); + var newNamespace = repositories.findNamespace(json.newNamespace()); + if (newNamespace != null && !json.mergeIfNewNamespaceAlreadyExists()) { + throw new ErrorResultException("New namespace already exists: " + json.newNamespace()); } if (newNamespace != null) { var newExtensions = repositories.findExtensions(newNamespace).stream() @@ -232,9 +232,9 @@ public void changeNamespace(ChangeNamespaceJson json) { .collect(Collectors.joining("','")); if(!duplicateExtensions.isEmpty()) { var message = "Can't merge namespaces, because new namespace '" + - json.newNamespace + + json.newNamespace() + "' and old namespace '" + - json.oldNamespace + + json.oldNamespace() + "' have " + (duplicateExtensions.indexOf(',') == -1 ? "a " : "") + "duplicate extension" + @@ -257,26 +257,26 @@ public UserPublishInfoJson getUserPublishInfo(String provider, String loginName) } var userPublishInfo = new UserPublishInfoJson(); - userPublishInfo.user = user.toUserJson(); - eclipse.adminEnrichUserJson(userPublishInfo.user, user); - userPublishInfo.activeAccessTokenNum = (int) repositories.countActiveAccessTokens(user); + userPublishInfo.setUser(user.toUserJson()); + eclipse.adminEnrichUserJson(userPublishInfo.getUser(), user); + userPublishInfo.setActiveAccessTokenNum((int) repositories.countActiveAccessTokens(user)); var extVersions = repositories.findLatestVersions(user); var types = new String[]{DOWNLOAD, MANIFEST, ICON, README, LICENSE, CHANGELOG, VSIXMANIFEST}; var fileUrls = storageUtil.getFileUrls(extVersions, UrlUtil.getBaseUrl(), types); - userPublishInfo.extensions = extVersions.stream() + userPublishInfo.setExtensions(extVersions.stream() .map(latest -> { var json = latest.toExtensionJson(); - json.preview = latest.isPreview(); - json.active = latest.getExtension().isActive(); - json.files = fileUrls.get(latest.getId()); + json.setPreview(latest.isPreview()); + json.setActive(latest.getExtension().isActive()); + json.setFiles(fileUrls.get(latest.getId())); return json; }) - .sorted(Comparator.comparing(j -> j.namespace) - .thenComparing(j -> j.name) - .thenComparing(j -> j.version) + .sorted(Comparator.comparing(ExtensionJson::getNamespace) + .thenComparing(ExtensionJson::getName) + .thenComparing(ExtensionJson::getVersion) ) - .collect(Collectors.toList()); + .toList()); return userPublishInfo; } @@ -335,11 +335,11 @@ public UserData checkAdminUser() { @Transactional public void logAdminAction(UserData admin, ResultJson result) { - if (result.success != null) { + if (result.getSuccess() != null) { var log = new PersistedLog(); log.setUser(admin); log.setTimestamp(TimeUtil.getCurrentUTC()); - log.setMessage(result.success); + log.setMessage(result.getSuccess()); entityManager.persist(log); } } diff --git a/server/src/main/java/org/eclipse/openvsx/admin/ChangeNamespaceJobRequestHandler.java b/server/src/main/java/org/eclipse/openvsx/admin/ChangeNamespaceJobRequestHandler.java index 5dbb8af52..2964e3fa0 100644 --- a/server/src/main/java/org/eclipse/openvsx/admin/ChangeNamespaceJobRequestHandler.java +++ b/server/src/main/java/org/eclipse/openvsx/admin/ChangeNamespaceJobRequestHandler.java @@ -66,7 +66,7 @@ public ChangeNamespaceJobRequestHandler( @Override public void run(ChangeNamespaceJobRequest jobRequest) throws Exception { - var oldNamespace = jobRequest.getData().oldNamespace; + var oldNamespace = jobRequest.getData().oldNamespace(); synchronized (LOCKS.computeIfAbsent(oldNamespace, key -> new Object())) { execute(jobRequest); } @@ -74,18 +74,18 @@ public void run(ChangeNamespaceJobRequest jobRequest) throws Exception { private void execute(ChangeNamespaceJobRequest jobRequest) { var json = jobRequest.getData(); - LOGGER.info(">> Change namespace from {} to {}", json.oldNamespace, json.newNamespace); - var oldNamespace = repositories.findNamespace(json.oldNamespace); + LOGGER.info(">> Change namespace from {} to {}", json.oldNamespace(), json.newNamespace()); + var oldNamespace = repositories.findNamespace(json.oldNamespace()); if(oldNamespace == null) { return; } - var newNamespaceOptional = Optional.ofNullable(repositories.findNamespace(json.newNamespace)); + var newNamespaceOptional = Optional.ofNullable(repositories.findNamespace(json.newNamespace())); var createNewNamespace = newNamespaceOptional.isEmpty(); var newNamespace = newNamespaceOptional.orElseGet(() -> { - validateNamespace(json.newNamespace); + validateNamespace(json.newNamespace()); var namespace = new Namespace(); - namespace.setName(json.newNamespace); + namespace.setName(json.newNamespace()); return namespace; }); @@ -129,14 +129,14 @@ private void execute(ChangeNamespaceJobRequest jobRequest) { .toList(); } - service.changeNamespaceInDatabase(newNamespace, oldNamespace, updatedResources, createNewNamespace, json.removeOldNamespace); + service.changeNamespaceInDatabase(newNamespace, oldNamespace, updatedResources, createNewNamespace, json.removeOldNamespace()); if(copyResources) { // remove the old resources from external storage pairs.stream() .map(Pair::getFirst) .forEach(storageUtil::removeFile); } - LOGGER.info("<< Changed namespace from {} to {}", json.oldNamespace, json.newNamespace); + LOGGER.info("<< Changed namespace from {} to {}", json.oldNamespace(), json.newNamespace()); } private void validateNamespace(String namespace) { diff --git a/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseProfile.java b/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseProfile.java index b2c629716..71f383861 100644 --- a/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseProfile.java +++ b/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseProfile.java @@ -23,37 +23,125 @@ public class EclipseProfile { - public String uid; + private String uid; - public String name; + private String name; - public String mail; + private String mail; - public String picture; + private String picture; @JsonProperty("first_name") - public String firstName; + private String firstName; @JsonProperty("last_name") - public String lastName; + private String lastName; @JsonProperty("full_name") - public String fullName; + private String fullName; @JsonProperty("github_handle") - public String githubHandle; + private String githubHandle; @JsonProperty("twitter_handle") - public String twitterHandle; + private String twitterHandle; @JsonProperty("publisher_agreements") @JsonDeserialize(using = PublisherAgreements.Deserializer.class) - public PublisherAgreements publisherAgreements; + private PublisherAgreements publisherAgreements; + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMail() { + return mail; + } + + public void setMail(String mail) { + this.mail = mail; + } + + public String getPicture() { + return picture; + } + + public void setPicture(String picture) { + this.picture = picture; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getGithubHandle() { + return githubHandle; + } + + public void setGithubHandle(String githubHandle) { + this.githubHandle = githubHandle; + } + + public String getTwitterHandle() { + return twitterHandle; + } + + public void setTwitterHandle(String twitterHandle) { + this.twitterHandle = twitterHandle; + } + + public PublisherAgreements getPublisherAgreements() { + return publisherAgreements; + } + + public void setPublisherAgreements(PublisherAgreements publisherAgreements) { + this.publisherAgreements = publisherAgreements; + } public static class PublisherAgreements { @JsonProperty("open-vsx") - public PublisherAgreement openVsx; + private PublisherAgreement openVsx; + + public PublisherAgreement getOpenVsx() { + return openVsx; + } + + public void setOpenVsx(PublisherAgreement openVsx) { + this.openVsx = openVsx; + } public static class Deserializer extends JsonDeserializer { @@ -76,9 +164,14 @@ public PublisherAgreements deserialize(JsonParser p, DeserializationContext ctxt } public static class PublisherAgreement { + private String version; - public String version; + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } } - } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseService.java b/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseService.java index 9e2b0ada5..3d5b233b4 100644 --- a/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseService.java +++ b/server/src/main/java/org/eclipse/openvsx/eclipse/EclipseService.java @@ -109,13 +109,13 @@ public void checkPublisherAgreement(UserData user) { throw new ErrorResultException("You must log in with an Eclipse Foundation account and sign a Publisher Agreement before publishing any extension."); } var profile = getPublicProfile(personId); - if (profile.publisherAgreements == null || profile.publisherAgreements.openVsx == null - || profile.publisherAgreements.openVsx.version == null) { + if (profile.getPublisherAgreements() == null || profile.getPublisherAgreements().getOpenVsx() == null + || profile.getPublisherAgreements().getOpenVsx().getVersion() == null) { throw new ErrorResultException("You must sign a Publisher Agreement with the Eclipse Foundation before publishing any extension."); } - if (!publisherAgreementVersion.equals(profile.publisherAgreements.openVsx.version)) { + if (!publisherAgreementVersion.equals(profile.getPublisherAgreements().getOpenVsx().getVersion())) { throw new ErrorResultException("Your Publisher Agreement with the Eclipse Foundation is outdated (version " - + profile.publisherAgreements.openVsx.version + "). The current version is " + + profile.getPublisherAgreements().getOpenVsx().getVersion() + "). The current version is " + publisherAgreementVersion + "."); } } @@ -154,7 +154,7 @@ public EclipseProfile getPublicProfile(String personId) { @Transactional public void updateUserData(UserData user, EclipseProfile profile) { user = entityManager.merge(user); - user.setEclipsePersonId(profile.name); + user.setEclipsePersonId(profile.getName()); } /** @@ -165,10 +165,10 @@ public void enrichUserJson(UserJson json, UserData user) { return; } - json.publisherAgreement = new UserJson.PublisherAgreement(); + var publisherAgreement = new UserJson.PublisherAgreement(); var personId = user.getEclipsePersonId(); if (personId == null) { - json.publisherAgreement.status = "none"; + publisherAgreement.setStatus("none"); return; } @@ -176,14 +176,14 @@ public void enrichUserJson(UserJson json, UserData user) { try { // Add information on the publisher agreement var agreement = getPublisherAgreement(user); - if (agreement == null || !agreement.isActive || agreement.version == null) - json.publisherAgreement.status = "none"; - else if (publisherAgreementVersion.equals(agreement.version)) - json.publisherAgreement.status = "signed"; + if (agreement == null || !agreement.isActive() || agreement.version() == null) + publisherAgreement.setStatus("none"); + else if (publisherAgreementVersion.equals(agreement.version())) + publisherAgreement.setStatus("signed"); else - json.publisherAgreement.status = "outdated"; - if (agreement != null && agreement.timestamp != null) - json.publisherAgreement.timestamp = TimeUtil.toUTCString(agreement.timestamp); + publisherAgreement.setStatus("outdated"); + if (agreement != null && agreement.timestamp() != null) + publisherAgreement.setTimestamp(TimeUtil.toUTCString(agreement.timestamp())); } catch (ErrorResultException e) { if(e.getStatus() == HttpStatus.FORBIDDEN) { usableToken = false; @@ -192,16 +192,17 @@ else if (publisherAgreementVersion.equals(agreement.version)) } } + json.setPublisherAgreement(publisherAgreement); // Report user as logged in only if there is a usable token: // we need the token to access the Eclipse REST API if(usableToken) { var eclipseLogin = new UserJson(); - eclipseLogin.provider = "eclipse"; - eclipseLogin.loginName = personId; - if (json.additionalLogins == null) - json.additionalLogins = Lists.newArrayList(eclipseLogin); + eclipseLogin.setProvider("eclipse"); + eclipseLogin.setLoginName(personId); + if (json.getAdditionalLogins() == null) + json.setAdditionalLogins(Lists.newArrayList(eclipseLogin)); else - json.additionalLogins.add(eclipseLogin); + json.getAdditionalLogins().add(eclipseLogin); } } @@ -210,21 +211,23 @@ public void adminEnrichUserJson(UserJson json, UserData user) { return; } - json.publisherAgreement = new UserJson.PublisherAgreement(); + var publisherAgreement = new UserJson.PublisherAgreement(); var personId = user.getEclipsePersonId(); if (personId == null) { - json.publisherAgreement.status = "none"; + publisherAgreement.setStatus("none"); return; } try { var profile = getPublicProfile(personId); - if (profile.publisherAgreements == null || profile.publisherAgreements.openVsx == null || StringUtils.isEmpty(profile.publisherAgreements.openVsx.version)) - json.publisherAgreement.status = "none"; - else if (publisherAgreementVersion.equals(profile.publisherAgreements.openVsx.version)) - json.publisherAgreement.status = "signed"; + if (profile.getPublisherAgreements() == null || profile.getPublisherAgreements().getOpenVsx() == null || StringUtils.isEmpty(profile.getPublisherAgreements().getOpenVsx().getVersion())) + publisherAgreement.setStatus("none"); + else if (publisherAgreementVersion.equals(profile.getPublisherAgreements().getOpenVsx().getVersion())) + publisherAgreement.setStatus("signed"); else - json.publisherAgreement.status = "outdated"; + publisherAgreement.setStatus("outdated"); + + json.setPublisherAgreement(publisherAgreement); } catch (ErrorResultException e) { logger.error("Failed to get public profile", e); } @@ -288,7 +291,7 @@ public PublisherAgreement getPublisherAgreement(UserData user) { var urlTemplate = eclipseApiUrl + "openvsx/publisher_agreement/{personId}"; var uriVariables = Map.of("personId", personId); var headers = new HttpHeaders(); - headers.setBearerAuth(eclipseToken.accessToken); + headers.setBearerAuth(eclipseToken.accessToken()); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); var request = new HttpEntity<>(headers); @@ -321,7 +324,7 @@ public PublisherAgreement signPublisherAgreement(UserData user) { var eclipseToken = checkEclipseToken(user); var headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); - headers.setBearerAuth(eclipseToken.accessToken); + headers.setBearerAuth(eclipseToken.accessToken()); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); var data = new SignAgreementParam(publisherAgreementVersion, user.getLoginName()); var request = new HttpEntity<>(data, headers); @@ -385,12 +388,13 @@ private PublisherAgreement parseAgreementResponse(ResponseEntity respons agreementResponse = objectMapper.readValue(json, PublisherAgreementResponse.class); } - var agreement = new PublisherAgreement(); - agreement.documentId = agreementResponse.documentID; - agreement.version = agreementResponse.version; - agreement.timestamp = parseDate(agreementResponse.effectiveDate); - agreement.isActive = TimeUtil.getCurrentUTC().isAfter(agreement.timestamp); - return agreement; + var timestamp = parseDate(agreementResponse.effectiveDate); + return new PublisherAgreement( + TimeUtil.getCurrentUTC().isAfter(timestamp), + agreementResponse.documentID, + agreementResponse.version, + timestamp + ); } catch (JsonProcessingException exc) { logger.error("Failed to parse JSON response (" + response.getStatusCode() + "):\n" + json, exc); throw new ErrorResultException("Parsing publisher agreement response failed: " + exc.getMessage(), @@ -418,7 +422,7 @@ public void revokePublisherAgreement(UserData user, UserData admin) { var eclipseToken = admin == null ? checkEclipseToken(user) : checkEclipseToken(admin); var headers = new HttpHeaders(); - headers.setBearerAuth(eclipseToken.accessToken); + headers.setBearerAuth(eclipseToken.accessToken()); var request = new HttpEntity<>(headers); var urlTemplate = eclipseApiUrl + "openvsx/publisher_agreement/{personId}"; var uriVariables = Map.of("personId", user.getEclipsePersonId()); @@ -442,7 +446,7 @@ private void checkApiUrl() { private AuthToken checkEclipseToken(UserData user) { var eclipseToken = tokens.getActiveToken(user, "eclipse"); - if (eclipseToken == null || StringUtils.isEmpty(eclipseToken.accessToken)) { + if (eclipseToken == null || StringUtils.isEmpty(eclipseToken.accessToken())) { throw new ErrorResultException("Authorization by Eclipse required.", HttpStatus.FORBIDDEN); } return eclipseToken; diff --git a/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreement.java b/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreement.java index 7ec4f2c74..757b5eb0a 100644 --- a/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreement.java +++ b/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreement.java @@ -12,31 +12,11 @@ import java.time.LocalDateTime; import java.util.Objects; -public class PublisherAgreement { - - public boolean isActive; - - public String documentId; - - /** Version of the last signed publisher agreement. */ - public String version; - - /** Timestamp of the last signed publisher agreement. */ - public LocalDateTime timestamp; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PublisherAgreement that = (PublisherAgreement) o; - return isActive == that.isActive - && Objects.equals(documentId, that.documentId) - && Objects.equals(version, that.version) - && Objects.equals(timestamp, that.timestamp); - } - - @Override - public int hashCode() { - return Objects.hash(isActive, documentId, version, timestamp); - } -} +/** + * + * @param isActive + * @param documentId + * @param version Version of the last signed publisher agreement. + * @param timestamp Timestamp of the last signed publisher agreement. + */ +public record PublisherAgreement(boolean isActive, String documentId, String version, LocalDateTime timestamp) {} diff --git a/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreementResponse.java b/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreementResponse.java index 876f2023b..29469e3b4 100644 --- a/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreementResponse.java +++ b/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherAgreementResponse.java @@ -14,7 +14,7 @@ /** * https://eclipsefdn.github.io/openvsx-publisher-agreement-specs/#/paths/~1publisher_agreement/post */ -public class PublisherAgreementResponse { +class PublisherAgreementResponse { /** Unique identifier for an addressable object in the API. */ @JsonProperty("PersonID") diff --git a/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherComplianceChecker.java b/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherComplianceChecker.java index 5432b2f23..fdaa25676 100644 --- a/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherComplianceChecker.java +++ b/server/src/main/java/org/eclipse/openvsx/eclipse/PublisherComplianceChecker.java @@ -26,6 +26,7 @@ import java.util.LinkedHashSet; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @Component @@ -87,9 +88,11 @@ private boolean isCompliant(UserData user) { } var profile = eclipseService.getPublicProfile(user.getEclipsePersonId()); - return profile.publisherAgreements != null - && profile.publisherAgreements.openVsx != null - && profile.publisherAgreements.openVsx.version != null; + return Optional.of(profile) + .map(EclipseProfile::getPublisherAgreements) + .map(EclipseProfile.PublisherAgreements::getOpenVsx) + .map(EclipseProfile.PublisherAgreement::getVersion) + .isPresent(); } private void deactivateExtensions(List accessTokens) { diff --git a/server/src/main/java/org/eclipse/openvsx/eclipse/SignAgreementParam.java b/server/src/main/java/org/eclipse/openvsx/eclipse/SignAgreementParam.java index 60479e48c..9505c0cf3 100644 --- a/server/src/main/java/org/eclipse/openvsx/eclipse/SignAgreementParam.java +++ b/server/src/main/java/org/eclipse/openvsx/eclipse/SignAgreementParam.java @@ -19,21 +19,35 @@ public class SignAgreementParam { /** * The version number of the document/agreement. */ - public String version; + private String version; /** * The GitHub username of the user. This must match what the Eclipse Foundation has on file * for the user to successfully sign the publisher agreement. */ @JsonProperty("github_handle") - public String githubHandle; + private String githubHandle; - public SignAgreementParam() { - } + public SignAgreementParam() {} public SignAgreementParam(String version, String githubHandle) { this.version = version; this.githubHandle = githubHandle; } + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getGithubHandle() { + return githubHandle; + } + + public void setGithubHandle(String githubHandle) { + this.githubHandle = githubHandle; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/entities/AdminStatistics.java b/server/src/main/java/org/eclipse/openvsx/entities/AdminStatistics.java index 13e5872a2..73a426bfb 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/AdminStatistics.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/AdminStatistics.java @@ -111,20 +111,20 @@ private void topMapToCsv(List headers, List values, Map mapExtensionsByRating() { return extensionsByRating.entrySet().stream() .map(entry -> { var mapping = new AdminStatisticsJson.ExtensionsByRating(); - mapping.rating = entry.getKey(); - mapping.extensions = entry.getValue(); + mapping.setRating(entry.getKey()); + mapping.setExtensions(entry.getValue()); return mapping; }) - .sorted(Comparator.comparingInt(er -> er.rating).reversed()) + .sorted(Comparator.comparingInt(er -> er.getRating()).reversed()) .collect(Collectors.toList()); } @@ -145,11 +145,11 @@ private List mapPublishersB return publishersByExtensionsPublished.entrySet().stream() .map(entry -> { var mapping = new AdminStatisticsJson.PublishersByExtensionsPublished(); - mapping.extensionsPublished = entry.getKey(); - mapping.publishers = entry.getValue(); + mapping.setExtensionsPublished(entry.getKey()); + mapping.setPublishers(entry.getValue()); return mapping; }) - .sorted(Comparator.comparingInt(pe -> pe.extensionsPublished).reversed()) + .sorted(Comparator.comparingInt(pe -> pe.getExtensionsPublished()).reversed()) .collect(Collectors.toList()); } @@ -157,11 +157,11 @@ private List mapTopMostActiveP return topMostActivePublishingUsers.entrySet().stream() .map(entry -> { var mapping = new AdminStatisticsJson.TopMostActivePublishingUsers(); - mapping.userLoginName = entry.getKey(); - mapping.publishedExtensionVersions = entry.getValue(); + mapping.setUserLoginName(entry.getKey()); + mapping.setPublishedExtensionVersions(entry.getValue()); return mapping; }) - .sorted(Comparator.comparingInt(pe -> pe.publishedExtensionVersions).reversed()) + .sorted(Comparator.comparingInt(pe -> pe.getPublishedExtensionVersions()).reversed()) .collect(Collectors.toList()); } @@ -169,28 +169,23 @@ private List mapTopNamespaceExtensio return topNamespaceExtensions.entrySet().stream() .map(entry -> { var mapping = new AdminStatisticsJson.TopNamespaceExtensions(); - mapping.namespace = entry.getKey(); - mapping.extensions = entry.getValue(); + mapping.setNamespace(entry.getKey()); + mapping.setExtensions(entry.getValue()); return mapping; }) - .sorted(Comparator.comparingInt(pe -> pe.extensions).reversed()) + .sorted(Comparator.comparingInt(pe -> pe.getExtensions()).reversed()) .collect(Collectors.toList()); } - public static class TopNamespaceExtensionVersions { - public String namespace; - - public int extensionVersions; - } private List mapTopNamespaceExtensionVersions() { return topNamespaceExtensionVersions.entrySet().stream() .map(entry -> { var mapping = new AdminStatisticsJson.TopNamespaceExtensionVersions(); - mapping.namespace = entry.getKey(); - mapping.extensionVersions = entry.getValue(); + mapping.setNamespace(entry.getKey()); + mapping.setExtensionVersions(entry.getValue()); return mapping; }) - .sorted(Comparator.comparingInt(pe -> pe.extensionVersions).reversed()) + .sorted(Comparator.comparingInt(pe -> pe.getExtensionVersions()).reversed()) .collect(Collectors.toList()); } @@ -198,11 +193,11 @@ private List mapTopMostDownload return topMostDownloadedExtensions.entrySet().stream() .map(entry -> { var mapping = new AdminStatisticsJson.TopMostDownloadedExtensions(); - mapping.extensionIdentifier = entry.getKey(); - mapping.downloads = entry.getValue(); + mapping.setExtensionIdentifier(entry.getKey()); + mapping.setDownloads(entry.getValue()); return mapping; }) - .sorted(Comparator.comparingLong(pe -> pe.downloads).reversed()) + .sorted(Comparator.comparingLong(pe -> pe.getDownloads()).reversed()) .collect(Collectors.toList()); } diff --git a/server/src/main/java/org/eclipse/openvsx/entities/AuthToken.java b/server/src/main/java/org/eclipse/openvsx/entities/AuthToken.java index 77f0a8bc9..032a9c5a9 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/AuthToken.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/AuthToken.java @@ -18,19 +18,14 @@ * This class is not mapped to a database entity, but parsed / serialized to * JSON via a column converter. */ -public class AuthToken implements Serializable { - - public String accessToken; - - public Instant issuedAt; - - public Instant expiresAt; - - public Set scopes; - - public String refreshToken; - - public Instant refreshExpiresAt; +public record AuthToken( + String accessToken, + Instant issuedAt, + Instant expiresAt, + Set scopes, + String refreshToken, + Instant refreshExpiresAt +) implements Serializable { @Override public boolean equals(Object o) { diff --git a/server/src/main/java/org/eclipse/openvsx/entities/Extension.java b/server/src/main/java/org/eclipse/openvsx/entities/Extension.java index 5a6fbc47b..38f91543f 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/Extension.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/Extension.java @@ -67,17 +67,17 @@ public class Extension implements Serializable { */ public ExtensionSearch toSearch(ExtensionVersion latest, List targetPlatforms) { var search = new ExtensionSearch(); - search.id = this.getId(); - search.name = this.getName(); - search.namespace = this.getNamespace().getName(); - search.extensionId = NamingUtil.toExtensionId(search); - search.downloadCount = this.getDownloadCount(); - search.targetPlatforms = targetPlatforms; - search.displayName = latest.getDisplayName(); - search.description = latest.getDescription(); - search.timestamp = latest.getTimestamp().toEpochSecond(ZoneOffset.UTC); - search.categories = latest.getCategories(); - search.tags = latest.getTags(); + search.setId(this.getId()); + search.setName(this.getName()); + search.setNamespace(this.getNamespace().getName()); + search.setExtensionId(NamingUtil.toExtensionId(search)); + search.setDownloadCount(this.getDownloadCount()); + search.setTargetPlatforms(targetPlatforms); + search.setDisplayName(latest.getDisplayName()); + search.setDescription(latest.getDescription()); + search.setTimestamp(latest.getTimestamp().toEpochSecond(ZoneOffset.UTC)); + search.setCategories(latest.getCategories()); + search.setTags(latest.getTags()); return search; } diff --git a/server/src/main/java/org/eclipse/openvsx/entities/ExtensionReview.java b/server/src/main/java/org/eclipse/openvsx/entities/ExtensionReview.java index 989c876aa..3e21966f2 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/ExtensionReview.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/ExtensionReview.java @@ -47,11 +47,11 @@ public class ExtensionReview { */ public ReviewJson toReviewJson() { var json = new ReviewJson(); - json.timestamp = TimeUtil.toUTCString(this.getTimestamp()); - json.user = this.getUser().toUserJson(); - json.title = this.getTitle(); - json.comment = this.getComment(); - json.rating = this.getRating(); + json.setTimestamp(TimeUtil.toUTCString(this.getTimestamp())); + json.setUser(this.getUser().toUserJson()); + json.setTitle(this.getTitle()); + json.setComment(this.getComment()); + json.setRating(this.getRating()); return json; } diff --git a/server/src/main/java/org/eclipse/openvsx/entities/ExtensionVersion.java b/server/src/main/java/org/eclipse/openvsx/entities/ExtensionVersion.java index 8160ff52d..e9827715b 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/ExtensionVersion.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/ExtensionVersion.java @@ -142,48 +142,48 @@ public enum Type { */ public ExtensionJson toExtensionJson() { var json = new ExtensionJson(); - json.targetPlatform = this.getTargetPlatform(); + json.setTargetPlatform(this.getTargetPlatform()); var namespace = extension.getNamespace(); - json.namespace = namespace.getName(); - json.namespaceDisplayName = StringUtils.isNotEmpty(namespace.getDisplayName()) + json.setNamespace(namespace.getName()); + json.setNamespaceDisplayName(StringUtils.isNotEmpty(namespace.getDisplayName()) ? namespace.getDisplayName() - : json.namespace; - json.name = extension.getName(); - json.averageRating = extension.getAverageRating(); - json.downloadCount = extension.getDownloadCount(); - json.version = this.getVersion(); - json.preRelease = this.isPreRelease(); + : json.getNamespace()); + json.setName(extension.getName()); + json.setAverageRating(extension.getAverageRating()); + json.setDownloadCount(extension.getDownloadCount()); + json.setVersion(this.getVersion()); + json.setPreRelease(this.isPreRelease()); if (this.getTimestamp() != null) { - json.timestamp = TimeUtil.toUTCString(this.getTimestamp()); + json.setTimestamp(TimeUtil.toUTCString(this.getTimestamp())); } - json.displayName = this.getDisplayName(); - json.description = this.getDescription(); - json.engines = this.getEnginesMap(); - json.categories = this.getCategories(); - json.extensionKind = this.getExtensionKind(); - json.tags = this.getTags(); - json.license = this.getLicense(); - json.homepage = this.getHomepage(); - json.repository = this.getRepository(); - json.sponsorLink = this.getSponsorLink(); - json.bugs = this.getBugs(); - json.markdown = this.getMarkdown(); - json.galleryColor = this.getGalleryColor(); - json.galleryTheme = this.getGalleryTheme(); - json.localizedLanguages = this.getLocalizedLanguages(); - json.qna = this.getQna(); + json.setDisplayName(this.getDisplayName()); + json.setDescription(this.getDescription()); + json.setEngines(this.getEnginesMap()); + json.setCategories(this.getCategories()); + json.setExtensionKind(this.getExtensionKind()); + json.setTags(this.getTags()); + json.setLicense(this.getLicense()); + json.setHomepage(this.getHomepage()); + json.setRepository(this.getRepository()); + json.setSponsorLink(this.getSponsorLink()); + json.setBugs(this.getBugs()); + json.setMarkdown(this.getMarkdown()); + json.setGalleryColor(this.getGalleryColor()); + json.setGalleryTheme(this.getGalleryTheme()); + json.setLocalizedLanguages(this.getLocalizedLanguages()); + json.setQna(this.getQna()); if (this.getPublishedWith() != null) { - json.publishedBy = this.getPublishedWith().getUser().toUserJson(); + json.setPublishedBy(this.getPublishedWith().getUser().toUserJson()); } if (this.getDependencies() != null) { - json.dependencies = toExtensionReferenceJson(this.getDependencies()); + json.setDependencies(toExtensionReferenceJson(this.getDependencies())); } if (this.getBundledExtensions() != null) { - json.bundledExtensions = toExtensionReferenceJson(this.getBundledExtensions()); + json.setBundledExtensions(toExtensionReferenceJson(this.getBundledExtensions())); } - json.deprecated = extension.isDeprecated(); - json.downloadable = extension.isDownloadable(); + json.setDeprecated(extension.isDeprecated()); + json.setDownloadable(extension.isDownloadable()); return json; } @@ -195,8 +195,8 @@ private List toExtensionReferenceJson(List exten return null; } var ref = new ExtensionReferenceJson(); - ref.namespace = fqn.substring(0, startIndex); - ref.extension = fqn.substring(startIndex + 1); + ref.setNamespace(fqn.substring(0, startIndex)); + ref.setExtension(fqn.substring(startIndex + 1)); return ref; }).filter(Objects::nonNull).collect(Collectors.toList()); } @@ -207,16 +207,16 @@ private List toExtensionReferenceJson(List exten public SearchEntryJson toSearchEntryJson() { var entry = new SearchEntryJson(); var extension = this.getExtension(); - entry.name = extension.getName(); - entry.namespace = extension.getNamespace().getName(); - entry.averageRating = extension.getAverageRating(); - entry.reviewCount = extension.getReviewCount(); - entry.downloadCount = extension.getDownloadCount(); - entry.version = this.getVersion(); - entry.timestamp = TimeUtil.toUTCString(this.getTimestamp()); - entry.displayName = this.getDisplayName(); - entry.description = this.getDescription(); - entry.deprecated = extension.isDeprecated(); + entry.setName(extension.getName()); + entry.setNamespace(extension.getNamespace().getName()); + entry.setAverageRating(extension.getAverageRating()); + entry.setReviewCount(extension.getReviewCount()); + entry.setDownloadCount(extension.getDownloadCount()); + entry.setVersion(this.getVersion()); + entry.setTimestamp(TimeUtil.toUTCString(this.getTimestamp())); + entry.setDisplayName(this.getDisplayName()); + entry.setDescription(this.getDescription()); + entry.setDeprecated(extension.isDeprecated()); return entry; } diff --git a/server/src/main/java/org/eclipse/openvsx/entities/Namespace.java b/server/src/main/java/org/eclipse/openvsx/entities/Namespace.java index b13803226..7a733eb4a 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/Namespace.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/Namespace.java @@ -178,16 +178,16 @@ public void setMemberships(List memberships) { public NamespaceDetailsJson toNamespaceDetailsJson() { var details = new NamespaceDetailsJson(); - details.name = name; - details.displayName = StringUtils.isNotEmpty(displayName) ? displayName : name; - details.description = description; - details.website = website; - details.supportLink = supportLink; - details.socialLinks = Map.of( + details.setName(name); + details.setDisplayName(StringUtils.isNotEmpty(displayName) ? displayName : name); + details.setDescription(description); + details.setWebsite(website); + details.setSupportLink(supportLink); + details.setSocialLinks(Map.of( SL_LINKEDIN, socialLinks.getOrDefault(SL_LINKEDIN, ""), SL_GITHUB, socialLinks.getOrDefault(SL_GITHUB, ""), SL_TWITTER, socialLinks.getOrDefault(SL_TWITTER, "") - ); + )); return details; } diff --git a/server/src/main/java/org/eclipse/openvsx/entities/NamespaceMembership.java b/server/src/main/java/org/eclipse/openvsx/entities/NamespaceMembership.java index f4a4d4d93..75262a84f 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/NamespaceMembership.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/NamespaceMembership.java @@ -39,11 +39,11 @@ public class NamespaceMembership implements Serializable { String role; public NamespaceMembershipJson toJson() { - var json = new NamespaceMembershipJson(); - json.namespace = this.namespace.name; - json.role = this.role; - json.user = this.user.toUserJson(); - return json; + return new NamespaceMembershipJson( + this.namespace.name, + this.role, + this.user.toUserJson() + ); } public long getId() { diff --git a/server/src/main/java/org/eclipse/openvsx/entities/PersonalAccessToken.java b/server/src/main/java/org/eclipse/openvsx/entities/PersonalAccessToken.java index 092975303..3375b0fdb 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/PersonalAccessToken.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/PersonalAccessToken.java @@ -53,13 +53,13 @@ public class PersonalAccessToken implements Serializable { */ public AccessTokenJson toAccessTokenJson() { var json = new AccessTokenJson(); - json.id = this.getId(); + json.setId(this.getId()); // The value is not included: it is displayed only when the token is created if (this.getCreatedTimestamp() != null) - json.createdTimestamp = TimeUtil.toUTCString(this.getCreatedTimestamp()); + json.setCreatedTimestamp(TimeUtil.toUTCString(this.getCreatedTimestamp())); if (this.getAccessedTimestamp() != null) - json.accessedTimestamp = TimeUtil.toUTCString(this.getAccessedTimestamp()); - json.description = this.getDescription(); + json.setAccessedTimestamp(TimeUtil.toUTCString(this.getAccessedTimestamp())); + json.setDescription(this.getDescription()); return json; } diff --git a/server/src/main/java/org/eclipse/openvsx/entities/SemanticVersion.java b/server/src/main/java/org/eclipse/openvsx/entities/SemanticVersion.java index 030b0b0da..bcfb77c23 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/SemanticVersion.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/SemanticVersion.java @@ -44,12 +44,12 @@ public static SemanticVersion parse(String version) { } } - int major; - int minor; - int patch; - String preRelease; - boolean isPreRelease; - String buildMetadata; + private int major; + private int minor; + private int patch; + private String preRelease; + private boolean isPreRelease; + private String buildMetadata; public int getMajor() { return major; diff --git a/server/src/main/java/org/eclipse/openvsx/entities/UserData.java b/server/src/main/java/org/eclipse/openvsx/entities/UserData.java index 87d091560..81439e1a1 100644 --- a/server/src/main/java/org/eclipse/openvsx/entities/UserData.java +++ b/server/src/main/java/org/eclipse/openvsx/entities/UserData.java @@ -68,11 +68,11 @@ public class UserData implements Serializable { */ public UserJson toUserJson() { var json = new UserJson(); - json.loginName = this.getLoginName(); - json.fullName = this.getFullName(); - json.avatarUrl = this.getAvatarUrl(); - json.homepage = this.getProviderUrl(); - json.provider = this.getProvider(); + json.setLoginName(this.getLoginName()); + json.setFullName(this.getFullName()); + json.setAvatarUrl(this.getAvatarUrl()); + json.setHomepage(this.getProviderUrl()); + json.setProvider(this.getProvider()); return json; } diff --git a/server/src/main/java/org/eclipse/openvsx/json/AccessTokenJson.java b/server/src/main/java/org/eclipse/openvsx/json/AccessTokenJson.java index 79b28381e..50834f4e8 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/AccessTokenJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/AccessTokenJson.java @@ -19,22 +19,71 @@ public class AccessTokenJson extends ResultJson { public static AccessTokenJson error(String message) { var result = new AccessTokenJson(); - result.error = message; + result.setError(message); return result; } - public Long id; + private Long id; @Nullable - public String value; + private String value; - public String createdTimestamp; + private String createdTimestamp; @Nullable - public String accessedTimestamp; + private String accessedTimestamp; - public String description; + private String description; - public String deleteTokenUrl; + private String deleteTokenUrl; + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Nullable + public String getValue() { + return value; + } + + public void setValue(@Nullable String value) { + this.value = value; + } + + public String getCreatedTimestamp() { + return createdTimestamp; + } + + public void setCreatedTimestamp(String createdTimestamp) { + this.createdTimestamp = createdTimestamp; + } + + @Nullable + public String getAccessedTimestamp() { + return accessedTimestamp; + } + + public void setAccessedTimestamp(@Nullable String accessedTimestamp) { + this.accessedTimestamp = accessedTimestamp; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDeleteTokenUrl() { + return deleteTokenUrl; + } + + public void setDeleteTokenUrl(String deleteTokenUrl) { + this.deleteTokenUrl = deleteTokenUrl; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/AdminStatisticsJson.java b/server/src/main/java/org/eclipse/openvsx/json/AdminStatisticsJson.java index 4bfc3dd83..8fdbd1635 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/AdminStatisticsJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/AdminStatisticsJson.java @@ -18,71 +18,279 @@ public class AdminStatisticsJson extends ResultJson { public static AdminStatisticsJson error(String message) { var result = new AdminStatisticsJson(); - result.error = message; + result.setError(message); return result; } - public int year; + private int year; - public int month; + private int month; - public long extensions; + private long extensions; - public long downloads; + private long downloads; - public long downloadsTotal; + private long downloadsTotal; - public long publishers; + private long publishers; - public double averageReviewsPerExtension; + private double averageReviewsPerExtension; - public long namespaceOwners; + private long namespaceOwners; - public List extensionsByRating; + private List extensionsByRating; - public List publishersByExtensionsPublished; + private List publishersByExtensionsPublished; - public List topMostActivePublishingUsers; + private List topMostActivePublishingUsers; - public List topNamespaceExtensions; + private List topNamespaceExtensions; - public List topNamespaceExtensionVersions; + private List topNamespaceExtensionVersions; - public List topMostDownloadedExtensions; + private List topMostDownloadedExtensions; + + public int getYear() { + return year; + } + + public void setYear(int year) { + this.year = year; + } + + public int getMonth() { + return month; + } + + public void setMonth(int month) { + this.month = month; + } + + public long getExtensions() { + return extensions; + } + + public void setExtensions(long extensions) { + this.extensions = extensions; + } + + public long getDownloads() { + return downloads; + } + + public void setDownloads(long downloads) { + this.downloads = downloads; + } + + public long getDownloadsTotal() { + return downloadsTotal; + } + + public void setDownloadsTotal(long downloadsTotal) { + this.downloadsTotal = downloadsTotal; + } + + public long getPublishers() { + return publishers; + } + + public void setPublishers(long publishers) { + this.publishers = publishers; + } + + public double getAverageReviewsPerExtension() { + return averageReviewsPerExtension; + } + + public void setAverageReviewsPerExtension(double averageReviewsPerExtension) { + this.averageReviewsPerExtension = averageReviewsPerExtension; + } + + public long getNamespaceOwners() { + return namespaceOwners; + } + + public void setNamespaceOwners(long namespaceOwners) { + this.namespaceOwners = namespaceOwners; + } + + public List getExtensionsByRating() { + return extensionsByRating; + } + + public void setExtensionsByRating(List extensionsByRating) { + this.extensionsByRating = extensionsByRating; + } + + public List getPublishersByExtensionsPublished() { + return publishersByExtensionsPublished; + } + + public void setPublishersByExtensionsPublished(List publishersByExtensionsPublished) { + this.publishersByExtensionsPublished = publishersByExtensionsPublished; + } + + public List getTopMostActivePublishingUsers() { + return topMostActivePublishingUsers; + } + + public void setTopMostActivePublishingUsers(List topMostActivePublishingUsers) { + this.topMostActivePublishingUsers = topMostActivePublishingUsers; + } + + public List getTopNamespaceExtensions() { + return topNamespaceExtensions; + } + + public void setTopNamespaceExtensions(List topNamespaceExtensions) { + this.topNamespaceExtensions = topNamespaceExtensions; + } + + public List getTopNamespaceExtensionVersions() { + return topNamespaceExtensionVersions; + } + + public void setTopNamespaceExtensionVersions(List topNamespaceExtensionVersions) { + this.topNamespaceExtensionVersions = topNamespaceExtensionVersions; + } + + public List getTopMostDownloadedExtensions() { + return topMostDownloadedExtensions; + } + + public void setTopMostDownloadedExtensions(List topMostDownloadedExtensions) { + this.topMostDownloadedExtensions = topMostDownloadedExtensions; + } public static class ExtensionsByRating { - public int rating; + private int rating; + + private int extensions; + + public int getRating() { + return rating; + } + + public void setRating(int rating) { + this.rating = rating; + } + + public int getExtensions() { + return extensions; + } - public int extensions; + public void setExtensions(int extensions) { + this.extensions = extensions; + } } public static class PublishersByExtensionsPublished { - public int extensionsPublished; + private int extensionsPublished; - public int publishers; + private int publishers; + + public int getExtensionsPublished() { + return extensionsPublished; + } + + public void setExtensionsPublished(int extensionsPublished) { + this.extensionsPublished = extensionsPublished; + } + + public int getPublishers() { + return publishers; + } + + public void setPublishers(int publishers) { + this.publishers = publishers; + } } public static class TopMostActivePublishingUsers { - public String userLoginName; + private String userLoginName; + + private int publishedExtensionVersions; - public int publishedExtensionVersions; + public String getUserLoginName() { + return userLoginName; + } + + public void setUserLoginName(String userLoginName) { + this.userLoginName = userLoginName; + } + + public int getPublishedExtensionVersions() { + return publishedExtensionVersions; + } + + public void setPublishedExtensionVersions(int publishedExtensionVersions) { + this.publishedExtensionVersions = publishedExtensionVersions; + } } public static class TopNamespaceExtensions { - public String namespace; + private String namespace; + + private int extensions; + + public String getNamespace() { + return namespace; + } - public int extensions; + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public int getExtensions() { + return extensions; + } + + public void setExtensions(int extensions) { + this.extensions = extensions; + } } public static class TopNamespaceExtensionVersions { - public String namespace; + private String namespace; + + private int extensionVersions; + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } - public int extensionVersions; + public int getExtensionVersions() { + return extensionVersions; + } + + public void setExtensionVersions(int extensionVersions) { + this.extensionVersions = extensionVersions; + } } public static class TopMostDownloadedExtensions { - public String extensionIdentifier; + private String extensionIdentifier; + + private long downloads; + + public String getExtensionIdentifier() { + return extensionIdentifier; + } + + public void setExtensionIdentifier(String extensionIdentifier) { + this.extensionIdentifier = extensionIdentifier; + } + + public long getDownloads() { + return downloads; + } - public long downloads; + public void setDownloads(long downloads) { + this.downloads = downloads; + } } } diff --git a/server/src/main/java/org/eclipse/openvsx/json/BadgeJson.java b/server/src/main/java/org/eclipse/openvsx/json/BadgeJson.java index 41befca2d..cbd905b04 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/BadgeJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/BadgeJson.java @@ -24,12 +24,36 @@ public class BadgeJson implements Serializable { @Schema(description = "Image URL of the badge") - public String url; + private String url; @Schema(description = "The link users will follow when clicking the badge") - public String href; + private String href; - public String description; + private String description; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } @Override public boolean equals(Object o) { diff --git a/server/src/main/java/org/eclipse/openvsx/json/ChangeNamespaceJson.java b/server/src/main/java/org/eclipse/openvsx/json/ChangeNamespaceJson.java index 6823a5a36..8ae93531a 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ChangeNamespaceJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ChangeNamespaceJson.java @@ -17,22 +17,9 @@ * Used to change a namespace */ @JsonInclude(JsonInclude.Include.NON_NULL) -public class ChangeNamespaceJson { - public String oldNamespace; - public String newNamespace; - public boolean removeOldNamespace; - public boolean mergeIfNewNamespaceAlreadyExists; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ChangeNamespaceJson that = (ChangeNamespaceJson) o; - return removeOldNamespace == that.removeOldNamespace && mergeIfNewNamespaceAlreadyExists == that.mergeIfNewNamespaceAlreadyExists && Objects.equals(oldNamespace, that.oldNamespace) && Objects.equals(newNamespace, that.newNamespace); - } - - @Override - public int hashCode() { - return Objects.hash(oldNamespace, newNamespace, removeOldNamespace, mergeIfNewNamespaceAlreadyExists); - } -} +public record ChangeNamespaceJson( + String oldNamespace, + String newNamespace, + boolean removeOldNamespace, + boolean mergeIfNewNamespaceAlreadyExists +) {} diff --git a/server/src/main/java/org/eclipse/openvsx/json/CsrfTokenJson.java b/server/src/main/java/org/eclipse/openvsx/json/CsrfTokenJson.java index 6e829d87d..143ed249d 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/CsrfTokenJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/CsrfTokenJson.java @@ -20,12 +20,34 @@ public class CsrfTokenJson extends ResultJson { public static CsrfTokenJson error(String message) { var info = new CsrfTokenJson(); - info.error = message; + info.setError(message); return info; } - public String value; + public CsrfTokenJson() {} - public String header; + public CsrfTokenJson(String value, String header) { + this.value = value; + this.header = header; + } + + private String value; + + private String header; + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + + public String getHeader() { + return header; + } + + public void setHeader(String header) { + this.header = header; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/ErrorJson.java b/server/src/main/java/org/eclipse/openvsx/json/ErrorJson.java index 984b8e3bf..82e1cd571 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ErrorJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ErrorJson.java @@ -14,13 +14,8 @@ /** * Used to describe an error situation as JSON response. + * @param message Error message + * @param code Error code, see constants in {@link org.eclipse.openvsx.security.CodedAuthException}. */ @JsonInclude(Include.NON_NULL) -public class ErrorJson { - - public String message; - - /** See constants in {@link org.eclipse.openvsx.security.CodedAuthException}. */ - public String code; - -} \ No newline at end of file +public record ErrorJson(String message, String code) {} \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/ExtensionJson.java b/server/src/main/java/org/eclipse/openvsx/json/ExtensionJson.java index ba4abb6db..eb5ebf4ef 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ExtensionJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ExtensionJson.java @@ -32,165 +32,541 @@ public class ExtensionJson extends ResultJson implements Serializable { public static ExtensionJson error(String message) { var info = new ExtensionJson(); - info.error = message; + info.setError(message); return info; } @Schema(description = "URL to get metadata of the extension's namespace") @NotNull - public String namespaceUrl; + private String namespaceUrl; @Schema(description = "URL to get the list of reviews of this extension") @NotNull - public String reviewsUrl; + private String reviewsUrl; @Schema(description = "Map of file types (download, manifest, icon, readme, license, changelog) to their respective URLs") - public Map files; + private Map files; @Schema(description = "Name of the extension") @NotNull - public String name; + private String name; @Schema(description = "Namespace of the extension") @NotNull - public String namespace; + private String namespace; @Schema(description = "Name of the target platform") - public String targetPlatform; + private String targetPlatform; @Schema(description = "Selected version, or the latest version if none was specified") @NotNull - public String version; + private String version; @Schema(description = "Indicates whether this is a pre-release version") - public Boolean preRelease; + private Boolean preRelease; @Schema(description = "Data of the user who published this version") @NotNull - public UserJson publishedBy; + private UserJson publishedBy; @Schema(hidden = true) - public Boolean active; + private Boolean active; @Schema(description = "The value 'true' means the publishing user is a privileged user or the publishing user is a member of the extension's namespace and the namespace has at least one owner.") @NotNull - public Boolean verified; + private Boolean verified; @Schema(description = "Deprecated: use 'verified' instead (this property is just the negation of 'verified')") @NotNull @Deprecated - public Boolean unrelatedPublisher; + private Boolean unrelatedPublisher; @Schema(description = "Access level of the extension's namespace. Deprecated: namespaces are now always restricted", allowableValues = {"public", "restricted"}) @NotNull @Deprecated - public String namespaceAccess; + private String namespaceAccess; @Schema(description = "Map of available versions to their metadata URLs. Deprecated: only returns the last 100 versions. Use allVersionsUrl instead.") @Deprecated - public Map allVersions; + private Map allVersions; @Schema(description = "URL to get a map of available versions to their metadata URLs.") - public String allVersionsUrl; + private String allVersionsUrl; @Schema(description = "Average rating") @Min(0) @Max(5) - public Double averageRating; + private Double averageRating; @Schema(description = "Number of downloads of the extension package") @Min(0) - public Integer downloadCount; + private Integer downloadCount; @Schema(description = "Number of reviews") @Min(0) - public Long reviewCount; + private Long reviewCount; @Schema(description = "Available version aliases ('latest' or 'pre-release')") - public List versionAlias; + private List versionAlias; @Schema(description = "Date and time when this version was published (ISO-8601)") @NotNull - public String timestamp; + private String timestamp; @Schema(description = "Indicates whether this is a preview extension") - public Boolean preview; + private Boolean preview; @Schema(description = "Name to be displayed in user interfaces") - public String displayName; + private String displayName; @Schema(description = "Namespace name to be displayed in user interfaces") @NotNull - public String namespaceDisplayName; + private String namespaceDisplayName; - public String description; + private String description; @Schema(description = "Map of engine names to the respective version constraints") - public Map engines; + private Map engines; - public List categories; + private List categories; @Schema(description = "A list that indicates where the extension should run in remote configurations. Values are \"ui\" (run locally), \"workspace\" (run on remote machine) and \"web\"") - public List extensionKind; + private List extensionKind; - public List tags; + private List tags; @Schema(description = "License identifier") - public String license; + private String license; @Schema(description = "URL of the extension's homepage") - public String homepage; + private String homepage; @Schema(description = "URL of the extension's source repository") - public String repository; + private String repository; @Schema(description = "URL to sponsor the extension") - public String sponsorLink; + private String sponsorLink; @Schema(description = "URL of the extension's bug tracker") - public String bugs; + private String bugs; @Schema(description = "Markdown rendering engine to use in user interfaces", allowableValues = {"standard", "github"}) - public String markdown; + private String markdown; @Schema(description = "CSS color to use as background in user interfaces") - public String galleryColor; + private String galleryColor; @Schema(description = "Theme type for user interfaces", allowableValues = {"light", "dark"}) - public String galleryTheme; + private String galleryTheme; @Schema(description = "Languages the extension has been translated in") - public List localizedLanguages; + private List localizedLanguages; @Schema(description = "URL of the extension's Q&A page") - public String qna; + private String qna; @Schema(description = "List of badges to display in user interfaces") - public List badges; + private List badges; @Schema(description = "List of dependencies to other extensions") - public List dependencies; + private List dependencies; @Schema(description = "List of extensions bundled with this extension") - public List bundledExtensions; + private List bundledExtensions; @Schema(description = "Map of download links by target platform") - public Map downloads; + private Map downloads; @Schema(description = "Map of target platforms by extension version") - public List allTargetPlatformVersions; + private List allTargetPlatformVersions; @Schema(description = "version metadata URL") - public String url; + private String url; @Schema(description = "Indicates whether the extension is deprecated") - public boolean deprecated; + private boolean deprecated; @Schema(description = "Reference to extension that replaces this extension when it's deprecated") - public ExtensionReplacementJson replacement; + private ExtensionReplacementJson replacement; @Schema(description = "Whether to show downloads in user interfaces") - public boolean downloadable; + private boolean downloadable; + + public String getNamespaceUrl() { + return namespaceUrl; + } + + public void setNamespaceUrl(String namespaceUrl) { + this.namespaceUrl = namespaceUrl; + } + + public String getReviewsUrl() { + return reviewsUrl; + } + + public void setReviewsUrl(String reviewsUrl) { + this.reviewsUrl = reviewsUrl; + } + + public Map getFiles() { + return files; + } + + public void setFiles(Map files) { + this.files = files; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public String getTargetPlatform() { + return targetPlatform; + } + + public void setTargetPlatform(String targetPlatform) { + this.targetPlatform = targetPlatform; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public Boolean getPreRelease() { + return preRelease; + } + + public void setPreRelease(Boolean preRelease) { + this.preRelease = preRelease; + } + + public UserJson getPublishedBy() { + return publishedBy; + } + + public void setPublishedBy(UserJson publishedBy) { + this.publishedBy = publishedBy; + } + + public Boolean getActive() { + return active; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public Boolean getVerified() { + return verified; + } + + public void setVerified(Boolean verified) { + this.verified = verified; + } + + public Boolean getUnrelatedPublisher() { + return unrelatedPublisher; + } + + public void setUnrelatedPublisher(Boolean unrelatedPublisher) { + this.unrelatedPublisher = unrelatedPublisher; + } + + public String getNamespaceAccess() { + return namespaceAccess; + } + + public void setNamespaceAccess(String namespaceAccess) { + this.namespaceAccess = namespaceAccess; + } + + public Map getAllVersions() { + return allVersions; + } + + public void setAllVersions(Map allVersions) { + this.allVersions = allVersions; + } + + public String getAllVersionsUrl() { + return allVersionsUrl; + } + + public void setAllVersionsUrl(String allVersionsUrl) { + this.allVersionsUrl = allVersionsUrl; + } + + public Double getAverageRating() { + return averageRating; + } + + public void setAverageRating(Double averageRating) { + this.averageRating = averageRating; + } + + public Integer getDownloadCount() { + return downloadCount; + } + + public void setDownloadCount(Integer downloadCount) { + this.downloadCount = downloadCount; + } + + public Long getReviewCount() { + return reviewCount; + } + + public void setReviewCount(Long reviewCount) { + this.reviewCount = reviewCount; + } + + public List getVersionAlias() { + return versionAlias; + } + + public void setVersionAlias(List versionAlias) { + this.versionAlias = versionAlias; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public Boolean getPreview() { + return preview; + } + + public void setPreview(Boolean preview) { + this.preview = preview; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getNamespaceDisplayName() { + return namespaceDisplayName; + } + + public void setNamespaceDisplayName(String namespaceDisplayName) { + this.namespaceDisplayName = namespaceDisplayName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getEngines() { + return engines; + } + + public void setEngines(Map engines) { + this.engines = engines; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + + public List getExtensionKind() { + return extensionKind; + } + + public void setExtensionKind(List extensionKind) { + this.extensionKind = extensionKind; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getLicense() { + return license; + } + + public void setLicense(String license) { + this.license = license; + } + + public String getHomepage() { + return homepage; + } + + public void setHomepage(String homepage) { + this.homepage = homepage; + } + + public String getRepository() { + return repository; + } + + public void setRepository(String repository) { + this.repository = repository; + } + + public String getSponsorLink() { + return sponsorLink; + } + + public void setSponsorLink(String sponsorLink) { + this.sponsorLink = sponsorLink; + } + + public String getBugs() { + return bugs; + } + + public void setBugs(String bugs) { + this.bugs = bugs; + } + + public String getMarkdown() { + return markdown; + } + + public void setMarkdown(String markdown) { + this.markdown = markdown; + } + + public String getGalleryColor() { + return galleryColor; + } + + public void setGalleryColor(String galleryColor) { + this.galleryColor = galleryColor; + } + + public String getGalleryTheme() { + return galleryTheme; + } + + public void setGalleryTheme(String galleryTheme) { + this.galleryTheme = galleryTheme; + } + + public List getLocalizedLanguages() { + return localizedLanguages; + } + + public void setLocalizedLanguages(List localizedLanguages) { + this.localizedLanguages = localizedLanguages; + } + + public String getQna() { + return qna; + } + + public void setQna(String qna) { + this.qna = qna; + } + + public List getBadges() { + return badges; + } + + public void setBadges(List badges) { + this.badges = badges; + } + + public List getDependencies() { + return dependencies; + } + + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + public List getBundledExtensions() { + return bundledExtensions; + } + + public void setBundledExtensions(List bundledExtensions) { + this.bundledExtensions = bundledExtensions; + } + + public Map getDownloads() { + return downloads; + } + + public void setDownloads(Map downloads) { + this.downloads = downloads; + } + + public List getAllTargetPlatformVersions() { + return allTargetPlatformVersions; + } + + public void setAllTargetPlatformVersions(List allTargetPlatformVersions) { + this.allTargetPlatformVersions = allTargetPlatformVersions; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isDeprecated() { + return deprecated; + } + + public void setDeprecated(boolean deprecated) { + this.deprecated = deprecated; + } + + public ExtensionReplacementJson getReplacement() { + return replacement; + } + + public void setReplacement(ExtensionReplacementJson replacement) { + this.replacement = replacement; + } + + public boolean isDownloadable() { + return downloadable; + } + + public void setDownloadable(boolean downloadable) { + this.downloadable = downloadable; + } @Override public boolean equals(Object o) { diff --git a/server/src/main/java/org/eclipse/openvsx/json/ExtensionReferenceJson.java b/server/src/main/java/org/eclipse/openvsx/json/ExtensionReferenceJson.java index 3ed8f915b..27e866a5f 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ExtensionReferenceJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ExtensionReferenceJson.java @@ -27,18 +27,51 @@ public class ExtensionReferenceJson implements Serializable { @Schema(description = "URL to get metadata of the referenced extension") @NotNull - public String url; + private String url; @Schema(description = "Namespace of the referenced extension") @NotNull - public String namespace; + private String namespace; @Schema(description = "Name of the referenced extension") @NotNull - public String extension; + private String extension; @Schema(hidden = true) - public String version; + private String version; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server/src/main/java/org/eclipse/openvsx/json/ExtensionReplacementJson.java b/server/src/main/java/org/eclipse/openvsx/json/ExtensionReplacementJson.java index 606bf16df..b01437054 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ExtensionReplacementJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ExtensionReplacementJson.java @@ -22,8 +22,24 @@ public class ExtensionReplacementJson implements Serializable { @Schema(description = "URL of the extension replacement") - public String url; + private String url; @Schema(description = "Name to be displayed in user interfaces") - public String displayName; + private String displayName; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } } diff --git a/server/src/main/java/org/eclipse/openvsx/json/NamespaceDetailsJson.java b/server/src/main/java/org/eclipse/openvsx/json/NamespaceDetailsJson.java index 26678d7d6..0766ff4ac 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/NamespaceDetailsJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/NamespaceDetailsJson.java @@ -19,42 +19,122 @@ public class NamespaceDetailsJson extends ResultJson implements Serializable { public static NamespaceDetailsJson error(String message) { var result = new NamespaceDetailsJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "Name of the namespace") @NotNull - public String name; + private String name; @Schema(description = "Display name of the namespace") @NotNull - public String displayName; + private String displayName; @Schema(description = "Description of the namespace") - public String description; + private String description; @Schema(description = "Logo URL of the namespace") - public String logo; + private String logo; @Schema(hidden = true) - public byte[] logoBytes; + private byte[] logoBytes; @Schema(description = "Website URL of the namespace") - public String website; + private String website; @Schema(description = "Support URL of the namespace") - public String supportLink; + private String supportLink; @Schema(description = "Map of social network names to their profile URLs") - public Map socialLinks; + private Map socialLinks; @Schema(description = "Map of extension names to their metadata URLs") - public List extensions; + private List extensions; @Schema(description = "Indicates whether the namespace has an owner") @NotNull - public boolean verified; + private boolean verified; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } + + public byte[] getLogoBytes() { + return logoBytes; + } + + public void setLogoBytes(byte[] logoBytes) { + this.logoBytes = logoBytes; + } + + public String getWebsite() { + return website; + } + + public void setWebsite(String website) { + this.website = website; + } + + public String getSupportLink() { + return supportLink; + } + + public void setSupportLink(String supportLink) { + this.supportLink = supportLink; + } + + public Map getSocialLinks() { + return socialLinks; + } + + public void setSocialLinks(Map socialLinks) { + this.socialLinks = socialLinks; + } + + public List getExtensions() { + return extensions; + } + + public void setExtensions(List extensions) { + this.extensions = extensions; + } + + public boolean isVerified() { + return verified; + } + + public void setVerified(boolean verified) { + this.verified = verified; + } @Override public boolean equals(Object o) { diff --git a/server/src/main/java/org/eclipse/openvsx/json/NamespaceJson.java b/server/src/main/java/org/eclipse/openvsx/json/NamespaceJson.java index 7bf14bc00..74f8d036b 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/NamespaceJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/NamespaceJson.java @@ -27,32 +27,79 @@ public class NamespaceJson extends ResultJson { public static NamespaceJson error(String message) { var result = new NamespaceJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "Name of the namespace") @NotNull - public String name; + private String name; @Schema(description = "Map of extension names to their metadata URLs (not required for creating)") - public Map extensions; + private Map extensions; @Schema(description = "Indicates whether the namespace has an owner (not required for creating)") @NotNull - public Boolean verified; + private Boolean verified; @Schema( description = "Access level of the namespace. Deprecated: namespaces are now always restricted", allowableValues = {"public", "restricted"} ) @Deprecated - public String access; + private String access; @Schema(hidden = true) - public String membersUrl; + private String membersUrl; @Schema(hidden = true) - public String roleUrl; + private String roleUrl; + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getExtensions() { + return extensions; + } + + public void setExtensions(Map extensions) { + this.extensions = extensions; + } + + public Boolean getVerified() { + return verified; + } + + public void setVerified(Boolean verified) { + this.verified = verified; + } + + public String getAccess() { + return access; + } + + public void setAccess(String access) { + this.access = access; + } + + public String getMembersUrl() { + return membersUrl; + } + + public void setMembersUrl(String membersUrl) { + this.membersUrl = membersUrl; + } + + public String getRoleUrl() { + return roleUrl; + } + + public void setRoleUrl(String roleUrl) { + this.roleUrl = roleUrl; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipJson.java b/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipJson.java index 908d510fe..2f75fb852 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipJson.java @@ -13,12 +13,8 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;; @JsonInclude(Include.NON_NULL) -public class NamespaceMembershipJson { - - public String namespace; - - public String role; - - public UserJson user; - -} \ No newline at end of file +public record NamespaceMembershipJson( + String namespace, + String role, + UserJson user +) {} \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipListJson.java b/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipListJson.java index 285678d7c..e7d85809d 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipListJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/NamespaceMembershipListJson.java @@ -27,11 +27,19 @@ public class NamespaceMembershipListJson extends ResultJson { public static NamespaceMembershipListJson error(String message) { var result = new NamespaceMembershipListJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "List of memberships") @NotNull - public List namespaceMemberships; + private List namespaceMemberships; + + public List getNamespaceMemberships() { + return namespaceMemberships; + } + + public void setNamespaceMemberships(List namespaceMemberships) { + this.namespaceMemberships = namespaceMemberships; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/QueryParamJson.java b/server/src/main/java/org/eclipse/openvsx/json/QueryParamJson.java index 3b15c6143..9bbb0305b 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/QueryParamJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/QueryParamJson.java @@ -27,25 +27,25 @@ public class QueryParamJson { @Schema(description = "Name of a namespace") - public String namespaceName; + private String namespaceName; @Schema(description = "Name of an extension") - public String extensionName; + private String extensionName; @Schema(description = "Version of an extension") - public String extensionVersion; + private String extensionVersion; @Schema(description = "Identifier in the form {namespace}.{extension}") - public String extensionId; + private String extensionId; @Schema(description = "Universally unique identifier of an extension") - public String extensionUuid; + private String extensionUuid; @Schema(description = "Universally unique identifier of a namespace") - public String namespaceUuid; + private String namespaceUuid; @Schema(description = "Whether to include all versions of an extension, ignored if extensionVersion is specified") - public boolean includeAllVersions; + private boolean includeAllVersions; @Schema(description = "Name of the target platform", allowableValues = { NAME_WIN32_X64, NAME_WIN32_IA32, NAME_WIN32_ARM64, @@ -54,13 +54,93 @@ public class QueryParamJson { NAME_DARWIN_X64, NAME_DARWIN_ARM64, NAME_WEB, NAME_UNIVERSAL }) - public String targetPlatform; + private String targetPlatform; @Schema(description = "Maximal number of entries to return", minimum = "0", defaultValue = "100") - public Integer size; + private Integer size; @Schema(description = "Number of entries to skip (usually a multiple of the page size)", minimum = "0", defaultValue = "0") - public Integer offset; + private Integer offset; + + public String getNamespaceName() { + return namespaceName; + } + + public void setNamespaceName(String namespaceName) { + this.namespaceName = namespaceName; + } + + public String getExtensionName() { + return extensionName; + } + + public void setExtensionName(String extensionName) { + this.extensionName = extensionName; + } + + public String getExtensionVersion() { + return extensionVersion; + } + + public void setExtensionVersion(String extensionVersion) { + this.extensionVersion = extensionVersion; + } + + public String getExtensionId() { + return extensionId; + } + + public void setExtensionId(String extensionId) { + this.extensionId = extensionId; + } + + public String getExtensionUuid() { + return extensionUuid; + } + + public void setExtensionUuid(String extensionUuid) { + this.extensionUuid = extensionUuid; + } + + public String getNamespaceUuid() { + return namespaceUuid; + } + + public void setNamespaceUuid(String namespaceUuid) { + this.namespaceUuid = namespaceUuid; + } + + public boolean isIncludeAllVersions() { + return includeAllVersions; + } + + public void setIncludeAllVersions(boolean includeAllVersions) { + this.includeAllVersions = includeAllVersions; + } + + public String getTargetPlatform() { + return targetPlatform; + } + + public void setTargetPlatform(String targetPlatform) { + this.targetPlatform = targetPlatform; + } + + public Integer getSize() { + return size; + } + + public void setSize(Integer size) { + this.size = size; + } + + public Integer getOffset() { + return offset; + } + + public void setOffset(Integer offset) { + this.offset = offset; + } public String[] toQueryParams() { var queryParams = new LinkedHashMap(); diff --git a/server/src/main/java/org/eclipse/openvsx/json/QueryRequest.java b/server/src/main/java/org/eclipse/openvsx/json/QueryRequest.java index 6bdd7f910..a83c33ccd 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/QueryRequest.java +++ b/server/src/main/java/org/eclipse/openvsx/json/QueryRequest.java @@ -9,50 +9,15 @@ ********************************************************************************/ package org.eclipse.openvsx.json; -import java.util.Objects; - -public class QueryRequest { - - public String namespaceName; - - public String extensionName; - - public String extensionVersion; - - public String extensionId; - - public String extensionUuid; - - public String namespaceUuid; - - public boolean includeAllVersions; - - public String targetPlatform; - - public int size; - - public int offset; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - QueryRequest that = (QueryRequest) o; - return includeAllVersions == that.includeAllVersions - && size == that.size - && offset == that.offset - && Objects.equals(namespaceName, that.namespaceName) - && Objects.equals(extensionName, that.extensionName) - && Objects.equals(extensionVersion, that.extensionVersion) - && Objects.equals(extensionId, that.extensionId) - && Objects.equals(extensionUuid, that.extensionUuid) - && Objects.equals(namespaceUuid, that.namespaceUuid) - && Objects.equals(targetPlatform, that.targetPlatform); - } - - @Override - public int hashCode() { - return Objects.hash(namespaceName, extensionName, extensionVersion, extensionId, extensionUuid, namespaceUuid, - includeAllVersions, targetPlatform, size, offset); - } -} \ No newline at end of file +public record QueryRequest ( + String namespaceName, + String extensionName, + String extensionVersion, + String extensionId, + String extensionUuid, + String namespaceUuid, + boolean includeAllVersions, + String targetPlatform, + int size, + int offset +){} \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/QueryRequestV2.java b/server/src/main/java/org/eclipse/openvsx/json/QueryRequestV2.java index 03c9faf86..7a1e90993 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/QueryRequestV2.java +++ b/server/src/main/java/org/eclipse/openvsx/json/QueryRequestV2.java @@ -9,25 +9,15 @@ ********************************************************************************/ package org.eclipse.openvsx.json; -public class QueryRequestV2 { - - public String namespaceName; - - public String extensionName; - - public String extensionVersion; - - public String extensionId; - - public String extensionUuid; - - public String namespaceUuid; - - public String includeAllVersions; - - public String targetPlatform; - - public int size; - - public int offset; -} \ No newline at end of file +public record QueryRequestV2( + String namespaceName, + String extensionName, + String extensionVersion, + String extensionId, + String extensionUuid, + String namespaceUuid, + String includeAllVersions, + String targetPlatform, + int size, + int offset +) {} \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/QueryResultJson.java b/server/src/main/java/org/eclipse/openvsx/json/QueryResultJson.java index 8577317fd..cdb4c472b 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/QueryResultJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/QueryResultJson.java @@ -28,21 +28,44 @@ public class QueryResultJson extends ResultJson { public static QueryResultJson error(String message) { var result = new QueryResultJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "Number of skipped entries according to the query") @NotNull @Min(0) - public int offset; + private int offset; @Schema(description = "Total number of entries that match the query") @NotNull @Min(0) - public int totalSize; + private int totalSize; @Schema(description = "Extensions that match the given query (may be empty)") - public List extensions; - + private List extensions; + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + + public List getExtensions() { + return extensions; + } + + public void setExtensions(List extensions) { + this.extensions = extensions; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/RegistryVersionJson.java b/server/src/main/java/org/eclipse/openvsx/json/RegistryVersionJson.java index 30c6481ad..db6eeb703 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/RegistryVersionJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/RegistryVersionJson.java @@ -22,11 +22,19 @@ public class RegistryVersionJson extends ResultJson { public static RegistryVersionJson error(String message) { var result = new RegistryVersionJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "Registry version") @NotNull - public String version; + private String version; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } } diff --git a/server/src/main/java/org/eclipse/openvsx/json/ResultJson.java b/server/src/main/java/org/eclipse/openvsx/json/ResultJson.java index e5f8d31dc..adbb6bdd5 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ResultJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ResultJson.java @@ -44,12 +44,35 @@ public static ResultJson error(String message) { } @Schema(description = "Indicates success of the operation (omitted if a more specific result type is returned)") - public String success; + private String success; @Schema(description = "Indicates a warning; when this is present, other properties can still be used") - public String warning; + private String warning; @Schema(description = "Indicates an error; when this is present, all other properties should be ignored") - public String error; + private String error; + public String getSuccess() { + return success; + } + + public void setSuccess(String success) { + this.success = success; + } + + public String getWarning() { + return warning; + } + + public void setWarning(String warning) { + this.warning = warning; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/ReviewJson.java b/server/src/main/java/org/eclipse/openvsx/json/ReviewJson.java index 25470e8e2..19970431d 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ReviewJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ReviewJson.java @@ -28,22 +28,62 @@ public class ReviewJson { @Schema(description = "Data of the user who posted this review") @NotNull - public UserJson user; + private UserJson user; @Schema(description = "Date and time when this review was posted (ISO-8601)") @NotNull - public String timestamp; + private String timestamp; @Schema(hidden = true) - public String title; + private String title; - public String comment; + private String comment; @Schema(description = "Number of stars") @NotNull @Min(0) @Max(5) - public int rating; + private int rating; + + public UserJson getUser() { + return user; + } + + public void setUser(UserJson user) { + this.user = user; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public int getRating() { + return rating; + } + + public void setRating(int rating) { + this.rating = rating; + } @Override public boolean equals(Object o) { diff --git a/server/src/main/java/org/eclipse/openvsx/json/ReviewListJson.java b/server/src/main/java/org/eclipse/openvsx/json/ReviewListJson.java index 9b700a508..503676746 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/ReviewListJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/ReviewListJson.java @@ -27,19 +27,42 @@ public class ReviewListJson extends ResultJson { public static ReviewListJson error(String message) { var info = new ReviewListJson(); - info.error = message; + info.setError(message); return info; } @Schema(hidden = true) @NotNull - public String postUrl; + private String postUrl; @Schema(hidden = true) @NotNull - public String deleteUrl; + private String deleteUrl; @NotNull - public List reviews; + private List reviews; + public String getPostUrl() { + return postUrl; + } + + public void setPostUrl(String postUrl) { + this.postUrl = postUrl; + } + + public String getDeleteUrl() { + return deleteUrl; + } + + public void setDeleteUrl(String deleteUrl) { + this.deleteUrl = deleteUrl; + } + + public List getReviews() { + return reviews; + } + + public void setReviews(List reviews) { + this.reviews = reviews; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/SearchEntryJson.java b/server/src/main/java/org/eclipse/openvsx/json/SearchEntryJson.java index b18d26bcf..56fdf826c 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/SearchEntryJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/SearchEntryJson.java @@ -31,57 +31,177 @@ public class SearchEntryJson implements Serializable { @Schema(description = "URL to get the full metadata of the extension") @NotNull - public String url; + private String url; @Schema(description = "Map of file types (download, manifest, icon, readme, license, changelog) to their respective URLs") @NotNull - public Map files; + private Map files; @Schema(description = "Name of the extension") @NotNull - public String name; + private String name; @Schema(description = "Namespace of the extension") @NotNull - public String namespace; + private String namespace; @Schema(description = "The latest published version") @NotNull - public String version; + private String version; @Schema(description = "Date and time when this version was published (ISO-8601)") @NotNull - public String timestamp; + private String timestamp; @Schema(description = "The value 'true' means the publishing user is a privileged user or the publishing user is a member of the extension's namespace and the namespace has at least one owner.") @NotNull - public Boolean verified; + private Boolean verified; @Schema(description = "Essential metadata of all available versions. Deprecated: only returns the last 100 versions. Use allVersionsUrl instead.") @Deprecated - public List allVersions; + private List allVersions; @Schema(description = "URL to get essential metadata of all available versions.") - public String allVersionsUrl; + private String allVersionsUrl; @Schema(description = "Average rating") @Min(0) @Max(5) - public Double averageRating; + private Double averageRating; @Schema(description = "Number of reviews") @Min(0) - public Long reviewCount; + private Long reviewCount; @Schema(description = "Number of downloads of the extension package") @Min(0) - public int downloadCount; + private int downloadCount; @Schema(description = "Name to be displayed in user interfaces") - public String displayName; + private String displayName; - public String description; + private String description; @Schema(description = "Indicates whether the extension is deprecated") - public boolean deprecated; + private boolean deprecated; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Map getFiles() { + return files; + } + + public void setFiles(Map files) { + this.files = files; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public Boolean getVerified() { + return verified; + } + + public void setVerified(Boolean verified) { + this.verified = verified; + } + + public List getAllVersions() { + return allVersions; + } + + public void setAllVersions(List allVersions) { + this.allVersions = allVersions; + } + + public String getAllVersionsUrl() { + return allVersionsUrl; + } + + public void setAllVersionsUrl(String allVersionsUrl) { + this.allVersionsUrl = allVersionsUrl; + } + + public Double getAverageRating() { + return averageRating; + } + + public void setAverageRating(Double averageRating) { + this.averageRating = averageRating; + } + + public Long getReviewCount() { + return reviewCount; + } + + public void setReviewCount(Long reviewCount) { + this.reviewCount = reviewCount; + } + + public int getDownloadCount() { + return downloadCount; + } + + public void setDownloadCount(int downloadCount) { + this.downloadCount = downloadCount; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isDeprecated() { + return deprecated; + } + + public void setDeprecated(boolean deprecated) { + this.deprecated = deprecated; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/SearchResultJson.java b/server/src/main/java/org/eclipse/openvsx/json/SearchResultJson.java index e9d37a8b5..9cd137723 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/SearchResultJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/SearchResultJson.java @@ -28,22 +28,45 @@ public class SearchResultJson extends ResultJson { public static SearchResultJson error(String message) { var result = new SearchResultJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "Number of skipped entries according to the search query") @NotNull @Min(0) - public int offset; + private int offset; @Schema(description = "Total number of entries that match the search query") @NotNull @Min(0) - public int totalSize; + private int totalSize; @Schema(description = "List of matching entries, limited to the size specified in the search query") @NotNull - public List extensions; + private List extensions; + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + + public List getExtensions() { + return extensions; + } + + public void setExtensions(List extensions) { + this.extensions = extensions; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/StatsJson.java b/server/src/main/java/org/eclipse/openvsx/json/StatsJson.java index c9445afa8..9d62fe7c0 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/StatsJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/StatsJson.java @@ -17,14 +17,37 @@ public class StatsJson extends ResultJson { public static StatsJson error(String message) { var user = new StatsJson(); - user.error = message; + user.setError(message); return user; } - public long userCount; + private long userCount; - public long extensionCount; + private long extensionCount; - public long namespaceCount; + private long namespaceCount; + public long getUserCount() { + return userCount; + } + + public void setUserCount(long userCount) { + this.userCount = userCount; + } + + public long getExtensionCount() { + return extensionCount; + } + + public void setExtensionCount(long extensionCount) { + this.extensionCount = extensionCount; + } + + public long getNamespaceCount() { + return namespaceCount; + } + + public void setNamespaceCount(long namespaceCount) { + this.namespaceCount = namespaceCount; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/TargetPlatformVersionJson.java b/server/src/main/java/org/eclipse/openvsx/json/TargetPlatformVersionJson.java index 634444f19..60e5f23e4 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/TargetPlatformVersionJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/TargetPlatformVersionJson.java @@ -11,15 +11,9 @@ import jakarta.validation.constraints.NotNull; -public class TargetPlatformVersionJson { - /*** - * Name of the target platform - */ - public String targetPlatform; - - /*** - * Selected version, or the latest version if none was specified - */ - @NotNull - public String version; -} +/** + * + * @param targetPlatform Name of the target platform + * @param version Selected version, or the latest version if none was specified + */ +public record TargetPlatformVersionJson(String targetPlatform, @NotNull String version) {} diff --git a/server/src/main/java/org/eclipse/openvsx/json/UserJson.java b/server/src/main/java/org/eclipse/openvsx/json/UserJson.java index a4e9641e9..8e74020de 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/UserJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/UserJson.java @@ -29,48 +29,144 @@ public class UserJson extends ResultJson implements Serializable { public static UserJson error(String message) { var user = new UserJson(); - user.error = message; + user.setError(message); return user; } @Schema(description = "Login name") @NotNull - public String loginName; + private String loginName; @Schema(hidden = true) - public String tokensUrl; + private String tokensUrl; @Schema(hidden = true) - public String createTokenUrl; + private String createTokenUrl; @Schema(hidden = true) - public String role; + private String role; @Schema(description = "Full name") - public String fullName; + private String fullName; @Schema(description = "URL to the user's avatar image") - public String avatarUrl; + private String avatarUrl; @Schema(description = "URL to the user's profile page") - public String homepage; + private String homepage; @Schema(description = "Authentication provider (e.g. github)") - public String provider; + private String provider; @Schema(hidden = true) - public PublisherAgreement publisherAgreement; + private PublisherAgreement publisherAgreement; @Schema(hidden = true) - public List additionalLogins; + private List additionalLogins; + + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + public String getTokensUrl() { + return tokensUrl; + } + + public void setTokensUrl(String tokensUrl) { + this.tokensUrl = tokensUrl; + } + + public String getCreateTokenUrl() { + return createTokenUrl; + } + + public void setCreateTokenUrl(String createTokenUrl) { + this.createTokenUrl = createTokenUrl; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getAvatarUrl() { + return avatarUrl; + } + + public void setAvatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + } + + public String getHomepage() { + return homepage; + } + + public void setHomepage(String homepage) { + this.homepage = homepage; + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public PublisherAgreement getPublisherAgreement() { + return publisherAgreement; + } + + public void setPublisherAgreement(PublisherAgreement publisherAgreement) { + this.publisherAgreement = publisherAgreement; + } + + public List getAdditionalLogins() { + return additionalLogins; + } + + public void setAdditionalLogins(List additionalLogins) { + this.additionalLogins = additionalLogins; + } @JsonInclude(Include.NON_NULL) public static class PublisherAgreement implements Serializable { /* 'none' | 'signed' | 'outdated' */ - public String status; + private String status; + + private String timestamp; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } - public String timestamp; + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } @Override public boolean equals(Object o) { diff --git a/server/src/main/java/org/eclipse/openvsx/json/UserPublishInfoJson.java b/server/src/main/java/org/eclipse/openvsx/json/UserPublishInfoJson.java index f9577baa8..1132c0dcf 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/UserPublishInfoJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/UserPublishInfoJson.java @@ -21,17 +21,40 @@ public class UserPublishInfoJson extends ResultJson { public static UserPublishInfoJson error(String message) { var userPublishInfo = new UserPublishInfoJson(); - userPublishInfo.error = message; + userPublishInfo.setError(message); return userPublishInfo; } @NotNull - public UserJson user; + private UserJson user; @NotNull - public List extensions; + private List extensions; @NotNull - public Integer activeAccessTokenNum; + private Integer activeAccessTokenNum; + public UserJson getUser() { + return user; + } + + public void setUser(UserJson user) { + this.user = user; + } + + public List getExtensions() { + return extensions; + } + + public void setExtensions(List extensions) { + this.extensions = extensions; + } + + public Integer getActiveAccessTokenNum() { + return activeAccessTokenNum; + } + + public void setActiveAccessTokenNum(Integer activeAccessTokenNum) { + this.activeAccessTokenNum = activeAccessTokenNum; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/json/VersionReferenceJson.java b/server/src/main/java/org/eclipse/openvsx/json/VersionReferenceJson.java index aa77d2a7b..6cc956c2e 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/VersionReferenceJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/VersionReferenceJson.java @@ -20,16 +20,56 @@ public class VersionReferenceJson { @Schema(description = "URL to get the full metadata of this version") - public String url; + private String url; @Schema(description = "Map of file types (download, manifest, icon, readme, license, changelog) to their respective URLs") - public Map files; + private Map files; - public String version; + private String version; @Schema(description = "Name of the target platform") - public String targetPlatform; + private String targetPlatform; @Schema(description = "Map of engine names to the respective version constraints") - public Map engines; + private Map engines; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Map getFiles() { + return files; + } + + public void setFiles(Map files) { + this.files = files; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getTargetPlatform() { + return targetPlatform; + } + + public void setTargetPlatform(String targetPlatform) { + this.targetPlatform = targetPlatform; + } + + public Map getEngines() { + return engines; + } + + public void setEngines(Map engines) { + this.engines = engines; + } } diff --git a/server/src/main/java/org/eclipse/openvsx/json/VersionReferencesJson.java b/server/src/main/java/org/eclipse/openvsx/json/VersionReferencesJson.java index d129f100d..706be597a 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/VersionReferencesJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/VersionReferencesJson.java @@ -25,21 +25,45 @@ public class VersionReferencesJson extends ResultJson{ public static VersionReferencesJson error(String message) { var result = new VersionReferencesJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "Number of skipped entries according to the version references request") @NotNull @Min(0) - public int offset; + private int offset; @Schema(description = "Total number of version references the extension has") @NotNull @Min(0) - public int totalSize; + private int totalSize; @Schema(description = "Essential metadata of all available versions, limited to the size specified in the version references request") @NotNull - public List versions; + private List versions; + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + + public List getVersions() { + return versions; + } + + public void setVersions(List versions) { + this.versions = versions; + } } diff --git a/server/src/main/java/org/eclipse/openvsx/json/VersionsJson.java b/server/src/main/java/org/eclipse/openvsx/json/VersionsJson.java index 8a48238ac..f94f35b5e 100644 --- a/server/src/main/java/org/eclipse/openvsx/json/VersionsJson.java +++ b/server/src/main/java/org/eclipse/openvsx/json/VersionsJson.java @@ -25,21 +25,45 @@ public class VersionsJson extends ResultJson { public static VersionsJson error(String message) { var result = new VersionsJson(); - result.error = message; + result.setError(message); return result; } @Schema(description = "Number of skipped entries according to the versions request") @NotNull @Min(0) - public int offset; + private int offset; @Schema(description = "Total number of versions the extension has") @NotNull @Min(0) - public int totalSize; + private int totalSize; @Schema(description = "Map of versions, limited to the size specified in the versions request") @NotNull - public Map versions; + private Map versions; + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + + public Map getVersions() { + return versions; + } + + public void setVersions(Map versions) { + this.versions = versions; + } } \ No newline at end of file diff --git a/server/src/main/java/org/eclipse/openvsx/mirror/DataMirrorService.java b/server/src/main/java/org/eclipse/openvsx/mirror/DataMirrorService.java index b85f143d6..fe7bc2b1e 100644 --- a/server/src/main/java/org/eclipse/openvsx/mirror/DataMirrorService.java +++ b/server/src/main/java/org/eclipse/openvsx/mirror/DataMirrorService.java @@ -143,14 +143,14 @@ public UserData createMirrorUser() { @Transactional public UserData getOrAddUser(UserJson json) { - var user = repositories.findUserByLoginName(json.provider, json.loginName); + var user = repositories.findUserByLoginName(json.getProvider(), json.getLoginName()); if (user == null) { user = new UserData(); - user.setLoginName(json.loginName); - user.setFullName(json.fullName); - user.setAvatarUrl(json.avatarUrl); - user.setProviderUrl(json.homepage); - user.setProvider(json.provider); + user.setLoginName(json.getLoginName()); + user.setFullName(json.getFullName()); + user.setAvatarUrl(json.getAvatarUrl()); + user.setProviderUrl(json.getHomepage()); + user.setProvider(json.getProvider()); entityManager.persist(user); } @@ -160,7 +160,7 @@ public UserData getOrAddUser(UserJson json) { public String getOrAddAccessTokenValue(UserData user, String description) { var token = repositories.findAccessToken(user, description); return token == null - ? users.createAccessToken(user, description).value + ? users.createAccessToken(user, description).getValue() : token.getValue(); } @@ -194,20 +194,20 @@ private boolean canActivate(ExtensionVersion extVersion) { @Transactional public void updateMetadata(String namespaceName, String extensionName, ExtensionJson latest) { var extension = repositories.findExtension(extensionName, namespaceName); - extension.setDownloadCount(latest.downloadCount); - extension.setAverageRating(latest.averageRating); - extension.setReviewCount(latest.reviewCount); + extension.setDownloadCount(latest.getDownloadCount()); + extension.setAverageRating(latest.getAverageRating()); + extension.setReviewCount(latest.getReviewCount()); var remoteReviews = upstream.getReviews(namespaceName, extensionName); var localReviews = repositories.findAllReviews(extension) .map(review -> new AbstractMap.SimpleEntry<>(review.toReviewJson(), review)); - remoteReviews.reviews.stream() + remoteReviews.getReviews().stream() .filter(review -> localReviews.stream().noneMatch(entry -> entry.getKey().equals(review))) .forEach(review -> addReview(review, extension)); localReviews.stream() - .filter(entry -> remoteReviews.reviews.stream().noneMatch(review -> review.equals(entry.getKey()))) + .filter(entry -> remoteReviews.getReviews().stream().noneMatch(review -> review.equals(entry.getKey()))) .map(Map.Entry::getValue) .forEach(entityManager::remove); } @@ -216,11 +216,11 @@ private void addReview(ReviewJson json, Extension extension) { var review = new ExtensionReview(); review.setExtension(extension); review.setActive(true); - review.setTimestamp(TimeUtil.fromUTCString(json.timestamp)); - review.setUser(getOrAddUser(json.user)); - review.setTitle(json.title); - review.setComment(json.comment); - review.setRating(json.rating); + review.setTimestamp(TimeUtil.fromUTCString(json.getTimestamp())); + review.setUser(getOrAddUser(json.getUser())); + review.setTitle(json.getTitle()); + review.setComment(json.getComment()); + review.setRating(json.getRating()); entityManager.persist(review); } @@ -236,8 +236,8 @@ public void deleteExtensionVersion(ExtensionVersion extVersion, UserData user) { } public void mirrorNamespaceMetadata(String namespaceName) { - var remoteVerified = upstream.getNamespace(namespaceName).verified; - var localVerified = local.getNamespace(namespaceName).verified; + var remoteVerified = upstream.getNamespace(namespaceName).getVerified(); + var localVerified = local.getNamespace(namespaceName).getVerified(); if(!localVerified && remoteVerified) { // verify the namespace by adding an owner to it var membership = repositories.findFirstMembership(namespaceName); @@ -260,7 +260,7 @@ public void ensureNamespaceMembership(UserData user, Namespace namespace) { public void ensureNamespace(String namespaceName) { if(!repositories.namespaceExists(namespaceName)) { var json = new NamespaceJson(); - json.name = namespaceName; + json.setName(namespaceName); admin.createNamespace(json); } } diff --git a/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionQueryRequestHandler.java b/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionQueryRequestHandler.java index 48a33d463..83f6ed754 100644 --- a/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionQueryRequestHandler.java +++ b/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionQueryRequestHandler.java @@ -49,8 +49,8 @@ public ExtensionQueryResult getResult(ExtensionQueryParam param, int pageSize, i if (!dataMirror.needsMatch()) { return result; } - return local.toQueryResult(result.results.get(0).extensions.stream().filter(e -> - dataMirror.match(e.publisher.publisherName, e.extensionName) + return local.toQueryResult(result.results().get(0).extensions().stream().filter(e -> + dataMirror.match(e.publisher().publisherName(), e.extensionName()) ).collect(Collectors.toList())); } catch (NotFoundException | ResponseStatusException exc) { // expected issues with upstream, try local diff --git a/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionService.java b/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionService.java index ab177d7a4..88ea3d069 100644 --- a/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionService.java +++ b/server/src/main/java/org/eclipse/openvsx/mirror/MirrorExtensionService.java @@ -103,7 +103,7 @@ private boolean shouldMirrorExtensionVersions(String namespaceName, String exten } var lastUpdated = extension.getLastUpdatedDate(); - return lastUpdated.toLocalDate().isBefore(lastModified) || lastUpdated.isBefore(TimeUtil.fromUTCString(latest.timestamp)); + return lastUpdated.toLocalDate().isBefore(lastModified) || lastUpdated.isBefore(TimeUtil.fromUTCString(latest.getTimestamp())); } private void mirrorExtensionVersions(String namespaceName, String extensionName, UserData mirrorUser, JobContext jobContext) { @@ -114,7 +114,7 @@ private void mirrorExtensionVersions(String namespaceName, String extensionName, Set versions; try { var json = upstream.getExtension(namespaceName, extensionName, targetPlatform); - versions = json.allVersions.keySet(); + versions = json.getAllVersions().keySet(); VersionAlias.ALIAS_NAMES.forEach(versions::remove); } catch (NotFoundException e) { // combination of extension and target platform doesn't exist, try next @@ -134,7 +134,7 @@ private void mirrorExtensionVersions(String namespaceName, String extensionName, .collect(Collectors.toList()) ); } - toAdd.sort(Comparator.comparing(extensionJson -> TimeUtil.fromUTCString(extensionJson.timestamp))); + toAdd.sort(Comparator.comparing(extensionJson -> TimeUtil.fromUTCString(extensionJson.getTimestamp()))); for(var i = 0; i < toAdd.size(); i++) { var json = toAdd.get(i); @@ -150,14 +150,14 @@ private void mirrorExtensionVersions(String namespaceName, String extensionName, } private void mirrorExtensionVersion(ExtensionJson json) throws RuntimeException { - var download = json.files.get("download"); + var download = json.getFiles().get("download"); var userJson = new UserJson(); - userJson.provider = json.publishedBy.provider; - userJson.loginName = json.publishedBy.loginName; - userJson.fullName = json.publishedBy.fullName; - userJson.avatarUrl = json.publishedBy.avatarUrl; - userJson.homepage = json.publishedBy.homepage; - var namespaceName = json.namespace; + userJson.setProvider(json.getPublishedBy().getProvider()); + userJson.setLoginName(json.getPublishedBy().getLoginName()); + userJson.setFullName(json.getPublishedBy().getFullName()); + userJson.setAvatarUrl(json.getPublishedBy().getAvatarUrl()); + userJson.setHomepage(json.getPublishedBy().getHomepage()); + var namespaceName = json.getNamespace(); var vsixResourceHeaders = backgroundNonRedirectingRestTemplate.headForHeaders("{resolveVsixLocation}", Map.of("resolveVsixLocation", download)); var vsixLocation = vsixResourceHeaders.getLocation(); @@ -173,11 +173,11 @@ private void mirrorExtensionVersion(ExtensionJson json) throws RuntimeException String signatureName = null; try (var extensionFile = downloadToFile(download, "extension_", ".vsix")) { - if(json.files.containsKey(DOWNLOAD_SIG)) { + if(json.getFiles().containsKey(DOWNLOAD_SIG)) { try( - var signatureZip = downloadToFile(json.files.get(DOWNLOAD_SIG), "extension_", ".sigzip"); + var signatureZip = downloadToFile(json.getFiles().get(DOWNLOAD_SIG), "extension_", ".sigzip"); var signatureFile = extractSignature(signatureZip); - var publicKeyFile = downloadToFile(json.files.get(PUBLIC_KEY), "public_", ".pem"); + var publicKeyFile = downloadToFile(json.getFiles().get(PUBLIC_KEY), "public_", ".pem"); ) { var verified = integrityService.verifyExtensionVersion(extensionFile, signatureFile, publicKeyFile); if (!verified) { @@ -185,7 +185,7 @@ private void mirrorExtensionVersion(ExtensionJson json) throws RuntimeException } } - var signaturePathParams = URI.create(json.files.get("signature")).getPath().split("/"); + var signaturePathParams = URI.create(json.getFiles().get("signature")).getPath().split("/"); signatureName = signaturePathParams[signaturePathParams.length - 1]; } @@ -197,7 +197,7 @@ private void mirrorExtensionVersion(ExtensionJson json) throws RuntimeException var accessTokenValue = data.getOrAddAccessTokenValue(user, description); var token = users.useAccessToken(accessTokenValue); - extensions.mirrorVersion(extensionFile, signatureName, token, filename, json.timestamp); + extensions.mirrorVersion(extensionFile, signatureName, token, filename, json.getTimestamp()); logger.debug("completed mirroring of extension version: {}", NamingUtil.toLogFormat(json)); } catch (IOException e) { throw new RuntimeException(e); diff --git a/server/src/main/java/org/eclipse/openvsx/repositories/ExtensionVersionJooqRepository.java b/server/src/main/java/org/eclipse/openvsx/repositories/ExtensionVersionJooqRepository.java index 50165de99..384e1eed2 100644 --- a/server/src/main/java/org/eclipse/openvsx/repositories/ExtensionVersionJooqRepository.java +++ b/server/src/main/java/org/eclipse/openvsx/repositories/ExtensionVersionJooqRepository.java @@ -275,23 +275,23 @@ private List findVersionStringsSorted(List conditions, Pageab public Page findActiveVersions(QueryRequest request) { var conditions = new ArrayList(); - if (!StringUtils.isEmpty(request.namespaceUuid)) { - conditions.add(NAMESPACE.PUBLIC_ID.eq(request.namespaceUuid)); + if (!StringUtils.isEmpty(request.namespaceUuid())) { + conditions.add(NAMESPACE.PUBLIC_ID.eq(request.namespaceUuid())); } - if (!StringUtils.isEmpty(request.namespaceName)) { - conditions.add(NAMESPACE.NAME.equalIgnoreCase(request.namespaceName)); + if (!StringUtils.isEmpty(request.namespaceName())) { + conditions.add(NAMESPACE.NAME.equalIgnoreCase(request.namespaceName())); } - if (!StringUtils.isEmpty(request.extensionUuid)) { - conditions.add(EXTENSION.PUBLIC_ID.eq(request.extensionUuid)); + if (!StringUtils.isEmpty(request.extensionUuid())) { + conditions.add(EXTENSION.PUBLIC_ID.eq(request.extensionUuid())); } - if (!StringUtils.isEmpty(request.extensionName)) { - conditions.add(EXTENSION.NAME.equalIgnoreCase(request.extensionName)); + if (!StringUtils.isEmpty(request.extensionName())) { + conditions.add(EXTENSION.NAME.equalIgnoreCase(request.extensionName())); } - if(request.targetPlatform != null) { - conditions.add(EXTENSION_VERSION.TARGET_PLATFORM.eq(request.targetPlatform)); + if(request.targetPlatform() != null) { + conditions.add(EXTENSION_VERSION.TARGET_PLATFORM.eq(request.targetPlatform())); } - if (!StringUtils.isEmpty(request.extensionVersion)) { - conditions.add(EXTENSION_VERSION.VERSION.eq(request.extensionVersion)); + if (!StringUtils.isEmpty(request.extensionVersion())) { + conditions.add(EXTENSION_VERSION.VERSION.eq(request.extensionVersion())); } var totalCol = "total"; @@ -302,7 +302,7 @@ public Page findActiveVersions(QueryRequest request) { totalQuery.addConditions(EXTENSION_VERSION.ACTIVE.eq(true)); var query = findAllActive(); - if(!request.includeAllVersions) { + if(!request.includeAllVersions()) { var distinctOn = new Field[] { EXTENSION_VERSION.EXTENSION_ID, EXTENSION_VERSION.UNIVERSAL_TARGET_PLATFORM, @@ -338,8 +338,8 @@ public Page findActiveVersions(QueryRequest request) { totalQuery.addConditions(conditions); query.addSelect(EXTENSION.DEPRECATED, EXTENSION.DOWNLOADABLE, EXTENSION.REPLACEMENT_ID); query.addConditions(conditions); - query.addOffset(request.offset); - query.addLimit(request.size); + query.addOffset(request.offset()); + query.addLimit(request.size()); var content = query.fetch().map(record -> { var extVersion = toExtensionVersionFull(record); @@ -355,7 +355,7 @@ public Page findActiveVersions(QueryRequest request) { return extVersion; }); var total = totalQuery.fetchOne(totalCol, Integer.class); - return new PageImpl<>(content, PageRequest.of(request.offset / request.size, request.size), total); + return new PageImpl<>(content, PageRequest.of(request.offset() / request.size(), request.size()), total); } public ExtensionVersion findActiveByVersionAndExtensionNameAndNamespaceName(String version, String extensionName, String namespaceName) { diff --git a/server/src/main/java/org/eclipse/openvsx/search/DatabaseSearchService.java b/server/src/main/java/org/eclipse/openvsx/search/DatabaseSearchService.java index 0268b6d48..47d7d31ef 100644 --- a/server/src/main/java/org/eclipse/openvsx/search/DatabaseSearchService.java +++ b/server/src/main/java/org/eclipse/openvsx/search/DatabaseSearchService.java @@ -66,35 +66,35 @@ public SearchHits search(ISearchService.Options options) { } // exlude namespaces - if(options.namespacesToExclude != null) { - for(var namespaceToExclude : options.namespacesToExclude) { + if(options.namespacesToExclude() != null) { + for(var namespaceToExclude : options.namespacesToExclude()) { matchingExtensions = matchingExtensions.filter(extension -> !extension.getNamespace().getName().equals(namespaceToExclude)); } } // filter target platform - if(TargetPlatform.isValid(options.targetPlatform)) { - matchingExtensions = matchingExtensions.filter(extension -> extension.getVersions().stream().anyMatch(ev -> ev.getTargetPlatform().equals(options.targetPlatform))); + if(TargetPlatform.isValid(options.targetPlatform())) { + matchingExtensions = matchingExtensions.filter(extension -> extension.getVersions().stream().anyMatch(ev -> ev.getTargetPlatform().equals(options.targetPlatform()))); } // filter category - if (options.category != null) { + if (options.category() != null) { matchingExtensions = matchingExtensions.filter(extension -> { var latest = repositories.findLatestVersion(extension, null, false, true); - return latest.getCategories().stream().anyMatch(category -> category.equalsIgnoreCase(options.category)); + return latest.getCategories().stream().anyMatch(category -> category.equalsIgnoreCase(options.category())); }); } // filter text - if (options.queryString != null) { + if (options.queryString() != null) { matchingExtensions = matchingExtensions.filter(extension -> { var latest = repositories.findLatestVersion(extension, null, false, true); - return extension.getName().toLowerCase().contains(options.queryString.toLowerCase()) - || extension.getNamespace().getName().contains(options.queryString.toLowerCase()) + return extension.getName().toLowerCase().contains(options.queryString().toLowerCase()) + || extension.getNamespace().getName().contains(options.queryString().toLowerCase()) || (latest.getDescription() != null && latest.getDescription() - .toLowerCase().contains(options.queryString.toLowerCase())) + .toLowerCase().contains(options.queryString().toLowerCase())) || (latest.getDisplayName() != null && latest.getDisplayName() - .toLowerCase().contains(options.queryString.toLowerCase())); + .toLowerCase().contains(options.queryString().toLowerCase())); }); } @@ -102,7 +102,7 @@ public SearchHits search(ISearchService.Options options) { // 'relevance' | 'timestamp' | 'rating' | 'downloadCount'; Stream searchEntries; - if("relevance".equals(options.sortBy) || "rating".equals(options.sortBy)) { + if("relevance".equals(options.sortBy()) || "rating".equals(options.sortBy())) { var searchStats = new SearchStats(repositories); searchEntries = matchingExtensions.stream().map(extension -> relevanceService.toSearchEntry(extension, searchStats)); } else { @@ -120,7 +120,7 @@ public SearchHits search(ISearchService.Options options) { "downloadCount", new DownloadedCountComparator() )); - var comparator = comparators.get(options.sortBy); + var comparator = comparators.get(options.sortBy()); if(comparator != null) { searchEntries = searchEntries.sorted(comparator); } @@ -129,15 +129,15 @@ public SearchHits search(ISearchService.Options options) { // need to do sortOrder // 'asc' | 'desc'; - if ("desc".equals(options.sortOrder)) { + if ("desc".equals(options.sortOrder())) { // reverse the order Collections.reverse(sortedExtensions); } // Paging var totalHits = sortedExtensions.size(); - var endIndex = Math.min(sortedExtensions.size(), options.requestedOffset + options.requestedSize); - var startIndex = Math.min(endIndex, options.requestedOffset); + var endIndex = Math.min(sortedExtensions.size(), options.requestedOffset() + options.requestedSize()); + var startIndex = Math.min(endIndex, options.requestedOffset()); sortedExtensions = sortedExtensions.subList(startIndex, endIndex); List> searchHits; @@ -200,7 +200,7 @@ class DownloadedCountComparator implements Comparator { @Override public int compare(ExtensionSearch ext1, ExtensionSearch ext2) { // download count - return Integer.compare(ext1.downloadCount, ext2.downloadCount); + return Integer.compare(ext1.getDownloadCount(), ext2.getDownloadCount()); } } @@ -211,13 +211,13 @@ class RatingComparator implements Comparator { @Override public int compare(ExtensionSearch ext1, ExtensionSearch ext2) { - if (ext1.rating == null) { + if (ext1.getRating() == null) { return -1; - } else if (ext2.rating == null) { + } else if (ext2.getRating() == null) { return 1; } // rating - return Double.compare(ext1.rating, ext2.rating); + return Double.compare(ext1.getRating(), ext2.getRating()); } } @@ -229,7 +229,7 @@ class TimestampComparator implements Comparator { @Override public int compare(ExtensionSearch ext1, ExtensionSearch ext2) { // timestamp - return Long.compare(ext1.timestamp, ext2.timestamp); + return Long.compare(ext1.getTimestamp(), ext2.getTimestamp()); } } @@ -240,7 +240,7 @@ class RelevanceComparator implements Comparator { @Override public int compare(ExtensionSearch ext1, ExtensionSearch ext2) { - return Double.compare(ext1.relevance, ext2.relevance); + return Double.compare(ext1.getRelevance(), ext2.getRelevance()); } } } diff --git a/server/src/main/java/org/eclipse/openvsx/search/ElasticSearchService.java b/server/src/main/java/org/eclipse/openvsx/search/ElasticSearchService.java index e30af755b..e9217fe76 100644 --- a/server/src/main/java/org/eclipse/openvsx/search/ElasticSearchService.java +++ b/server/src/main/java/org/eclipse/openvsx/search/ElasticSearchService.java @@ -246,7 +246,7 @@ public void removeSearchEntry(Extension extension) { } public SearchHits search(Options options) { - var resultWindow = options.requestedOffset + options.requestedSize; + var resultWindow = options.requestedOffset() + options.requestedSize(); if(resultWindow > getMaxResultWindow()) { return new SearchHitsImpl<>(0, TotalHitsRelation.OFF, 0f, null, null, Collections.emptyList(), null, null); } @@ -255,11 +255,11 @@ public SearchHits search(Options options) { queryBuilder.withQuery(builder -> builder.bool(boolQuery -> createSearchQuery(boolQuery, options))); // Sort search results according to 'sortOrder' and 'sortBy' options - sortResults(queryBuilder, options.sortOrder, options.sortBy); + sortResults(queryBuilder, options.sortOrder(), options.sortBy()); var pages = new ArrayList(); - pages.add(PageRequest.of(options.requestedOffset / options.requestedSize, options.requestedSize)); - if(options.requestedOffset % options.requestedSize > 0) { + pages.add(PageRequest.of(options.requestedOffset() / options.requestedSize(), options.requestedSize())); + if(options.requestedOffset() % options.requestedSize() > 0) { // size is not exact multiple of offset; this means we need to get two pages // e.g. when offset is 20 and size is 50, you want results 20 to 70 which span pages 0 and 1 of a 50 item page pages.add(pages.get(0).next()); @@ -283,8 +283,8 @@ public SearchHits search(Options options) { List> searchHits = new ArrayList<>(firstSearchHitsPage.getSearchHits()); searchHits.addAll(secondSearchHitsPage.getSearchHits()); - var endIndex = Math.min(searchHits.size(), options.requestedOffset + options.requestedSize); - var startIndex = Math.min(endIndex, options.requestedOffset); + var endIndex = Math.min(searchHits.size(), options.requestedOffset() + options.requestedSize()); + var startIndex = Math.min(endIndex, options.requestedOffset()); searchHits = searchHits.subList(startIndex, endIndex); return new SearchHitsImpl<>( firstSearchHitsPage.getTotalHits(), @@ -302,17 +302,17 @@ public SearchHits search(Options options) { } private ObjectBuilder createSearchQuery(BoolQuery.Builder boolQuery, Options options) { - if (!StringUtils.isEmpty(options.queryString)) { + if (!StringUtils.isEmpty(options.queryString())) { boolQuery.should(QueryBuilders.term(builder -> builder.field("extensionId.keyword") - .value(options.queryString) + .value(options.queryString()) .caseInsensitive(true) .boost(10f) )); // Fuzzy matching of search query in multiple fields var multiMatchQuery = QueryBuilders.multiMatch(builder -> - builder.query(options.queryString) + builder.query(options.queryString()) .fields("name").boost(5f) .fields("displayName").boost(5f) .fields("tags").boost(3f) @@ -325,24 +325,24 @@ private ObjectBuilder createSearchQuery(BoolQuery.Builder boolQuery, boolQuery.should(multiMatchQuery).boost(5f); // Prefix matching of search query in display name and namespace - var prefixString = options.queryString.trim().toLowerCase(); + var prefixString = options.queryString().trim().toLowerCase(); var namePrefixQuery = QueryBuilders.prefix(builder -> builder.field("displayName").value(prefixString)); boolQuery.should(namePrefixQuery).boost(2f); var namespacePrefixQuery = QueryBuilders.prefix(builder -> builder.field("namespace").value(prefixString)); boolQuery.should(namespacePrefixQuery); } - if (!StringUtils.isEmpty(options.category)) { + if (!StringUtils.isEmpty(options.category())) { // Filter by selected category - boolQuery.must(QueryBuilders.matchPhrase(builder -> builder.field("categories").query(options.category))); + boolQuery.must(QueryBuilders.matchPhrase(builder -> builder.field("categories").query(options.category()))); } - if (TargetPlatform.isValid(options.targetPlatform)) { + if (TargetPlatform.isValid(options.targetPlatform())) { // Filter by selected target platform - boolQuery.must(QueryBuilders.matchPhrase(builder -> builder.field("targetPlatforms").query(options.targetPlatform))); + boolQuery.must(QueryBuilders.matchPhrase(builder -> builder.field("targetPlatforms").query(options.targetPlatform()))); } - if (options.namespacesToExclude != null) { + if (options.namespacesToExclude() != null) { // Exclude namespaces - for(var namespaceToExclude : options.namespacesToExclude) { + for(var namespaceToExclude : options.namespacesToExclude()) { boolQuery.mustNot(QueryBuilders.term(builder -> builder.field("namespace.keyword").value(namespaceToExclude))); } } diff --git a/server/src/main/java/org/eclipse/openvsx/search/ExtensionSearch.java b/server/src/main/java/org/eclipse/openvsx/search/ExtensionSearch.java index bb5a3dbbf..bb8bb66a8 100644 --- a/server/src/main/java/org/eclipse/openvsx/search/ExtensionSearch.java +++ b/server/src/main/java/org/eclipse/openvsx/search/ExtensionSearch.java @@ -23,38 +23,143 @@ public class ExtensionSearch implements Serializable { @Field(index = false) - public long id; + private long id; @Field(index = false, type = FieldType.Float) - public double relevance; + private double relevance; - public String name; + private String name; - public String namespace; + private String namespace; @Field(index = false) - public String extensionId; + private String extensionId; - public List targetPlatforms; + private List targetPlatforms; - public String displayName; + private String displayName; - public String description; + private String description; @Field(index = false) - public long timestamp; + private long timestamp; @Nullable @Field(index = false, type = FieldType.Float) - public Double rating; + private Double rating; @Field(index = false) - public int downloadCount; + private int downloadCount; @Field(index = false) - public List categories; + private List categories; - public List tags; + private List tags; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getRelevance() { + return relevance; + } + + public void setRelevance(double relevance) { + this.relevance = relevance; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public String getExtensionId() { + return extensionId; + } + + public void setExtensionId(String extensionId) { + this.extensionId = extensionId; + } + + public List getTargetPlatforms() { + return targetPlatforms; + } + + public void setTargetPlatforms(List targetPlatforms) { + this.targetPlatforms = targetPlatforms; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + @Nullable + public Double getRating() { + return rating; + } + + public void setRating(@Nullable Double rating) { + this.rating = rating; + } + + public int getDownloadCount() { + return downloadCount; + } + + public void setDownloadCount(int downloadCount) { + this.downloadCount = downloadCount; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } @Override public boolean equals(Object o) { diff --git a/server/src/main/java/org/eclipse/openvsx/search/ISearchService.java b/server/src/main/java/org/eclipse/openvsx/search/ISearchService.java index b91150964..accb8f988 100644 --- a/server/src/main/java/org/eclipse/openvsx/search/ISearchService.java +++ b/server/src/main/java/org/eclipse/openvsx/search/ISearchService.java @@ -63,30 +63,17 @@ public interface ISearchService { */ void removeSearchEntries(Collection ids); - public static class Options { - public final String queryString; - public final String category; - public final String targetPlatform; - public final int requestedSize; - public final int requestedOffset; - public final String sortOrder; - public final String sortBy; - public final boolean includeAllVersions; - public final String[] namespacesToExclude; - - public Options(String queryString, String category, String targetPlatform, int size, int offset, - String sortOrder, String sortBy, boolean includeAllVersions, String... namespacesToExclude) { - this.queryString = queryString; - this.category = category; - this.targetPlatform = targetPlatform; - this.requestedSize = size; - this.requestedOffset = offset; - this.sortOrder = sortOrder; - this.sortBy = sortBy; - this.includeAllVersions = includeAllVersions; - this.namespacesToExclude = namespacesToExclude; - } - + public record Options( + String queryString, + String category, + String targetPlatform, + int requestedSize, + int requestedOffset, + String sortOrder, + String sortBy, + boolean includeAllVersions, + String[] namespacesToExclude + ) { @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server/src/main/java/org/eclipse/openvsx/search/RelevanceService.java b/server/src/main/java/org/eclipse/openvsx/search/RelevanceService.java index bcb99cfca..d39f06d06 100644 --- a/server/src/main/java/org/eclipse/openvsx/search/RelevanceService.java +++ b/server/src/main/java/org/eclipse/openvsx/search/RelevanceService.java @@ -55,8 +55,8 @@ public ExtensionSearch toSearchEntry(Extension extension, SearchStats stats) { var latest = repositories.findLatestVersion(extension, null, false, true); var targetPlatforms = repositories.findExtensionTargetPlatforms(extension); var entry = extension.toSearch(latest, targetPlatforms); - entry.rating = calculateRating(extension, stats); - entry.relevance = calculateRelevance(extension, latest, stats, entry); + entry.setRating(calculateRating(extension, stats)); + entry.setRelevance(calculateRelevance(extension, latest, stats, entry)); return entry; } @@ -78,7 +78,7 @@ private double calculateRelevance(Extension extension, ExtensionVersion latest, var countRelevance = saturate(reviewCount, 0.25); ratingValue = (extension.getAverageRating() / 5.0) * countRelevance; } - var downloadsValue = entry.downloadCount / stats.downloadRef; + var downloadsValue = entry.getDownloadCount() / stats.downloadRef; var timestamp = latest.getTimestamp(); var timestampValue = Duration.between(stats.oldest, timestamp).toSeconds() / stats.timestampRef; var relevance = ratingRelevance * limit(ratingValue) + downloadsRelevance * limit(downloadsValue) @@ -94,7 +94,7 @@ private double calculateRelevance(Extension extension, ExtensionVersion latest, relevance *= deprecatedRelevance; } - if (Double.isNaN(entry.relevance) || Double.isInfinite(entry.relevance)) { + if (Double.isNaN(entry.getRelevance()) || Double.isInfinite(entry.getRelevance())) { var message = "Invalid relevance for entry " + NamingUtil.toExtensionId(entry); try { message += " " + new ObjectMapper().writeValueAsString(stats); diff --git a/server/src/main/java/org/eclipse/openvsx/security/OAuth2UserServices.java b/server/src/main/java/org/eclipse/openvsx/security/OAuth2UserServices.java index b4c91bfe9..f749e381f 100644 --- a/server/src/main/java/org/eclipse/openvsx/security/OAuth2UserServices.java +++ b/server/src/main/java/org/eclipse/openvsx/security/OAuth2UserServices.java @@ -137,12 +137,12 @@ private IdPrincipal loadEclipseUser(OAuth2UserRequest userRequest) { try { var accessToken = userRequest.getAccessToken().getTokenValue(); var profile = eclipse.getUserProfile(accessToken); - if (StringUtils.isEmpty(profile.githubHandle)) + if (StringUtils.isEmpty(profile.getGithubHandle())) throw new CodedAuthException("Your Eclipse profile is missing a GitHub username.", ECLIPSE_MISSING_GITHUB_ID); - if (!profile.githubHandle.equalsIgnoreCase(userData.getLoginName())) + if (!profile.getGithubHandle().equalsIgnoreCase(userData.getLoginName())) throw new CodedAuthException("The GitHub username setting in your Eclipse profile (" - + profile.githubHandle + + profile.getGithubHandle() + ") does not match your GitHub authentication (" + userData.getLoginName() + ").", ECLIPSE_MISMATCH_GITHUB_ID); diff --git a/server/src/main/java/org/eclipse/openvsx/security/TokenService.java b/server/src/main/java/org/eclipse/openvsx/security/TokenService.java index 1ca058179..53546d952 100644 --- a/server/src/main/java/org/eclipse/openvsx/security/TokenService.java +++ b/server/src/main/java/org/eclipse/openvsx/security/TokenService.java @@ -63,11 +63,15 @@ public AuthToken updateTokens(long userId, String registrationId, OAuth2AccessTo if (accessToken == null) { return updateGitHubToken(userData, null); } - var token = new AuthToken(); - token.accessToken = accessToken.getTokenValue(); - token.scopes = accessToken.getScopes(); - token.issuedAt = accessToken.getIssuedAt(); - token.expiresAt = accessToken.getExpiresAt(); + + var token = new AuthToken( + accessToken.getTokenValue(), + accessToken.getIssuedAt(), + accessToken.getExpiresAt(), + accessToken.getScopes(), + null, + null + ); return updateGitHubToken(userData, token); } @@ -75,16 +79,23 @@ public AuthToken updateTokens(long userId, String registrationId, OAuth2AccessTo if (accessToken == null) { return updateEclipseToken(userData, null); } - var token = new AuthToken(); - token.accessToken = accessToken.getTokenValue(); - token.scopes = accessToken.getScopes(); - token.issuedAt = accessToken.getIssuedAt(); - token.expiresAt = accessToken.getExpiresAt(); + + String refresh = null; + Instant refreshExpiresAt = null; if (refreshToken != null) { - token.refreshToken = refreshToken.getTokenValue(); - token.refreshExpiresAt = refreshToken.getExpiresAt(); + refresh = refreshToken.getTokenValue(); + refreshExpiresAt = refreshToken.getExpiresAt(); } + var token = new AuthToken( + accessToken.getTokenValue(), + accessToken.getIssuedAt(), + accessToken.getExpiresAt(), + accessToken.getScopes(), + refresh, + refreshExpiresAt + ); + return updateEclipseToken(userData, token); } } @@ -115,7 +126,7 @@ public AuthToken getActiveToken(UserData userData, String registrationId) { case "eclipse": { var token = userData.getEclipseToken(); - if (token != null && isExpired(token.expiresAt)) { + if (token != null && isExpired(token.expiresAt())) { OAuth2AccessToken newAccessToken = null; OAuth2RefreshToken newRefreshToken = null; var newTokens = refreshEclipseToken(token); @@ -138,7 +149,7 @@ private boolean isExpired(Instant instant) { } protected Pair refreshEclipseToken(AuthToken token) { - if(token.refreshToken == null || isExpired(token.refreshExpiresAt)) { + if(token.refreshToken() == null || isExpired(token.refreshExpiresAt())) { return null; } @@ -154,7 +165,7 @@ protected Pair refreshEclipseToken(AuthTo .put("grant_type", "refresh_token") .put("client_id", reg.getClientId()) .put("client_secret", reg.getClientSecret()) - .put("refresh_token", token.refreshToken); + .put("refresh_token", token.refreshToken()); try { var request = new HttpEntity<>(objectMapper.writeValueAsString(data), headers); diff --git a/server/src/main/java/org/eclipse/openvsx/util/ErrorResultException.java b/server/src/main/java/org/eclipse/openvsx/util/ErrorResultException.java index f24f90c71..e79d576ee 100644 --- a/server/src/main/java/org/eclipse/openvsx/util/ErrorResultException.java +++ b/server/src/main/java/org/eclipse/openvsx/util/ErrorResultException.java @@ -57,7 +57,7 @@ public ResponseEntity toResponseEntity() { public ResponseEntity toResponseEntity(Class resultType) { try { var json = resultType.getDeclaredConstructor().newInstance(); - json.error = getMessage(); + json.setError(getMessage()); var responseStatus = status != null ? status : HttpStatus.BAD_REQUEST; return new ResponseEntity<>(json, responseStatus); } catch (ReflectiveOperationException exc) { diff --git a/server/src/main/java/org/eclipse/openvsx/util/NamingUtil.java b/server/src/main/java/org/eclipse/openvsx/util/NamingUtil.java index ba9375975..245ccc00b 100644 --- a/server/src/main/java/org/eclipse/openvsx/util/NamingUtil.java +++ b/server/src/main/java/org/eclipse/openvsx/util/NamingUtil.java @@ -50,7 +50,7 @@ public static String toLogFormat(ExtensionVersion extVersion) { } public static String toLogFormat(ExtensionJson json) { - return toLogFormat(json.namespace, json.name, json.targetPlatform, json.version); + return toLogFormat(json.getNamespace(), json.getName(), json.getTargetPlatform(), json.getVersion()); } public static String toLogFormat(String namespace, String extension, String version) { @@ -75,11 +75,11 @@ public static String toExtensionId(Extension extension) { } public static String toExtensionId(ExtensionQueryResult.Extension extension) { - return toExtensionId(extension.publisher.publisherName, extension.extensionName); + return toExtensionId(extension.publisher().publisherName(), extension.extensionName()); } public static String toExtensionId(ExtensionSearch search) { - return toExtensionId(search.namespace, search.name); + return toExtensionId(search.getNamespace(), search.getName()); } public static String toExtensionId(String namespace, String extension) { diff --git a/server/src/main/java/org/eclipse/openvsx/util/UrlUtil.java b/server/src/main/java/org/eclipse/openvsx/util/UrlUtil.java index 7eb9f9f4d..f84480f87 100644 --- a/server/src/main/java/org/eclipse/openvsx/util/UrlUtil.java +++ b/server/src/main/java/org/eclipse/openvsx/util/UrlUtil.java @@ -57,7 +57,7 @@ public static String createApiFileBaseUrl(String baseUrl, String namespaceName, } public static String createApiVersionUrl(String baseUrl, ExtensionJson json) { - return createApiVersionUrl(baseUrl, json.namespace, json.name, json.targetPlatform, json.version); + return createApiVersionUrl(baseUrl, json.getNamespace(), json.getName(), json.getTargetPlatform(), json.getVersion()); } public static String createApiVersionUrl(String baseUrl, ExtensionVersion extVersion) { diff --git a/server/src/test/java/org/eclipse/openvsx/IntegrationTest.java b/server/src/test/java/org/eclipse/openvsx/IntegrationTest.java index 0bb9a4ca1..fa5d208b5 100644 --- a/server/src/test/java/org/eclipse/openvsx/IntegrationTest.java +++ b/server/src/test/java/org/eclipse/openvsx/IntegrationTest.java @@ -98,22 +98,22 @@ void testPublishExtension() throws Exception { private void createNamespace() { var requestBody = new NamespaceJson(); - requestBody.name = "EditorConfig"; + requestBody.setName("EditorConfig"); var response = restTemplate.postForEntity(apiCall("/api/-/namespace/create?token={token}"), requestBody, ResultJson.class, "test_token"); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); - assertThat(response.getBody().error).isNull(); - assertThat(response.getBody().success).isEqualTo("Created namespace " + requestBody.name); + assertThat(response.getBody().getError()).isNull(); + assertThat(response.getBody().getSuccess()).isEqualTo("Created namespace " + requestBody.getName()); } private void duplicateNamespaceLowercase() { var requestBody = new NamespaceJson(); - requestBody.name = "editorconfig"; + requestBody.setName("editorconfig"); var response = restTemplate.postForEntity(apiCall("/api/-/namespace/create?token={token}"), requestBody, ResultJson.class, "test_token"); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); - assertThat(response.getBody().success).isNull(); - assertThat(response.getBody().error).isEqualTo("Namespace already exists: EditorConfig"); + assertThat(response.getBody().getSuccess()).isNull(); + assertThat(response.getBody().getError()).isEqualTo("Namespace already exists: EditorConfig"); } private void getNamespaceMetadata(String path) { @@ -128,8 +128,8 @@ private void verifyToken() { var response = restTemplate.getForEntity(apiCall("/api/editorconfig/verify-pat?token=test_token"), ResultJson.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); var json = response.getBody(); - assertThat(json.error).isNull(); - assertThat(json.success).isEqualTo("Valid token"); + assertThat(json.getError()).isNull(); + assertThat(json.getSuccess()).isEqualTo("Valid token"); } private void publishExtension() throws IOException { @@ -138,8 +138,8 @@ private void publishExtension() throws IOException { var response = restTemplate.postForEntity(apiCall("/api/-/publish?token={token}"), bytes, ExtensionJson.class, "test_token"); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); - assertThat(response.getBody().error).isNull(); - assertThat(response.getBody().name).isEqualTo("EditorConfig"); + assertThat(response.getBody().getError()).isNull(); + assertThat(response.getBody().getName()).isEqualTo("EditorConfig"); } } @@ -149,14 +149,14 @@ private void publishDuplicateExtensionLowercase() throws IOException { var response = restTemplate.postForEntity(apiCall("/api/-/publish?token={token}"), bytes, ExtensionJson.class, "test_token"); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); - assertThat(response.getBody().error).isEqualTo("Extension editorconfig.editorconfig 0.16.6 is already published."); + assertThat(response.getBody().getError()).isEqualTo("Extension editorconfig.editorconfig 0.16.6 is already published."); } } private void getExtensionMetadata(String url) { var response = restTemplate.getForEntity(apiCall(url), ExtensionJson.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getBody().description).isEqualTo("EditorConfig Support for Visual Studio Code"); + assertThat(response.getBody().getDescription()).isEqualTo("EditorConfig Support for Visual Studio Code"); } private void getVersionsMetadata(String namespace, String extension, String target) { @@ -167,18 +167,18 @@ private void getVersionsMetadata(String namespace, String extension, String targ var response = restTemplate.getForEntity(apiCall(path + "/versions"), VersionsJson.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getBody().versions.size()).isEqualTo(1); + assertThat(response.getBody().getVersions().size()).isEqualTo(1); var version = "0.16.6"; var versionPath = path + "/" + version; - assertThat(response.getBody().versions.get(version)).isEqualTo(apiCall(versionPath)); + assertThat(response.getBody().getVersions().get(version)).isEqualTo(apiCall(versionPath)); } private void getVersionReferencesMetadata(String path) { var response = restTemplate.getForEntity(apiCall(path), VersionReferencesJson.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getBody().versions.size()).isEqualTo(1); - assertThat(response.getBody().versions.get(0).version).isEqualTo("0.16.6"); + assertThat(response.getBody().getVersions().size()).isEqualTo(1); + assertThat(response.getBody().getVersions().get(0).getVersion()).isEqualTo("0.16.6"); } private void getFile(String path) { @@ -191,15 +191,15 @@ private void getFile(String path) { private void getReviews() { var response = restTemplate.getForEntity(apiCall("/api/editorconfig/editorconfig/reviews"), ReviewListJson.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getBody().error).isNull(); - assertThat(response.getBody().reviews.size()).isEqualTo(0); + assertThat(response.getBody().getError()).isNull(); + assertThat(response.getBody().getReviews().size()).isEqualTo(0); } private void searchExtension() { var response = restTemplate.getForEntity(apiCall("/api/-/search?query=editorconfig"), SearchResultJson.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getBody().extensions.size()).isEqualTo(1); - assertThat(response.getBody().extensions.get(0).description) + assertThat(response.getBody().getExtensions().size()).isEqualTo(1); + assertThat(response.getBody().getExtensions().get(0).getDescription()) .isEqualTo("EditorConfig Support for Visual Studio Code"); } diff --git a/server/src/test/java/org/eclipse/openvsx/RegistryAPITest.java b/server/src/test/java/org/eclipse/openvsx/RegistryAPITest.java index b6e78aabe..100305eeb 100644 --- a/server/src/test/java/org/eclipse/openvsx/RegistryAPITest.java +++ b/server/src/test/java/org/eclipse/openvsx/RegistryAPITest.java @@ -119,8 +119,8 @@ void testPublicNamespace() throws Exception { mockMvc.perform(get("/api/{namespace}", "foobar")) .andExpect(status().isOk()) .andExpect(content().json(namespaceJson(n -> { - n.name = "foobar"; - n.verified = false; + n.setName("foobar"); + n.setVerified(false); }))); } @@ -135,8 +135,8 @@ void testVerifiedNamespace() throws Exception { mockMvc.perform(get("/api/{namespace}", "foobar")) .andExpect(status().isOk()) .andExpect(content().json(namespaceJson(n -> { - n.name = "foobar"; - n.verified = true; + n.setName("foobar"); + n.setVerified(true); }))); } @@ -156,12 +156,12 @@ void testExtension() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}", "foo", "bar")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -177,10 +177,10 @@ void testExtensionWithPublicKey() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}", "foo", "bar")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.files = Map.of("publicKey", "http://localhost/api/-/public-key/" + keyPair.getPublicId()); + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setFiles(Map.of("publicKey", "http://localhost/api/-/public-key/" + keyPair.getPublicId())); }))); } @@ -193,13 +193,13 @@ void testExtensionNonDefaultTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}", "foo", "bar")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (alpine x64)"; - e.targetPlatform = "alpine-x64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (alpine x64)"); + e.setTargetPlatform("alpine-x64"); }))); } @@ -212,13 +212,13 @@ void testExtensionLinuxTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{target}", "foo", "bar", "linux-x64")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.targetPlatform = "linux-x64"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (linux x64)"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (linux x64)"); + e.setTargetPlatform("linux-x64"); }))); } @@ -257,12 +257,12 @@ void testExtensionVersion() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{version}", "foo", "bar", "1.0.0")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -275,12 +275,13 @@ void testExtensionVersionNonDefaultTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{version}", "foo", "bar", "1.0.0")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (darwin arm64)"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (darwin arm64)"); + e.setTargetPlatform("darwin-arm64"); }))); } @@ -293,12 +294,13 @@ void testExtensionVersionMacOSXTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{target}/{version}", "foo", "bar", "darwin-arm64", "1.0.0")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (darwin arm64)"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (darwin arm64)"); + e.setTargetPlatform("darwin-arm64"); }))); } @@ -311,13 +313,13 @@ void testLatestExtensionVersion() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{version}", "foo", "bar", "latest")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.versionAlias = List.of("latest"); + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setVersionAlias(List.of("latest")); }))); } @@ -331,14 +333,14 @@ void testLatestExtensionVersionNonDefaultTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{version}", "foo", "bar", "latest")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (alpine arm64)"; - e.versionAlias = List.of("latest"); - e.targetPlatform = "alpine-arm64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (alpine arm64)"); + e.setTargetPlatform("alpine-arm64"); + e.setVersionAlias(List.of("latest")); }))); } @@ -352,14 +354,14 @@ void testLatestExtensionVersionAlpineLinuxTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{target}/{version}", "foo", "bar", "alpine-arm64", "latest")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (alpine arm64)"; - e.versionAlias = List.of("latest"); - e.targetPlatform = "alpine-arm64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (alpine arm64)"); + e.setTargetPlatform("alpine-arm64"); + e.setVersionAlias(List.of("latest")); }))); } @@ -373,14 +375,14 @@ void testPreReleaseExtensionVersion() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{version}", "foo", "bar", "pre-release")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.versionAlias = List.of("pre-release", "latest"); - e.preRelease = true; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setVersionAlias(List.of("pre-release", "latest")); + e.setPreRelease(true); }))); } @@ -395,14 +397,15 @@ void testPreReleaseExtensionVersionNonDefaultTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{version}", "foo", "bar", "pre-release")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (web)"; - e.versionAlias = List.of("pre-release", "latest"); - e.preRelease = true; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (web)"); + e.setTargetPlatform("web"); + e.setVersionAlias(List.of("pre-release", "latest")); + e.setPreRelease(true); }))); } @@ -417,14 +420,15 @@ void testPreReleaseExtensionVersionWebTarget() throws Exception { mockMvc.perform(get("/api/{namespace}/{extension}/{target}/{version}", "foo", "bar", "web", "pre-release")) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar (web)"; - e.versionAlias = List.of("pre-release", "latest"); - e.preRelease = true; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar (web)"); + e.setTargetPlatform("web"); + e.setVersionAlias(List.of("pre-release", "latest")); + e.setPreRelease(true); }))); } @@ -535,21 +539,21 @@ void testReviews() throws Exception { .andExpect(status().isOk()) .andExpect(content().json(reviewsJson(rs -> { var u1 = new UserJson(); - u1.loginName = "user1"; + u1.setLoginName("user1"); var r1 = new ReviewJson(); - r1.user = u1; - r1.rating = 3; - r1.comment = "Somewhat ok"; - r1.timestamp = "2000-01-01T10:00Z"; - rs.reviews.add(r1); + r1.setUser(u1); + r1.setRating(3); + r1.setComment("Somewhat ok"); + r1.setTimestamp("2000-01-01T10:00Z"); + rs.getReviews().add(r1); var u2 = new UserJson(); - u2.loginName = "user2"; + u2.setLoginName("user2"); var r2 = new ReviewJson(); - r2.user = u2; - r2.rating = 4; - r2.comment = "Quite good"; - r2.timestamp = "2000-01-01T10:00Z"; - rs.reviews.add(r2); + r2.setUser(u2); + r2.setRating(4); + r2.setComment("Quite good"); + r2.setTimestamp("2000-01-01T10:00Z"); + rs.getReviews().add(r2); }))); } @@ -563,15 +567,15 @@ void testSearch() throws Exception { mockMvc.perform(get("/api/-/search?query={query}&size={size}&offset={offset}", "foo", "10", "0")) .andExpect(status().isOk()) .andExpect(content().json(searchJson(s -> { - s.offset = 0; - s.totalSize = 1; + s.setOffset(0); + s.setTotalSize(1); var e1 = new SearchEntryJson(); - e1.namespace = "foo"; - e1.name = "bar"; - e1.version = "1.0.0"; - e1.timestamp = "2000-01-01T10:00Z"; - e1.displayName = "Foo Bar"; - s.extensions.add(e1); + e1.setNamespace("foo"); + e1.setName("bar"); + e1.setVersion("1.0.0"); + e1.setTimestamp("2000-01-01T10:00Z"); + e1.setDisplayName("Foo Bar"); + s.getExtensions().add(e1); }))); } @@ -597,12 +601,12 @@ void testGetQueryExtensionName() throws Exception { mockMvc.perform(get("/api/-/query?extensionName={extensionName}", "bar")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -612,12 +616,12 @@ void testGetQueryNamespace() throws Exception { mockMvc.perform(get("/api/-/query?namespaceName={namespaceName}", "foo")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -646,12 +650,12 @@ void testGetQueryExtensionId() throws Exception { mockMvc.perform(get("/api/-/query?extensionId={extensionId}", "foo.bar")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -661,12 +665,12 @@ void testGetQueryExtensionVersion() throws Exception { mockMvc.perform(get("/api/-/query?extensionId={id}&extensionVersion={version}", "foo.bar", "1.0.0")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -676,12 +680,12 @@ void testGetQueryExtensionUuid() throws Exception { mockMvc.perform(get("/api/-/query?extensionUuid={extensionUuid}", "5678")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -691,53 +695,61 @@ void testGetQueryNamespaceUuid() throws Exception { mockMvc.perform(get("/api/-/query?namespaceUuid={namespaceUuid}", "1234")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @Test void testGetQueryMultipleTargets() throws Exception { var versions = mockExtensionVersionTargetPlatforms(); - var query = new QueryRequest(); - query.namespaceUuid = "1234"; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + null, + null, + null, + null, + null, + "1234", + false, + null, + 100, + 0 + ); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); mockMvc.perform(get("/api/-/query?namespaceUuid={namespaceUuid}", "1234")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.targetPlatform = "darwin-x64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("darwin-x64"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.targetPlatform = "linux-x64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("linux-x64"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.targetPlatform = "alpine-arm64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("alpine-arm64"); }))); } @@ -747,12 +759,12 @@ void testGetQueryV2ExtensionName() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionName={extensionName}", "bar")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -762,12 +774,12 @@ void testGetQueryV2Namespace() throws Exception { mockMvc.perform(get("/api/v2/-/query?namespaceName={namespaceName}", "foo")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -796,84 +808,92 @@ void testGetQueryV2ExtensionId() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}", "foo.bar")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @Test void testGetQueryV2IncludeAllVersionsTrue() throws Exception { var versions = mockExtensionVersionVersionsTargetPlatforms(); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.includeAllVersions = true; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + null, + null, + null, + null, + true, + null, + 100, + 0 + ); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&includeAllVersions={includeAllVersions}", "foo.bar", "true")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.targetPlatform = "darwin-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/darwin-x64/1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("darwin-x64"); + e.setUrl("http://localhost/api/foo/bar/darwin-x64/1.0.0"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.targetPlatform = "darwin-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/darwin-x64/2.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("darwin-x64"); + e.setUrl("http://localhost/api/foo/bar/darwin-x64/2.0.0"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.targetPlatform = "linux-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/linux-x64/1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("linux-x64"); + e.setUrl("http://localhost/api/foo/bar/linux-x64/1.0.0"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.targetPlatform = "linux-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/linux-x64/2.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("linux-x64"); + e.setUrl("http://localhost/api/foo/bar/linux-x64/2.0.0"); }))); } @Test void testGetQueryV2IncludeAllVersionsFalse() throws Exception { var versions = mockExtensionVersionVersions(); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.includeAllVersions = false; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + null, + null, + null, + null, + false, + null, + 100, + 0 + ); versions = versions.stream().filter(ev -> ev.getVersion().equals("3.0.0")).collect(Collectors.toList()); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); @@ -881,27 +901,32 @@ void testGetQueryV2IncludeAllVersionsFalse() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&includeAllVersions={includeAllVersions}", "foo.bar", "false")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "3.0.0"; - e.versionAlias = List.of("latest"); - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/universal/3.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("3.0.0"); + e.setVersionAlias(List.of("latest")); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setUrl("http://localhost/api/foo/bar/universal/3.0.0"); }))); } @Test void testGetQueryV2IncludeAllVersionsLinks() throws Exception { var versions = mockExtensionVersionVersions(); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.includeAllVersions = false; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + null, + null, + null, + null, + false, + null, + 100, + 0 + ); versions = versions.stream().filter(ev -> ev.getVersion().equals("3.0.0")).collect(Collectors.toList()); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); @@ -909,32 +934,38 @@ void testGetQueryV2IncludeAllVersionsLinks() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&includeAllVersions={includeAllVersions}", "foo.bar", "links")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "3.0.0"; - e.versionAlias = List.of("latest"); - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = Map.of( + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("3.0.0"); + e.setVersionAlias(List.of("latest")); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setAllVersions(Map.of( "latest", "http://localhost/api/foo/bar/latest", "3.0.0", "http://localhost/api/foo/bar/3.0.0", "2.0.0", "http://localhost/api/foo/bar/2.0.0", "1.0.0", "http://localhost/api/foo/bar/1.0.0" - ); - e.url = "http://localhost/api/foo/bar/universal/3.0.0"; + )); + e.setUrl("http://localhost/api/foo/bar/universal/3.0.0"); }))); } @Test void testGetQueryV2MultipleTargetsIncludeAllVersionsLinks() throws Exception { var versions = mockExtensionVersionVersionsTargetPlatforms(); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.includeAllVersions = false; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + null, + null, + null, + null, + false, + null, + 100, + 0 + ); versions = versions.stream().filter(ev -> ev.getVersion().equals("2.0.0")).collect(Collectors.toList()); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); @@ -942,88 +973,96 @@ void testGetQueryV2MultipleTargetsIncludeAllVersionsLinks() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&includeAllVersions={includeAllVersions}", "foo.bar", "links")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.targetPlatform = "darwin-x64"; - e.versionAlias = List.of("latest"); - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = Map.of( + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setTargetPlatform("darwin-x64"); + e.setVersionAlias(List.of("latest")); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setAllVersions(Map.of( "latest", "http://localhost/api/foo/bar/latest", "2.0.0", "http://localhost/api/foo/bar/2.0.0", "1.0.0", "http://localhost/api/foo/bar/1.0.0" - ); - e.url = "http://localhost/api/foo/bar/darwin-x64/2.0.0"; + )); + e.setUrl("http://localhost/api/foo/bar/darwin-x64/2.0.0"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.targetPlatform = "linux-x64"; - e.versionAlias = List.of("latest"); - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = Map.of( + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setTargetPlatform("linux-x64"); + e.setVersionAlias(List.of("latest")); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setAllVersions(Map.of( "latest", "http://localhost/api/foo/bar/latest", "2.0.0", "http://localhost/api/foo/bar/2.0.0", "1.0.0", "http://localhost/api/foo/bar/1.0.0" - ); - e.url = "http://localhost/api/foo/bar/linux-x64/2.0.0"; + )); + e.setUrl("http://localhost/api/foo/bar/linux-x64/2.0.0"); }))); } @Test void testGetQueryV2TargetPlatformIncludeAllVersionsTrue() throws Exception { var versions = mockExtensionVersionVersionsTargetPlatforms("linux-x64"); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.targetPlatform = "linux-x64"; - query.includeAllVersions = true; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + null, + null, + null, + null, + true, + "linux-x64", + 100, + 0 + ); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&targetPlatform={targetPlatform}&includeAllVersions={includeAllVersions}", "foo.bar", "linux-x64", "true")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.targetPlatform = "linux-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/linux-x64/1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setTargetPlatform("linux-x64"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setUrl("http://localhost/api/foo/bar/linux-x64/1.0.0"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.targetPlatform = "linux-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/linux-x64/2.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setTargetPlatform("linux-x64"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setUrl("http://localhost/api/foo/bar/linux-x64/2.0.0"); }))); } @Test void testGetQueryV2ExtensionVersionIncludeAllVersionsTrue() throws Exception { var versions = mockExtensionVersionVersionsTargetPlatforms(); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.extensionVersion = "2.0.0"; - query.includeAllVersions = false; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + "2.0.0", + null, + null, + null, + false, + null, + 100, + 0 + ); versions = versions.stream().filter(ev -> ev.getVersion().equals("2.0.0")).collect(Collectors.toList()); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); @@ -1031,39 +1070,42 @@ void testGetQueryV2ExtensionVersionIncludeAllVersionsTrue() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&extensionVersion={extensionVersion}&includeAllVersions={includeAllVersions}", "foo.bar", "2.0.0", "true")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.targetPlatform = "darwin-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/darwin-x64/2.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setTargetPlatform("darwin-x64"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setUrl("http://localhost/api/foo/bar/darwin-x64/2.0.0"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.targetPlatform = "linux-x64"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/linux-x64/2.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setTargetPlatform("linux-x64"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setUrl("http://localhost/api/foo/bar/linux-x64/2.0.0"); }))); } @Test void testGetQueryV2ExtensionVersionIncludeAllVersionsFalse() throws Exception { var versions = mockExtensionVersionVersions(); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.extensionVersion = "2.0.0"; - query.includeAllVersions = false; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + "2.0.0", + null, + null, + null, + false, + null, + 100, + 0 + ); versions = versions.stream().filter(ev -> ev.getVersion().equals("2.0.0")).collect(Collectors.toList()); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); @@ -1071,27 +1113,31 @@ void testGetQueryV2ExtensionVersionIncludeAllVersionsFalse() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&extensionVersion={extensionVersion}&includeAllVersions={includeAllVersions}", "foo.bar", "2.0.0", "false")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = null; - e.url = "http://localhost/api/foo/bar/universal/2.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setUrl("http://localhost/api/foo/bar/universal/2.0.0"); }))); } @Test void testGetQueryV2ExtensionVersionIncludeAllVersionsLinks() throws Exception { var versions = mockExtensionVersionVersions(); - var query = new QueryRequest(); - query.namespaceName = "foo"; - query.extensionName = "bar"; - query.extensionVersion = "2.0.0"; - query.includeAllVersions = false; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + "foo", + "bar", + "2.0.0", + null, + null, + null, + false, + null, + 100, + 0 + ); versions = versions.stream().filter(ev -> ev.getVersion().equals("2.0.0")).collect(Collectors.toList()); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); @@ -1099,19 +1145,19 @@ void testGetQueryV2ExtensionVersionIncludeAllVersionsLinks() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionId={extensionId}&extensionVersion={extensionVersion}&includeAllVersions={includeAllVersions}", "foo.bar", "2.0.0", "links")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "2.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.allVersions = Map.of( + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("2.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setAllVersions(Map.of( "latest", "http://localhost/api/foo/bar/latest", "3.0.0", "http://localhost/api/foo/bar/3.0.0", "2.0.0", "http://localhost/api/foo/bar/2.0.0", "1.0.0", "http://localhost/api/foo/bar/1.0.0" - ); - e.url = "http://localhost/api/foo/bar/universal/2.0.0"; + )); + e.setUrl("http://localhost/api/foo/bar/universal/2.0.0"); }))); } @@ -1121,12 +1167,12 @@ void testGetQueryV2ExtensionUuid() throws Exception { mockMvc.perform(get("/api/v2/-/query?extensionUuid={extensionUuid}", "5678")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @@ -1136,54 +1182,61 @@ void testGetQueryV2NamespaceUuid() throws Exception { mockMvc.perform(get("/api/v2/-/query?namespaceUuid={namespaceUuid}", "1234")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); }))); } @Test void testGetQueryV2MultipleTargets() throws Exception { var versions = mockExtensionVersionTargetPlatforms(); - var query = new QueryRequest(); - query.namespaceUuid = "1234"; - query.includeAllVersions = false; - query.offset = 0; - query.size = 100; + var query = new QueryRequest( + null, + null, + null, + null, + null, + "1234", + false, + null, + 100, + 0 + ); Mockito.when(repositories.findActiveVersions(query)) .thenReturn(new PageImpl<>(versions, Pageable.ofSize(100), versions.size())); mockMvc.perform(get("/api/v2/-/query?namespaceUuid={namespaceUuid}", "1234")) .andExpect(status().isOk()) .andExpect(content().json(queryResultJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.targetPlatform = "darwin-x64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("darwin-x64"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.targetPlatform = "linux-x64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("linux-x64"); }, e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; - e.verified = false; - e.timestamp = "2000-01-01T10:00Z"; - e.displayName = "Foo Bar"; - e.targetPlatform = "alpine-arm64"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); + e.setVerified(false); + e.setTimestamp("2000-01-01T10:00Z"); + e.setDisplayName("Foo Bar"); + e.setTargetPlatform("alpine-arm64"); }))); } @@ -1242,7 +1295,7 @@ void testCreateNamespace() throws Exception { mockAccessToken(); mockMvc.perform(post("/api/-/namespace/create?token={token}", "my_token") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foobar"; }))) + .content(namespaceJson(n -> { n.setName("foobar"); }))) .andExpect(status().isCreated()) .andExpect(redirectedUrl("http://localhost/api/foobar")) .andExpect(content().json(successJson("Created namespace foobar"))); @@ -1263,7 +1316,7 @@ void testCreateNamespaceInvalidName() throws Exception { mockAccessToken(); mockMvc.perform(post("/api/-/namespace/create?token={token}", "my_token") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foo.bar"; }))) + .content(namespaceJson(n -> { n.setName("foo.bar"); }))) .andExpect(status().isBadRequest()) .andExpect(content().json(errorJson("Invalid namespace name: foo.bar"))); } @@ -1274,7 +1327,7 @@ void testCreateNamespaceInactiveToken() throws Exception { token.setActive(false); mockMvc.perform(post("/api/-/namespace/create?token={token}", "my_token") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foobar"; }))) + .content(namespaceJson(n -> { n.setName("foobar"); }))) .andExpect(status().isBadRequest()) .andExpect(content().json(errorJson("Invalid access token."))); } @@ -1287,7 +1340,7 @@ void testCreateExistingNamespace() throws Exception { mockMvc.perform(post("/api/-/namespace/create?token={token}", "my_token") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foobar"; }))) + .content(namespaceJson(n -> { n.setName("foobar"); }))) .andExpect(status().isBadRequest()) .andExpect(content().json(errorJson("Namespace already exists: foobar"))); } @@ -1376,14 +1429,14 @@ void testPublishRequireLicenseOk() throws Exception { .content(bytes)) .andExpect(status().isCreated()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); var u = new UserJson(); - u.loginName = "test_user"; - e.publishedBy = u; - e.verified = true; - e.downloadable = true; + u.setLoginName("test_user"); + e.setPublishedBy(u); + e.setVerified(true); + e.setDownloadable(true); }))); } finally { extensions.requireLicense = previousRequireLicense; @@ -1423,14 +1476,14 @@ void testPublishVerifiedOwner() throws Exception { .content(bytes)) .andExpect(status().isCreated()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); var u = new UserJson(); - u.loginName = "test_user"; - e.publishedBy = u; - e.verified = true; - e.downloadable = true; + u.setLoginName("test_user"); + e.setPublishedBy(u); + e.setVerified(true); + e.setDownloadable(true); }))); } @@ -1444,14 +1497,14 @@ void testPublishVerifiedContributor() throws Exception { .content(bytes)) .andExpect(status().isCreated()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); var u = new UserJson(); - u.loginName = "test_user"; - e.publishedBy = u; - e.verified = true; - e.downloadable = true; + u.setLoginName("test_user"); + e.setPublishedBy(u); + e.setVerified(true); + e.setDownloadable(true); }))); } @@ -1465,14 +1518,14 @@ void testPublishSoleContributor() throws Exception { .content(bytes)) .andExpect(status().isCreated()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); var u = new UserJson(); - u.loginName = "test_user"; - e.publishedBy = u; - e.verified = false; - e.downloadable = true; + u.setLoginName("test_user"); + e.setPublishedBy(u); + e.setVerified(false); + e.setDownloadable(true); }))); } @@ -1486,14 +1539,14 @@ void testPublishRestrictedPrivileged() throws Exception { .content(bytes)) .andExpect(status().isCreated()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foo"; - e.name = "bar"; - e.version = "1.0.0"; + e.setNamespace("foo"); + e.setName("bar"); + e.setVersion("1.0.0"); var u = new UserJson(); - u.loginName = "test_user"; - e.publishedBy = u; - e.verified = true; - e.downloadable = true; + u.setLoginName("test_user"); + e.setPublishedBy(u); + e.setVerified(true); + e.setDownloadable(true); }))); } @@ -1600,7 +1653,7 @@ void testPostReview() throws Exception { mockMvc.perform(post("/api/{namespace}/{extension}/review", "foo", "bar") .contentType(MediaType.APPLICATION_JSON) .content(reviewJson(r -> { - r.rating = 3; + r.setRating(3); })) .with(user("test_user")) .with(csrf().asHeader())) @@ -1613,7 +1666,7 @@ void testPostReviewNotLoggedIn() throws Exception { mockMvc.perform(post("/api/{namespace}/{extension}/review", "foo", "bar") .contentType(MediaType.APPLICATION_JSON) .content(reviewJson(r -> { - r.rating = 3; + r.setRating(3); })).with(csrf().asHeader())) .andExpect(status().isForbidden()); } @@ -1623,7 +1676,7 @@ void testPostReviewInvalidRating() throws Exception { mockMvc.perform(post("/api/{namespace}/{extension}/review", "foo", "bar") .contentType(MediaType.APPLICATION_JSON) .content(reviewJson(r -> { - r.rating = 100; + r.setRating(100); })) .with(user("test_user")) .with(csrf().asHeader())) @@ -1637,7 +1690,7 @@ void testPostReviewUnknownExtension() throws Exception { mockMvc.perform(post("/api/{namespace}/{extension}/review", "foo", "bar") .contentType(MediaType.APPLICATION_JSON) .content(reviewJson(r -> { - r.rating = 3; + r.setRating(3); })) .with(user("test_user")) .with(csrf().asHeader())) @@ -1658,7 +1711,7 @@ void testPostExistingReview() throws Exception { mockMvc.perform(post("/api/{namespace}/{extension}/review", "foo", "bar") .contentType(MediaType.APPLICATION_JSON) .content(reviewJson(r -> { - r.rating = 3; + r.setRating(3); })) .with(user("test_user")) .with(csrf().asHeader())) @@ -1758,13 +1811,21 @@ private String namespaceJson(Consumer content) throws JsonProcess } private void mockInactiveExtensionVersion(String namespaceName, String extensionName) { - var request = new QueryRequest(); - request.namespaceName = namespaceName; - request.extensionName = extensionName; - request.size = 100; + var query = new QueryRequest( + namespaceName, + extensionName, + null, + null, + null, + null, + false, + null, + 100, + 0 + ); - Mockito.when(repositories.findActiveVersions(request)) - .thenReturn(new PageImpl<>(Collections.emptyList(), Pageable.ofSize(request.size), 0)); + Mockito.when(repositories.findActiveVersions(query)) + .thenReturn(new PageImpl<>(Collections.emptyList(), Pageable.ofSize(query.size()), 0)); } private List mockExtensionVersionVersionsTargetPlatforms() { @@ -1885,10 +1946,10 @@ private void mockExtensionVersion() { Mockito.when(repositories.findActiveVersions(any(QueryRequest.class))) .then((Answer>) invocation -> { var request = invocation.getArgument(0, QueryRequest.class); - var versions = namespace.getPublicId().equals(request.namespaceUuid) - || namespace.getName().equals(request.namespaceName) - || extension.getPublicId().equals(request.extensionUuid) - || extension.getName().equals(request.extensionName) + var versions = namespace.getPublicId().equals(request.namespaceUuid()) + || namespace.getName().equals(request.namespaceName()) + || extension.getPublicId().equals(request.extensionUuid()) + || extension.getName().equals(request.extensionName()) ? List.of(extVersion) : Collections.emptyList(); @@ -2080,7 +2141,7 @@ private void mockReviews() { private String reviewsJson(Consumer content) throws JsonProcessingException { var json = new ReviewListJson(); - json.reviews = new ArrayList<>(); + json.setReviews(new ArrayList<>()); content.accept(json); return new ObjectMapper().writeValueAsString(json); } @@ -2090,12 +2151,12 @@ private List mockSearch() { var extension = extVersion.getExtension(); extension.setId(1L); var entry1 = new ExtensionSearch(); - entry1.id = 1; + entry1.setId(1); var searchHit = new SearchHit<>("0", "1", null, 1.0f, null, null, null, null, null, null, entry1); var searchHits = new SearchHitsImpl<>(1, TotalHitsRelation.EQUAL_TO, 1.0f, "1", null, List.of(searchHit), null, null); Mockito.when(search.isEnabled()) .thenReturn(true); - var searchOptions = new ISearchService.Options("foo", null, null, 10, 0, "desc", "relevance", false); + var searchOptions = new ISearchService.Options("foo", null, null, 10, 0, "desc", "relevance", false, null); Mockito.when(search.search(searchOptions)) .thenReturn(searchHits); return List.of(extVersion); @@ -2103,7 +2164,7 @@ private List mockSearch() { private String searchJson(Consumer content) throws JsonProcessingException { var json = new SearchResultJson(); - json.extensions = new ArrayList<>(); + json.setExtensions(new ArrayList<>()); content.accept(json); return new ObjectMapper().writeValueAsString(json); } diff --git a/server/src/test/java/org/eclipse/openvsx/UserAPITest.java b/server/src/test/java/org/eclipse/openvsx/UserAPITest.java index bcd5967fc..2d96665fc 100644 --- a/server/src/test/java/org/eclipse/openvsx/UserAPITest.java +++ b/server/src/test/java/org/eclipse/openvsx/UserAPITest.java @@ -88,9 +88,9 @@ void testLoggedIn() throws Exception { mockMvc.perform(get("/user")) .andExpect(status().isOk()) .andExpect(content().json(userJson(u -> { - u.loginName = "test_user"; - u.fullName = "Test User"; - u.homepage = "http://example.com/test"; + u.setLoginName("test_user"); + u.setFullName("Test User"); + u.setHomepage("http://example.com/test"); }))); } @@ -99,7 +99,7 @@ void testNotLoggedIn() throws Exception { mockMvc.perform(get("/user")) .andExpect(status().isOk()) .andExpect(content().json(userJson(u -> { - u.error = "Not logged in."; + u.setError("Not logged in."); }))); } @@ -111,12 +111,12 @@ void testAccessTokens() throws Exception { .andExpect(status().isOk()) .andExpect(content().json(accessTokensJson(a -> { var t1 = new AccessTokenJson(); - t1.description = "This is token 1"; - t1.createdTimestamp = "2000-01-01T10:00Z"; + t1.setDescription("This is token 1"); + t1.setCreatedTimestamp("2000-01-01T10:00Z"); a.add(t1); var t3 = new AccessTokenJson(); - t3.description = "This is token 3"; - t3.createdTimestamp = "2000-01-01T10:00Z"; + t3.setDescription("This is token 3"); + t3.setCreatedTimestamp("2000-01-01T10:00Z"); a.add(t3); }))); } @@ -137,8 +137,8 @@ void testCreateAccessToken() throws Exception { .with(csrf().asHeader())) .andExpect(status().isCreated()) .andExpect(content().json(accessTokenJson(t -> { - t.value = "foobar"; - t.description = "This is my token"; + t.setValue("foobar"); + t.setDescription("This is my token"); }))); } @@ -219,10 +219,10 @@ void testOwnNamespaces() throws Exception { .andExpect(status().isOk()) .andExpect(content().json(namespacesJson(a -> { var ns1 = new NamespaceJson(); - ns1.name = "foo"; + ns1.setName("foo"); a.add(ns1); var ns2 = new NamespaceJson(); - ns2.name = "bar"; + ns2.setName("bar"); a.add(ns2); }))); } @@ -242,19 +242,13 @@ void testNamespaceMembers() throws Exception { .andExpect(status().isOk()) .andExpect(content().json(membershipsJson(a -> { var u1 = new UserJson(); - u1.loginName = "test_user"; - var m1 = new NamespaceMembershipJson(); - m1.user = u1; - m1.namespace = "foobar"; - m1.role = NamespaceMembership.ROLE_OWNER; - a.namespaceMemberships.add(m1); + u1.setLoginName("test_user"); + var m1 = new NamespaceMembershipJson("foobar", NamespaceMembership.ROLE_OWNER, u1); + a.getNamespaceMemberships().add(m1); var u2 = new UserJson(); - u2.loginName = "other_user"; - var m2 = new NamespaceMembershipJson(); - m2.user = u2; - m2.namespace = "foobar"; - m2.role = NamespaceMembership.ROLE_CONTRIBUTOR; - a.namespaceMemberships.add(m2); + u2.setLoginName("other_user"); + var m2 = new NamespaceMembershipJson("foobar", NamespaceMembership.ROLE_CONTRIBUTOR, u2); + a.getNamespaceMemberships().add(m2); }))); } @@ -540,7 +534,7 @@ private void mockNamespaceMemberships(String userRole) { private String membershipsJson(Consumer content) throws JsonProcessingException { var json = new NamespaceMembershipListJson(); - json.namespaceMemberships = new ArrayList<>(); + json.setNamespaceMemberships(new ArrayList<>()); content.accept(json); return new ObjectMapper().writeValueAsString(json); } diff --git a/server/src/test/java/org/eclipse/openvsx/adapter/VSCodeAPITest.java b/server/src/test/java/org/eclipse/openvsx/adapter/VSCodeAPITest.java index 683263235..71a36d265 100644 --- a/server/src/test/java/org/eclipse/openvsx/adapter/VSCodeAPITest.java +++ b/server/src/test/java/org/eclipse/openvsx/adapter/VSCodeAPITest.java @@ -626,7 +626,7 @@ private Extension mockSearch(String targetPlatform, boolean active) { private Extension mockSearch(String targetPlatform, String namespaceName, boolean active) { var builtInExtensionNamespace = "vscode"; var entry1 = new ExtensionSearch(); - entry1.id = 1; + entry1.setId(1); List> searchResults = !builtInExtensionNamespace.equals(namespaceName) ? Collections.singletonList(new SearchHit<>("0", "1", null, 1.0f, null, null, null, null, null, null, entry1)) : Collections.emptyList(); @@ -637,13 +637,13 @@ private Extension mockSearch(String targetPlatform, String namespaceName, boolea .thenReturn(true); Mockito.when(search.isEnabled()) .thenReturn(true); - var searchOptions = new ISearchService.Options("yaml", null, targetPlatform, 50, 0, "desc", "relevance", false, builtInExtensionNamespace); + var searchOptions = new ISearchService.Options("yaml", null, targetPlatform, 50, 0, "desc", "relevance", false, new String[]{builtInExtensionNamespace}); Mockito.when(search.search(searchOptions)) .thenReturn(searchHits); var extension = mockExtension(); List results = active ? List.of(extension) : Collections.emptyList(); - Mockito.when(repositories.findActiveExtensionsById(List.of(entry1.id))) + Mockito.when(repositories.findActiveExtensionsById(List.of(entry1.getId()))) .thenReturn(results); var publicIds = Set.of(extension.getPublicId()); diff --git a/server/src/test/java/org/eclipse/openvsx/admin/AdminAPITest.java b/server/src/test/java/org/eclipse/openvsx/admin/AdminAPITest.java index 90d1453bb..8cb57bb66 100644 --- a/server/src/test/java/org/eclipse/openvsx/admin/AdminAPITest.java +++ b/server/src/test/java/org/eclipse/openvsx/admin/AdminAPITest.java @@ -118,10 +118,10 @@ void testGetExtension() throws Exception { .with(csrf().asHeader())) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foobar"; - e.name = "baz"; - e.version = "2.0.0"; - e.active = true; + e.setNamespace("foobar"); + e.setName("baz"); + e.setVersion("2.0.0"); + e.setActive(true); }))); } @@ -138,10 +138,10 @@ void testGetInactiveExtension() throws Exception { .with(csrf().asHeader())) .andExpect(status().isOk()) .andExpect(content().json(extensionJson(e -> { - e.namespace = "foobar"; - e.name = "baz"; - e.version = "2.0.0"; - e.active = false; + e.setNamespace("foobar"); + e.setName("baz"); + e.setVersion("2.0.0"); + e.setActive(false); }))); } @@ -349,7 +349,7 @@ void testGetNamespace() throws Exception { .with(csrf().asHeader())) .andExpect(status().isOk()) .andExpect(content().json(namespaceJson(n -> { - n.name = "foobar"; + n.setName("foobar"); }))); } @@ -389,12 +389,10 @@ void testGetNamespaceMembers() throws Exception { .with(csrf().asHeader())) .andExpect(status().isOk()) .andExpect(content().json(namespaceMemberJson(nml -> { - var m = new NamespaceMembershipJson(); - m.namespace = "foobar"; - m.user = new UserJson(); - m.user.loginName = "other_user"; - m.role = "owner"; - nml.namespaceMemberships = Arrays.asList(m); + var u = new UserJson(); + u.setLoginName("other_user"); + var m = new NamespaceMembershipJson("foobar", "owner", u); + nml.setNamespaceMemberships(List.of(m)); }))); } @@ -402,7 +400,7 @@ void testGetNamespaceMembers() throws Exception { void testCreateNamespaceNotLoggedIn() throws Exception { mockMvc.perform(post("/admin/create-namespace") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foobar"; })) + .content(namespaceJson(n -> { n.setName("foobar"); })) .with(csrf().asHeader())) .andExpect(status().isForbidden()); } @@ -412,7 +410,7 @@ void testCreateNamespaceNotAdmin() throws Exception { mockNormalUser(); mockMvc.perform(post("/admin/create-namespace") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foobar"; })) + .content(namespaceJson(n -> { n.setName("foobar"); })) .with(user("test_user")) .with(csrf().asHeader())) .andExpect(status().isForbidden()); @@ -423,7 +421,7 @@ void testCreateNamespace() throws Exception { mockAdminUser(); mockMvc.perform(post("/admin/create-namespace") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foobar"; })) + .content(namespaceJson(n -> { n.setName("foobar"); })) .with(user("admin_user").authorities(new SimpleGrantedAuthority(("ROLE_ADMIN")))) .with(csrf().asHeader())) .andExpect(status().isCreated()) @@ -439,7 +437,7 @@ void testCreateExistingNamespace() throws Exception { mockMvc.perform(post("/admin/create-namespace") .contentType(MediaType.APPLICATION_JSON) - .content(namespaceJson(n -> { n.name = "foobar"; })) + .content(namespaceJson(n -> { n.setName("foobar"); })) .with(user("admin_user").authorities(new SimpleGrantedAuthority(("ROLE_ADMIN")))) .with(csrf().asHeader())) .andExpect(status().isBadRequest()) @@ -485,14 +483,14 @@ void testGetUserPublishInfo() throws Exception { .with(csrf().asHeader())) .andExpect(status().isOk()) .andExpect(content().json(publishInfoJson(upi -> { - upi.user = new UserJson(); - upi.user.loginName = "test"; - upi.activeAccessTokenNum = 1; + upi.setUser(new UserJson()); + upi.getUser().setLoginName("test"); + upi.setActiveAccessTokenNum(1); var ext1 = new ExtensionJson(); - ext1.namespace = "foobar"; - ext1.name = "baz"; - ext1.version = "1.0.0"; - upi.extensions = Arrays.asList(ext1); + ext1.setNamespace("foobar"); + ext1.setName("baz"); + ext1.setVersion("1.0.0"); + upi.setExtensions(List.of(ext1)); }))); } @@ -745,89 +743,89 @@ void testArchivedReportJson() throws Exception { .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()) .andExpect(content().json(adminStatisticsJson(s -> { - s.year = year; - s.month = month; - s.extensions = extensions; - s.downloads = downloads; - s.downloadsTotal = downloadsTotal; - s.publishers = publishers; - s.averageReviewsPerExtension = averageReviewsPerExtension; - s.namespaceOwners = namespaceOwners; + s.setYear(year); + s.setMonth(month); + s.setExtensions(extensions); + s.setDownloads(downloads); + s.setDownloadsTotal(downloadsTotal); + s.setPublishers(publishers); + s.setAverageReviewsPerExtension(averageReviewsPerExtension); + s.setNamespaceOwners(namespaceOwners); var rating5 = new AdminStatisticsJson.ExtensionsByRating(); - rating5.rating = 5; - rating5.extensions = 136; + rating5.setRating(5); + rating5.setExtensions(136); var rating4 = new AdminStatisticsJson.ExtensionsByRating(); - rating4.rating = 4; - rating4.extensions = 427; + rating4.setRating(4); + rating4.setExtensions(427); var rating3 = new AdminStatisticsJson.ExtensionsByRating(); - rating3.rating = 3; - rating3.extensions = 560; + rating3.setRating(3); + rating3.setExtensions(560); var rating2 = new AdminStatisticsJson.ExtensionsByRating(); - rating2.rating = 2; - rating2.extensions = 16; + rating2.setRating(2); + rating2.setExtensions(16); var rating1 = new AdminStatisticsJson.ExtensionsByRating(); - rating1.rating = 1; - rating1.extensions = 7; - s.extensionsByRating = List.of(rating5, rating4, rating3, rating2, rating1); + rating1.setRating(1); + rating1.setExtensions(7); + s.setExtensionsByRating(List.of(rating5, rating4, rating3, rating2, rating1)); var publishers4 = new AdminStatisticsJson.PublishersByExtensionsPublished(); - publishers4.extensionsPublished = 4; - publishers4.publishers = 52; + publishers4.setExtensionsPublished(4); + publishers4.setPublishers(52); var publishers3 = new AdminStatisticsJson.PublishersByExtensionsPublished(); - publishers3.extensionsPublished = 3; - publishers3.publishers = 70; + publishers3.setExtensionsPublished(3); + publishers3.setPublishers(70); var publishers2 = new AdminStatisticsJson.PublishersByExtensionsPublished(); - publishers2.extensionsPublished = 2; - publishers2.publishers = 99; + publishers2.setExtensionsPublished(2); + publishers2.setPublishers(99); var publishers1 = new AdminStatisticsJson.PublishersByExtensionsPublished(); - publishers1.extensionsPublished = 1; - publishers1.publishers = 670; - s.publishersByExtensionsPublished = List.of(publishers4, publishers3, publishers2, publishers1); + publishers1.setExtensionsPublished(1); + publishers1.setPublishers(670); + s.setPublishersByExtensionsPublished(List.of(publishers4, publishers3, publishers2, publishers1)); var activePublisher1 = new AdminStatisticsJson.TopMostActivePublishingUsers(); - activePublisher1.userLoginName = "u_bar"; - activePublisher1.publishedExtensionVersions = 543; + activePublisher1.setUserLoginName("u_bar"); + activePublisher1.setPublishedExtensionVersions(543); var activePublisher2 = new AdminStatisticsJson.TopMostActivePublishingUsers(); - activePublisher2.userLoginName = "u_foo"; - activePublisher2.publishedExtensionVersions = 93; + activePublisher2.setUserLoginName("u_foo"); + activePublisher2.setPublishedExtensionVersions(93); var activePublisher3 = new AdminStatisticsJson.TopMostActivePublishingUsers(); - activePublisher3.userLoginName = "u_baz"; - activePublisher3.publishedExtensionVersions = 82; - s.topMostActivePublishingUsers = List.of(activePublisher1, activePublisher2, activePublisher3); + activePublisher3.setUserLoginName("u_baz"); + activePublisher3.setPublishedExtensionVersions(82); + s.setTopMostActivePublishingUsers(List.of(activePublisher1, activePublisher2, activePublisher3)); var namespaceExtensions1 = new AdminStatisticsJson.TopNamespaceExtensions(); - namespaceExtensions1.namespace = "n_baz"; - namespaceExtensions1.extensions = 1239; + namespaceExtensions1.setNamespace("n_baz"); + namespaceExtensions1.setExtensions(1239); var namespaceExtensions2 = new AdminStatisticsJson.TopNamespaceExtensions(); - namespaceExtensions2.namespace = "n_bar"; - namespaceExtensions2.extensions = 48; + namespaceExtensions2.setNamespace("n_bar"); + namespaceExtensions2.setExtensions(48); var namespaceExtensions3 = new AdminStatisticsJson.TopNamespaceExtensions(); - namespaceExtensions3.namespace = "n_foo"; - namespaceExtensions3.extensions = 9; - s.topNamespaceExtensions = List.of(namespaceExtensions1, namespaceExtensions2, namespaceExtensions3); + namespaceExtensions3.setNamespace("n_foo"); + namespaceExtensions3.setExtensions(9); + s.setTopNamespaceExtensions(List.of(namespaceExtensions1, namespaceExtensions2, namespaceExtensions3)); var namespaceExtensionVersions1 = new AdminStatisticsJson.TopNamespaceExtensionVersions(); - namespaceExtensionVersions1.namespace = "nv_baz"; - namespaceExtensionVersions1.extensionVersions = 932; + namespaceExtensionVersions1.setNamespace("nv_baz"); + namespaceExtensionVersions1.setExtensionVersions(932); var namespaceExtensionVersions2 = new AdminStatisticsJson.TopNamespaceExtensionVersions(); - namespaceExtensionVersions2.namespace = "nv_foo"; - namespaceExtensionVersions2.extensionVersions = 234; + namespaceExtensionVersions2.setNamespace("nv_foo"); + namespaceExtensionVersions2.setExtensionVersions(234); var namespaceExtensionVersions3 = new AdminStatisticsJson.TopNamespaceExtensionVersions(); - namespaceExtensionVersions3.namespace = "nv_bar"; - namespaceExtensionVersions3.extensionVersions = 67; - s.topNamespaceExtensionVersions = List.of(namespaceExtensionVersions1, namespaceExtensionVersions2, namespaceExtensionVersions3); + namespaceExtensionVersions3.setNamespace("nv_bar"); + namespaceExtensionVersions3.setExtensionVersions(67); + s.setTopNamespaceExtensionVersions(List.of(namespaceExtensionVersions1, namespaceExtensionVersions2, namespaceExtensionVersions3)); var mostDownloadedExtensions1 = new AdminStatisticsJson.TopMostDownloadedExtensions(); - mostDownloadedExtensions1.extensionIdentifier = "foo.baz"; - mostDownloadedExtensions1.downloads = 4378L; + mostDownloadedExtensions1.setExtensionIdentifier("foo.baz"); + mostDownloadedExtensions1.setDownloads(4378L); var mostDownloadedExtensions2 = new AdminStatisticsJson.TopMostDownloadedExtensions(); - mostDownloadedExtensions2.extensionIdentifier = "foo.bar"; - mostDownloadedExtensions2.downloads = 3847L; + mostDownloadedExtensions2.setExtensionIdentifier("foo.bar"); + mostDownloadedExtensions2.setDownloads(3847L); var mostDownloadedExtensions3 = new AdminStatisticsJson.TopMostDownloadedExtensions(); - mostDownloadedExtensions3.extensionIdentifier = "bar.foo"; - mostDownloadedExtensions3.downloads = 1237L; - s.topMostDownloadedExtensions = List.of(mostDownloadedExtensions1, mostDownloadedExtensions2, mostDownloadedExtensions3); + mostDownloadedExtensions3.setExtensionIdentifier("bar.foo"); + mostDownloadedExtensions3.setDownloads(1237L); + s.setTopMostDownloadedExtensions(List.of(mostDownloadedExtensions1, mostDownloadedExtensions2, mostDownloadedExtensions3)); }))); } @@ -869,12 +867,7 @@ void testChangeNamespace() throws Exception { "\"mergeIfNewNamespaceAlreadyExists\": true" + "}"; - var json = new ChangeNamespaceJson(); - json.oldNamespace = "foo"; - json.newNamespace = "bar"; - json.removeOldNamespace = false; - json.mergeIfNewNamespaceAlreadyExists = true; - + var json = new ChangeNamespaceJson("foo", "bar", false, true); mockMvc.perform(post("/admin/change-namespace") .with(user("admin_user").authorities(new SimpleGrantedAuthority(("ROLE_ADMIN")))) .with(csrf().asHeader()) diff --git a/server/src/test/java/org/eclipse/openvsx/cache/CacheServiceTest.java b/server/src/test/java/org/eclipse/openvsx/cache/CacheServiceTest.java index 42513d24b..950bd025a 100644 --- a/server/src/test/java/org/eclipse/openvsx/cache/CacheServiceTest.java +++ b/server/src/test/java/org/eclipse/openvsx/cache/CacheServiceTest.java @@ -117,11 +117,11 @@ void testUpdateExistingUser() { assertNull(cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class)); var json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), extVersion.getVersion()); - assertEquals(loginName, json.publishedBy.loginName); - assertEquals(fullName, json.publishedBy.fullName); - assertEquals(htmlUrl, json.publishedBy.homepage); - assertEquals(authority, json.publishedBy.provider); - assertEquals(avatarUrl, json.publishedBy.avatarUrl); + assertEquals(loginName, json.getPublishedBy().getLoginName()); + assertEquals(fullName, json.getPublishedBy().getFullName()); + assertEquals(htmlUrl, json.getPublishedBy().getHomepage()); + assertEquals(authority, json.getPublishedBy().getProvider()); + assertEquals(avatarUrl, json.getPublishedBy().getAvatarUrl()); var cachedJson = cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class); assertEquals(json, cachedJson); @@ -138,8 +138,8 @@ void testPostReview() { extVersion.getTargetPlatform(), extVersion.getVersion()); var json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), extVersion.getVersion()); - assertEquals(Long.valueOf(0), json.reviewCount); - assertNull(json.averageRating); + assertEquals(Long.valueOf(0), json.getReviewCount()); + assertNull(json.getAverageRating()); var poster = new UserData(); poster.setLoginName("user1"); @@ -147,16 +147,16 @@ void testPostReview() { setLoggedInUser(poster); var review = new ReviewJson(); - review.rating = 3; - review.comment = "Somewhat ok"; - review.timestamp = "2000-01-01T10:00Z"; + review.setRating(3); + review.setComment("Somewhat ok"); + review.setTimestamp("2000-01-01T10:00Z"); registry.postReview(review, namespace.getName(), extension.getName()); assertNull(cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class)); json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), extVersion.getVersion()); - assertEquals(Long.valueOf(1), json.reviewCount); - assertEquals(Double.valueOf(3), json.averageRating); + assertEquals(Long.valueOf(1), json.getReviewCount()); + assertEquals(Double.valueOf(3), json.getAverageRating()); var cachedJson = cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class); assertEquals(json, cachedJson); @@ -178,21 +178,21 @@ void testDeleteReview() { setLoggedInUser(poster); var review = new ReviewJson(); - review.rating = 3; - review.comment = "Somewhat ok"; - review.timestamp = "2000-01-01T10:00Z"; + review.setRating(3); + review.setComment("Somewhat ok"); + review.setTimestamp("2000-01-01T10:00Z"); registry.postReview(review, namespace.getName(), extension.getName()); var json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), extVersion.getVersion()); - assertEquals(Long.valueOf(1), json.reviewCount); - assertEquals(Double.valueOf(3), json.averageRating); + assertEquals(Long.valueOf(1), json.getReviewCount()); + assertEquals(Double.valueOf(3), json.getAverageRating()); registry.deleteReview(namespace.getName(), extension.getName()); assertNull(cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class)); json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), extVersion.getVersion()); - assertEquals(Long.valueOf(0), json.reviewCount); - assertNull(json.averageRating); + assertEquals(Long.valueOf(0), json.getReviewCount()); + assertNull(json.getAverageRating()); var cachedJson = cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class); assertEquals(json, cachedJson); @@ -231,15 +231,15 @@ void testDeleteExtensionVersion() { insertNewVersion(extension, extVersion.getPublishedWith(), newVersion); var json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), newVersion); - assertTrue(json.allVersions.containsKey(newVersion)); - assertTrue(json.allVersions.containsKey(oldVersion)); + assertTrue(json.getAllVersions().containsKey(newVersion)); + assertTrue(json.getAllVersions().containsKey(oldVersion)); admins.deleteExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), newVersion, admin); assertNull(cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class)); json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), extVersion.getVersion()); - assertFalse(json.allVersions.containsKey(newVersion)); - assertTrue(json.allVersions.containsKey(oldVersion)); + assertFalse(json.getAllVersions().containsKey(newVersion)); + assertTrue(json.getAllVersions().containsKey(oldVersion)); var cachedJson = cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class); assertEquals(json, cachedJson); @@ -265,10 +265,10 @@ void testUpdateExtension() { assertNull(cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class)); var json = registry.getExtension(namespace.getName(), extension.getName(), extVersion.getTargetPlatform(), oldVersion); - assertTrue(json.allVersions.containsKey(oldVersion)); - assertTrue(json.allVersions.containsKey(newVersion)); - assertTrue(json.allVersions.containsKey("latest")); - assertTrue(json.allVersions.containsKey("pre-release")); + assertTrue(json.getAllVersions().containsKey(oldVersion)); + assertTrue(json.getAllVersions().containsKey(newVersion)); + assertTrue(json.getAllVersions().containsKey("latest")); + assertTrue(json.getAllVersions().containsKey("pre-release")); var cachedJson = cache.getCache(CACHE_EXTENSION_JSON).get(cacheKey, ExtensionJson.class); assertEquals(json, cachedJson); diff --git a/server/src/test/java/org/eclipse/openvsx/eclipse/EclipseServiceTest.java b/server/src/test/java/org/eclipse/openvsx/eclipse/EclipseServiceTest.java index a4f625455..1511eed77 100644 --- a/server/src/test/java/org/eclipse/openvsx/eclipse/EclipseServiceTest.java +++ b/server/src/test/java/org/eclipse/openvsx/eclipse/EclipseServiceTest.java @@ -16,6 +16,7 @@ import java.io.IOException; import java.io.InputStreamReader; +import java.time.Instant; import java.time.LocalDateTime; import java.util.Map; @@ -95,11 +96,11 @@ void testGetPublicProfile() throws Exception { var profile = eclipse.getPublicProfile("test"); assertThat(profile).isNotNull(); - assertThat(profile.name).isEqualTo("test"); - assertThat(profile.githubHandle).isEqualTo("test"); - assertThat(profile.publisherAgreements).isNotNull(); - assertThat(profile.publisherAgreements.openVsx).isNotNull(); - assertThat(profile.publisherAgreements.openVsx.version).isEqualTo("1"); + assertThat(profile.getName()).isEqualTo("test"); + assertThat(profile.getGithubHandle()).isEqualTo("test"); + assertThat(profile.getPublisherAgreements()).isNotNull(); + assertThat(profile.getPublisherAgreements().getOpenVsx()).isNotNull(); + assertThat(profile.getPublisherAgreements().getOpenVsx().getVersion()).isEqualTo("1"); } @Test @@ -110,11 +111,12 @@ void testGetUserProfile() throws Exception { var profile = eclipse.getUserProfile("12345"); assertThat(profile).isNotNull(); - assertThat(profile.name).isEqualTo("test"); - assertThat(profile.githubHandle).isEqualTo("test"); - assertThat(profile.publisherAgreements).isNotNull(); - assertThat(profile.publisherAgreements.openVsx).isNotNull(); - assertThat(profile.publisherAgreements.openVsx.version).isEqualTo("1"); + + assertThat(profile.getName()).isEqualTo("test"); + assertThat(profile.getGithubHandle()).isEqualTo("test"); + assertThat(profile.getPublisherAgreements()).isNotNull(); + assertThat(profile.getPublisherAgreements().getOpenVsx()).isNotNull(); + assertThat(profile.getPublisherAgreements().getOpenVsx().getVersion()).isEqualTo("1"); } @Test @@ -128,10 +130,10 @@ void testGetPublisherAgreement() throws Exception { var agreement = eclipse.getPublisherAgreement(user); assertThat(agreement).isNotNull(); - assertThat(agreement.isActive).isEqualTo(true); - assertThat(agreement.documentId).isEqualTo("abcd"); - assertThat(agreement.version).isEqualTo("1"); - assertThat(agreement.timestamp).isEqualTo(LocalDateTime.of(2020, 10, 9, 5, 10, 32)); + assertThat(agreement.isActive()).isEqualTo(true); + assertThat(agreement.documentId()).isEqualTo("abcd"); + assertThat(agreement.version()).isEqualTo("1"); + assertThat(agreement.timestamp()).isEqualTo(LocalDateTime.of(2020, 10, 9, 5, 10, 32)); } @Test @@ -166,10 +168,10 @@ void testSignPublisherAgreement() throws Exception { var agreement = eclipse.signPublisherAgreement(user); assertThat(agreement).isNotNull(); - assertThat(agreement.isActive).isEqualTo(true); - assertThat(agreement.documentId).isEqualTo("abcd"); - assertThat(agreement.version).isEqualTo("1"); - assertThat(agreement.timestamp).isEqualTo(LocalDateTime.of(2020, 10, 9, 5, 10, 32)); + assertThat(agreement.isActive()).isEqualTo(true); + assertThat(agreement.documentId()).isEqualTo("abcd"); + assertThat(agreement.version()).isEqualTo("1"); + assertThat(agreement.timestamp()).isEqualTo(LocalDateTime.of(2020, 10, 9, 5, 10, 32)); } @Test @@ -193,10 +195,10 @@ void testSignPublisherAgreementReactivateExtension() throws Exception { var agreement = eclipse.signPublisherAgreement(user); assertThat(agreement).isNotNull(); - assertThat(agreement.isActive).isEqualTo(true); - assertThat(agreement.documentId).isEqualTo("abcd"); - assertThat(agreement.version).isEqualTo("1"); - assertThat(agreement.timestamp).isEqualTo(LocalDateTime.of(2020, 10, 9, 5, 10, 32)); + assertThat(agreement.isActive()).isEqualTo(true); + assertThat(agreement.documentId()).isEqualTo("abcd"); + assertThat(agreement.version()).isEqualTo("1"); + assertThat(agreement.timestamp()).isEqualTo(LocalDateTime.of(2020, 10, 9, 5, 10, 32)); assertThat(extVersion.isActive()).isTrue(); assertThat(extension.isActive()).isTrue(); } @@ -230,8 +232,7 @@ void testRevokePublisherAgreementByAdmin() { var admin = new UserData(); admin.setLoginName("admin"); - admin.setEclipseToken(new AuthToken()); - admin.getEclipseToken().accessToken = "67890"; + admin.setEclipseToken(new AuthToken("67890", null, null, null, null, null)); Mockito.when(tokens.getActiveToken(admin, "eclipse")) .thenReturn(admin.getEclipseToken()); @@ -241,8 +242,7 @@ void testRevokePublisherAgreementByAdmin() { private UserData mockUser() { var user = new UserData(); user.setLoginName("test"); - user.setEclipseToken(new AuthToken()); - user.getEclipseToken().accessToken = "12345"; + user.setEclipseToken(new AuthToken("12345", null, null, null, null, null)); Mockito.when(tokens.getActiveToken(user, "eclipse")) .thenReturn(user.getEclipseToken()); return user; diff --git a/server/src/test/java/org/eclipse/openvsx/repositories/RepositoryServiceSmokeTest.java b/server/src/test/java/org/eclipse/openvsx/repositories/RepositoryServiceSmokeTest.java index 8826b860e..dccee03fc 100644 --- a/server/src/test/java/org/eclipse/openvsx/repositories/RepositoryServiceSmokeTest.java +++ b/server/src/test/java/org/eclipse/openvsx/repositories/RepositoryServiceSmokeTest.java @@ -71,8 +71,7 @@ void testExecuteQueries() { Stream.of(extension, namespace, userData, extVersion, personalAccessToken, keyPair).forEach(em::persist); em.flush(); - var queryRequest = new QueryRequest(); - queryRequest.size = 1; + var queryRequest = new QueryRequest(null, null, null, null, null, null, false, null, 1, 0); // record executed queries var methodsToBeCalled = Stream.of(repositories.getClass().getDeclaredMethods()) diff --git a/server/src/test/java/org/eclipse/openvsx/search/DatabaseSearchServiceTest.java b/server/src/test/java/org/eclipse/openvsx/search/DatabaseSearchServiceTest.java index 599feaeb0..d1a97a29d 100644 --- a/server/src/test/java/org/eclipse/openvsx/search/DatabaseSearchServiceTest.java +++ b/server/src/test/java/org/eclipse/openvsx/search/DatabaseSearchServiceTest.java @@ -50,7 +50,7 @@ void testCategory() { var ext3 = mockExtension("openshift", 4.0, 100, 0, "redhat", List.of("Snippets", "Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3))); - var searchOptions = new ISearchService.Options(null, "Programming Languages", TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false); + var searchOptions = new ISearchService.Options(null, "Programming Languages", TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false, null); var result = search.search(searchOptions); // should find two extensions assertThat(result.getTotalHits()).isEqualTo(2); @@ -63,7 +63,7 @@ void testRelevance() { var ext3 = mockExtension("openshift", 1.0, 100, 10, "redhat", List.of("Snippets", "Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3))); - var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "relevance", false); + var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "relevance", false, null); var result = search.search(searchOptions); // should find all extensions but order should be different assertThat(result.getTotalHits()).isEqualTo(3); @@ -81,7 +81,7 @@ void testReverse() { var ext2 = mockExtension("java", 4.0, 100, 0, "redhat", List.of("Snippets", "Programming Languages")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2))); - var searchOptions = new ISearchService.Options(null, "Programming Languages", TargetPlatform.NAME_UNIVERSAL, 50, 0, "desc", null, false); + var searchOptions = new ISearchService.Options(null, "Programming Languages", TargetPlatform.NAME_UNIVERSAL, 50, 0, "desc", null, false, null); var result = search.search(searchOptions); // should find two extensions assertThat(result.getTotalHits()).isEqualTo(2); @@ -103,7 +103,7 @@ void testSimplePageSize() { Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4, ext5, ext6, ext7))); var pageSizeItems = 5; - var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, pageSizeItems, 0, null, null, false); + var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, pageSizeItems, 0, null, null, false, null); var result = search.search(searchOptions); // 7 total hits @@ -131,7 +131,7 @@ void testPages() { Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4, ext5, ext6, ext7))); var pageSizeItems = 2; - var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, pageSizeItems, 4, null, null, false); + var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, pageSizeItems, 4, null, null, false, null); var result = search.search(searchOptions); // 7 total hits @@ -152,7 +152,7 @@ void testQueryStringPublisherName() { var ext4 = mockExtension("foo", 4.0, 100, 0, "bar", List.of("Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4))); - var searchOptions = new ISearchService.Options("redhat", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false); + var searchOptions = new ISearchService.Options("redhat", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false, null); var result = search.search(searchOptions); // namespace finding assertThat(result.getTotalHits()).isEqualTo(3); @@ -172,7 +172,7 @@ void testQueryStringExtensionName() { var ext4 = mockExtension("foo", 4.0, 100, 0, "bar", List.of("Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4))); - var searchOptions = new ISearchService.Options("openshift", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false); + var searchOptions = new ISearchService.Options("openshift", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false, null); var result = search.search(searchOptions); // extension name finding assertThat(result.getTotalHits()).isEqualTo(1); @@ -192,7 +192,7 @@ void testQueryStringDescription() { var ext4 = mockExtension("foo", 4.0, 100, 0, "bar", List.of("Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4))); - var searchOptions = new ISearchService.Options("my custom desc", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false); + var searchOptions = new ISearchService.Options("my custom desc", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false, null); var result = search.search(searchOptions); // custom description assertThat(result.getTotalHits()).isEqualTo(1); @@ -212,7 +212,7 @@ void testQueryStringDisplayName() { var ext4 = mockExtension("foo", 4.0, 100, 0, "bar", List.of("Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4))); - var searchOptions = new ISearchService.Options("Red Hat", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false); + var searchOptions = new ISearchService.Options("Red Hat", null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, null, false, null); var result = search.search(searchOptions); // custom displayname @@ -235,7 +235,7 @@ void testSortByTimeStamp() { ext4.getVersions().get(0).setTimestamp(LocalDateTime.parse("2021-10-06T00:00")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4))); - var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "timestamp", false); + var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "timestamp", false, null); var result = search.search(searchOptions); // all extensions should be there assertThat(result.getTotalHits()).isEqualTo(4); @@ -256,7 +256,7 @@ void testSortByDownloadCount() { var ext4 = mockExtension("foo", 4.0, 100, 500, "bar", List.of("Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4))); - var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "downloadCount", false); + var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "downloadCount", false, null); var result = search.search(searchOptions); // all extensions should be there assertThat(result.getTotalHits()).isEqualTo(4); @@ -277,7 +277,7 @@ void testSortByRating() { var ext4 = mockExtension("foo", 1.0, 1, 0, "bar", List.of("Other")); Mockito.when(repositories.findAllActiveExtensions()).thenReturn(Streamable.of(List.of(ext1, ext2, ext3, ext4))); - var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "rating", false); + var searchOptions = new ISearchService.Options(null, null, TargetPlatform.NAME_UNIVERSAL, 50, 0, null, "rating", false, null); var result = search.search(searchOptions); // all extensions should be there assertThat(result.getTotalHits()).isEqualTo(4); @@ -293,7 +293,7 @@ void testSortByRating() { // ---------- UTILITY ----------// long getIdFromExtensionHits(List> hits, int index) { - return hits.get(index).getContent().id; + return hits.get(index).getContent().getId(); } long getIdFromExtensionName(String extensionName) { diff --git a/server/src/test/java/org/eclipse/openvsx/search/ElasticSearchServiceTest.java b/server/src/test/java/org/eclipse/openvsx/search/ElasticSearchServiceTest.java index e6200eaf6..978b6ea54 100644 --- a/server/src/test/java/org/eclipse/openvsx/search/ElasticSearchServiceTest.java +++ b/server/src/test/java/org/eclipse/openvsx/search/ElasticSearchServiceTest.java @@ -63,7 +63,7 @@ void testRelevanceAverageRating() { search.updateSearchEntry(ext2); assertThat(index.entries).hasSize(2); - assertThat(index.entries.get(0).relevance).isLessThan(index.entries.get(1).relevance); + assertThat(index.entries.get(0).getRelevance()).isLessThan(index.entries.get(1).getRelevance()); } @Test @@ -75,7 +75,7 @@ void testRelevanceReviewCount() { search.updateSearchEntry(ext2); assertThat(index.entries).hasSize(2); - assertThat(index.entries.get(0).relevance).isLessThan(index.entries.get(1).relevance); + assertThat(index.entries.get(0).getRelevance()).isLessThan(index.entries.get(1).getRelevance()); } @Test @@ -87,7 +87,7 @@ void testRelevanceDownloadCount() { search.updateSearchEntry(ext2); assertThat(index.entries).hasSize(2); - assertThat(index.entries.get(0).relevance).isLessThan(index.entries.get(1).relevance); + assertThat(index.entries.get(0).getRelevance()).isLessThan(index.entries.get(1).getRelevance()); } @Test @@ -99,7 +99,7 @@ void testRelevanceTimestamp() { search.updateSearchEntry(ext2); assertThat(index.entries).hasSize(2); - assertThat(index.entries.get(0).relevance).isLessThan(index.entries.get(1).relevance); + assertThat(index.entries.get(0).getRelevance()).isLessThan(index.entries.get(1).getRelevance()); } @Test @@ -111,7 +111,7 @@ void testRelevanceUnverified1() { search.updateSearchEntry(ext2); assertThat(index.entries).hasSize(2); - assertThat(index.entries.get(0).relevance).isLessThan(index.entries.get(1).relevance); + assertThat(index.entries.get(0).getRelevance()).isLessThan(index.entries.get(1).getRelevance()); } @Test @@ -123,7 +123,7 @@ void testRelevanceUnverified2() { search.updateSearchEntry(ext2); assertThat(index.entries).hasSize(2); - assertThat(index.entries.get(0).relevance).isLessThan(index.entries.get(1).relevance); + assertThat(index.entries.get(0).getRelevance()).isLessThan(index.entries.get(1).getRelevance()); } @Test @@ -174,7 +174,7 @@ void testHardUpdateNotExists() { void testSearchResultWindowTooLarge() { mockIndex(true); - var options = new ISearchService.Options("foo", "bar", "universal", 50, 10000, null, null, false); + var options = new ISearchService.Options("foo", "bar", "universal", 50, 10000, null, null, false, null); var searchHits = search.search(options); assertThat(searchHits.getSearchHits()).isEmpty(); assertThat(searchHits.getTotalHits()).isEqualTo(0L);