Search in sources :

Example 71 with PathVariable

use of org.springframework.web.bind.annotation.PathVariable in project dhis2-core by dhis2.

the class TrackedEntityInstanceController method getAttributeImage.

@GetMapping("/{teiId}/{attributeId}/image")
public void getAttributeImage(@PathVariable("teiId") String teiId, @PathVariable("attributeId") String attributeId, @RequestParam(required = false) Integer width, @RequestParam(required = false) Integer height, @RequestParam(required = false) ImageFileDimension dimension, HttpServletResponse response) throws WebMessageException {
    User user = currentUserService.getCurrentUser();
    org.hisp.dhis.trackedentity.TrackedEntityInstance trackedEntityInstance = instanceService.getTrackedEntityInstance(teiId);
    List<String> trackerAccessErrors = trackerAccessManager.canRead(user, trackedEntityInstance);
    List<TrackedEntityAttributeValue> attribute = trackedEntityInstance.getTrackedEntityAttributeValues().stream().filter(val -> val.getAttribute().getUid().equals(attributeId)).collect(Collectors.toList());
    if (!trackerAccessErrors.isEmpty()) {
        throw new WebMessageException(unauthorized("You're not authorized to access the TrackedEntityInstance with id: " + teiId));
    }
    if (attribute.size() == 0) {
        throw new WebMessageException(notFound("Attribute not found for ID " + attributeId));
    }
    TrackedEntityAttributeValue value = attribute.get(0);
    if (value == null) {
        throw new WebMessageException(notFound("Value not found for ID " + attributeId));
    }
    if (value.getAttribute().getValueType() != ValueType.IMAGE) {
        throw new WebMessageException(conflict("Attribute must be of type image"));
    }
    // ---------------------------------------------------------------------
    // Get file resource
    // ---------------------------------------------------------------------
    FileResource fileResource = fileResourceService.getFileResource(value.getValue());
    if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
        throw new WebMessageException(notFound("A data value file resource with id " + value.getValue() + " does not exist."));
    }
    if (fileResource.getStorageStatus() != FileResourceStorageStatus.STORED) {
        throw new WebMessageException(conflict("The content is being processed and is not available yet. Try again later.", "The content requested is in transit to the file store and will be available at a later time."));
    }
    // ---------------------------------------------------------------------
    // Build response and return
    // ---------------------------------------------------------------------
    FileResourceUtils.setImageFileDimensions(fileResource, MoreObjects.firstNonNull(dimension, ImageFileDimension.ORIGINAL));
    response.setContentType(fileResource.getContentType());
    response.setContentLength((int) fileResource.getContentLength());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
    try (InputStream inputStream = fileResourceService.getFileResourceContent(fileResource)) {
        BufferedImage img = ImageIO.read(inputStream);
        height = height == null ? img.getHeight() : height;
        width = width == null ? img.getWidth() : width;
        BufferedImage resizedImg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D canvas = resizedImg.createGraphics();
        canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        canvas.drawImage(img, 0, 0, width, height, null);
        canvas.dispose();
        ImageIO.write(resizedImg, fileResource.getFormat(), response.getOutputStream());
    } catch (IOException ex) {
        throw new WebMessageException(error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend."));
    }
}
Also used : ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) PathVariable(org.springframework.web.bind.annotation.PathVariable) APPLICATION_XML_VALUE(org.springframework.http.MediaType.APPLICATION_XML_VALUE) RequestParam(org.springframework.web.bind.annotation.RequestParam) ValueType(org.hisp.dhis.common.ValueType) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) StringUtils(org.apache.commons.lang3.StringUtils) FileResourceStorageStatus(org.hisp.dhis.fileresource.FileResourceStorageStatus) TEI_IMPORT(org.hisp.dhis.scheduling.JobType.TEI_IMPORT) NodeUtils(org.hisp.dhis.node.NodeUtils) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) PutMapping(org.springframework.web.bind.annotation.PutMapping) FileResourceService(org.hisp.dhis.fileresource.FileResourceService) ImageIO(javax.imageio.ImageIO) GridUtils(org.hisp.dhis.system.grid.GridUtils) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) PostMapping(org.springframework.web.bind.annotation.PostMapping) ContextService(org.hisp.dhis.webapi.service.ContextService) DxfNamespaces(org.hisp.dhis.common.DxfNamespaces) BufferedImage(java.awt.image.BufferedImage) TrackedEntityInstanceQueryParams(org.hisp.dhis.trackedentity.TrackedEntityInstanceQueryParams) HttpHeaders(org.springframework.http.HttpHeaders) FieldFilterService(org.hisp.dhis.fieldfilter.FieldFilterService) CacheStrategy(org.hisp.dhis.common.cache.CacheStrategy) TrackedEntityInstanceCriteria(org.hisp.dhis.webapi.controller.event.webrequest.TrackedEntityInstanceCriteria) Collectors(java.util.stream.Collectors) TrackedEntityInstanceSchemaDescriptor(org.hisp.dhis.schema.descriptors.TrackedEntityInstanceSchemaDescriptor) ImageFileDimension(org.hisp.dhis.fileresource.ImageFileDimension) List(java.util.List) FileResourceUtils(org.hisp.dhis.webapi.utils.FileResourceUtils) FieldFilterParams(org.hisp.dhis.fieldfilter.FieldFilterParams) TrackerAccessManager(org.hisp.dhis.trackedentity.TrackerAccessManager) WebMessageUtils.conflict(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.conflict) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RootNode(org.hisp.dhis.node.types.RootNode) Joiner(com.google.common.base.Joiner) DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) WebMessageUtils.notFound(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.notFound) TrackerEntityInstanceRequest(org.hisp.dhis.webapi.strategy.old.tracker.imports.request.TrackerEntityInstanceRequest) TrackedEntityInstanceStrategyHandler(org.hisp.dhis.webapi.strategy.old.tracker.imports.TrackedEntityInstanceStrategyHandler) CollectionNode(org.hisp.dhis.node.types.CollectionNode) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Controller(org.springframework.stereotype.Controller) StreamUtils(org.hisp.dhis.commons.util.StreamUtils) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) WebMessageUtils.importSummaries(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.importSummaries) WebMessageUtils.importSummary(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.importSummary) WebMessageUtils.error(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.error) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) WebMessageUtils.jobConfigurationReport(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.jobConfigurationReport) BadRequestException(org.hisp.dhis.webapi.controller.exception.BadRequestException) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) WebMessageUtils.unauthorized(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.unauthorized) TrackedEntityCriteriaMapper(org.hisp.dhis.webapi.controller.event.mapper.TrackedEntityCriteriaMapper) TrackedEntityInstance(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance) TrackedEntityInstanceSupportService(org.hisp.dhis.webapi.service.TrackedEntityInstanceSupportService) TrackedEntityInstanceService(org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstanceService) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) Pager(org.hisp.dhis.common.Pager) FileResource(org.hisp.dhis.fileresource.FileResource) HttpServletResponse(javax.servlet.http.HttpServletResponse) TrackedEntityInstanceParams(org.hisp.dhis.dxf2.events.TrackedEntityInstanceParams) MoreObjects(com.google.common.base.MoreObjects) IOException(java.io.IOException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) Grid(org.hisp.dhis.common.Grid) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) java.awt(java.awt) CurrentUserService(org.hisp.dhis.user.CurrentUserService) FileResourceDomain(org.hisp.dhis.fileresource.FileResourceDomain) InputStream(java.io.InputStream) User(org.hisp.dhis.user.User) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) InputStream(java.io.InputStream) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) FileResource(org.hisp.dhis.fileresource.FileResource) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 72 with PathVariable

