Search in sources :

Example 16 with ModelId

use of org.eclipse.vorto.model.ModelId in project vorto by eclipse.

the class DefaultPayloadMappingService method saveSpecification.

@Override
public void saveSpecification(IMappingSpecification specification, IUserContext user) {
    MappingSpecificationSerializer.create(specification).iterator().forEachRemaining(serializer -> {
        final ModelId createdModelId = serializer.getModelId();
        String serializedMapping = serializer.serialize();
        LOGGER.trace(String.format("Saving mapping: %s", serializedMapping));
        this.modelRepositoryFactory.getRepositoryByModel(createdModelId).save(createdModelId, serializedMapping.getBytes(), createdModelId.getName() + ".mapping", user, false);
        try {
            workflowService.start(createdModelId, user);
        } catch (WorkflowException e) {
            throw new RuntimeException("Could not start workflow for mapping model", e);
        }
    });
}
Also used : WorkflowException(org.eclipse.vorto.repository.workflow.WorkflowException) ModelId(org.eclipse.vorto.model.ModelId)

Example 17 with ModelId

use of org.eclipse.vorto.model.ModelId 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 18 with ModelId

use of org.eclipse.vorto.model.ModelId in project vorto by eclipse.

the class NodeDiagnosticUtils method getModelId.

public static Optional<ModelId> getModelId(String path) {
    Collection<String> fragments = Arrays.asList(path.split("/")).stream().filter(str -> !Strings.isNullOrEmpty(str)).collect(Collectors.toList());
    String[] pathFragments = fragments.toArray(new String[fragments.size()]);
    if (ModelType.supports(pathFragments[pathFragments.length - 1])) {
        if (pathFragments.length > 3) {
            return Optional.of(new ModelId(pathFragments[pathFragments.length - 3], String.join(".", Arrays.copyOfRange(pathFragments, 0, pathFragments.length - 3)), pathFragments[pathFragments.length - 2]));
        }
    } else {
        if (pathFragments.length > 2) {
            return Optional.of(new ModelId(pathFragments[pathFragments.length - 2], String.join(".", Arrays.copyOfRange(pathFragments, 0, pathFragments.length - 2)), pathFragments[pathFragments.length - 1]));
        }
    }
    return Optional.empty();
}
Also used : Strings(com.google.common.base.Strings) Arrays(java.util.Arrays) Node(javax.jcr.Node) Collection(java.util.Collection) Optional(java.util.Optional) Property(javax.jcr.Property) Collectors(java.util.stream.Collectors) ModelId(org.eclipse.vorto.model.ModelId) ModelParserFactory(org.eclipse.vorto.repository.core.impl.parser.ModelParserFactory) ModelType(org.eclipse.vorto.model.ModelType) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) ModelId(org.eclipse.vorto.model.ModelId)

Example 19 with ModelId

use of org.eclipse.vorto.model.ModelId in project vorto by eclipse.

the class ModelRepository method doAttachFileInSession.

