Search in sources :

Example 1 with ErrorResultException

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

the class AdminService method editNamespaceMember.

@Transactional(rollbackOn = ErrorResultException.class)
public ResultJson editNamespaceMember(String namespaceName, String userName, String provider, String role, UserData admin) throws ErrorResultException {
    var namespace = repositories.findNamespace(namespaceName);
    if (namespace == null) {
        throw new ErrorResultException("Namespace not found: " + namespaceName);
    }
    var user = repositories.findUserByLoginName(provider, userName);
    if (user == null) {
        throw new ErrorResultException("User not found: " + provider + "/" + userName);
    }
    ResultJson result;
    if (role.equals("remove")) {
        result = users.removeNamespaceMember(namespace, user);
    } else {
        result = users.addNamespaceMember(namespace, user, role);
    }
    for (var extension : repositories.findActiveExtensions(namespace)) {
        search.updateSearchEntry(extension);
    }
    logAdminAction(admin, result);
    return result;
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) ResultJson(org.eclipse.openvsx.json.ResultJson) Transactional(javax.transaction.Transactional)

Example 2 with ErrorResultException

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

the class ExtensionService method createExtensionVersion.

private ExtensionVersion createExtensionVersion(ExtensionProcessor processor, UserData user, PersonalAccessToken token) {
    var namespaceName = processor.getNamespace();
    var namespace = repositories.findNamespace(namespaceName);
    if (namespace == null) {
        throw new ErrorResultException("Unknown publisher: " + namespaceName + "\nUse the 'create-namespace' command to create a namespace corresponding to your publisher name.");
    }
    if (!users.hasPublishPermission(user, namespace)) {
        throw new ErrorResultException("Insufficient access rights for publisher: " + namespace.getName());
    }
    var extensionName = processor.getExtensionName();
    var nameIssue = validator.validateExtensionName(extensionName);
    if (nameIssue.isPresent()) {
        throw new ErrorResultException(nameIssue.get().toString());
    }
    var extVersion = processor.getMetadata();
    if (extVersion.getDisplayName() != null && extVersion.getDisplayName().trim().isEmpty()) {
        extVersion.setDisplayName(null);
    }
    extVersion.setTimestamp(TimeUtil.getCurrentUTC());
    extVersion.setPublishedWith(token);
    extVersion.setActive(true);
    var extension = repositories.findExtension(extensionName, namespace);
    if (extension == null) {
        extension = new Extension();
        extension.setName(extensionName);
        extension.setNamespace(namespace);
        vsCodeIdService.createPublicId(extension);
        entityManager.persist(extension);
    } else {
        var existingVersion = repositories.findVersion(extVersion.getVersion(), extension);
        if (existingVersion != null) {
            throw new ErrorResultException("Extension " + namespace.getName() + "." + extension.getName() + " version " + extVersion.getVersion() + " is already published" + (existingVersion.isActive() ? "." : ", but is currently inactive and therefore not visible."));
        }
    }
    extVersion.setExtension(extension);
    entityManager.persist(extVersion);
    var metadataIssues = validator.validateMetadata(extVersion);
    if (!metadataIssues.isEmpty()) {
        if (metadataIssues.size() == 1) {
            throw new ErrorResultException(metadataIssues.get(0).toString());
        }
        throw new ErrorResultException("Multiple issues were found in the extension metadata:\n" + Joiner.on("\n").join(metadataIssues));
    }
    return extVersion;
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) Extension(org.eclipse.openvsx.entities.Extension)

Example 3 with ErrorResultException

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

the class VSCodeAdapter method extensionQuery.

