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;
}
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));
}
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;
}
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;
}
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);
}
}
Aggregations