use of org.springframework.web.bind.annotation.PathVariable in project dhis2-core by dhis2.

the class TrackerImportController method getJobReport.

@GetMapping(value = "/jobs/{uid}/report", produces = APPLICATION_JSON_VALUE)
public TrackerImportReport getJobReport(@PathVariable String uid, @RequestParam(defaultValue = "errors", required = false) String reportMode, HttpServletResponse response) throws HttpStatusCodeException, NotFoundException {
    TrackerBundleReportMode trackerBundleReportMode = TrackerBundleReportMode.getTrackerBundleReportMode(reportMode);
    setNoStore(response);
    return Optional.ofNullable(notifier.getJobSummaryByJobId(JobType.TRACKER_IMPORT_JOB, uid)).map(report -> trackerImportService.buildImportReport((TrackerImportReport) report, trackerBundleReportMode)).orElseThrow(() -> NotFoundException.notFoundUid(uid));
}
Also used : DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) PathVariable(org.springframework.web.bind.annotation.PathVariable) ContextUtils.setNoStore(org.hisp.dhis.webapi.utils.ContextUtils.setNoStore) RequestParam(org.springframework.web.bind.annotation.RequestParam) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) TrackerImportService(org.hisp.dhis.tracker.TrackerImportService) Deque(java.util.Deque) StreamUtils(org.hisp.dhis.commons.util.StreamUtils) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) CurrentUser(org.hisp.dhis.user.CurrentUser) Notifier(org.hisp.dhis.system.notification.Notifier) RequestBody(org.springframework.web.bind.annotation.RequestBody) WebMessageUtils.ok(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.ok) HttpServletRequest(javax.servlet.http.HttpServletRequest) TrackerStatus(org.hisp.dhis.tracker.report.TrackerStatus) TrackerImportReportRequest(org.hisp.dhis.webapi.controller.tracker.TrackerImportReportRequest) TrackerJobWebMessageResponse(org.hisp.dhis.tracker.job.TrackerJobWebMessageResponse) JobType(org.hisp.dhis.scheduling.JobType) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) TrackerBundleParams(org.hisp.dhis.webapi.controller.tracker.TrackerBundleParams) Event(org.hisp.dhis.tracker.domain.Event) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) NotFoundException(org.hisp.dhis.webapi.controller.exception.NotFoundException) ContextService(org.hisp.dhis.webapi.service.ContextService) CsvEventService(org.hisp.dhis.dxf2.events.event.csv.CsvEventService) Notification(org.hisp.dhis.system.notification.Notification) TrackerImportStrategyHandler(org.hisp.dhis.webapi.strategy.tracker.imports.TrackerImportStrategyHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) TrackerImportReport(org.hisp.dhis.tracker.report.TrackerImportReport) IOException(java.io.IOException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RestController(org.springframework.web.bind.annotation.RestController) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) TrackerBundleReportMode(org.hisp.dhis.tracker.TrackerBundleReportMode) ParseException(org.locationtech.jts.io.ParseException) Optional(java.util.Optional) RESOURCE_PATH(org.hisp.dhis.webapi.controller.tracker.TrackerControllerSupport.RESOURCE_PATH) CodeGenerator(org.hisp.dhis.common.CodeGenerator) ResponseEntity(org.springframework.http.ResponseEntity) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) InputStream(java.io.InputStream) TrackerBundleReportMode(org.hisp.dhis.tracker.TrackerBundleReportMode) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 73 with PathVariable

