All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fivefaces.structureclient.controller.UserFacingApiController Maven / Gradle / Ivy

There is a newer version: 1.0.62
Show newest version
package com.fivefaces.structureclient.controller;

import com.fivefaces.cloud.file_storage.FileService;
import com.fivefaces.cloud.workflow.WorkflowExecutionResult;
import com.fivefaces.cloud.workflow.WorkflowService;
import com.fivefaces.integration.MessageTransmitter;
import com.fivefaces.setting.entity.Setting;
import com.fivefaces.setting.service.SettingService;
import com.fivefaces.structure.query.builder.StructureQuery;
import com.fivefaces.structure.service.StructureService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static com.fivefaces.structureclient.config.security.SecurityConstants.PATIENT_API_PATH;
import static com.fivefaces.structureclient.config.security.SecurityConstants.UNMANNED_API_PATH;
import static com.fivefaces.structureclient.config.security.SecurityConstants.USER_API_PATH;

@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping(value = {USER_API_PATH + "/v1", PATIENT_API_PATH + "/v1", UNMANNED_API_PATH + "/v1"},
        produces = MediaType.APPLICATION_JSON_VALUE)
public class UserFacingApiController extends AbstractStructureController {

    private final WorkflowService workflowService;
    private final FileService fileService;
    private final SettingService settingService;
    private final StructureService structureService;
    private final MessageTransmitter messageTransmitter;

    @PostMapping("/query")
    @ResponseBody
    public ResponseEntity>> handleQuery(@RequestBody final String query) {
        log.info("/query\n" + query);
        return ResponseEntity.ok(query(StructureQuery.fromJson(query).build()));
    }

    @PostMapping("/count")
    @ResponseBody
    public ResponseEntity handleCount(@RequestBody final String query) {
        log.info("/count\n" + query);
        return ResponseEntity.ok(count(StructureQuery.fromJson(query).build()));
    }

    @PostMapping("/namedQuery")
    @ResponseBody
    public ResponseEntity>> handleNamedQuery(@RequestBody final Map input) {
        log.info("/namedQuery\n" + new JSONObject(input));
        Setting sqlQuery = settingService.getSettingByName("NamedQuery " + input.get("queryName"));
        return ResponseEntity.ok(namedQuery(sqlQuery.getValue(), (Map) input.get("params")));
    }

    @PostMapping("/queries")
    @ResponseBody
    public ResponseEntity>>> handleQueries(@RequestBody final String queries) {
        Map>> results = queries(queries);
        return ResponseEntity.ok(results);
    }

    @PostMapping("/query/file")
    @ResponseBody
    public ResponseEntity>> handleFileQuery(@RequestBody final String query) {
        log.info("/query\n" + query);
        List> queryResult = query(StructureQuery.fromJson(query).build());
        List> urls = generateUrls(queryResult);
        return ResponseEntity.ok(urls);
    }

