Search in sources :

Example 16 with ErrorResultException

use of org.eclipse.openvsx.util.ErrorResultException in project openvsx by eclipse.

the class AdminAPI method deleteExtension.

@PostMapping(path = "/admin/extension/{namespaceName}/{extensionName}/delete", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResultJson> deleteExtension(@PathVariable String namespaceName, @PathVariable String extensionName, @RequestBody(required = false) List<String> versions) {
    try {
        ResultJson result;
        var adminUser = admins.checkAdminUser();
        if (versions == null) {
            result = admins.deleteExtension(namespaceName, extensionName, adminUser);
        } else {
            var results = new ArrayList<ResultJson>();
            for (var version : versions) {
                results.add(admins.deleteExtensionVersion(namespaceName, extensionName, 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"));
        }
        return ResponseEntity.ok(result);
    } catch (ErrorResultException exc) {
        return exc.toResponseEntity();
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) ExtensionVersion(org.eclipse.openvsx.entities.ExtensionVersion) RequestParam(org.springframework.web.bind.annotation.RequestParam) LocalDateTime(java.time.LocalDateTime) ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) Autowired(org.springframework.beans.factory.annotation.Autowired) NamespaceMembershipListJson(org.eclipse.openvsx.json.NamespaceMembershipListJson) UrlUtil(org.eclipse.openvsx.util.UrlUtil) AdminStatistics(org.eclipse.openvsx.entities.AdminStatistics) TimeUtil(org.eclipse.openvsx.util.TimeUtil) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) Strings(com.google.common.base.Strings) PersistedLog(org.eclipse.openvsx.entities.PersistedLog) NamespaceJson(org.eclipse.openvsx.json.NamespaceJson) GetMapping(org.springframework.web.bind.annotation.GetMapping) URI(java.net.URI) ExtensionJson(org.eclipse.openvsx.json.ExtensionJson) DateTimeException(java.time.DateTimeException) NotFoundException(org.eclipse.openvsx.util.NotFoundException) Period(java.time.Period) SearchUtilService(org.eclipse.openvsx.search.SearchUtilService) PostMapping(org.springframework.web.bind.annotation.PostMapping) LongStream(java.util.stream.LongStream) ResponseStatusException(org.springframework.web.server.ResponseStatusException) Extension(org.eclipse.openvsx.entities.Extension) MediaType(org.springframework.http.MediaType) SemanticVersion(org.eclipse.openvsx.util.SemanticVersion) ROLE_ADMIN(org.eclipse.openvsx.entities.UserData.ROLE_ADMIN) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) ResultJson(org.eclipse.openvsx.json.ResultJson) Objects(java.util.Objects) RepositoryService(org.eclipse.openvsx.repositories.RepositoryService) HttpStatus(org.springframework.http.HttpStatus) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) Streamable(org.springframework.data.util.Streamable) StatsJson(org.eclipse.openvsx.json.StatsJson) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) UserPublishInfoJson(org.eclipse.openvsx.json.UserPublishInfoJson) ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) ResultJson(org.eclipse.openvsx.json.ResultJson) ArrayList(java.util.ArrayList) Objects(java.util.Objects) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 17 with ErrorResultException

use of org.eclipse.openvsx.util.ErrorResultException in project openvsx by eclipse.

the class LocalRegistryService method query.