use of org.springframework.web.bind.annotation.PathVariable in project judge by zjnu-acm.

the class MockGenerator method generate.

private void generate(Class<?> key, RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod, String url, TestClass testClass, String lowerMethod) {
    Method method = handlerMethod.getMethod();
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    out.println("/**");
    out.println(" * Test of " + method.getName() + " method, of class " + key.getSimpleName() + ".");
    for (Class<?> type : method.getParameterTypes()) {
        testClass.addImport(type);
    }
    out.println(" *");
    out.println(" * {@link " + key.getSimpleName() + "#" + method.getName() + Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", ", "(", ")}")));
    out.println(" */");
    testClass.addImport(Test.class);
    out.println("@Test");
    out.println("public void test" + StringUtils.capitalize(method.getName()) + "() throws Exception {");
    out.println("\tlog.info(\"" + method.getName() + "\");");
    List<String> variableDeclares = new ArrayList<>(4);
    Map<String, Class<?>> params = new LinkedHashMap<>(4);
    String body = null;
    Class<?> bodyType = null;
    MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
    Parameter[] parameters = method.getParameters();
    List<String> files = new ArrayList<>(4);
    List<String> pathVariables = new ArrayList<>(4);
    Map<String, String> headers = Maps.newTreeMap();
    String locale = null;
    for (MethodParameter methodParameter : methodParameters) {
        Class<?> type = methodParameter.getParameterType();
        String typeName = type.getSimpleName();
        String name = "";
        testClass.addImport(type);
        boolean unknown = false;
        RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
        PathVariable pathVariable = methodParameter.getParameterAnnotation(PathVariable.class);
        RequestHeader requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
        if (requestParam != null) {
            name = requestParam.value();
            if (name.isEmpty()) {
                name = requestParam.name();
            }
        } else if (pathVariable != null) {
            name = pathVariable.value();
            if (name.isEmpty()) {
                name = pathVariable.name();
            }
            if (name.isEmpty()) {
                name = parameters[methodParameter.getParameterIndex()].getName();
            }
            pathVariables.add(name);
            variableDeclares.add("\t" + typeName + " " + name + " = " + getDefaultValue(type) + ";");
            continue;
        } else if (methodParameter.hasParameterAnnotation(RequestBody.class)) {
            body = "request";
            bodyType = type;
            variableDeclares.add("\t" + typeName + " request = " + getDefaultValue(type) + ";");
            continue;
        } else if (requestHeader != null) {
            name = requestHeader.value();
            if (name.isEmpty()) {
                name = requestHeader.name();
            }
            if (name.isEmpty()) {
                name = parameters[methodParameter.getParameterIndex()].getName();
            }
            String camelCase = camelCase(name);
            headers.put(name, camelCase);
            variableDeclares.add("\t" + typeName + " " + camelCase + " = " + getDefaultValue(type) + ";");
            continue;
        } else if (HttpServletResponse.class == type || HttpServletRequest.class == type) {
            continue;
        } else if (Locale.class == type) {
            locale = "locale";
            variableDeclares.add("\t" + typeName + " " + locale + " = Locale.getDefault();");
            continue;
        } else {
            unknown = true;
        }
        if (name.isEmpty()) {
            name = parameters[methodParameter.getParameterIndex()].getName();
        }
        if (unknown && type.getClassLoader() != null && type != MultipartFile.class) {
            ReflectionUtils.doWithFields(type, field -> process(field.getName(), camelCase(field.getName()), field.getType(), params, files, variableDeclares, testClass, method, lowerMethod), field -> !Modifier.isStatic(field.getModifiers()));
            continue;
        } else if (unknown) {
            System.err.println("param " + methodParameter.getParameterIndex() + " with type " + typeName + " in " + method + " has no annotation");
        }
        process(name, camelCase(name), type, params, files, variableDeclares, testClass, method, lowerMethod);
    }
    for (String variableDeclare : variableDeclares) {
        out.println(variableDeclare);
    }
    testClass.addImport(MvcResult.class);
    if (files.isEmpty()) {
        testClass.addStaticImport(MockMvcRequestBuilders.class, lowerMethod);
        out.print("\tMvcResult result = mvc.perform(" + lowerMethod + "(" + url);
        for (String pathVariable : pathVariables) {
            out.print(", " + pathVariable);
        }
        out.print(")");
    } else {
        String methodName = "multipart";
        if (!ClassUtils.hasMethod(MockMvcRequestBuilders.class, "multipart", String.class, String[].class)) {
            methodName = "fileUpload";
        }
        testClass.addStaticImport(MockMvcRequestBuilders.class, methodName);
        out.print("\tMvcResult result = mvc.perform(" + methodName + "(" + url);
        for (String pathVariable : pathVariables) {
            out.print(", " + pathVariable);
        }
        out.print(")");
        for (String file : files) {
            out.print(".file(" + file + ")");
        }
    }
    boolean newLine = params.size() >= 2;
    for (Map.Entry<String, Class<?>> entry : params.entrySet()) {
        String paramName = entry.getKey();
        String variableName = camelCase(paramName);
        Class<?> paramType = entry.getValue();
        String value;
        if (paramType.isPrimitive()) {
            value = com.google.common.primitives.Primitives.wrap(paramType).getSimpleName() + ".toString(" + variableName + ")";
        } else if (paramType == String.class) {
            value = variableName;
        } else {
            testClass.addImport(Objects.class);
            value = "Objects.toString(" + variableName + ", \"\")";
        }
        if (newLine) {
            out.println();
            out.print("\t\t\t");
        }
        out.print(".param(\"" + paramName + "\", " + value + ")");
    }
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        out.println();
        out.print("\t\t\t.header(\"" + entry.getKey() + "\", " + entry.getValue() + ")");
    }
    if (locale != null) {
        out.println();
        out.print("\t\t\t.locale(" + locale + ")");
    }
    switch(lowerMethod) {
        case "get":
        case "delete":
            if (body != null) {
                System.err.println("RequestBody annotation found on " + method + " with request method " + lowerMethod);
            }
            if (!requestMappingInfo.getConsumesCondition().isEmpty()) {
                System.err.println("request consumes " + requestMappingInfo.getConsumesCondition() + " found on " + method);
            }
    }
    if (body != null) {
        out.println();
        if (bodyType == String.class || bodyType == byte[].class) {
            out.print("\t\t\t.content(" + body + ")");
        } else {
            testClass.addField(ObjectMapper.class, "objectMapper", "@Autowired");
            out.print("\t\t\t.content(objectMapper.writeValueAsString(" + body + "))");
        }
        testClass.addImport(MediaType.class);
        out.print(".contentType(MediaType.APPLICATION_JSON)");
    }
    testClass.addStaticImport(MockMvcResultMatchers.class, "status");
    out.println(")");
    out.println("\t\t\t.andExpect(status().isOk())");
    out.println("\t\t\t.andReturn();");
    out.println("}");
    testClass.addMethod(sw.toString());
}
Also used : Locale(java.util.Locale) RequestParam(org.springframework.web.bind.annotation.RequestParam) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) CtMethod(org.apache.ibatis.javassist.CtMethod) Objects(java.util.Objects) MethodParameter(org.springframework.core.MethodParameter) Parameter(java.lang.reflect.Parameter) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) MockMvcRequestBuilders(org.springframework.test.web.servlet.request.MockMvcRequestBuilders) MethodParameter(org.springframework.core.MethodParameter) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap) PathVariable(org.springframework.web.bind.annotation.PathVariable)

