Search in sources :

Example 1 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class ModelRepositoryController method getUserModels.

// ##################### Downloads ################################
@GetMapping(value = { "/mine/download" })
public void getUserModels(Principal principal, final HttpServletResponse response) {
    List<ModelId> userModels = Lists.newArrayList();
    User user = accountService.getUser(principal.getName());
    Collection<Namespace> namespaces = null;
    try {
        namespaces = userNamespaceRoleService.getNamespaces(user, user);
    } catch (OperationForbiddenException | DoesNotExistException e) {
        LOGGER.error(e.getMessage(), e);
    }
    for (Namespace namespace : namespaces) {
        IModelRepository modelRepo = getModelRepository(namespace.getWorkspaceId());
        List<ModelInfo> modelInfos = modelRepo.search(String.format("author:%s", user.getUsername()));
        List<ModelId> modelIds = modelInfos.stream().map(modelInfo -> modelInfo.getId()).collect(Collectors.toList());
        userModels.addAll(modelIds);
    }
    LOGGER.info("Exporting information models for user - results: " + userModels.size());
    sendAsZipFile(response, user.getUsername() + "-models.zip", getModelsAndDependencies(userModels));
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) InfomodelTemplate(org.eclipse.vorto.repository.web.core.templates.InfomodelTemplate) RequestParam(org.springframework.web.bind.annotation.RequestParam) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiParam(io.swagger.annotations.ApiParam) Autowired(org.springframework.beans.factory.annotation.Autowired) ModelAlreadyExistsException(org.eclipse.vorto.repository.core.ModelAlreadyExistsException) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) RequestContextHolder(org.springframework.web.context.request.RequestContextHolder) Future(java.util.concurrent.Future) Map(java.util.Map) Diagnostic(org.eclipse.vorto.repository.core.Diagnostic) AsyncModelMappingsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelMappingsFetcher) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ModelParserFactory(org.eclipse.vorto.repository.core.impl.parser.ModelParserFactory) PostMapping(org.springframework.web.bind.annotation.PostMapping) AsyncModelLinksFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelLinksFetcher) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) User(org.eclipse.vorto.repository.domain.User) Namespace(org.eclipse.vorto.repository.domain.Namespace) RestController(org.springframework.web.bind.annotation.RestController) Executors(java.util.concurrent.Executors) IOUtils(org.apache.commons.io.IOUtils) Permission(org.eclipse.vorto.repository.core.PolicyEntry.Permission) DefaultUserAccountService(org.eclipse.vorto.repository.account.impl.DefaultUserAccountService) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ModelFullDetailsDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelFullDetailsDTO) ControllerUtils(org.eclipse.vorto.repository.web.ControllerUtils) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) FatalModelRepositoryException(org.eclipse.vorto.repository.core.FatalModelRepositoryException) IWorkflowService(org.eclipse.vorto.repository.workflow.IWorkflowService) Lists(com.google.common.collect.Lists) Attachment(org.eclipse.vorto.repository.core.Attachment) AsyncModelSyntaxFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelSyntaxFetcher) UserRepositoryRoleService(org.eclipse.vorto.repository.services.UserRepositoryRoleService) ModelProperty(org.eclipse.vorto.model.ModelProperty) ModelNotReleasedException(org.eclipse.vorto.repository.model.ModelNotReleasedException) GenericApplicationException(org.eclipse.vorto.repository.web.GenericApplicationException) IOException(java.io.IOException) IModelPolicyManager(org.eclipse.vorto.repository.core.IModelPolicyManager) NamespaceService(org.eclipse.vorto.repository.services.NamespaceService) ExecutionException(java.util.concurrent.ExecutionException) HttpStatus(org.springframework.http.HttpStatus) ApiResponse(io.swagger.annotations.ApiResponse) AttachmentValidator(org.eclipse.vorto.repository.core.impl.validation.AttachmentValidator) AttachResult(org.eclipse.vorto.repository.web.api.v1.dto.AttachResult) ModelTemplate(org.eclipse.vorto.repository.web.core.templates.ModelTemplate) PathVariable(org.springframework.web.bind.annotation.PathVariable) ValidationReport(org.eclipse.vorto.repository.importer.ValidationReport) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) ApiOperation(io.swagger.annotations.ApiOperation) Logger(org.apache.log4j.Logger) AbstractRepositoryController(org.eclipse.vorto.repository.web.AbstractRepositoryController) ByteArrayInputStream(java.io.ByteArrayInputStream) PutMapping(org.springframework.web.bind.annotation.PutMapping) ModelMinimalInfoDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelMinimalInfoDTO) ZipEntry(java.util.zip.ZipEntry) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) AsyncWorkflowActionsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncWorkflowActionsFetcher) FileContent(org.eclipse.vorto.repository.core.FileContent) IDiagnostics(org.eclipse.vorto.repository.core.IDiagnostics) Collection(java.util.Collection) ModelValidationHelper(org.eclipse.vorto.repository.core.impl.utils.ModelValidationHelper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) Collectors(java.util.stream.Collectors) ModelId(org.eclipse.vorto.model.ModelId) Objects(java.util.Objects) List(java.util.List) Principal(java.security.Principal) Optional(java.util.Optional) WorkflowException(org.eclipse.vorto.repository.workflow.WorkflowException) Authentication(org.springframework.security.core.Authentication) IUserContext(org.eclipse.vorto.repository.core.IUserContext) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses) AsyncModelAttachmentsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelAttachmentsFetcher) Status(org.eclipse.vorto.repository.web.Status) GetMapping(org.springframework.web.bind.annotation.GetMapping) ExecutorService(java.util.concurrent.ExecutorService) ModelContent(org.eclipse.vorto.repository.web.core.dto.ModelContent) ModelNamespaceNotOfficialException(org.eclipse.vorto.repository.model.ModelNamespaceNotOfficialException) AsyncModelReferenceFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelReferenceFetcher) IBulkOperationsService(org.eclipse.vorto.repository.model.IBulkOperationsService) UserNamespaceRoleService(org.eclipse.vorto.repository.services.UserNamespaceRoleService) HttpServletResponse(javax.servlet.http.HttpServletResponse) PolicyEntry(org.eclipse.vorto.repository.core.PolicyEntry) ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) ModelType(org.eclipse.vorto.model.ModelType) TimeUnit(java.util.concurrent.TimeUnit) ModelResource(org.eclipse.vorto.repository.core.ModelResource) PrincipalType(org.eclipse.vorto.repository.core.PolicyEntry.PrincipalType) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) UserContext(org.eclipse.vorto.repository.core.impl.UserContext) OperationForbiddenException(org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) User(org.eclipse.vorto.repository.domain.User) ModelId(org.eclipse.vorto.model.ModelId) Namespace(org.eclipse.vorto.repository.domain.Namespace) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 2 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class PayloadMappingController method saveMappingSpecification.