@PostMapping(path = "/vscode/gallery/extensionquery", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@CrossOrigin
public ExtensionQueryResult extensionQuery(@RequestBody ExtensionQueryParam param) {
    String queryString = null;
    String category = null;
    PageRequest pageRequest;
    String sortOrder;
    String sortBy;
    Set<String> extensionIds;
    Set<String> extensionNames;
    if (param.filters == null || param.filters.isEmpty()) {
        pageRequest = PageRequest.of(0, DEFAULT_PAGE_SIZE);
        sortBy = "relevance";
        sortOrder = "desc";
        extensionIds = Collections.emptySet();
        extensionNames = Collections.emptySet();
    } else {
        var filter = param.filters.get(0);
        extensionIds = new HashSet<>(filter.findCriteria(FILTER_EXTENSION_ID));
        extensionNames = new HashSet<>(filter.findCriteria(FILTER_EXTENSION_NAME));
        queryString = filter.findCriterion(FILTER_SEARCH_TEXT);
        if (queryString == null)
            queryString = filter.findCriterion(FILTER_TAG);
        category = filter.findCriterion(FILTER_CATEGORY);
        var pageSize = filter.pageSize > 0 ? filter.pageSize : DEFAULT_PAGE_SIZE;
        pageRequest = PageRequest.of(filter.pageNumber - 1, pageSize);
        sortOrder = getSortOrder(filter.sortOrder);
        sortBy = getSortBy(filter.sortBy);
    }
    Long totalCount = null;
    List<ExtensionDTO> extensions;
    if (!extensionIds.isEmpty()) {
        extensions = repositories.findAllActiveExtensionDTOsByPublicId(extensionIds);
    } else if (!extensionNames.isEmpty()) {
        extensions = extensionNames.stream().map(name -> name.split("\\.")).filter(split -> split.length == 2).map(split -> {
            var name = split[1];
            var namespaceName = split[0];
            return repositories.findActiveExtensionDTOByNameAndNamespaceName(name, namespaceName);
        }).filter(Objects::nonNull).collect(Collectors.toList());
    } else if (!search.isEnabled()) {
        extensions = Collections.emptyList();
    } else {
        try {
            var offset = pageRequest.getPageNumber() * pageRequest.getPageSize();
            var searchOptions = new SearchUtilService.Options(queryString, category, pageRequest.getPageSize(), offset, sortOrder, sortBy, false);
            var searchResult = search.search(searchOptions, pageRequest);
            totalCount = searchResult.getTotalHits();
            var ids = searchResult.getSearchHits().stream().map(hit -> hit.getContent().id).collect(Collectors.toList());
            var extensionsMap = repositories.findAllActiveExtensionDTOsById(ids).stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
            // keep the same order as search results
            extensions = ids.stream().map(extensionsMap::get).filter(Objects::nonNull).collect(Collectors.toList());
        } catch (ErrorResultException exc) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, exc.getMessage(), exc);
        }
    }
    if (totalCount == null) {
        totalCount = (long) extensions.size();
    }
    var flags = param.flags;
    Map<ExtensionDTO, List<ExtensionVersionDTO>> extensionVersions;
    if (test(flags, FLAG_INCLUDE_LATEST_VERSION_ONLY)) {
        extensionVersions = extensions.stream().map(ExtensionDTO::getLatest).collect(Collectors.groupingBy(ExtensionVersionDTO::getExtension));
    } else if (test(flags, FLAG_INCLUDE_VERSIONS) || test(flags, FLAG_INCLUDE_VERSION_PROPERTIES)) {
        var idMap = extensions.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
        // similar to ExtensionVersion.SORT_COMPARATOR, difference is that it compares by extension id first
        var comparator = Comparator.<ExtensionVersionDTO, Long>comparing(ev -> ev.getExtension().getId()).thenComparing(ExtensionVersionDTO::getSemanticVersion).thenComparing(ExtensionVersionDTO::getTimestamp).reversed();
        extensionVersions = repositories.findAllActiveExtensionVersionDTOsByExtensionId(idMap.keySet()).stream().map(ev -> {
            ev.setExtension(idMap.get(ev.getExtensionId()));
            return ev;
        }).sorted(comparator).collect(Collectors.groupingBy(ExtensionVersionDTO::getExtension));
    } else {
        extensionVersions = Collections.emptyMap();
    }
    Map<ExtensionVersionDTO, List<FileResourceDTO>> resources;
    if (test(flags, FLAG_INCLUDE_FILES) && !extensionVersions.isEmpty()) {
        var types = List.of(MANIFEST, README, LICENSE, ICON, DOWNLOAD, CHANGELOG, WEB_RESOURCE);
        var idsMap = extensionVersions.values().stream().flatMap(Collection::stream).collect(Collectors.toMap(ev -> ev.getId(), ev -> ev));
        resources = repositories.findAllFileResourceDTOsByExtensionVersionIdAndType(idsMap.keySet(), types).stream().map(r -> {
            r.setExtensionVersion(idsMap.get(r.getExtensionVersionId()));
            return r;
        }).collect(Collectors.groupingBy(FileResourceDTO::getExtensionVersion));
    } else {
        resources = Collections.emptyMap();
    }
    Map<Long, Integer> activeReviewCounts;
    if (test(flags, FLAG_INCLUDE_STATISTICS) && !extensions.isEmpty()) {
        var ids = extensions.stream().map(ExtensionDTO::getId).collect(Collectors.toList());
        activeReviewCounts = repositories.findAllActiveReviewCountsByExtensionId(ids);
    } else {
        activeReviewCounts = Collections.emptyMap();
    }
    var extensionQueryResults = new ArrayList<ExtensionQueryResult.Extension>();
    for (var extension : extensions) {
        var queryExt = toQueryExtension(extension, activeReviewCounts, flags);
        queryExt.versions = extensionVersions.getOrDefault(extension, Collections.emptyList()).stream().map(extVer -> toQueryVersion(extVer, resources, flags)).collect(Collectors.toList());
        extensionQueryResults.add(queryExt);
    }
    return toQueryResult(extensionQueryResults, totalCount);
}
Also used : ExtensionVersion(org.eclipse.openvsx.entities.ExtensionVersion) java.util(java.util) ExtensionDTO(org.eclipse.openvsx.dto.ExtensionDTO) ExtensionFile(org.eclipse.openvsx.adapter.ExtensionQueryResult.ExtensionFile) ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) Autowired(org.springframework.beans.factory.annotation.Autowired) ArrayUtils(org.apache.commons.lang3.ArrayUtils) UrlUtil(org.eclipse.openvsx.util.UrlUtil) Criterion(org.eclipse.openvsx.adapter.ExtensionQueryParam.Criterion) CacheControl(org.springframework.http.CacheControl) ModelMap(org.springframework.ui.ModelMap) Value(org.springframework.beans.factory.annotation.Value) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) Statistic(org.eclipse.openvsx.adapter.ExtensionQueryResult.Statistic) FileResource(org.eclipse.openvsx.entities.FileResource) NotFoundException(org.eclipse.openvsx.util.NotFoundException) SearchUtilService(org.eclipse.openvsx.search.SearchUtilService) ResponseStatusException(org.springframework.web.server.ResponseStatusException) ExtensionVersionDTO(org.eclipse.openvsx.dto.ExtensionVersionDTO) MediaType(org.springframework.http.MediaType) PageRequest(org.springframework.data.domain.PageRequest) FileResourceDTO(org.eclipse.openvsx.dto.FileResourceDTO) GoogleCloudStorageService(org.eclipse.openvsx.storage.GoogleCloudStorageService) Collectors(java.util.stream.Collectors) ExtensionQueryParam(org.eclipse.openvsx.adapter.ExtensionQueryParam) TimeUnit(java.util.concurrent.TimeUnit) RepositoryService(org.eclipse.openvsx.repositories.RepositoryService) HttpStatus(org.springframework.http.HttpStatus) ModelAndView(org.springframework.web.servlet.ModelAndView) FLAG_PREVIEW(org.eclipse.openvsx.adapter.ExtensionQueryResult.Extension.FLAG_PREVIEW) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Property(org.eclipse.openvsx.adapter.ExtensionQueryResult.Property) ResponseEntity(org.springframework.http.ResponseEntity) StorageUtilService(org.eclipse.openvsx.storage.StorageUtilService) ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) ExtensionDTO(org.eclipse.openvsx.dto.ExtensionDTO) ExtensionVersionDTO(org.eclipse.openvsx.dto.ExtensionVersionDTO) FileResourceDTO(org.eclipse.openvsx.dto.FileResourceDTO) PageRequest(org.springframework.data.domain.PageRequest) ResponseStatusException(org.springframework.web.server.ResponseStatusException)