private boolean doAttachFileInSession(ModelId modelId, FileContent fileContent, IUserContext userContext, Session session, Tag[] tags) throws RepositoryException {
    try {
        ModelIdHelper modelIdHelper = new ModelIdHelper(modelId);
        Node modelFolderNode = session.getNode(modelIdHelper.getFullPath());
        Node attachmentFolderNode;
        if (!modelFolderNode.hasNode(ATTACHMENTS_NODE)) {
            attachmentFolderNode = modelFolderNode.addNode(ATTACHMENTS_NODE, NT_FOLDER);
        } else {
            attachmentFolderNode = modelFolderNode.getNode(ATTACHMENTS_NODE);
        }
        String[] tagIds = Arrays.stream(tags).filter(Objects::nonNull).map(Tag::getId).collect(Collectors.toList()).toArray(new String[tags.length]);
        // purposes), removes the tag from all other attachments
        if (Arrays.asList(tags).contains(TAG_DISPLAY_IMAGE)) {
            NodeIterator attachments = attachmentFolderNode.getNodes();
            while (attachments.hasNext()) {
                Node next = attachments.nextNode();
                Property attachmentTags = next.getProperty(VORTO_TAGS);
                Value[] attachmentTagsValuesFiltered = Arrays.stream(attachmentTags.getValues()).filter(v -> {
                    try {
                        return !v.getString().equals(TAG_DISPLAY_IMAGE.getId());
                    // swallowing here
                    } catch (RepositoryException re) {
                        return false;
                    }
                }).toArray(Value[]::new);
                next.setProperty(VORTO_TAGS, attachmentTagsValuesFiltered);
            }
        }
        Node contentNode;
        if (attachmentFolderNode.hasNode(fileContent.getFileName())) {
            Node attachmentNode = attachmentFolderNode.getNode(fileContent.getFileName());
            attachmentNode.addMixin(VORTO_META);
            attachmentNode.setProperty(VORTO_TAGS, tagIds, PropertyType.STRING);
            contentNode = (Node) attachmentNode.getPrimaryItem();
        } else {
            Node attachmentNode = attachmentFolderNode.addNode(fileContent.getFileName(), NT_FILE);
            attachmentNode.addMixin(VORTO_META);
            attachmentNode.setProperty(VORTO_TAGS, tagIds, PropertyType.STRING);
            contentNode = attachmentNode.addNode(JCR_CONTENT, NT_RESOURCE);
        }
        Binary binary = session.getValueFactory().createBinary(new ByteArrayInputStream(fileContent.getContent()));
        contentNode.setProperty(JCR_DATA, binary);
        session.save();
        eventPublisher.publishEvent(new AppEvent(this, getById(modelId), userContext, EventType.MODEL_UPDATED));
        return true;
    } catch (AccessDeniedException e) {
        throw new NotAuthorizedException(modelId, e);
    }
}
Also used : DependencyManager(org.eclipse.vorto.repository.core.impl.utils.DependencyManager) java.util(java.util) EventType(org.eclipse.vorto.repository.core.events.EventType) javax.jcr.query(javax.jcr.query) AppEvent(org.eclipse.vorto.repository.core.events.AppEvent) Function(java.util.function.Function) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) Model(org.eclipse.vorto.core.api.model.model.Model) Logger(org.apache.log4j.Logger) Lists(com.google.common.collect.Lists) ObjectMapperFactory(org.eclipse.vorto.plugin.generator.adapter.ObjectMapperFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) IModelWorkspace(org.eclipse.vorto.utilities.reader.IModelWorkspace) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) org.eclipse.vorto.repository.core(org.eclipse.vorto.repository.core) ModelState(org.eclipse.vorto.repository.workflow.ModelState) ModelParserFactory(org.eclipse.vorto.repository.core.impl.parser.ModelParserFactory) Attachment(org.eclipse.vorto.repository.core.Attachment) PrivilegeService(org.eclipse.vorto.repository.services.PrivilegeService) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) ModelSearchUtil(org.eclipse.vorto.repository.core.impl.utils.ModelSearchUtil) ModelIdHelper(org.eclipse.vorto.repository.core.impl.utils.ModelIdHelper) ModelReferencesHelper(org.eclipse.vorto.repository.core.impl.utils.ModelReferencesHelper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ModelId(org.eclipse.vorto.model.ModelId) ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) Namespace(org.eclipse.vorto.repository.domain.Namespace) Collectors(java.util.stream.Collectors) ModelType(org.eclipse.vorto.model.ModelType) NamespaceService(org.eclipse.vorto.repository.services.NamespaceService) IOUtils(org.apache.commons.io.IOUtils) ChangeSet(org.eclipse.vorto.model.refactor.ChangeSet) RefactoringTask(org.eclipse.vorto.model.refactor.RefactoringTask) AttachmentValidator(org.eclipse.vorto.repository.core.impl.validation.AttachmentValidator) ModelWorkspaceReader(org.eclipse.vorto.utilities.reader.ModelWorkspaceReader) NewNamespacesNotSupersetException(org.eclipse.vorto.repository.tenant.NewNamespacesNotSupersetException) ModelUtils(org.eclipse.vorto.repository.utils.ModelUtils) IModelParser(org.eclipse.vorto.repository.core.impl.parser.IModelParser) javax.jcr(javax.jcr) InputStream(java.io.InputStream) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) AppEvent(org.eclipse.vorto.repository.core.events.AppEvent) ModelIdHelper(org.eclipse.vorto.repository.core.impl.utils.ModelIdHelper) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 20 with ModelId

use of org.eclipse.vorto.model.ModelId in project vorto by eclipse.