Example 74 with PathVariable

use of org.springframework.web.bind.annotation.PathVariable in project vorto by eclipse.

the class DefaultPayloadMappingService method getModelContentByModelAndMappingId.

private IModel getModelContentByModelAndMappingId(final String _modelId, @PathVariable final String mappingId) {
    final ModelId modelId = ModelId.fromPrettyFormat(_modelId);
    final ModelId mappingModelId = ModelId.fromPrettyFormat(mappingId);
    IModelRepository repository = this.modelRepositoryFactory.getRepositoryByModel(modelId);
    ModelInfo vortoModelInfo = repository.getById(modelId);
    ModelInfo mappingModelInfo = this.modelRepositoryFactory.getRepositoryByModel(mappingModelId).getById(mappingModelId);
    if (vortoModelInfo == null) {
        throw new ModelNotFoundException(String.format("Could not find vorto model with ID: %s", modelId));
    } else if (mappingModelInfo == null) {
        throw new ModelNotFoundException(String.format("Could not find mapping with ID: %s", mappingId));
    }
    IModelWorkspace mappingWorkspace = getWorkspaceForModel(mappingModelInfo.getId());
    Optional<Model> model = mappingWorkspace.get().stream().filter(_model -> ModelUtils.fromEMFModelId(ModelIdFactory.newInstance(_model)).equals(vortoModelInfo.getId())).findFirst();
    if (model.isPresent()) {
        final Model flattenedModel = ModelConversionUtils.convertToFlatHierarchy(model.get());
        return ModelDtoFactory.createResource(flattenedModel, Optional.of((MappingModel) mappingWorkspace.get().stream().filter(_model -> _model instanceof MappingModel && mappingMatchesModelId((MappingModel) _model, vortoModelInfo)).findFirst().get()));
    } else {
        return null;
    }
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) PathVariable(org.springframework.web.bind.annotation.PathVariable) ModelIdFactory(org.eclipse.vorto.core.api.model.model.ModelIdFactory) DependencyManager(org.eclipse.vorto.repository.core.impl.utils.DependencyManager) IPayloadMappingService(org.eclipse.vorto.repository.mapping.IPayloadMappingService) MappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.MappingSpecification) IUserContext(org.eclipse.vorto.repository.core.IUserContext) ModelNotFoundException(org.eclipse.vorto.repository.core.ModelNotFoundException) MappingModel(org.eclipse.vorto.core.api.model.mapping.MappingModel) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Infomodel(org.eclipse.vorto.model.Infomodel) ModelIdToModelContentConverter(org.eclipse.vorto.repository.conversion.ModelIdToModelContentConverter) ArrayList(java.util.ArrayList) ModelConversionUtils(org.eclipse.vorto.core.api.model.ModelConversionUtils) Model(org.eclipse.vorto.core.api.model.model.Model) IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) HashSet(java.util.HashSet) Logger(org.apache.log4j.Logger) IWorkflowService(org.eclipse.vorto.repository.workflow.IWorkflowService) InfomodelValue(org.eclipse.vorto.model.runtime.InfomodelValue) IMappingSpecification(org.eclipse.vorto.mapping.engine.model.spec.IMappingSpecification) ByteArrayInputStream(java.io.ByteArrayInputStream) EntityModel(org.eclipse.vorto.model.EntityModel) IModelWorkspace(org.eclipse.vorto.utilities.reader.IModelWorkspace) Service(org.springframework.stereotype.Service) Map(java.util.Map) IModelRepositoryFactory(org.eclipse.vorto.repository.core.IModelRepositoryFactory) MappingSpecificationSerializer(org.eclipse.vorto.mapping.engine.serializer.MappingSpecificationSerializer) ModelProperty(org.eclipse.vorto.model.ModelProperty) IModel(org.eclipse.vorto.model.IModel) FileContent(org.eclipse.vorto.repository.core.FileContent) MappingEngine(org.eclipse.vorto.mapping.engine.MappingEngine) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) ModelDtoFactory(org.eclipse.vorto.repository.web.core.ModelDtoFactory) ModelId(org.eclipse.vorto.model.ModelId) FunctionblockModel(org.eclipse.vorto.model.FunctionblockModel) Stereotype(org.eclipse.vorto.model.Stereotype) List(java.util.List) ModelContent(org.eclipse.vorto.model.ModelContent) EnumModel(org.eclipse.vorto.model.EnumModel) ModelWorkspaceReader(org.eclipse.vorto.utilities.reader.ModelWorkspaceReader) Optional(java.util.Optional) ModelUtils(org.eclipse.vorto.repository.utils.ModelUtils) WorkflowException(org.eclipse.vorto.repository.workflow.WorkflowException) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) ModelNotFoundException(org.eclipse.vorto.repository.core.ModelNotFoundException) MappingModel(org.eclipse.vorto.core.api.model.mapping.MappingModel) Model(org.eclipse.vorto.core.api.model.model.Model) EntityModel(org.eclipse.vorto.model.EntityModel) IModel(org.eclipse.vorto.model.IModel) FunctionblockModel(org.eclipse.vorto.model.FunctionblockModel) EnumModel(org.eclipse.vorto.model.EnumModel) ModelId(org.eclipse.vorto.model.ModelId) IModelWorkspace(org.eclipse.vorto.utilities.reader.IModelWorkspace) MappingModel(org.eclipse.vorto.core.api.model.mapping.MappingModel)