Example 4 with ErrorResultException

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

the class LocalRegistryService method createNamespace.

@Transactional(rollbackOn = ErrorResultException.class)
public ResultJson createNamespace(NamespaceJson json, String tokenValue) {
    var namespaceIssue = validator.validateNamespace(json.name);
    if (namespaceIssue.isPresent()) {
        throw new ErrorResultException(namespaceIssue.get().toString());
    }
    var token = users.useAccessToken(tokenValue);
    if (token == null) {
        throw new ErrorResultException("Invalid access token.");
    }
    eclipse.checkPublisherAgreement(token.getUser());
    var namespace = repositories.findNamespace(json.name);
    if (namespace != null) {
        throw new ErrorResultException("Namespace already exists: " + namespace.getName());
    }
    // Create the requested namespace
    namespace = new Namespace();
    namespace.setName(json.name);
    entityManager.persist(namespace);
    // Assign the requesting user as contributor
    var membership = new NamespaceMembership();
    membership.setNamespace(namespace);
    membership.setUser(token.getUser());
    membership.setRole(NamespaceMembership.ROLE_CONTRIBUTOR);
    entityManager.persist(membership);
    return ResultJson.success("Created namespace " + namespace.getName());
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) NamespaceMembership(org.eclipse.openvsx.entities.NamespaceMembership) Namespace(org.eclipse.openvsx.entities.Namespace) Transactional(javax.transaction.Transactional)

Example 5 with ErrorResultException

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

the class UserService method addNamespaceMember.

@Transactional(rollbackOn = ErrorResultException.class)
public ResultJson addNamespaceMember(Namespace namespace, UserData user, String role) {
    if (!(role.equals(NamespaceMembership.ROLE_OWNER) || role.equals(NamespaceMembership.ROLE_CONTRIBUTOR))) {
        throw new ErrorResultException("Invalid role: " + role);
    }
    var membership = repositories.findMembership(user, namespace);
    if (membership != null) {
        if (role.equals(membership.getRole())) {
            throw new ErrorResultException("User " + user.getLoginName() + " already has the role " + role + ".");
        }
        membership.setRole(role);
        return ResultJson.success("Changed role of " + user.getLoginName() + " in " + namespace.getName() + " to " + role + ".");
    }
    membership = new NamespaceMembership();
    membership.setNamespace(namespace);
    membership.setUser(user);
    membership.setRole(role);
    entityManager.persist(membership);
    return ResultJson.success("Added " + user.getLoginName() + " as " + role + " of " + namespace.getName() + ".");
}
Also used : ErrorResultException(org.eclipse.openvsx.util.ErrorResultException) NamespaceMembership(org.eclipse.openvsx.entities.NamespaceMembership) Transactional(javax.transaction.Transactional)

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