@Override
public QueryResultJson query(QueryParamJson param) {
    if (!Strings.isNullOrEmpty(param.extensionId)) {
        var split = param.extensionId.split("\\.");
        if (split.length != 2 || split[0].isEmpty() || split[1].isEmpty())
            throw new ErrorResultException("The 'extensionId' parameter must have the format 'namespace.extension'.");
        if (!Strings.isNullOrEmpty(param.namespaceName) && !param.namespaceName.equals(split[0]))
            throw new ErrorResultException("Conflicting parameters 'extensionId' and 'namespaceName'");
        if (!Strings.isNullOrEmpty(param.extensionName) && !param.extensionName.equals(split[1]))
            throw new ErrorResultException("Conflicting parameters 'extensionId' and 'extensionName'");
        param.namespaceName = split[0];
        param.extensionName = split[1];
    }
    List<ExtensionVersionDTO> extensionVersions = new ArrayList<>();
    // Add extension by UUID (public_id)
    if (!Strings.isNullOrEmpty(param.extensionUuid)) {
        extensionVersions.addAll(repositories.findActiveExtensionVersionDTOsByExtensionPublicId(param.extensionUuid));
    }
    // Add extensions by namespace UUID (public_id)
    if (!Strings.isNullOrEmpty(param.namespaceUuid)) {
        extensionVersions.addAll(repositories.findActiveExtensionVersionDTOsByNamespacePublicId(param.namespaceUuid));
    }
    // Add a specific version of an extension
    if (!Strings.isNullOrEmpty(param.namespaceName) && !Strings.isNullOrEmpty(param.extensionName) && !Strings.isNullOrEmpty(param.extensionVersion) && !param.includeAllVersions) {
        var extensionVersion = repositories.findActiveExtensionVersionDTOByVersion(param.extensionVersion, param.extensionName, param.namespaceName);
        if (extensionVersion != null) {
            extensionVersions.add(extensionVersion);
        }
    // Add extension by namespace and name
    } else if (!Strings.isNullOrEmpty(param.namespaceName) && !Strings.isNullOrEmpty(param.extensionName)) {
        extensionVersions.addAll(repositories.findActiveExtensionVersionDTOsByExtensionName(param.extensionName, param.namespaceName));
    // Add extensions by namespace
    } else if (!Strings.isNullOrEmpty(param.namespaceName)) {
        extensionVersions.addAll(repositories.findActiveExtensionVersionDTOsByNamespaceName(param.namespaceName));
    // Add extensions by name
    } else if (!Strings.isNullOrEmpty(param.extensionName)) {
        extensionVersions.addAll(repositories.findActiveExtensionVersionDTOsByExtensionName(param.extensionName));
    }
    extensionVersions = extensionVersions.stream().collect(Collectors.groupingBy(ExtensionVersionDTO::getId)).values().stream().map(l -> l.get(0)).filter(ev -> addToResult(ev, param)).collect(Collectors.toList());
    if (Strings.isNullOrEmpty(param.extensionVersion) && !param.includeAllVersions) {
        var latestIds = extensionVersions.stream().map(ExtensionVersionDTO::getExtension).map(ExtensionDTO::getLatestId).filter(Objects::nonNull).collect(Collectors.toList());
        extensionVersions = extensionVersions.stream().filter(ev -> latestIds.contains(ev.getId())).collect(Collectors.toList());
    }
    var extensionIds = extensionVersions.stream().map(ExtensionVersionDTO::getExtensionId).collect(Collectors.toSet());
    var reviewCounts = getReviewCounts(extensionIds);
    var versionStrings = getVersionStrings(extensionIds);
    var previewsByExtensionId = getPreviews(extensionIds);
    var fileResourcesByExtensionVersionId = getFileResources(extensionVersions);
    var membershipsByNamespaceId = getMemberships(extensionVersions);
    var result = new QueryResultJson();
    result.extensions = extensionVersions.stream().sorted(getExtensionVersionComparator()).map(ev -> {
        var reviewCount = reviewCounts.getOrDefault(ev.getExtensionId(), 0);
        var preview = previewsByExtensionId.get(ev.getExtensionId());
        var versions = versionStrings.get(ev.getExtensionId());
        var fileResources = fileResourcesByExtensionVersionId.getOrDefault(ev.getId(), Collections.emptyList());
        return toExtensionVersionJson(ev, reviewCount, preview, versions, fileResources, membershipsByNamespaceId);
    }).collect(Collectors.toList());
    return result;
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) Autowired(org.springframework.beans.factory.annotation.Autowired) QueryParamJson(org.eclipse.openvsx.json.QueryParamJson) CacheControl(org.springframework.http.CacheControl) ExtensionSearch(org.eclipse.openvsx.search.ExtensionSearch) ISearchService(org.eclipse.openvsx.search.ISearchService) FileResource(org.eclipse.openvsx.entities.FileResource) Namespace(org.eclipse.openvsx.entities.Namespace) ReviewJson(org.eclipse.openvsx.json.ReviewJson) ExtensionJson(org.eclipse.openvsx.json.ExtensionJson) SearchUtilService(org.eclipse.openvsx.search.SearchUtilService) ResponseStatusException(org.springframework.web.server.ResponseStatusException) Transactional(javax.transaction.Transactional) PageRequest(org.springframework.data.domain.PageRequest) ExtensionReview(org.eclipse.openvsx.entities.ExtensionReview) Collectors(java.util.stream.Collectors) Stream(java.util.stream.Stream) Maps(org.apache.jena.ext.com.google.common.collect.Maps) org.eclipse.openvsx.dto(org.eclipse.openvsx.dto) CollectionUtil(org.eclipse.openvsx.util.CollectionUtil) QueryResultJson(org.eclipse.openvsx.json.QueryResultJson) NamespaceMembership(org.eclipse.openvsx.entities.NamespaceMembership) java.util(java.util) Iterables(com.google.common.collect.Iterables) ExtensionVersion(org.eclipse.openvsx.entities.ExtensionVersion) ReviewListJson(org.eclipse.openvsx.json.ReviewListJson) ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) UrlUtil(org.eclipse.openvsx.util.UrlUtil) TimeUtil(org.eclipse.openvsx.util.TimeUtil) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) NamespaceJson(org.eclipse.openvsx.json.NamespaceJson) NotFoundException(org.eclipse.openvsx.util.NotFoundException) SearchHit(org.springframework.data.elasticsearch.core.SearchHit) UrlUtil.createApiUrl(org.eclipse.openvsx.util.UrlUtil.createApiUrl) Extension(org.eclipse.openvsx.entities.Extension) SearchHits(org.springframework.data.elasticsearch.core.SearchHits) SemanticVersion(org.eclipse.openvsx.util.SemanticVersion) EntityManager(javax.persistence.EntityManager) ResultJson(org.eclipse.openvsx.json.ResultJson) TimeUnit(java.util.concurrent.TimeUnit) SearchResultJson(org.eclipse.openvsx.json.SearchResultJson) RepositoryService(org.eclipse.openvsx.repositories.RepositoryService) HttpStatus(org.springframework.http.HttpStatus) Component(org.springframework.stereotype.Component) SearchEntryJson(org.eclipse.openvsx.json.SearchEntryJson) ResponseEntity(org.springframework.http.ResponseEntity) EclipseService(org.eclipse.openvsx.eclipse.EclipseService) InputStream(java.io.InputStream) StorageUtilService(org.eclipse.openvsx.storage.StorageUtilService) QueryResultJson(org.eclipse.openvsx.json.QueryResultJson)