@PutMapping(value = "/{modelId:.+}")
@PreAuthorize("hasAuthority('model_creator')")
public void saveMappingSpecification(@RequestBody MappingSpecification mappingSpecification, @PathVariable String modelId) {
    try {
        String namespaceName = ModelId.fromPrettyFormat(modelId).getNamespace();
        Namespace namespace = namespaceService.getByName(namespaceName);
        if (null == namespace) {
            LOGGER.error(String.format("Namespace [%s] not found", namespaceName));
            return;
        }
        IUserContext userContext;
        if (namespace != null) {
            userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication(), namespace.getWorkspaceId());
        } else {
            userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
        }
        this.mappingService.saveSpecification(mappingSpecification, userContext);
    } catch (DoesNotExistException dnee) {
        LOGGER.error(dnee);
    }
}
Also used : IUserContext(org.eclipse.vorto.repository.core.IUserContext) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) Namespace(org.eclipse.vorto.repository.domain.Namespace) PutMapping(org.springframework.web.bind.annotation.PutMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 3 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class NamespaceRequestCache method namespace.

/**
 * Resolves a cached {@link Namespace} by name if applicable.<br/>
 * This will also attempt to resolve a "virtual" namespace string, consisting in the real
 * namespace appended with an arbitrary number of {@literal .[sub-namespace]} strings to the
 * root namespace.<br/>
 * The latter is useful when invoking e.g. {@link NamespaceService#getByName(String)} with
 * {@link ModelId#getNamespace()} since the latter does not trim out the "virtual" sub-namespaces.
 * <br/>
 * For instance, when given {@literal com.bosch.iot.suite.example.octopussuiteedition}:
 * <ol>
 *   <li>
 *     Attempts to resolve {@literal com.bosch.iot.suite.example.octopussuiteedition} and get
 *     its workspace ID, which fails
 *   </li>
 *   <li>
 *     Attempts to resolve {@literal com.bosch.iot.suite.example} and get its workspace ID, which
 *     fails again
 *   </li>
 *   <li>
 *     Attempts to resolve {@literal com.bosch.iot.suite} and get its workspace ID, which
 *     succeeds
 *   </li>
 * </ol>
 * Note: virtual namespaces are cached within the scope of a request. <br/>
 *
 * @param name
 * @return
 */
public Optional<Namespace> namespace(String name) {
    // boilerplate null/empty checks
    if (Objects.isNull(name) || name.trim().isEmpty()) {
        return Optional.empty();
    }
    // lazy population
    populateIfEmpty();
    // lookup into virtual namespace map first
    if (virtualNamespaces.containsKey(name)) {
        Namespace result = virtualNamespaces.get(name);
        LOGGER.debug(String.format("Resolved virtual namespace [%s] to [%s]", name, result.getName()));
        return Optional.of(result);
    }
    // resolving by name equality
    Optional<Namespace> result = this.namespaces.stream().filter(n -> n.getName().equals(name)).findAny();
    if (result.isPresent()) {
        LOGGER.debug(String.format("Resolved namespace [%s]", name));
        return result;
    } else {
        return resolveVirtualNamespaceRecursively(name, name);
    }
}
Also used : Predicate(java.util.function.Predicate) Collection(java.util.Collection) RequestScope(org.springframework.web.context.annotation.RequestScope) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Autowired(org.springframework.beans.factory.annotation.Autowired) Collectors(java.util.stream.Collectors) ModelId(org.eclipse.vorto.model.ModelId) Namespace(org.eclipse.vorto.repository.domain.Namespace) NAMESPACE_SEPARATOR(org.eclipse.vorto.repository.services.NamespaceService.NAMESPACE_SEPARATOR) NamespaceService(org.eclipse.vorto.repository.services.NamespaceService) Objects(java.util.Objects) Logger(org.apache.log4j.Logger) NamespaceRepository(org.eclipse.vorto.repository.repositories.NamespaceRepository) Service(org.springframework.stereotype.Service) Map(java.util.Map) Optional(java.util.Optional) Collections(java.util.Collections) PRIVATE_NAMESPACE_PREFIX(org.eclipse.vorto.repository.services.NamespaceService.PRIVATE_NAMESPACE_PREFIX) Namespace(org.eclipse.vorto.repository.domain.Namespace)

Example 4 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class BackupRestoreService method restoreRepository.

@Override
public Collection<Namespace> restoreRepository(byte[] backupFile, Predicate<Namespace> namespaceFilter) {
    Preconditions.checkNotNull(backupFile, "Backup file must not be null");
    try {
        Collection<Namespace> namespacesRestored = Lists.newArrayList();
        Map<String, byte[]> backups = getBackups(backupFile);
        backups.forEach((namespaceName, backup) -> {
            LOGGER.info(String.format("Restoring backup for [%s]", namespaceName));
            Namespace namespace = namespaceRepository.findByName(namespaceName);
            if (null != namespace && namespaceFilter.test(namespace)) {
                try {
                    String workspaceId = namespace.getWorkspaceId();
                    IRepositoryManager repoMgr = modelRepositoryFactory.getRepositoryManager(workspaceId, authSupplier.get());
                    if (!repoMgr.exists(workspaceId)) {
                        repoMgr.createWorkspace(workspaceId);
                    } else {
                        repoMgr.removeWorkspace(workspaceId);
                        repoMgr.createWorkspace(workspaceId);
                    }
                    repoMgr.restore(backup);
                    this.modelRepositoryFactory.getPolicyManager(workspaceId, SecurityContextHolder.getContext().getAuthentication()).restorePolicyEntries();
                    namespacesRestored.add(namespace);
                } catch (Exception e) {
                    LOGGER.error(String.format("Error while restoring [%s]", namespaceName), e);
                }
            } else {
                LOGGER.info(String.format("Skipping restoration of [%s] either because the namespace could not be found, or was filtered out.", namespaceName));
            }
        });
        if (!namespacesRestored.isEmpty()) {
            indexingService.reindexAllModels();
        }
        return namespacesRestored;
    } catch (IOException e) {
        throw new GenericApplicationException("Problem while reading zip file during restore", e);
    }
}
Also used : IRepositoryManager(org.eclipse.vorto.repository.core.IRepositoryManager) IOException(java.io.IOException) GenericApplicationException(org.eclipse.vorto.repository.web.GenericApplicationException) Namespace(org.eclipse.vorto.repository.domain.Namespace) GenericApplicationException(org.eclipse.vorto.repository.web.GenericApplicationException) IOException(java.io.IOException)

Example 5 with Namespace

use of org.eclipse.vorto.repository.domain.Namespace in project vorto by eclipse.

the class NamespaceProvider method mockComNamespace.

public static Namespace mockComNamespace() {
    Namespace namespace = new Namespace();
    namespace.setName("com");
    namespace.setId(2L);
    namespace.setWorkspaceId("playground");
    return namespace;
}
Also used : Namespace(org.eclipse.vorto.repository.domain.Namespace)

Aggregations

Namespace (org.eclipse.vorto.repository.domain.Namespace)16 DoesNotExistException (org.eclipse.vorto.repository.services.exceptions.DoesNotExistException)7 IUserContext (org.eclipse.vorto.repository.core.IUserContext)6 OperationForbiddenException (org.eclipse.vorto.repository.services.exceptions.OperationForbiddenException)6 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)6 Map (java.util.Map)5 ResponseEntity (org.springframework.http.ResponseEntity)5 Collection (java.util.Collection)4 Optional (java.util.Optional)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 Collectors (java.util.stream.Collectors)4 NamespaceService (org.eclipse.vorto.repository.services.NamespaceService)4 Autowired (org.springframework.beans.factory.annotation.Autowired)4 PutMapping (org.springframework.web.bind.annotation.PutMapping)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 ApiParam (io.swagger.annotations.ApiParam)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 User (org.eclipse.vorto.repository.domain.User)3 GetMapping (org.springframework.web.bind.annotation.GetMapping)3