Example 75 with PathVariable

use of org.springframework.web.bind.annotation.PathVariable in project vorto by eclipse.

the class ModelRepositoryController method getModelForUI.

/**
 * Fetches all data required to populate the returned {@link ModelFullDetailsDTO} (see class docs
 * for details), in addition the model's "file" contents as file added to the response.<br/>
 * Following error cases apply:
 * <ul>
 *   <li>
 *     If {@link ModelId#fromPrettyFormat(String)} fails throwing {@link IllegalArgumentException},
 *     returns {@code null} with status {@link HttpStatus#NOT_FOUND}.
 *   </li>
 *   <li>
 *     If {@link ModelRepositoryController#getWorkspaceId(String)} fails throwing
 *     {@link FatalModelRepositoryException}, returns {@code null} with status
 *     {@link HttpStatus#NOT_FOUND}.
 *   </li>
 *   <li>
 *     If any operation such as:
 *     <ul>
 *       <li>
 *         {@link IModelRepository#getByIdWithPlatformMappings(ModelId)}
 *       </li>
 *       <li>
 *         {@link IModelRepository#getAttachments(ModelId)}
 *       </li>
 *       <li>
 *         {@link IModelPolicyManager#getPolicyEntries(ModelId)}
 *       </li>
 *     </ul>
 *     ... fails throwing {@link NotAuthorizedException}, returns {@code null} with status
 *     {@link HttpStatus#FORBIDDEN};
 *   </li>
 * </ul>
 *
 * @param modelId
 * @return
 */
@GetMapping("/ui/{modelId:.+}")
public ResponseEntity<ModelFullDetailsDTO> getModelForUI(@PathVariable String modelId, final HttpServletResponse response) {
    try {
        // resolve user
        Authentication user = SecurityContextHolder.getContext().getAuthentication();
        // resolve model ID
        ModelId modelID = ModelId.fromPrettyFormat(modelId);
        // resolve ModeShape workspace ID
        String workspaceId = getWorkspaceId(modelId);
        // fetches model info
        ModelInfo modelInfo = getModelRepository(modelID).getByIdWithPlatformMappings(modelID);
        if (Objects.isNull(modelInfo)) {
            LOGGER.warn(String.format("Model resource with id [%s] not found. ", modelId));
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
        // starts spawning threads to retrieve models etc.
        final ExecutorService executor = Executors.newCachedThreadPool();
        // fetches mappings
        Collection<ModelMinimalInfoDTO> mappings = ConcurrentHashMap.newKeySet();
        modelInfo.getPlatformMappings().entrySet().stream().forEach(e -> {
            executor.submit(new AsyncModelMappingsFetcher(mappings, e).with(SecurityContextHolder.getContext()).with(RequestContextHolder.getRequestAttributes()).with(getModelRepositoryFactory()));
        });
        // fetches references from model ids built with the root ModelInfo
        Collection<ModelMinimalInfoDTO> references = ConcurrentHashMap.newKeySet();
        modelInfo.getReferences().stream().forEach(id -> executor.submit(new AsyncModelReferenceFetcher(references, id).with(SecurityContextHolder.getContext()).with(RequestContextHolder.getRequestAttributes()).with(getModelRepositoryFactory())));
        // fetches referenced by
        Collection<ModelMinimalInfoDTO> referencedBy = ConcurrentHashMap.newKeySet();
        modelInfo.getReferencedBy().stream().forEach(id -> executor.submit(new AsyncModelReferenceFetcher(referencedBy, id).with(SecurityContextHolder.getContext()).with(RequestContextHolder.getRequestAttributes()).with(getModelRepositoryFactory())));
        // fetches attachments
        Collection<Attachment> attachments = ConcurrentHashMap.newKeySet();
        executor.submit(new AsyncModelAttachmentsFetcher(attachments, modelID, userRepositoryRoleService.isSysadmin(user.getName())).with(SecurityContextHolder.getContext()).with(RequestContextHolder.getRequestAttributes()).with(getModelRepositoryFactory()));
        // fetches links
        Collection<ModelLink> links = ConcurrentHashMap.newKeySet();
        executor.submit(new AsyncModelLinksFetcher(modelID, links).with(SecurityContextHolder.getContext()).with(RequestContextHolder.getRequestAttributes()).with(getModelRepositoryFactory()));
        // fetches available workflow actions
        Collection<String> actions = ConcurrentHashMap.newKeySet();
        executor.submit(new AsyncWorkflowActionsFetcher(workflowService, actions, modelID, UserContext.user(user, workspaceId)).with(SecurityContextHolder.getContext()).with(RequestContextHolder.getRequestAttributes()));
        // fetches model syntax
        Future<String> encodedSyntaxFuture = executor.submit(new AsyncModelSyntaxFetcher(modelID, SecurityContextHolder.getContext(), RequestContextHolder.getRequestAttributes(), getModelRepositoryFactory()));
        // shuts down executor and waits for completion of tasks until configured timeout
        // also retrieves callable content
        executor.shutdown();
        // single-threaded calls
        // fetches policies in this thread
        Collection<PolicyEntry> policies = getPolicyManager(workspaceId).getPolicyEntries(modelID).stream().filter(p -> userHasPolicyEntry(p, user, workspaceId)).collect(Collectors.toList());
        // getting callables and setting executor timeout
        String encodedSyntax = null;
        try {
            // callable content
            encodedSyntax = encodedSyntaxFuture.get();
            // timeout
            if (!executor.awaitTermination(requestTimeoutInSeconds, TimeUnit.SECONDS)) {
                LOGGER.warn(String.format("Requesting UI data for model ID [%s] took over [%d] seconds and programmatically timed out.", modelID, requestTimeoutInSeconds));
                return new ResponseEntity<>(null, HttpStatus.GATEWAY_TIMEOUT);
            }
        } catch (InterruptedException ie) {
            LOGGER.error("Awaiting executor termination was interrupted.");
            return new ResponseEntity<>(null, HttpStatus.SERVICE_UNAVAILABLE);
        } catch (ExecutionException ee) {
            LOGGER.error("Failed to retrieve and encode model syntax asynchronously");
            return new ResponseEntity<>(null, HttpStatus.SERVICE_UNAVAILABLE);
        }
        // builds DTO
        ModelFullDetailsDTO dto = new ModelFullDetailsDTO().withModelInfo(modelInfo).withMappings(mappings).withReferences(references).withReferencedBy(referencedBy).withAttachments(attachments).withLinks(links).withActions(actions).withEncodedModelSyntax(encodedSyntax).withPolicies(policies);
        return new ResponseEntity<>(dto, HttpStatus.OK);
    }// could not resolve "pretty format" for given model ID
     catch (IllegalArgumentException iae) {
        LOGGER.warn(String.format("Could not resolve given model ID [%s]", modelId), iae);
        return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    }// could not find namespace to resolve workspace ID from
     catch (FatalModelRepositoryException fmre) {
        LOGGER.warn(String.format("Could not resolve workspace ID from namespace inferred by model ID [%s]", modelId), fmre);
        return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    } catch (NotAuthorizedException nae) {
        LOGGER.warn(String.format("Could not authorize fetching data from given model ID [%s] for calling user", modelId), nae);
        return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
    }
}
Also used : AsyncWorkflowActionsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncWorkflowActionsFetcher) 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) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) AsyncModelAttachmentsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelAttachmentsFetcher) FatalModelRepositoryException(org.eclipse.vorto.repository.core.FatalModelRepositoryException) Attachment(org.eclipse.vorto.repository.core.Attachment) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) PolicyEntry(org.eclipse.vorto.repository.core.PolicyEntry) AsyncModelMappingsFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelMappingsFetcher) ModelFullDetailsDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelFullDetailsDTO) ExecutionException(java.util.concurrent.ExecutionException) ModelId(org.eclipse.vorto.model.ModelId) AsyncModelReferenceFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelReferenceFetcher) AsyncModelLinksFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelLinksFetcher) ResponseEntity(org.springframework.http.ResponseEntity) ModelMinimalInfoDTO(org.eclipse.vorto.repository.web.api.v1.dto.ModelMinimalInfoDTO) ModelLink(org.eclipse.vorto.repository.web.api.v1.dto.ModelLink) Authentication(org.springframework.security.core.Authentication) AsyncModelSyntaxFetcher(org.eclipse.vorto.repository.web.core.async.AsyncModelSyntaxFetcher) ExecutorService(java.util.concurrent.ExecutorService) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

PathVariable (org.springframework.web.bind.annotation.PathVariable)83 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)65 List (java.util.List)61 RequestParam (org.springframework.web.bind.annotation.RequestParam)54 Collectors (java.util.stream.Collectors)50 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)48 RestController (org.springframework.web.bind.annotation.RestController)44 Autowired (org.springframework.beans.factory.annotation.Autowired)43 RequestBody (org.springframework.web.bind.annotation.RequestBody)42 MediaType (org.springframework.http.MediaType)40 ApiOperation (io.swagger.annotations.ApiOperation)37 HttpStatus (org.springframework.http.HttpStatus)33 IOException (java.io.IOException)32 Set (java.util.Set)29 ApiParam (io.swagger.annotations.ApiParam)27 HttpServletResponse (javax.servlet.http.HttpServletResponse)27 Map (java.util.Map)26 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)26 ResponseEntity (org.springframework.http.ResponseEntity)25 GetMapping (org.springframework.web.bind.annotation.GetMapping)24