Search in sources :

Example 1 with MappingSpecification

use of org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification in project vorto by eclipse.

the class ModelRepositoryControllerTest method verifyFullModelPayloadForUI.

/**
 * This test performs the following:
 * <ol>
 *   <li>
 *     Creates the {@literal com.test} namespace with a sysadmin user, to hold the models.
 *   </li>
 *   <li>
 *     Adds a non-sysadmin user with {@literal model_creator} role to the {@literal com.test}
 *     namespace.
 *   </li>
 *   <li>
 *     Creates a "Zone" datatype model from the corresponding file resource.
 *   </li>
 *   <li>
 *     Creates a "Lamp" functionblock model from the corresponding file resource.
 *   </li>
 *   <li>
 *     Creates an "Address" functionblock model from the corresponding file resource.
 *   </li>
 *   <li>
 *     Creates a "StreetLamp" model from the corresponding file resource, using the above
 *     functionblocks as dependencies.
 *   </li>
 *   <li>
 *     Adds an attachment to the "StreetLamp" model.
 *   </li>
 *   <li>
 *     Adds a link to the "StreetLamp" model.
 *   </li>
 *   <li>
 *     Adds a mapping to the "StreetLamp" model.
 *   </li>
 *   <li>
 *     Loads the "StreetLamp" model with the REST call used by the UI, and verifies / validates:
 *     <ul>
 *       <li>
 *         Basic {@link org.eclipse.vorto.repository.core.ModelInfo} properties.
 *       </li>
 *       <li>
 *         The Base64-encoded model syntax
 *         (see {@link ModelFullDetailsDTO#getEncodedModelSyntax()})
 *       </li>
 *       <li>
 *         Mapping (see {@link ModelFullDetailsDTO#getMappings()}).
 *       </li>
 *       <li>
 *         Attachment (see {@link ModelFullDetailsDTO#getAttachments()}
 *       </li>
 *       <li>
 *         Link (see {@link ModelFullDetailsDTO#getLinks()}
 *       </li>
 *       <li>
 *         References (see {@link ModelFullDetailsDTO#getReferences()}
 *       </li>
 *       <li>
 *         "Referenced by" (see {@link ModelFullDetailsDTO#getReferencedBy()})
 *       </li>
 *       <li>
 *         Policies (see {@link ModelFullDetailsDTO#getPolicies()} and
 *         {@link ModelFullDetailsDTO#getBestPolicy()} for the creating user, and conversely, for
 *         an extraneous user with no access.
 *       </li>
 *       <li>
 *         Workflow actions (see {@link ModelFullDetailsDTO#getActions()} for the creating user,
 *         and conversely, for an extraneous user with no access.
 *       </li>
 *     </ul>
 *   </li>
 *   <li>
 *     Loads the "Lamp" functionblock model with the REST call used by the UI, and verifies the
 *     "referenced by" node (see {@link ModelFullDetailsDTO#getReferencedBy()}.
 *   </li>
 *   <li>
 *     Finally, cleans up and deletes all 4 models, then the namespace.
 *   </li>
 * </ol>
 *
 * @throws Exception
 */