Example 18 with ErrorResultException

use of org.eclipse.openvsx.util.ErrorResultException in project openvsx by eclipse.

the class EclipseServiceTest method testPublisherAgreementAlreadySigned.

@Test
public void testPublisherAgreementAlreadySigned() throws Exception {
    var user = mockUser();
    Mockito.when(restTemplate.postForEntity(any(String.class), any(), eq(String.class))).thenThrow(new HttpClientErrorException(HttpStatus.CONFLICT));
    try {
        eclipse.signPublisherAgreement(user);
        fail("Expected an ErrorResultException");
    } catch (ErrorResultException exc) {
        assertThat(exc.getMessage()).isEqualTo("A publisher agreement is already present for user test.");
    }
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Test(org.junit.jupiter.api.Test)

Example 19 with ErrorResultException

use of org.eclipse.openvsx.util.ErrorResultException in project openvsx by eclipse.

the class OAuth2UserServices method loadEclipseUser.

private IdPrincipal loadEclipseUser(OAuth2UserRequest userRequest) {
    var authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null)
        throw new CodedAuthException("Please log in with GitHub before connecting your Eclipse account.", NEED_MAIN_LOGIN);
    if (!(authentication.getPrincipal() instanceof IdPrincipal))
        throw new CodedAuthException("The current authentication is invalid.", NEED_MAIN_LOGIN);
    var principal = (IdPrincipal) authentication.getPrincipal();
    var userData = entityManager.find(UserData.class, principal.getId());
    if (userData == null)
        throw new CodedAuthException("The current authentication has no backing data.", NEED_MAIN_LOGIN);
    try {
        var accessToken = userRequest.getAccessToken().getTokenValue();
        var profile = eclipse.getUserProfile(accessToken);
        if (Strings.isNullOrEmpty(profile.githubHandle))
            throw new CodedAuthException("Your Eclipse profile is missing a GitHub username.", ECLIPSE_MISSING_GITHUB_ID);
        if (!profile.githubHandle.equalsIgnoreCase(userData.getLoginName()))
            throw new CodedAuthException("The GitHub username setting in your Eclipse profile (" + profile.githubHandle + ") does not match your GitHub authentication (" + userData.getLoginName() + ").", ECLIPSE_MISMATCH_GITHUB_ID);
        eclipse.updateUserData(userData, profile);
        if (profile.publisherAgreements == null) {
            eclipse.getPublisherAgreement(userData, accessToken);
        }
        return principal;
    } catch (ErrorResultException exc) {
        throw new AuthenticationServiceException(exc.getMessage(), exc);
    }
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) CodedAuthException(org.eclipse.openvsx.security.CodedAuthException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 20 with ErrorResultException

use of org.eclipse.openvsx.util.ErrorResultException in project openvsx by eclipse.

the class EclipseService method getUserProfile.

/**
 * Get the user profile available through an access token.
 */
public EclipseProfile getUserProfile(String accessToken) {
    checkApiUrl();
    var headers = new HttpHeaders();
    headers.setBearerAuth(accessToken);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    var requestUrl = UrlUtil.createApiUrl(eclipseApiUrl, "openvsx", "profile");
    var request = new RequestEntity<>(headers, HttpMethod.GET, URI.create(requestUrl));
    try {
        var response = restTemplate.exchange(request, String.class);
        return parseEclipseProfile(response);
    } catch (RestClientException exc) {
        logger.error("Get request failed with URL: " + requestUrl, exc);
        throw new ErrorResultException("Request for retrieving user profile failed: " + exc.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) HttpHeaders(org.springframework.http.HttpHeaders) RestClientException(org.springframework.web.client.RestClientException) RequestEntity(org.springframework.http.RequestEntity)

Aggregations

ErrorResultException (org.eclipse.openvsx.util.ErrorResultException)22 Transactional (javax.transaction.Transactional)5 HttpHeaders (org.springframework.http.HttpHeaders)5 RestClientException (org.springframework.web.client.RestClientException)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 IOException (java.io.IOException)3 Collectors (java.util.stream.Collectors)3 Extension (org.eclipse.openvsx.entities.Extension)3 ExtensionVersion (org.eclipse.openvsx.entities.ExtensionVersion)3 ExtensionJson (org.eclipse.openvsx.json.ExtensionJson)3 ResultJson (org.eclipse.openvsx.json.ResultJson)3 RepositoryService (org.eclipse.openvsx.repositories.RepositoryService)3 SearchUtilService (org.eclipse.openvsx.search.SearchUtilService)3 NotFoundException (org.eclipse.openvsx.util.NotFoundException)3 UrlUtil (org.eclipse.openvsx.util.UrlUtil)3 Autowired (org.springframework.beans.factory.annotation.Autowired)3 HttpStatus (org.springframework.http.HttpStatus)3 ResponseEntity (org.springframework.http.ResponseEntity)3 GetMapping (org.springframework.web.bind.annotation.GetMapping)3 ResponseStatusException (org.springframework.web.server.ResponseStatusException)3