the class ModelRepository method doGetLinksInSession.

private Set<ModelLink> doGetLinksInSession(ModelId modelID, Session session) throws RepositoryException {
    ObjectMapper objectMapper = ObjectMapperFactory.getInstance();
    Node fileNode = getFileNode(modelID, session);
    if (fileNode.hasProperty(VORTO_LINKS)) {
        return getVortoLinksPropertyValues(fileNode.getProperty(VORTO_LINKS)).stream().map(value -> deserializeLinkDto(objectMapper, value)).collect(Collectors.toSet());
    }
    return Collections.emptySet();
}
Also used : DependencyManager(org.eclipse.vorto.repository.core.impl.utils.DependencyManager) java.util(java.util) EventType(org.eclipse.vorto.repository.core.events.EventType) javax.jcr.query(javax.jcr.query) AppEvent(org.eclipse.vorto.repository.core.events.AppEvent) Function(java.util.function.Function) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) Model(org.eclipse.vorto.core.api.model.model.Model) Logger(org.apache.log4j.Logger) Lists(com.google.common.collect.Lists) ObjectMapperFactory(org.eclipse.vorto.plugin.generator.adapter.ObjectMapperFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) IModelWorkspace(org.eclipse.vorto.utilities.reader.IModelWorkspace) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) org.eclipse.vorto.repository.core(org.eclipse.vorto.repository.core) ModelState(org.eclipse.vorto.repository.workflow.ModelState) ModelParserFactory(org.eclipse.vorto.repository.core.impl.parser.ModelParserFactory) Attachment(org.eclipse.vorto.repository.core.Attachment) PrivilegeService(org.eclipse.vorto.repository.services.PrivilegeService) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) ModelSearchUtil(org.eclipse.vorto.repository.core.impl.utils.ModelSearchUtil) ModelIdHelper(org.eclipse.vorto.repository.core.impl.utils.ModelIdHelper) ModelReferencesHelper(org.eclipse.vorto.repository.core.impl.utils.ModelReferencesHelper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ModelId(org.eclipse.vorto.model.ModelId) ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) Namespace(org.eclipse.vorto.repository.domain.Namespace) Collectors(java.util.stream.Collectors) ModelType(org.eclipse.vorto.model.ModelType) NamespaceService(org.eclipse.vorto.repository.services.NamespaceService) IOUtils(org.apache.commons.io.IOUtils) ChangeSet(org.eclipse.vorto.model.refactor.ChangeSet) RefactoringTask(org.eclipse.vorto.model.refactor.RefactoringTask) AttachmentValidator(org.eclipse.vorto.repository.core.impl.validation.AttachmentValidator) ModelWorkspaceReader(org.eclipse.vorto.utilities.reader.ModelWorkspaceReader) NewNamespacesNotSupersetException(org.eclipse.vorto.repository.tenant.NewNamespacesNotSupersetException) ModelUtils(org.eclipse.vorto.repository.utils.ModelUtils) IModelParser(org.eclipse.vorto.repository.core.impl.parser.IModelParser) javax.jcr(javax.jcr) InputStream(java.io.InputStream) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

ModelId (org.eclipse.vorto.model.ModelId)124 Test (org.junit.Test)48 ModelInfo (org.eclipse.vorto.repository.core.ModelInfo)29 IOException (java.io.IOException)28 ClassPathResource (org.springframework.core.io.ClassPathResource)25 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)19 ByteArrayInputStream (java.io.ByteArrayInputStream)14 ResponseEntity (org.springframework.http.ResponseEntity)14 IModelRepository (org.eclipse.vorto.repository.core.IModelRepository)13 ModelType (org.eclipse.vorto.model.ModelType)12 IUserContext (org.eclipse.vorto.repository.core.IUserContext)12 Autowired (org.springframework.beans.factory.annotation.Autowired)12 GetMapping (org.springframework.web.bind.annotation.GetMapping)11 Optional (java.util.Optional)10 List (java.util.List)9 IOUtils (org.apache.commons.io.IOUtils)9 ValidationException (org.eclipse.vorto.repository.core.impl.validation.ValidationException)9 ModelLink (org.eclipse.vorto.repository.web.api.v1.dto.ModelLink)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 ApiOperation (io.swagger.annotations.ApiOperation)8