@Test
public void verifyFullModelPayloadForUI() throws Exception {
    // required for some extra properties in DTOs not annotated with Jackson polymorphism
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // model names, id strings and file names
    String namespace = "com.test";
    String version = "1.0.0";
    String idFormat = "%s.%s:%s";
    String zoneModelName = "Zone";
    String zoneModelID = String.format(idFormat, namespace, zoneModelName, version);
    String zoneFileName = zoneModelName.concat(".type");
    String lampModelName = "Lamp";
    String lampModelID = String.format(idFormat, namespace, lampModelName, version);
    String lampFileName = lampModelName.concat(".fbmodel");
    String addressModelName = "Address";
    String addressModelID = String.format(idFormat, namespace, addressModelName, version);
    String addressFileName = addressModelName.concat(".fbmodel");
    String streetLampModelName = "StreetLamp";
    String streetLampModelID = String.format(idFormat, namespace, streetLampModelName, version);
    String streetLampFileName = streetLampModelName.concat(".infomodel");
    String streetLampAttachmentFileName = "StreetLampAttachment.json";
    String streetLampLinkURL = "https://vorto.eclipse.org/";
    String streetLampLinkName = "Vorto";
    // creates the namespace as sysadmin
    createNamespaceSuccessfully(namespace, userSysadmin);
    // creates the collaborator payload to add userModelCreator to the namespace
    Collaborator userModelCreatorCollaborator = new Collaborator();
    userModelCreatorCollaborator.setAuthenticationProviderId(GITHUB);
    userModelCreatorCollaborator.setRoles(Arrays.asList("model_viewer", "model_creator"));
    userModelCreatorCollaborator.setTechnicalUser(false);
    userModelCreatorCollaborator.setUserId(USER_MODEL_CREATOR_NAME);
    // allows creator rights to userCreator on namespace
    repositoryServer.perform(put(String.format("/rest/namespaces/%s/users", namespace)).with(userSysadmin).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(userModelCreatorCollaborator))).andExpect(status().isOk());
    // creates the Zone model
    createModel(userModelCreator, zoneFileName, zoneModelID);
    // creates the Lamp model
    createModel(userModelCreator, lampFileName, lampModelID);
    // creates the Address model
    createModel(userModelCreator, addressFileName, addressModelID);
    // creates the StreetLamp model
    createModel(userModelCreator, streetLampFileName, streetLampModelID);
    // adds an attachment to the StreetLamp model (still requires sysadmin for this)
    addAttachment(streetLampModelID, userSysadmin, streetLampAttachmentFileName, MediaType.APPLICATION_JSON).andExpect(status().isOk()).andExpect(content().json(objectMapper.writeValueAsString(AttachResult.success(ModelId.fromPrettyFormat(streetLampModelID), streetLampAttachmentFileName))));
    // adds a link to the StreetLamp model
    ModelLink link = new ModelLink(streetLampLinkURL, streetLampLinkName);
    addLink(streetLampModelID, userModelCreator, link);
    // saves a minimal mapping specification for the street lamp model
    Infomodel streetLampInfomodel = new Infomodel(ModelId.fromPrettyFormat(streetLampModelID));
    streetLampInfomodel.setTargetPlatformKey("myTargetPlatform");
    MappingSpecification mapping = new MappingSpecification(streetLampInfomodel);
    repositoryServer.perform(put(String.format("/rest/mappings/specifications/%s", streetLampModelID)).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(mapping)).with(userModelCreator)).andExpect(status().isOk());
    // expected ID of the payload mapping model
    String mappingId = String.format("%s.%s:%sPayloadMapping:%s", // root namespace
    namespace, // virtual namespace for mapping
    streetLampModelName.toLowerCase(), // mapping name part 1 matching root model
    streetLampModelName, // root model version
    version);
    // fetches the full model for the UI
    repositoryServer.perform(get(String.format("/rest/models/ui/%s", streetLampModelID)).with(userModelCreator)).andExpect(status().isOk()).andDo(mvcResult -> {
        ModelFullDetailsDTO output = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ModelFullDetailsDTO.class);
        LOGGER.info(new StringBuilder("\nReceived response body:\n\n").append(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(output)).toString());
    }).andExpect(jsonPath("$.modelInfo").exists()).andExpect(jsonPath("$.modelInfo.id.name").value(streetLampModelName)).andExpect(jsonPath("$.modelInfo.id.namespace").value(namespace)).andExpect(jsonPath("$.modelInfo.type").value("InformationModel")).andExpect(jsonPath("$.modelInfo.author").value(USER_MODEL_CREATOR_NAME)).andExpect(jsonPath("$.mappings").isNotEmpty()).andExpect(jsonPath("$.mappings[0].id").value(mappingId)).andExpect(jsonPath("$.references", hasSize(2))).andExpect(jsonPath("$.referencedBy", hasSize(1))).andExpect(jsonPath("$.referencedBy[0].id").value(mappingId)).andExpect(jsonPath("$.attachments").exists()).andExpect(jsonPath("$.attachments[0].filename").value(streetLampAttachmentFileName)).andExpect(jsonPath("$.attachments[0].modelId.name").value(streetLampModelName)).andExpect(jsonPath("$.links").exists()).andExpect(jsonPath("$.links[0].url").value(equalTo(link.getUrl()))).andExpect(jsonPath("$.links[0].displayText").value(equalTo(link.getDisplayText()))).andExpect(jsonPath("$.actions").exists()).andExpect(jsonPath("$.actions").isEmpty()).andExpect(jsonPath("$.policies", hasSize(2))).andExpect(jsonPath("$.bestPolicy").exists()).andExpect(jsonPath("$.bestPolicy.principalId").value("model_creator")).andExpect(jsonPath("$.bestPolicy.permission").value(Permission.FULL_ACCESS.toString())).andExpect(jsonPath("$.encodedModelSyntax").value(Base64.getEncoder().encodeToString(createContentAsString(streetLampFileName).getBytes())));
    // cleanup: deletes models in reverse order of creation, then namespace
    repositoryServer.perform(delete(String.format("/rest/models/%s", mappingId)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", streetLampModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", lampModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", addressModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/models/%s", zoneModelID)).with(userModelCreator)).andExpect(status().isOk());
    repositoryServer.perform(delete(String.format("/rest/namespaces/%s", namespace)).with(userSysadmin)).andExpect(status().isNoContent());
    // removes test-specific configuration
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
}
Also used : Arrays(java.util.Arrays) MockMvcResultMatchers.jsonPath(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath) MappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ModelFullDetailsDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelFullDetailsDTO) Autowired(org.springframework.beans.factory.annotation.Autowired) Infomodel(org.eclipse.vorto.model.Infomodel) MockMvcResultMatchers.content(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) MockMvcRequestBuilders.delete(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete) Logger(org.apache.log4j.Logger) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) MockMvcRequestBuilders.post(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) MockMvcRequestBuilders.put(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put) MediaType(org.springframework.http.MediaType) Test(org.junit.Test) ModelId(org.eclipse.vorto.model.ModelId) Sets(com.google.common.collect.Sets) ModelType(org.eclipse.vorto.model.ModelType) Base64(java.util.Base64) AttachmentValidator(org.eclipse.vorto.repository.core.impl.validation.AttachmentValidator) MockMvcRequestBuilders.get(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get) Permission(org.eclipse.vorto.repository.core.PolicyEntry.Permission) AttachResult(org.eclipse.vorto.repository.web.api.v1.dto.AttachResult) ModelFullDetailsDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelFullDetailsDTO) Collaborator(org.eclipse.vorto.repository.web.api.v1.dto.Collaborator) MappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) Infomodel(org.eclipse.vorto.model.Infomodel) Test(org.junit.Test)