    /**
     * Instantiates a synchronous workflow.
     * This is designed to be called from the UI to perform synchronously the given workflow
     * 

* The multipart file is stored using the file service - with the attachment payload added to the given jsonSubject * * @param jsonInput as string such as example above * @param file The file * @return The response of the workflow execution * @throws IOException if there is a problem with the file */ @PostMapping(value = "/instantiateWorkflowMultipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody public ResponseEntity instantiateWorkflowMultipart(Authentication authentication, @RequestParam final String jsonInput, @RequestParam(required = false) MultipartFile file) throws IOException { log.info("/instantiateWorkflowMultipart\n" + jsonInput); JSONObject payload = new JSONObject(jsonInput); addAttachment(payload, file); addAuthorization(payload, authentication); String workflowName = payload.getString("workflow"); WorkflowExecutionResult result = workflowService.instantiateWorkflow(workflowName, payload.toString()); if ("FAILED".equals(result.getStatus())) { throw new WorkflowFailedException("Workflow " + workflowName + " failed", result); } return ResponseEntity.ok(result); } @PostMapping("/instantiateSyncWorkflow") @ResponseBody public ResponseEntity instantiateSyncWorkflow(Authentication authentication, @RequestBody final String jsonInput) { log.info("/instantiateSyncWorkflow\n" + jsonInput); JSONObject payload = new JSONObject(jsonInput); addAuthorization(payload, authentication); if (payload.has("executeAtUTC")) { return delayExecution(jsonInput); } else { String workflowName = payload.getString("workflow"); WorkflowExecutionResult result = workflowService.instantiateSyncWorkflow(workflowName, payload.toString()); if ("FAILED".equals(result.getStatus())) { throw new WorkflowFailedException("Workflow " + workflowName + " failed", result); } return ResponseEntity.ok(result); } } @PostMapping("/instantiateWorkflow") @ResponseBody public ResponseEntity instantiateWorkflow(Authentication authentication, @RequestBody final String jsonInput) { log.info("/instantiateWorkflow\n" + jsonInput); JSONObject payload = new JSONObject(jsonInput); addAuthorization(payload, authentication); if (payload.has("executeAtUTC")) { /* This is for convienience - but if delaying stuff from a workflow machine - all you need to do is create the delayed_workflow record using /insert */ return delayExecution(jsonInput); } else { String workflowName = payload.getString("workflow"); WorkflowExecutionResult result = workflowService.instantiateWorkflow(workflowName, payload.toString()); if ("FAILED".equals(result.getStatus())) { throw new WorkflowFailedException("Workflow " + workflowName + " failed", result); } return ResponseEntity.ok(result); } } @PostMapping("/workflowExecutionStatus") @ResponseBody public ResponseEntity instantiateWorkflow(@RequestBody final String jsonInput) { log.info("/workflowExecutionStatus\n" + jsonInput); JSONObject payload = new JSONObject(jsonInput); String executionId = payload.getString("executionId"); WorkflowExecutionResult result = workflowService.getExecutionResult(executionId); if ("FAILED".equals(result.getStatus())) { throw new WorkflowFailedException("Workflow failed", result); } return ResponseEntity.ok(result); } @PostMapping("/getQueueWithService") @ResponseBody public ResponseEntity handleGetQueueWithService(@RequestBody final String jsonInput) { final List jsonValues = geQueueWithService(jsonInput); return ResponseEntity.ok(jsonValues.get(0).toString()); } @PostMapping("/transmit") @ResponseBody public ResponseEntity transmitMessage(@RequestBody final String payload) { JSONObject jsonObject = new JSONObject(payload); String responseBody; try { responseBody = messageTransmitter.transmitMessage(jsonObject); return ResponseEntity.ok(responseBody); } catch (Exception e) { return ResponseEntity.badRequest().build(); } } private void addAttachment(JSONObject payload, MultipartFile file) throws IOException { if (file == null) { return; } JSONObject query = payload.getJSONObject("query"); if (!query.has("attachments")) { query.put("attachments", Collections.emptyList()); } query.getJSONArray("attachments").put(createAttachmentForFile(file)); } private void addAuthorization(JSONObject json, Authentication authentication) { JSONObject query = json.getJSONObject("query"); query.put("authorization", new JSONObject(authentication.getPrincipal())); } private JSONObject createAttachmentForFile(MultipartFile file) throws IOException { JSONObject attachment = new JSONObject(); String fileDestination = settingService.getSettingByName("File Service File Destination").getValue(); String fullFilePath = fileService.saveFile(fileDestination, file.getOriginalFilename(), file.getBytes()); attachment.put("type", file.getContentType()); attachment.put("canonicalFilePath", fullFilePath); return attachment; } private ResponseEntity delayExecution(final String jsonInput) { JSONObject delayedPayload = new JSONObject(); delayedPayload.put("type", "delayed_workflow"); delayedPayload.put("query", new JSONObject(jsonInput)); try { structureService.insert("delay", delayedPayload); } catch (Exception e) { return ResponseEntity.badRequest().build(); } return ResponseEntity.ok(new WorkflowExecutionResult(null, null, null, null)); } private List> generateUrls(List> queryResult) { return queryResult.stream() .map(this::buildImageEntity) .collect(Collectors.toList()); } @NotNull private Map buildImageEntity(Map q) { Map map = new HashMap<>(); map.put("fileName", q.get("fileKey")); map.put("link", getFileUrl((String) q.get("fileKey"))); map.put("name", q.get("uniqueName")); map.put("id", q.get("id")); return map; } private String getFileUrl(String fileKey) { String fileDestination = settingService.getSettingByName("File Service File Destination").getValue(); return fileService.getFileUrl(fileDestination, fileKey); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy