Search in sources :

Example 6 with ModelResource

use of org.eclipse.vorto.repository.core.ModelResource in project vorto by eclipse.

the class RemoteImporter method convert.

@Override
protected List<ModelResource> convert(FileUpload fileUpload, Context context) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    body.add("file", new FileContentResource(fileUpload));
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
    ResponseEntity<byte[]> conversionResult = restTemplate.postForEntity(this.endpointUrl + "/api/2/plugins/importers/{pluginkey}/file_conversion", requestEntity, byte[].class, this.info.getKey());
    IModelWorkspace workspace = IModelWorkspace.newReader().addZip(new ZipInputStream(new ByteArrayInputStream(conversionResult.getBody()))).read();
    List<ModelResource> resources = new ArrayList<>();
    ChangeSet changeSet = RefactoringTask.from(workspace).toNamespaceForAllModels(context.getTargetNamespace().get()).execute();
    for (Model model : changeSet.get()) {
        resources.add(new ModelResource(model));
    }
    return resources;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ArrayList(java.util.ArrayList) IModelWorkspace(org.eclipse.vorto.utilities.reader.IModelWorkspace) ZipInputStream(java.util.zip.ZipInputStream) ModelResource(org.eclipse.vorto.repository.core.ModelResource) ByteArrayInputStream(java.io.ByteArrayInputStream) Model(org.eclipse.vorto.core.api.model.model.Model) FileContentResource(org.eclipse.vorto.repository.plugin.FileContentResource) ChangeSet(org.eclipse.vorto.model.refactor.ChangeSet) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 7 with ModelResource

use of org.eclipse.vorto.repository.core.ModelResource in project vorto by eclipse.

the class AbstractModelParser method parse.

@Override
public ModelInfo parse(InputStream is) {
    Injector injector = getInjector();
    XtextResourceSet resourceSet = workspace.getResourceSet();
    Resource resource = createResource(fileName, getContent(is), resourceSet).orElseThrow(() -> new ValidationException("Xtext is not able to create a resource for this model. Check if you are using the correct parser.", getModelInfoFromFilename()));
    if (resource.getContents().size() <= 0) {
        throw new ValidationException("Xtext is not able to create a model out of this file. Check if the file you are using is correct.", getModelInfoFromFilename());
    }
    Model model = (Model) resource.getContents().get(0);
    // always load direct references to make the model complete
    workspace.loadFromRepository(getReferences(model));
    if (this.isValidationEnabled) {
        /* Execute validators */
        IResourceValidator validator = injector.getInstance(IResourceValidator.class);
        List<Issue> issues = validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
        if (issues.size() > 0) {
            List<ModelId> missingReferences = getMissingReferences(model, issues);
            if (missingReferences.size() > 0) {
                throw new CouldNotResolveReferenceException(getModelInfo(model).orElse(getModelInfoFromFilename()), missingReferences);
            } else {
                Set<ValidationIssue> validationIssues = convertIssues(issues);
                throw new ValidationException(collate(validationIssues), validationIssues, getModelInfo(model).orElse(getModelInfoFromFilename()));
            }
        }
        if (!resource.getErrors().isEmpty()) {
            throw new ValidationException(resource.getErrors().get(0).getMessage(), getModelInfo(model).orElse(getModelInfoFromFilename()));
        }
    }
    return new ModelResource((Model) resource.getContents().get(0));
}
Also used : ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) Issue(org.eclipse.xtext.validation.Issue) IResourceValidator(org.eclipse.xtext.validation.IResourceValidator) CouldNotResolveReferenceException(org.eclipse.vorto.repository.core.impl.validation.CouldNotResolveReferenceException) ModelResource(org.eclipse.vorto.repository.core.ModelResource) Resource(org.eclipse.emf.ecore.resource.Resource) ModelResource(org.eclipse.vorto.repository.core.ModelResource) Injector(com.google.inject.Injector) XtextResourceSet(org.eclipse.xtext.resource.XtextResourceSet) Model(org.eclipse.vorto.core.api.model.model.Model) ModelId(org.eclipse.vorto.model.ModelId)

Example 8 with ModelResource

use of org.eclipse.vorto.repository.core.ModelResource in project vorto by eclipse.

the class AbstractModelImporter method sortAndSaveToRepository.

private List<ModelInfo> sortAndSaveToRepository(List<ModelResource> resources, FileUpload extractedFile, Context context) {
    final IUserContext user = context.getUser();
    List<ModelInfo> savedModels = new ArrayList<>();
    DependencyManager dm = new DependencyManager();
    for (ModelResource resource : resources) {
        dm.addResource(resource);
    }
    dm.getSorted().forEach(resource -> {
        try {
            IModelRepository modelRepository = modelRepoFactory.getRepositoryByModel(resource.getId());
            ModelInfo importedModel = modelRepository.save((ModelResource) resource, user);
            savedModels.add(importedModel);
            postProcessImportedModel(importedModel, new FileContent(extractedFile.getFileName(), extractedFile.getContent()), user);
        } catch (Exception e) {
            logger.error("Problem importing model", e);
            throw new ModelImporterException("Problem importing model", e);
        }
    });
    return savedModels;
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) FileContent(org.eclipse.vorto.repository.core.FileContent) IUserContext(org.eclipse.vorto.repository.core.IUserContext) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) ModelResource(org.eclipse.vorto.repository.core.ModelResource) ArrayList(java.util.ArrayList) DependencyManager(org.eclipse.vorto.repository.core.impl.utils.DependencyManager) IOException(java.io.IOException) BulkUploadException(org.eclipse.vorto.repository.web.core.exceptions.BulkUploadException)