Example 2 with MappingSpecification

use of org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification in project vorto by eclipse.

the class DefaultPayloadMappingService method getOrCreateSpecification.

@Override
public IMappingSpecification getOrCreateSpecification(ModelId modelId) {
    ModelContent modelContent = getModelContent(modelId, createTargetPlatformKey(modelId));
    Infomodel infomodel = (Infomodel) modelContent.getModels().get(modelContent.getRoot());
    MappingSpecification specification = new MappingSpecification();
    specification.setInfoModel(infomodel);
    addReferencesRecursive(infomodel, infomodel.getTargetPlatformKey());
    return specification;
}
Also used : MappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification) IMappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.IMappingSpecification) Infomodel(org.eclipse.vorto.model.Infomodel) ModelContent(org.eclipse.vorto.model.ModelContent)

Example 3 with MappingSpecification

use of org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification in project vorto by eclipse.

the class PayloadMappingController method downloadModelById.

@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful download of mapping specification"), @ApiResponse(code = 400, message = "Wrong input"), @ApiResponse(code = 404, message = "Model not found") })
@PreAuthorize("hasAuthority('model_viewer')")
@GetMapping(value = "/{modelId:.+}/file")
public void downloadModelById(@PathVariable final String modelId, final HttpServletResponse response) {
    Objects.requireNonNull(modelId, "modelId must not be null");
    final ModelId modelID = ModelId.fromPrettyFormat(modelId);
    response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + modelID.getNamespace() + "_" + modelID.getName() + "_" + modelID.getVersion() + "-mappingspec.json");
    response.setContentType(APPLICATION_OCTET_STREAM);
    try {
        MappingSpecification spec = (MappingSpecification) this.mappingService.getOrCreateSpecification(modelID);
        ObjectMapper mapper = new ObjectMapper();
        IOUtils.copy(new ByteArrayInputStream(mapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(spec)), response.getOutputStream());
        response.flushBuffer();
    } catch (Exception e) {
        throw new RuntimeException("Error copying file.", e);
    }
}
Also used : MappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification) IMappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.IMappingSpecification) ByteArrayInputStream(java.io.ByteArrayInputStream) ModelId(org.eclipse.vorto.model.ModelId) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DoesNotExistException(org.eclipse.vorto.repository.services.exceptions.DoesNotExistException) ModelNotFoundException(org.eclipse.vorto.repository.core.ModelNotFoundException) ModelAlreadyExistsException(org.eclipse.vorto.repository.core.ModelAlreadyExistsException) GetMapping(org.springframework.web.bind.annotation.GetMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

MappingSpecification (org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification)3 IMappingSpecification (org.eclipse.vorto.mapping.engine.model.spec.IMappingSpecification)2 Infomodel (org.eclipse.vorto.model.Infomodel)2 ModelId (org.eclipse.vorto.model.ModelId)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Sets (com.google.common.collect.Sets)1 ApiResponses (io.swagger.annotations.ApiResponses)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 Arrays (java.util.Arrays)1 Base64 (java.util.Base64)1 Logger (org.apache.log4j.Logger)1 ModelContent (org.eclipse.vorto.model.ModelContent)1 ModelType (org.eclipse.vorto.model.ModelType)1 ModelAlreadyExistsException (org.eclipse.vorto.repository.core.ModelAlreadyExistsException)1 ModelNotFoundException (org.eclipse.vorto.repository.core.ModelNotFoundException)1 Permission (org.eclipse.vorto.repository.core.PolicyEntry.Permission)1 AttachmentValidator (org.eclipse.vorto.repository.core.impl.validation.AttachmentValidator)1 DoesNotExistException (org.eclipse.vorto.repository.services.exceptions.DoesNotExistException)1 AttachResult (org.eclipse.vorto.repository.web.api.v1.dto.AttachResult)1