Example 9 with ModelResource

use of org.eclipse.vorto.repository.core.ModelResource in project vorto by eclipse.

the class AbstractModelImporter method doImport.

@Override
public List<ModelInfo> doImport(String uploadHandleId, Context context) {
    StorageItem uploadedItem = this.uploadStorage.get(uploadHandleId);
    if (uploadedItem == null) {
        throw new ModelImporterException(String.format("No uploaded file found for handleId '%s'", uploadHandleId));
    }
    List<ModelInfo> importedModels = new ArrayList<>();
    try {
        if (handleZipUploads() && isZipFile(uploadedItem.getValue())) {
            getUploadedFilesFromZip(uploadedItem.getValue().getContent()).stream().forEach(extractedFile -> {
                List<ModelResource> resources = this.convert(extractedFile, context);
                importedModels.addAll(sortAndSaveToRepository(resources, extractedFile, context));
            });
        } else {
            List<ModelResource> resources = this.convert(uploadedItem.getValue(), context);
            importedModels.addAll(sortAndSaveToRepository(resources, uploadedItem.getValue(), context));
        }
    } finally {
        this.uploadStorage.remove(uploadHandleId);
    }
    return importedModels;
}
Also used : ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) ModelResource(org.eclipse.vorto.repository.core.ModelResource) ArrayList(java.util.ArrayList) StorageItem(org.eclipse.vorto.repository.core.impl.StorageItem)

Example 10 with ModelResource

use of org.eclipse.vorto.repository.core.ModelResource in project vorto by eclipse.

the class ModelRepositoryController method saveModel.

@ApiOperation("Saves a model to the repository.")
@PreAuthorize("hasAuthority('sysadmin') or " + "hasPermission(T(org.eclipse.vorto.model.ModelId).fromPrettyFormat(#modelId)," + "T(org.eclipse.vorto.repository.core.PolicyEntry.Permission).MODIFY)")
@PutMapping(value = "/{modelId:.+}", produces = "application/json")
public ResponseEntity<ValidationReport> saveModel(@ApiParam(value = "modelId", required = true) @PathVariable String modelId, @RequestBody ModelContent content) {
    try {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        IModelRepository modelRepository = getModelRepository(ModelId.fromPrettyFormat(modelId));
        ModelId modelID = ModelId.fromPrettyFormat(modelId);
        if (modelRepository.getById(modelID) == null) {
            return new ResponseEntity<>(ValidationReport.invalid(null, "Model was not found"), HttpStatus.NOT_FOUND);
        }
        IUserContext userContext = UserContext.user(authentication, getWorkspaceId(modelId));
        ModelResource modelInfo = (ModelResource) modelParserFactory.getParser("model" + ModelType.valueOf(content.getType()).getExtension()).parse(new ByteArrayInputStream(content.getContentDsl().getBytes()));
        if (!modelID.equals(modelInfo.getId())) {
            return new ResponseEntity<>(ValidationReport.invalid(modelInfo, "You may not change the model ID (name, namespace, version). For this please create a new model."), HttpStatus.BAD_REQUEST);
        }
        ValidationReport validationReport = modelValidationHelper.validateModelUpdate(modelInfo, userContext);
        if (validationReport.isValid()) {
            modelRepository.save(modelInfo.getId(), content.getContentDsl().getBytes(), modelInfo.getId().getName() + modelInfo.getType().getExtension(), userContext);
        }
        return new ResponseEntity<>(validationReport, HttpStatus.OK);
    } catch (ValidationException validationException) {
        LOGGER.warn(validationException);
        return new ResponseEntity<>(ValidationReport.invalid(null, validationException), HttpStatus.BAD_REQUEST);
    }
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) ModelResource(org.eclipse.vorto.repository.core.ModelResource) ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) ByteArrayInputStream(java.io.ByteArrayInputStream) ValidationReport(org.eclipse.vorto.repository.importer.ValidationReport) Authentication(org.springframework.security.core.Authentication) ModelId(org.eclipse.vorto.model.ModelId) ApiOperation(io.swagger.annotations.ApiOperation) PutMapping(org.springframework.web.bind.annotation.PutMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Aggregations

ModelResource (org.eclipse.vorto.repository.core.ModelResource)12 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ArrayList (java.util.ArrayList)4 Model (org.eclipse.vorto.core.api.model.model.Model)4 ModelId (org.eclipse.vorto.model.ModelId)3 ChangeSet (org.eclipse.vorto.model.refactor.ChangeSet)3 IUserContext (org.eclipse.vorto.repository.core.IUserContext)3 ModelInfo (org.eclipse.vorto.repository.core.ModelInfo)3 IModelWorkspace (org.eclipse.vorto.utilities.reader.IModelWorkspace)3 ApiOperation (io.swagger.annotations.ApiOperation)2 FileContent (org.eclipse.vorto.repository.core.FileContent)2 IModelRepository (org.eclipse.vorto.repository.core.IModelRepository)2 ValidationException (org.eclipse.vorto.repository.core.impl.validation.ValidationException)2 ResponseEntity (org.springframework.http.ResponseEntity)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 Authentication (org.springframework.security.core.Authentication)2 Injector (com.google.inject.Injector)1 IOException (java.io.IOException)1 ZipInputStream (java.util.zip.ZipInputStream)1 Resource (org.eclipse.emf.ecore.resource.Resource)1