diff --git a/build.sh b/build.sh index ef4f10565705b3eb3d0fae54b60de23671f356bf..6a18d98ecec05885651675049490ca44c990ec7f 100755 --- a/build.sh +++ b/build.sh @@ -26,7 +26,7 @@ else DOCKER="sudo docker" fi -IMAGE="hbpmip/portal-backend" +IMAGE="kfilippopolitis/portal-backend" VCS_REF=$(git describe --tags --dirty) VERSION=$(git describe --tags --dirty) diff --git a/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java b/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java index adc3df815fbc74d27f78e8bbf661ff31fc168a89..90d05b9d3254d1f36989a533923a6d5961d56549 100644 --- a/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java +++ b/src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java @@ -274,7 +274,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public void logout() { // POSTã™ã‚‹ãƒªã‚¯ã‚¨ã‚¹ãƒˆãƒ‘ãƒ©ãƒ¡ãƒ¼ã‚¿ãƒ¼ã‚’ä½œæˆ - UserActionLogging.LogAction("refresh token ", this.oauth2ClientContext.getAccessToken().getRefreshToken().getValue()); + ActionLogging.LogAction("refresh token ", this.oauth2ClientContext.getAccessToken().getRefreshToken().getValue()); RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); formParams.add("client_id", hbp().getClientId()); @@ -284,7 +284,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); // ãƒªã‚¯ã‚¨ã‚¹ãƒˆã‚’ä½œæˆ - UserActionLogging.LogAction("logoutUri is ", logoutUri); + ActionLogging.LogAction("logoutUri is ", logoutUri); RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(formParams, httpHeaders, HttpMethod.POST, URI.create(logoutUri)); diff --git a/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java b/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java index 27e9b8e5db7cf2339bfea34fee0d17893ee97336..f495c5d8f8dc58651ff72deb0d49dcaf9b96e6bf 100644 --- a/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java @@ -13,7 +13,7 @@ import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.model.galaxy.WorkflowDTO; import eu.hbp.mip.utils.CustomResourceLoader; import eu.hbp.mip.utils.HTTPUtil; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; @@ -57,22 +57,24 @@ public class AlgorithmsApi { @ApiOperation(value = "List all algorithms", response = String.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<AlgorithmDTO>> getAlgorithms() { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List all algorithms", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Executing..."); LinkedList<AlgorithmDTO> exaremeAlgorithms = getExaremeAlgorithms(); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Loaded "+ exaremeAlgorithms.size() +" exareme algorithms"); LinkedList<AlgorithmDTO> galaxyAlgorithms = getGalaxyWorkflows(); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Loaded "+ galaxyAlgorithms.size() +" galaxy algorithms"); LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); if (exaremeAlgorithms != null) { algorithms.addAll(exaremeAlgorithms); } else { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List all algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Getting exareme algorithms failed and returned null"); } if (galaxyAlgorithms != null) { algorithms.addAll(galaxyAlgorithms); } else { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List all algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Getting galaxy workflows failed and returned null"); } @@ -80,7 +82,7 @@ public class AlgorithmsApi { try { disabledAlgorithms = getDisabledAlgorithms(); } catch (IOException e) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List all algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", disabledAlgorithmsCouldNotBeLoaded); } @@ -91,7 +93,8 @@ public class AlgorithmsApi { allowedAlgorithms.add(algorithm); } } - + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", + "Successfully listed "+ allowedAlgorithms.size() +" algorithms"); return ResponseEntity.ok(allowedAlgorithms); } @@ -101,8 +104,6 @@ public class AlgorithmsApi { * @return a list of AlgorithmDTOs or null if something fails */ public LinkedList<AlgorithmDTO> getExaremeAlgorithms() { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List exareme algorithms", ""); - LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); // Get exareme algorithms try { @@ -115,11 +116,11 @@ public class AlgorithmsApi { }.getType() ); } catch (IOException e) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List exareme algorithms", "An exception occurred: " + e.getMessage()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "An exception occurred: " + e.getMessage()); return null; } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List exareme algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Completed, returned " + algorithms.size() + " algorithms."); return algorithms; } @@ -130,7 +131,6 @@ public class AlgorithmsApi { * @return a list of AlgorithmDTOs or null if something fails */ public LinkedList<AlgorithmDTO> getGalaxyWorkflows() { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", ""); List<Workflow> workflowList; try { @@ -140,7 +140,7 @@ public class AlgorithmsApi { workflowList = new ArrayList<>(workflowsClient.getWorkflows()); } catch (Exception e) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Error when calling list galaxy workflows: " + e.getMessage()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Error when calling list galaxy workflows: " + e.getMessage()); return null; } @@ -160,28 +160,28 @@ public class AlgorithmsApi { } else { // Something unexpected happened String msgErr = gson.toJson(response.errorBody()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Error Response: " + msgErr); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Error Response: " + msgErr); return null; } } catch (Exception e) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "An exception occurred: " + e.getMessage()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "An exception occurred: " + e.getMessage()); return null; } } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Workflows fetched: " + workflows.size()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Workflows fetched: " + workflows.size()); // Convert the workflows to algorithms LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); for (WorkflowDTO workflow : workflows) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Converting workflow: " + workflow); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Converting workflow: " + workflow); algorithms.add(workflow.convertToAlgorithmDTO()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Converted algorithm: " + algorithms.get(algorithms.size() - 1)); } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List Galaxy workflows", "Completed!"); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Completed!"); return algorithms; } diff --git a/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java b/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java index 2e5fb3dc551a96cf0fd34b89cd4d159d7fcbb67f..467e558d2626d54fcf9705445eded95786ddd01f 100644 --- a/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java @@ -10,7 +10,7 @@ import eu.hbp.mip.model.Article; import eu.hbp.mip.model.User; import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.repositories.ArticleRepository; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,6 +45,7 @@ public class ArticlesApi { ) { User user = userInfo.getUser(); Iterable<Article> articles; + ActionLogging.LogUserAction(user.getUsername() , "(GET) /articles", "Loading articles..."); if(own != null && own) { @@ -54,7 +55,7 @@ public class ArticlesApi { { articles = articleRepository.findByStatusOrCreatedBy("published", user); } - + int articlesSize = 0; if(status != null) { for(Iterator<Article> i = articles.iterator(); i.hasNext();) @@ -64,9 +65,10 @@ public class ArticlesApi { { i.remove(); } + articlesSize++; } } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get articles", "id : Get All articles"); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /articles", "Successfully Loaded "+ articlesSize +" articles"); return ResponseEntity.ok(articles); } @@ -78,8 +80,8 @@ public class ArticlesApi { public ResponseEntity<Void> addAnArticle( @RequestBody @ApiParam(value = "Article to create", required = true) @Valid Article article ) { - User user = userInfo.getUser(); + ActionLogging.LogUserAction(user.getUsername() , "(POST) /articles", "Creating article..."); article.setCreatedAt(new Date()); if ("published".equals(article.getStatus())) { @@ -127,7 +129,7 @@ public class ArticlesApi { } articleRepository.save(article); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Created article", "id : " + article.getSlug()); + ActionLogging.LogUserAction(user.getUsername() , "(POST) /articles", "Successfully created article with id : " + article.getSlug()); return new ResponseEntity<>(HttpStatus.CREATED); } @@ -137,7 +139,7 @@ public class ArticlesApi { public ResponseEntity<Article> getAnArticle( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug ) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Getting an article", "id : " + slug); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /articles/{slug}", "Loading article with id : " + slug); User user = userInfo.getUser(); Article article; @@ -146,6 +148,7 @@ public class ArticlesApi { if(article == null) { //LOGGER.warn("Cannot find article : " + slug); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /articles/{slug}", "Article not found"); return ResponseEntity.badRequest().body(null); } @@ -154,6 +157,8 @@ public class ArticlesApi { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } + ActionLogging.LogUserAction(user.getUsername() , "(GET) /articles/{slug}", "Successfully Loaded article with id : " + slug); + return ResponseEntity.ok(article); } @@ -165,7 +170,7 @@ public class ArticlesApi { @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug, @RequestBody @ApiParam(value = "Article to update", required = true) @Valid Article article ) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update an article", "id : " + slug); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(PUT) /articles/{slug}", "Updating article with id : " + slug); User user = userInfo.getUser(); @@ -197,7 +202,8 @@ public class ArticlesApi { articleRepository.save(article); - + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(PUT) /articles/{slug}", "Successfully pdated article with id : " + slug); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); } diff --git a/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java b/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java index a800711b544db852553de1ed7938781ffa14f995..9d16351226a59a11e099af55740644b462a09adb 100644 --- a/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java @@ -19,7 +19,7 @@ import eu.hbp.mip.repositories.ExperimentRepository; import eu.hbp.mip.repositories.ModelRepository; import eu.hbp.mip.utils.ClaimUtils; import eu.hbp.mip.utils.HTTPUtil; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -90,26 +90,30 @@ public class ExperimentApi { Experiment experiment; UUID experimentUuid; + User user = userInfo.getUser(); + + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Loading Experiment with uuid : "+uuid); + try { experimentUuid = UUID.fromString(uuid); } catch (IllegalArgumentException iae) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get Experiment", "Invalid Experiment UUID."); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Invalid Experiment UUID."); return ResponseEntity.badRequest().body("Invalid Experiment UUID"); } experiment = experimentRepository.findOne(experimentUuid); if (experiment == null) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get Experiment", "Experiment Not found."); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment Not found."); return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } - if (!experiment.isShared() && experiment.getCreatedBy().getUsername().compareTo(userInfo.getUser().getUsername()) != 0) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get Experiment", "Accessing Experiment is unauthorized."); + if (!experiment.isShared() && !experiment.getCreatedBy().getUsername().equals(user.getUsername())) { + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Accessing Experiment is unauthorized."); return new ResponseEntity<>("You don't have access to the experiment.", HttpStatus.UNAUTHORIZED); } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get an experiment ", " uuid : " + uuid); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment was Loaded with uuid : " + uuid +"."); return new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -118,7 +122,12 @@ public class ExperimentApi { @ApiOperation(value = "Create an experiment", response = Experiment.class) @RequestMapping(value = "/runAlgorithm", method = RequestMethod.POST) public ResponseEntity<String> runExperiment(Authentication authentication, @RequestBody ExperimentExecutionDTO experimentExecutionDTO) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run algorithm", "Running the algorithm..."); + User user = userInfo.getUser(); + // Get the type and name of algorithm + String algorithmType = experimentExecutionDTO.getAlgorithms().get(0).getType(); + String algorithmName = experimentExecutionDTO.getAlgorithms().get(0).getName(); + + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Executing " + algorithmName + " with algorithmType : " + algorithmType + "."); if (authenticationIsEnabled) { // Getting the dataset from the experiment parameters @@ -126,32 +135,28 @@ public class ExperimentApi { for (ExperimentExecutionDTO.AlgorithmExecutionDTO.AlgorithmExecutionParamDTO parameter : experimentExecutionDTO.getAlgorithms().get(0).getParameters()) { if (parameter.getLabel().equals("dataset")) { experimentDatasets = parameter.getValue(); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run algorithm", "Got the dataset parameter!"); break; } } if (experimentDatasets == null || experimentDatasets.equals("")) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run algorithm", + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "A dataset should be specified to run an algorithm."); return ResponseEntity.badRequest().body("Please provide at least one dataset to run the algorithm."); } // --- Validating proper access rights on the datasets --- - if (!ClaimUtils.userHasDatasetsAuthorization(userInfo.getUser().getUsername(), authentication.getAuthorities(), experimentDatasets)) { + if (!ClaimUtils.userHasDatasetsAuthorization(user.getUsername(), authentication.getAuthorities(), experimentDatasets)) { return ResponseEntity.badRequest().body("You are not authorized to use these datasets."); } } - // --- Run the experiment --- - - // Get the type of algorithm - String algorithmType = experimentExecutionDTO.getAlgorithms().get(0).getType(); - // Run with the appropriate engine if (algorithmType.equals("workflow")) { + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm","Algorithm runs on Galaxy."); return runGalaxyWorkflow(experimentExecutionDTO); } else { + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm","Algorithm runs on Exareme."); return runExaremeAlgorithm(experimentExecutionDTO); } } @@ -161,25 +166,28 @@ public class ExperimentApi { public ResponseEntity<String> markExperimentAsViewed( @ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Mark an experiment as viewed", " uuid : " + uuid); - Experiment experiment; UUID experimentUuid; User user = userInfo.getUser(); + + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Marking as viewed the experiment with uuid : " + uuid + "."); + try { experimentUuid = UUID.fromString(uuid); } catch (IllegalArgumentException iae) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Mark an experiment as viewed", "Invalid Experiment UUID" + uuid); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Invalid Experiment UUID" + uuid + "."); return ResponseEntity.badRequest().body("Invalid Experiment UUID"); } experiment = experimentRepository.findOne(experimentUuid); - if (!experiment.getCreatedBy().getUsername().equals(user.getUsername())) - return new ResponseEntity<>("You're not the owner of this experiment", HttpStatus.BAD_REQUEST); + if (!experiment.getCreatedBy().getUsername().equals(user.getUsername())){ + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "You're not the owner of this experiment"); + return new ResponseEntity<>("You're not the owner of this experiment", HttpStatus.UNAUTHORIZED); + } experiment.setResultsViewed(true); experimentRepository.save(experiment); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Experiment updated (marked as viewed)", " "); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Experiment with uuid: " + uuid + " was marked as viewed."); return new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -189,7 +197,7 @@ public class ExperimentApi { public ResponseEntity<String> markExperimentAsShared( @ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Mark an experiment as shared", " uuid : " + uuid); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{uuid}/markAsShared", "Marking as shared the experiment with uuid : " + uuid + "."); return doMarkExperimentAsShared(uuid, true); } @@ -198,7 +206,7 @@ public class ExperimentApi { @RequestMapping(value = "/{uuid}/markAsUnshared", method = RequestMethod.GET) public ResponseEntity<String> markExperimentAsUnshared( @ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Mark an experiment as unshared", " uuid : " + uuid); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{uuid}/markAs/Unshared", "Marking as unshared the experiment with uuid : " + uuid + "."); return doMarkExperimentAsShared(uuid, false); } @@ -208,9 +216,12 @@ public class ExperimentApi { public ResponseEntity<String> listExperiments( @ApiParam(value = "maxResultCount") @RequestParam int maxResultCount) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List experiments", " maxResultCount : " + maxResultCount); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Listing experiments with a maximum amount of : " + maxResultCount + "."); - return doListExperiments(false, null); + List<Experiment> expList = doListExperiments(false, null); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Successfully listed experiments."); + + return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); } @ApiOperation(value = "list experiments", response = Experiment.class, responseContainer = "List") @@ -218,25 +229,28 @@ public class ExperimentApi { public ResponseEntity<String> listExperiments(@ApiParam(value = "slug") @RequestParam("slug") String modelSlug, @ApiParam(value = "maxResultCount") @RequestParam("maxResultCount") int maxResultCount) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List experiments", " modelSlug : " + modelSlug); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Listing experiments with a maximum amount of :" + maxResultCount +"with modelSlug : " + modelSlug + "."); - if (maxResultCount <= 0 && (modelSlug == null || "".equals(modelSlug))) { + if (maxResultCount <= 0 || modelSlug == null || "".equals(modelSlug)) { return new ResponseEntity<>("You must provide at least a slug or a limit of result", HttpStatus.BAD_REQUEST); } - return doListExperiments(false, modelSlug); + List<Experiment> expList = doListExperiments(false, null); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Successfully listed my experiments."); + return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); } @ApiOperation(value = "list my experiments", response = Experiment.class, responseContainer = "List") @RequestMapping(method = RequestMethod.GET, params = {"mine"}) public ResponseEntity<String> listMyExperiments(Authentication authentication, @ApiParam(value = "mine") @RequestParam("mine") boolean mine) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List my experiments", " mine : " + mine); - - return doListExperiments(true, null); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{mine}", "Listing my experiments."); + List<Experiment> expList = doListExperiments(true, null); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{mine}", "Successfully listed my experiments."); + return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); } - private ResponseEntity<String> doListExperiments(boolean mine, String modelSlug) { + private List<Experiment> doListExperiments(boolean mine, String modelSlug) { User user = userInfo.getUser(); Iterable<Experiment> myExperiments = experimentRepository.findByCreatedBy(user); @@ -258,31 +272,32 @@ public class ExperimentApi { } } } - - return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); + return expList; } private ResponseEntity<String> doMarkExperimentAsShared(String uuid, boolean shared) { Experiment experiment; UUID experimentUuid; User user = userInfo.getUser(); + try { experimentUuid = UUID.fromString(uuid); } catch (IllegalArgumentException iae) { //LOGGER.trace("Invalid UUID", iae); //LOGGER.warn("An invalid Experiment UUID was received !"); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "List my experiments", "Listing my experiments."); return ResponseEntity.badRequest().body("Invalid Experiment UUID"); } experiment = experimentRepository.findOne(experimentUuid); if (!experiment.getCreatedBy().getUsername().equals(user.getUsername())) - return new ResponseEntity<>("You're not the owner of this experiment", HttpStatus.BAD_REQUEST); + return new ResponseEntity<>("You're not the owner of this experiment", HttpStatus.UNAUTHORIZED); experiment.setShared(shared); experimentRepository.save(experiment); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Experiment updated (marked as shared)", ""); + ActionLogging.LogUserAction(user.getUsername(), "Experiment updated (marked as shared)", ""); return new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -301,31 +316,31 @@ public class ExperimentApi { experiment.setName(experimentExecutionDTO.getName()); experimentRepository.save(experiment); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Created an experiment", " id : " + experiment.getUuid()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Created an experiment", " algorithms : " + experiment.getAlgorithms()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Created an experiment", " model : " + experiment.getModel().getSlug()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Created an experiment", " name : " + experiment.getName()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " id : " + experiment.getUuid()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " algorithms : " + experiment.getAlgorithms()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " model : " + experiment.getModel().getSlug()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " name : " + experiment.getName()); return experiment; } private void saveExperiment(Experiment experiment) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Saved an experiment", " id : " + experiment.getUuid()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Saved an experiment", " algorithms : " + experiment.getAlgorithms()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Saved an experiment", " model : " + experiment.getModel().getSlug()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Saved an experiment", " name : " + experiment.getName()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Saved an experiment", " historyId : " + experiment.getWorkflowHistoryId()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Saved an experiment", " status : " + experiment.getWorkflowStatus()); + User user = userInfo.getUser(); + + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " id : " + experiment.getUuid()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " algorithms : " + experiment.getAlgorithms()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " model : " + experiment.getModel().getSlug()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " name : " + experiment.getName()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " historyId : " + experiment.getWorkflowHistoryId()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " status : " + experiment.getWorkflowStatus()); experimentRepository.save(experiment); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Experiment saved", ""); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Saved experiment"); } private void finishExperiment(Experiment experiment) { experiment.setFinished(new Date()); experimentRepository.save(experiment); - - UserActionLogging.LogAction("Experiment finished!", ""); } /* -------------------------------------- EXAREME CALLS ---------------------------------------------------------*/ @@ -337,9 +352,11 @@ public class ExperimentApi { * @return the response to be returned */ public ResponseEntity<String> runExaremeAlgorithm(ExperimentExecutionDTO experimentExecutionDTO) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run exareme algorithm", "Running the algorithm..."); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Running the algorithm..."); Experiment experiment = createExperiment(experimentExecutionDTO); + User user = userInfo.getUser(); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :"+ experiment.getUuid()); // Run the 1st algorithm from the list String algorithmName = experimentExecutionDTO.getAlgorithms().get(0).getName(); @@ -350,46 +367,38 @@ public class ExperimentApi { String body = gson.toJson(algorithmParameters); String url = queryExaremeUrl + "/" + algorithmName; - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run exareme algorithm", "url: " + url + ", body: " + body); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "url: " + url + ", body: " + body); ResponseEntity<String> response = new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run exareme algorithm", + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Completed, returning: " + experiment.toString()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run exareme algorithm", + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Starting exareme execution thread"); new Thread(() -> { - // ATTENTION: Inside the Thread only LogAction should be used, not LogAction! - UserActionLogging.LogAction("Run exareme algorithm", - "Thread started!"); + // ATTENTION: Inside the Thread only LogExperimentAction should be used, not LogUserAction! + ActionLogging.LogExperimentAction(experiment.getName(),"Thread named :" + Thread.currentThread().getName() + " with id :"+ Thread.currentThread().getId() + " started!"); try { - UserActionLogging.LogAction("Run exareme algorithm", - "Thread started!"); StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, body, results); - UserActionLogging.LogAction("Run exareme algorithm", - "Algorithm finished with code: " + code); + ActionLogging.LogExperimentAction(experiment.getName(),"Algorithm finished with code: " + code); // Results are stored in the experiment object experiment.setResult("[" + results.toString() + "]"); experiment.setHasError(code >= 400); experiment.setHasServerError(code >= 500); } catch (Exception e) { - UserActionLogging.LogAction("Run exareme algorithm", - "There was an exception: " + e.getMessage()); + ActionLogging.LogExperimentAction(experiment.getName(),"There was an exception: " + e.getMessage()); experiment.setHasError(true); experiment.setHasServerError(true); experiment.setResult(e.getMessage()); } - UserActionLogging.LogAction("Run exareme algorithm", - "Finished the experiment: " + experiment.toString()); - finishExperiment(experiment); - UserActionLogging.LogAction("Run exareme algorithm", - "Finished!"); + finishExperiment(experiment); + ActionLogging.LogExperimentAction(experiment.getName(),"Finished the experiment: " + experiment.toString()); }).start(); return response; @@ -405,9 +414,12 @@ public class ExperimentApi { * @return the response to be returned */ public ResponseEntity<String> runGalaxyWorkflow(ExperimentExecutionDTO experimentExecutionDTO) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run workflow", "Running a workflow..."); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Running a workflow..."); Experiment experiment = createExperiment(experimentExecutionDTO); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :"+ experiment.getUuid()); + User user = userInfo.getUser(); + // Run the 1st algorithm from the list String workflowId = experimentExecutionDTO.getAlgorithms().get(0).getName(); @@ -435,7 +447,7 @@ public class ExperimentApi { } } if (workflow == null) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run workflow", + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Could not find algorithm code: " + workflowId); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("Could not find galaxy algorithm.").toString()); @@ -454,7 +466,7 @@ public class ExperimentApi { // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run workflow", "Running Galaxy workflow with id: " + workflow.getId()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Running Galaxy workflow with id: " + workflow.getId()); // Call Galaxy to run the workflow Call<PostWorkflowToGalaxyDtoResponse> call = service.postWorkflowToGalaxy(workflow.getId(), galaxyApiKey, requestBodyJson); @@ -463,7 +475,7 @@ public class ExperimentApi { if (response.code() == 200) { // Call succeeded String responseBody = gson.toJson(response.body()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run workflow", "Response: " + responseBody); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Response: " + responseBody); String historyId = (String) new JSONObject(responseBody).get("history_id"); experiment.setWorkflowHistoryId(historyId); @@ -473,7 +485,7 @@ public class ExperimentApi { } else { // Something unexpected happened String msgErr = gson.toJson(response.errorBody()); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run workflow", "Error Response: " + msgErr); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Error Response: " + msgErr); // Values are read from streams. JSONObject jObjectError = new JSONObject(msgErr); @@ -485,7 +497,7 @@ public class ExperimentApi { } } catch (Exception e) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run workflow", "An exception occurred: " + e.getMessage()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "An exception occurred: " + e.getMessage()); experiment.setHasError(true); experiment.setHasServerError(true); experiment.setResult(e.getMessage()); @@ -495,7 +507,7 @@ public class ExperimentApi { // Start the process of fetching the status updateWorkflowExperiment(experiment); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run workflow", "Run workflow completed!"); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Run workflow completed!"); return new ResponseEntity(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -509,61 +521,56 @@ public class ExperimentApi { * @return nothing, just updates the experiment */ public void updateWorkflowExperiment(Experiment experiment) { + User user = userInfo.getUser(); if (experiment == null) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update workflow experiment", "The experiment does not exist."); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "The experiment does not exist."); return; } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update workflow experiment", + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " Experiment id : " + experiment.getUuid()); - if (experiment.getWorkflowHistoryId() == null) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update workflow experiment", "History Id does not exist."); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "History Id does not exist."); return; } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update workflow experiment", "Starting Thread..."); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Starting Thread..."); new Thread(() -> { while (true) { - // ATTENTION: Inside the Thread only LogAction should be used, not LogAction! - UserActionLogging.LogAction("Update workflow experiment", "Thread is running..."); + // ATTENTION: Inside the Thread only LogExperimentAction should be used, not LogExperimentAction! + ActionLogging.LogExperimentAction(experiment.getName(), "Thread is running..."); try { sleep(2000); } catch (InterruptedException e) { - UserActionLogging.LogAction("Update workflow experiment", - "Sleep was disrupted: " + e.getMessage()); + ActionLogging.LogExperimentAction(experiment.getName(),"Sleep was disrupted: " + e.getMessage()); } - UserActionLogging.LogAction("Update workflow experiment", - "Fetching status for experiment Id: " + experiment.getUuid()); + ActionLogging.LogExperimentAction(experiment.getName(),"Fetching status for experiment Id: " + experiment.getUuid()); - String state = getWorkflowStatus(experiment.getWorkflowHistoryId()); - UserActionLogging.LogAction("Update workflow experiment", "State is: " + state); + String state = getWorkflowStatus(experiment.getWorkflowHistoryId(), experiment.getName()); + ActionLogging.LogExperimentAction(experiment.getName(), "State is: " + state); switch (state) { case "running": // Do nothing, when the experiment is created the status is set to running - UserActionLogging.LogAction("Update workflow experiment", - "Workflow is still running."); + ActionLogging.LogExperimentAction(experiment.getName(),"Workflow is still running."); break; case "completed": // Get only the job result that is visible - List<GalaxyWorkflowResult> workflowJobsResults = getWorkflowResults(experiment.getWorkflowHistoryId()); - UserActionLogging.LogAction("Update workflow experiment", - "Results are: " + workflowJobsResults.toString()); + List<GalaxyWorkflowResult> workflowJobsResults = getWorkflowResults(experiment); + ActionLogging.LogExperimentAction(experiment.getName(),"Results are: " + workflowJobsResults.toString()); boolean resultFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getVisible()) { - UserActionLogging.LogAction("Update workflow experiment", - "Visible result are: " + jobResult.getId()); + ActionLogging.LogExperimentAction(experiment.getName(),"Visible result are: " + jobResult.getId()); - String result = getWorkflowResultBody(experiment.getWorkflowHistoryId(), jobResult.getId()); + String result = getWorkflowResultBody(experiment, jobResult.getId()); - UserActionLogging.LogAction("Update workflow experiment", "Result: " + result); + ActionLogging.LogExperimentAction(experiment.getName(),"Result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -575,7 +582,7 @@ public class ExperimentApi { } if (!resultFound) { // If there is no visible result - UserActionLogging.LogAction("Update workflow experiment", "No visible result"); + ActionLogging.LogExperimentAction(experiment.getName(),"No visible result"); experiment.setResult("[" + new ErrorResponse("The workflow has no visible result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -586,19 +593,17 @@ public class ExperimentApi { case "error": // Get the job result that failed - workflowJobsResults = getWorkflowResults(experiment.getWorkflowHistoryId()); - UserActionLogging.LogAction("Update workflow experiment", - "Error results are: " + workflowJobsResults.toString()); + workflowJobsResults = getWorkflowResults(experiment); + ActionLogging.LogExperimentAction(experiment.getName(),"Error results are: " + workflowJobsResults.toString()); boolean failedJobFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getState().equals("error")) { - UserActionLogging.LogAction("Update workflow experiment", - "Failed job is: " + jobResult.getId()); + ActionLogging.LogExperimentAction(experiment.getName(),"Failed job is: " + jobResult.getId()); - String result = getWorkflowJobError(jobResult.getId()); + String result = getWorkflowJobError(jobResult.getId(), experiment.getName()); - UserActionLogging.LogAction("Update workflow experiment", "Job result: " + result); + ActionLogging.LogExperimentAction(experiment.getName(),"Job result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -610,7 +615,7 @@ public class ExperimentApi { } if (!failedJobFound) { // If there is no visible failed job - UserActionLogging.LogAction("Update workflow experiment", "No failed result"); + ActionLogging.LogExperimentAction(experiment.getName(),"No failed result"); experiment.setResult("[" + new ErrorResponse("The workflow has no failed result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -628,8 +633,7 @@ public class ExperimentApi { // If result exists return if (experiment.getResult() != null) { - UserActionLogging.LogAction("Update workflow experiment", - "Result exists: " + experiment.getResult()); + ActionLogging.LogExperimentAction(experiment.getName(),"Result exists: " + experiment.getResult()); return; } } @@ -644,9 +648,9 @@ public class ExperimentApi { * "error" -> When the workflow produced an error * "completed" -> When the workflow completed successfully */ - public String getWorkflowStatus(String historyId) { - // ATTENTION: This function is used from a Thread. Only LogAction should be used, not LogAction! - UserActionLogging.LogAction("Get workflow status", " History Id : " + historyId); + public String getWorkflowStatus(String historyId, String experimentName) { + // ATTENTION: This function is used from a Thread. Only LogExperimentAction should be used, not LogUserAction! + ActionLogging.LogExperimentAction(experimentName, " History Id : " + historyId); // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); @@ -656,15 +660,15 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - UserActionLogging.LogAction("Get workflow status", " Response code: " + ActionLogging.LogExperimentAction(experimentName, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return "internalError"; } result = new Gson().toJson(response.body()); - UserActionLogging.LogAction("Get workflow status", " Result: " + result); + ActionLogging.LogExperimentAction(experimentName, " Result: " + result); } catch (IOException e) { - UserActionLogging.LogAction("Get workflow status" + ActionLogging.LogExperimentAction(experimentName , " An exception happened: " + e.getMessage()); return "internalError"; } @@ -674,12 +678,12 @@ public class ExperimentApi { JSONObject resultJson = new JSONObject(result); state = resultJson.getString("state"); } catch (JSONException e) { - UserActionLogging.LogAction("Get workflow status" + ActionLogging.LogExperimentAction(experimentName , " An exception happened: " + e.getMessage()); return "internalError"; } - UserActionLogging.LogAction("Get workflow status", " Completed!"); + ActionLogging.LogExperimentAction(experimentName, " Completed!"); switch (state) { case "ok": return "completed"; @@ -696,11 +700,14 @@ public class ExperimentApi { } /** - * @param historyId The historyId of the workflow + * @param experiment The experiment of the workflow * @return a List<GalaxyWorkflowResult> or null when an error occurred */ - public List<GalaxyWorkflowResult> getWorkflowResults(String historyId) { - UserActionLogging.LogAction("Get workflow results", " historyId : " + historyId); + public List<GalaxyWorkflowResult> getWorkflowResults(Experiment experiment) { + + String historyId = experiment.getWorkflowHistoryId(); + String experimentName = experiment.getName(); + ActionLogging.LogExperimentAction(experimentName, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<List<GalaxyWorkflowResult>> call = service.getWorkflowResultsFromGalaxy(historyId, galaxyApiKey); @@ -709,31 +716,35 @@ public class ExperimentApi { try { Response<List<GalaxyWorkflowResult>> response = call.execute(); if (response.code() >= 400) { - UserActionLogging.LogAction("Get workflow results", " Response code: " + ActionLogging.LogExperimentAction(experimentName, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } getGalaxyWorkflowResultList = response.body(); - UserActionLogging.LogAction("Get workflow results", " Result: " + response.body()); + ActionLogging.LogExperimentAction(experimentName, " Result: " + response.body()); } catch (IOException e) { - UserActionLogging.LogAction("Get workflow results" + ActionLogging.LogExperimentAction(experimentName , " An exception happened: " + e.getMessage()); return null; } - UserActionLogging.LogAction("Get workflow results", " Completed!"); + ActionLogging.LogExperimentAction(experimentName, " Completed!"); return getGalaxyWorkflowResultList; } /** - * @param historyId the historyId of the workflow + * @param experiment The experiment of the workflow * @param contentId the id of the job result that we want * @return the result of the specific workflow job, null if there was an error */ - public String getWorkflowResultBody(String historyId, String contentId) { - UserActionLogging.LogAction("Get workflow results Body", " historyId : " + historyId); + public String getWorkflowResultBody(Experiment experiment, String contentId) { + + String historyId = experiment.getWorkflowHistoryId(); + String experimentName = experiment.getName(); + + ActionLogging.LogExperimentAction(experimentName, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> call = @@ -743,20 +754,20 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - UserActionLogging.LogAction("Get workflow results Body", " Response code: " + ActionLogging.LogExperimentAction(experimentName, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } resultJson = new Gson().toJson(response.body()); - UserActionLogging.LogAction("Get workflow results Body", " Result: " + resultJson); + ActionLogging.LogExperimentAction(experimentName, " Result: " + resultJson); } catch (IOException e) { - UserActionLogging.LogAction("Get workflow results Body", + ActionLogging.LogExperimentAction(experimentName, " An exception happened: " + e.getMessage()); return null; } - UserActionLogging.LogAction("Get workflow results Body", " Completed!"); + ActionLogging.LogExperimentAction(experimentName, " Completed!"); return resultJson; } @@ -765,9 +776,8 @@ public class ExperimentApi { * @param jobId the id of the workflow job that failed * @return the error that was produced or null if an error occurred */ - public String getWorkflowJobError(String jobId) { - UserActionLogging.LogAction("Get workflow job error", " jobId : " + jobId); - + public String getWorkflowJobError(String jobId, String experimentName) { + ActionLogging.LogExperimentAction(experimentName, " jobId : " + jobId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> callError = service.getErrorMessageOfWorkflowFromGalaxy(jobId, galaxyApiKey); @@ -776,7 +786,7 @@ public class ExperimentApi { try { Response<Object> response = callError.execute(); if (response.code() >= 400) { - UserActionLogging.LogAction("Get workflow job error", "Response code: " + ActionLogging.LogExperimentAction(experimentName, "Response code: " + response.code() + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } @@ -786,19 +796,19 @@ public class ExperimentApi { JsonElement jsonElement = new JsonParser().parse(jsonString); JsonObject rootObject = jsonElement.getAsJsonObject(); fullError = rootObject.get("stderr").getAsString(); - UserActionLogging.LogAction("Get workflow job error", "Error: " + fullError); + ActionLogging.LogExperimentAction(experimentName, "Error: " + fullError); String[] arrOfStr = fullError.split("ValueError", 0); String specError = arrOfStr[arrOfStr.length - 1]; returnError = specError.substring(1); - UserActionLogging.LogAction("Get workflow job error", "Parsed Error: " + returnError); + ActionLogging.LogExperimentAction(experimentName, "Parsed Error: " + returnError); } catch (IOException e) { - UserActionLogging.LogAction("Get workflow job error", "Exception: " + e.getMessage()); + ActionLogging.LogExperimentAction(experimentName, "Exception: " + e.getMessage()); return null; } - UserActionLogging.LogAction("Get workflow job error", "Completed successfully!"); + ActionLogging.LogExperimentAction(experimentName, "Completed successfully!"); return returnError; } diff --git a/src/main/java/eu/hbp/mip/controllers/FilesAPI.java b/src/main/java/eu/hbp/mip/controllers/FilesAPI.java index 3b4ec96ab88749ea8cfb64777c8bd79f090fa12d..74d8c80930bb7b7b77f2a727f4d0f13f25192dc9 100644 --- a/src/main/java/eu/hbp/mip/controllers/FilesAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/FilesAPI.java @@ -1,5 +1,6 @@ package eu.hbp.mip.controllers; +import eu.hbp.mip.model.User; import eu.hbp.mip.model.UserInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -14,7 +15,7 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import java.time.LocalDateTime; @@ -36,12 +37,11 @@ public class FilesAPI { public ResponseEntity<Void> getProtectedFile( @ApiParam(value = "filename", required = true) @PathVariable("filename") String filename ) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get protected file", " filename : " + filename); + User user = userInfo.getUser(); + ActionLogging.LogUserAction(user.getUsername() , "(GET) /protected/{filename:.+}", "Loading protected file with filename : " + filename); String filepath = "/protected/" + filename; - String user = userInfo.getUser().getUsername(); - String time = LocalDateTime.now().toString(); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Downloaded " + filepath, ""); + ActionLogging.LogUserAction(user.getUsername() , "(GET) /protected/{filename:.+}" + filepath, "Downloaded protected file"); HttpHeaders headers = new HttpHeaders(); headers.add("X-Accel-Redirect", filepath); diff --git a/src/main/java/eu/hbp/mip/controllers/MiningApi.java b/src/main/java/eu/hbp/mip/controllers/MiningApi.java index 75369d0b4b02faf2a755a3b42ad31b12d61f9674..e05b4ca9495d39f3a915e46bdbc9216d45a29808 100644 --- a/src/main/java/eu/hbp/mip/controllers/MiningApi.java +++ b/src/main/java/eu/hbp/mip/controllers/MiningApi.java @@ -22,7 +22,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import org.springframework.web.bind.annotation.*; @@ -51,7 +51,7 @@ public class MiningApi { @ApiOperation(value = "Create a histogram on Exareme", response = String.class) @RequestMapping(value = "/histograms", method = RequestMethod.POST) public ResponseEntity runExaremeHistograms(@RequestBody List<HashMap<String, String>> queryList) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run an histogram", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(POST) /mining/histogram", "Executing histogram..."); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "MULTIPLE_HISTOGRAMS"; @@ -60,16 +60,18 @@ public class MiningApi { StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, query, results); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(POST) /mining/histogram", "Executed histogram with result :" + results.toString()); return ResponseEntity.ok(gson.toJson(results.toString())); - } catch (IOException e) { - return new ResponseEntity<>("Not found", HttpStatus.BAD_REQUEST); + } catch (IOException e) { + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(POST) /mining/histogram", "Histogram algorithm was not found"); + return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } } @ApiOperation(value = "Create a descriptive statistic on Exareme", response = String.class) @RequestMapping(value = "/descriptive_stats", method = RequestMethod.POST) public ResponseEntity runExaremeDescriptiveStats(@RequestBody List<HashMap<String, String>> queryList) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run descriptive stats", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats", "Executing Exareme descriptive stats..."); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "DESCRIPTIVE_STATS"; @@ -77,17 +79,18 @@ public class MiningApi { try { StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, query, results); - + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats", "Executed descriptive stats with result : " + results.toString()); return ResponseEntity.ok(gson.toJson(results.toString())); } catch (IOException e) { - return new ResponseEntity<>("Not found", HttpStatus.BAD_REQUEST); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats", "Descriptive stats algorithm was not found"); + return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } } @ApiOperation(value = "Create a descriptive statistic on Exareme", response = String.class) @RequestMapping(value = "/descriptive_stats_v2", method = RequestMethod.POST) public ResponseEntity runExaremeDescriptiveStatsV2(@RequestBody List<HashMap<String, String>> queryList) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Run descriptive stats v2", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats_v2", "Executing an Exareme descriptive stats v2"); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "DESCRIPTIVE_STATS_v2"; @@ -96,16 +99,18 @@ public class MiningApi { StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, query, results); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats_v2", "Successfully executed descriptive stats v2 with results : " + results.toString()); return ResponseEntity.ok(gson.toJson(results.toString())); } catch (IOException e) { - return new ResponseEntity<>("Not found", HttpStatus.BAD_REQUEST); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats_v2", "Descriptive stats v2 algorithm was not found"); + return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } } @ApiOperation(value = "Check if a formula is valid", response = String.class) @RequestMapping(value = "/checkFormula", method = RequestMethod.POST) public ResponseEntity checkFormulaValidity(String formula) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Check Formula Validity", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/checkFormula", "Executing checkFormula ..."); return ResponseEntity.ok(""); } diff --git a/src/main/java/eu/hbp/mip/controllers/ModelsApi.java b/src/main/java/eu/hbp/mip/controllers/ModelsApi.java index 633c01783d340a9b76bd71723fc62dd16db16fb1..de5c7f5d4d121c6f4134069f72a72230ac4745f6 100644 --- a/src/main/java/eu/hbp/mip/controllers/ModelsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ModelsApi.java @@ -17,7 +17,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import java.io.IOException; import java.util.*; @@ -48,13 +48,13 @@ public class ModelsApi { @Autowired private VariableRepository variableRepository; - @ApiOperation(value = "Get models", response = Model.class, responseContainer = "List") + @ApiOperation(value = "get models", response = Model.class, responseContainer = "List") @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List> getModels( @ApiParam(value = "Only ask own models") @RequestParam(value = "own", required = false) Boolean own, @ApiParam(value = "Only ask published models") @RequestParam(value = "valid", required = false) Boolean valid ) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get models",""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /models","Loading models ..."); User user = userInfo.getUser(); @@ -86,6 +86,8 @@ public class ModelsApi { m.setDataset(datasetRepository.findOne(m.getDataset().getCode())); modelsList.add(m); } + + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /models","Successfully loaded " + modelsList.size() + " models."); return ResponseEntity.ok(modelsList); } @@ -97,10 +99,8 @@ public class ModelsApi { public ResponseEntity<Model> addAModel( @RequestBody @ApiParam(value = "Model to create", required = true) Model model ) { - - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Create a model",""); - User user = userInfo.getUser(); + ActionLogging.LogUserAction(user.getUsername() , "(POST) /models","Creating a model"); model.setTitle(model.getConfig().getTitle().get("text")); model.setCreatedBy(user); @@ -129,7 +129,7 @@ public class ModelsApi { } modelRepository.save(model); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Model saved (also saved model.config and model.query)"," id : " + model.getSlug()); + ActionLogging.LogUserAction(user.getUsername() , "(POST) /models","Created model with id : " + model.getSlug()+ ", model.config and model.query"); return ResponseEntity.status(HttpStatus.CREATED).body(model); } @@ -192,20 +192,22 @@ public class ModelsApi { public ResponseEntity<Model> getAModel( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug ) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get a model", " id : " + slug); User user = userInfo.getUser(); - Model model = modelRepository.findOne(slug); + ActionLogging.LogUserAction(user.getUsername() , "(GET) /models/{slug}", "Loading model with id : " + slug); + Model model = modelRepository.findOne(slug); if(model == null) { //LOGGER.warn("Cannot find model : " + slug); + ActionLogging.LogUserAction(user.getUsername() , "(GET) /models/{slug}", "Model was not found"); return ResponseEntity.badRequest().body(null); } if (!model.getValid() && !model.getCreatedBy().getUsername().equals(user.getUsername())) { + ActionLogging.LogUserAction(user.getUsername() , "(GET) /models/{slug}", "You are not authorized to retrieve models. "); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } @@ -213,6 +215,7 @@ public class ModelsApi { Collection<String> yAxisVarsColl = new LinkedHashSet<>(yAxisVars); model.getConfig().setyAxisVariables(new LinkedList<>(yAxisVarsColl)); + ActionLogging.LogUserAction(user.getUsername() , "(GET) /models/{slug}", "Loaded model with id : " + slug); return ResponseEntity.ok(model); } @@ -224,9 +227,8 @@ public class ModelsApi { @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug, @RequestBody @ApiParam(value = "Model to update", required = true) Model model ) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Update a model", " id : "+ slug); - User user = userInfo.getUser(); + ActionLogging.LogUserAction(user.getUsername() , "(PUT) /models/{slug}", "Updating model with id : "+ slug); Model oldModel = modelRepository.findOne(slug); if(!user.getUsername().equals(oldModel.getCreatedBy().getUsername())) @@ -269,7 +271,7 @@ public class ModelsApi { datasetRepository.save(model.getDataset()); modelRepository.save(model); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Model updated (also saved/updated model.config and model.query)", " id : "+ slug); + ActionLogging.LogUserAction(user.getUsername() , "(PUT) /models/{slug}", "Updated model and saved/updated model.config and model.query"); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } diff --git a/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java b/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java index 7b6b3e65017204ea3e52897e15a2345a82deeda4..41518bd11da72009e1cc65e58da24ff8af50036f 100644 --- a/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java +++ b/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java @@ -11,7 +11,7 @@ import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.utils.ClaimUtils; import eu.hbp.mip.utils.CustomResourceLoader; import eu.hbp.mip.utils.InputStreamConverter; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -48,7 +48,7 @@ public class PathologiesApi { @RequestMapping(name = "/pathologies", method = RequestMethod.GET) public ResponseEntity<String> getPathologies(Authentication authentication) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Load pathologies", "Running ..."); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /pathologies", "Loading pathologies ..."); // Load pathologies from file Resource resource = resourceLoader.getResource("file:/opt/portal/api/pathologies.json"); @@ -57,14 +57,17 @@ public class PathologiesApi { allPathologies = gson.fromJson(InputStreamConverter.convertInputStreamToString(resource.getInputStream()), new TypeToken<List<PathologyDTO>>() { }.getType()); } catch (IOException e) { + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /pathologies", "Unable to load pathologies"); return ResponseEntity.badRequest().body(pathologiesCouldNotBeLoaded); } // If authentication is disabled return everything if (!authenticationIsEnabled) { + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /pathologies", "Successfully loaded "+ allPathologies.size() +" pathologies"); return ResponseEntity.ok().body(gson.toJson(allPathologies)); } + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /pathologies", "Successfully loaded all authorized pathologies"); return ResponseEntity.ok().body(ClaimUtils.getAuthorizedPathologies( userInfo.getUser().getUsername(), authentication.getAuthorities(), allPathologies)); } diff --git a/src/main/java/eu/hbp/mip/controllers/SecurityApi.java b/src/main/java/eu/hbp/mip/controllers/SecurityApi.java index 397f1ae6c149a3693632a0b7817709d6cb2318f3..852e7e12c68ca3d8560d4503eb061ffd77422835 100644 --- a/src/main/java/eu/hbp/mip/controllers/SecurityApi.java +++ b/src/main/java/eu/hbp/mip/controllers/SecurityApi.java @@ -8,7 +8,7 @@ import eu.hbp.mip.configuration.SecurityConfiguration; import eu.hbp.mip.model.User; import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.repositories.UserRepository; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -45,7 +45,7 @@ public class SecurityApi { public Object user(Principal principal, HttpServletResponse response) { ObjectMapper mapper = new ObjectMapper(); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "get user from /user", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /user", "Loading user : " + userInfo.getUser().getUsername()); try { String userJSON = mapper.writeValueAsString(userInfo.getUser()); Cookie cookie = new Cookie("user", URLEncoder.encode(userJSON, "UTF-8")); @@ -77,7 +77,7 @@ public class SecurityApi { userRepository.save(user); } - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "user agreeNDA", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(POST) /user", "User has agreed on the NDA"); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @@ -86,6 +86,8 @@ public class SecurityApi { @ConditionalOnExpression("${hbp.authentication.enabled:0}") public void noLogin(HttpServletResponse httpServletResponse) throws IOException { userInfo.setFakeAuth(true); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /user/login/hbp", "Unathorized login."); + httpServletResponse.sendRedirect(securityConfiguration.getFrontendRedirectAfterLogin()); } @@ -112,7 +114,7 @@ public class SecurityApi { JsonObject object = new JsonObject(); object.addProperty("authorization", stringEncoded); object.addProperty("context", galaxyContext); - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "get galaxy information", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /user/galaxy", "Successfully Loaded galaxy information."); return ResponseEntity.ok(gson.toJson(object)); } diff --git a/src/main/java/eu/hbp/mip/controllers/StatsApi.java b/src/main/java/eu/hbp/mip/controllers/StatsApi.java index 56d25679321043aec77613e0d028c0332ef49604..7fb491ee8e0fd1c90fd122529f454c742e7bde56 100644 --- a/src/main/java/eu/hbp/mip/controllers/StatsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/StatsApi.java @@ -8,7 +8,7 @@ import eu.hbp.mip.model.GeneralStats; import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.repositories.ArticleRepository; import eu.hbp.mip.repositories.UserRepository; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; @@ -36,13 +36,14 @@ public class StatsApi { @ApiOperation(value = "Get general statistics", response = GeneralStats.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<GeneralStats> getGeneralStatistics() { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get statistics (count on users, articles and variables)", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /stats", "Loading general statistics"); GeneralStats stats = new GeneralStats(); stats.setUsers(userRepository.count()); stats.setArticles(articleRepository.count()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /stats", "Loaded " + userRepository.count() + " user statistics and " + articleRepository.count() + " artcle statistics."); return ResponseEntity.ok(stats); } diff --git a/src/main/java/eu/hbp/mip/controllers/UsersApi.java b/src/main/java/eu/hbp/mip/controllers/UsersApi.java index 0620c34e444315dc6c472c304539f9c6b5d8d28d..9485f99fedc2aff53d636a656b731b7260e22960 100644 --- a/src/main/java/eu/hbp/mip/controllers/UsersApi.java +++ b/src/main/java/eu/hbp/mip/controllers/UsersApi.java @@ -7,7 +7,7 @@ package eu.hbp.mip.controllers; import eu.hbp.mip.model.User; import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.repositories.UserRepository; -import eu.hbp.mip.utils.UserActionLogging; +import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -36,7 +36,7 @@ public class UsersApi { public ResponseEntity<User> getAUser( @ApiParam(value = "username", required = true) @PathVariable("username") String username ) { - UserActionLogging.LogUserAction(userInfo.getUser().getUsername(), "Get a user", ""); + ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /users/{username}", "Loaded a user with username : " + userInfo.getUser().getUsername()); return ResponseEntity.ok(userRepository.findOne(username)); } diff --git a/src/main/java/eu/hbp/mip/utils/ActionLogging.java b/src/main/java/eu/hbp/mip/utils/ActionLogging.java new file mode 100644 index 0000000000000000000000000000000000000000..8e97572769643ae236eed2bc2cc0dd16d597c551 --- /dev/null +++ b/src/main/java/eu/hbp/mip/utils/ActionLogging.java @@ -0,0 +1,38 @@ +package eu.hbp.mip.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.UUID; + +public class ActionLogging { + + private static final Logger LOGGER = LoggerFactory.getLogger(ActionLogging.class); + private static Integer maxEndpointLen = 5; + private static Integer maxInfoLen = 5; + + public static void LogUserAction(String userName, String endpoint, String actionInfo) { + maxEndpointLen = (maxEndpointLen < userName.length() ? userName.length() : maxEndpointLen); + maxInfoLen = (maxInfoLen < endpoint.length() ? endpoint.length() : maxInfoLen); + String endpointSpacing = String.format("%" + (maxEndpointLen - userName.length() + 2) + "s", ""); + String infoSpacing = String.format("%" + (maxInfoLen - endpoint.length() + 2) + "s", ""); + LOGGER.info(" User -> " + userName + + endpointSpacing + + ", Endpoint -> " + endpoint + + infoSpacing + + ", Info -> " + actionInfo); + } + + // Used from Threads because threads can't get userName. + public static void LogExperimentAction(String experimentName, String actionInfo) { + LOGGER.info(" Experiment -> "+ experimentName + + " , Info -> " + actionInfo); + } + + // Used when a user is not authorised yet + public static void LogAction(String actionName, String actionIdInfo) { + LOGGER.info(" Action -> " + actionName + + " , Info -> " + actionIdInfo); + } + +} diff --git a/src/main/java/eu/hbp/mip/utils/ClaimUtils.java b/src/main/java/eu/hbp/mip/utils/ClaimUtils.java index eeceb5d21d41463e7b8412d649fad80454fdc675..bad70279e61372a828d80977075981ce61c42a88 100644 --- a/src/main/java/eu/hbp/mip/utils/ClaimUtils.java +++ b/src/main/java/eu/hbp/mip/utils/ClaimUtils.java @@ -27,7 +27,7 @@ public class ClaimUtils { List<String> userClaims = Arrays.asList(authorities.toString().toLowerCase() .replaceAll("[\\s+\\]\\[]", "").split(",")); - UserActionLogging.LogUserAction(username, "User Claims", userClaims.toString()); + ActionLogging.LogUserAction(username, "(POST) /experiments/runAlgorithm", userClaims.toString()); // Don't check for dataset claims if "super" claim exists allowing everything if (!userClaims.contains(ClaimUtils.allDatasetsAllowedClaim())) { @@ -35,12 +35,12 @@ public class ClaimUtils { for (String dataset : experimentDatasets.split(",")) { String datasetRole = ClaimUtils.getDatasetClaim(dataset); if (!userClaims.contains(datasetRole.toLowerCase())) { - UserActionLogging.LogUserAction(username, "Run algorithm", + ActionLogging.LogUserAction(username, "(POST) /experiments/runAlgorithm", "You are not allowed to use dataset: " + dataset); return false; } } - UserActionLogging.LogUserAction(username, "Run algorithm", + ActionLogging.LogUserAction(username, "(POST) /experiments/runAlgorithm", "User is authorized to use the datasets: " + experimentDatasets); } return true; @@ -49,14 +49,14 @@ public class ClaimUtils { public static String getAuthorizedPathologies(String username, Collection<? extends GrantedAuthority> authorities, List<PathologyDTO> allPathologies) { // --- Providing only the allowed pathologies/datasets to the user --- - UserActionLogging.LogUserAction(username, - "Load pathologies", "Filter out the unauthorised datasets."); + ActionLogging.LogUserAction(username, + "(GET) /pathologies", "Filter out the unauthorised datasets."); List<String> userClaims = Arrays.asList(authorities.toString().toLowerCase() .replaceAll("[\\s+\\]\\[]", "").split(",")); - UserActionLogging.LogUserAction(username, - "Load pathologies", "User Claims: " + userClaims); + ActionLogging.LogUserAction(username, + "(GET) /pathologies", "User Claims: " + userClaims); // If the "dataset_all" claim exists then return everything if (userClaims.contains(ClaimUtils.allDatasetsAllowedClaim())) { @@ -68,14 +68,14 @@ public class ClaimUtils { List<PathologyDTO.PathologyDatasetDTO> userPathologyDatasets = new ArrayList<PathologyDTO.PathologyDatasetDTO>(); for (PathologyDTO.PathologyDatasetDTO dataset : curPathology.getDatasets()) { if (userClaims.contains(ClaimUtils.getDatasetClaim(dataset.getCode()))) { - UserActionLogging.LogUserAction(username, "Load pathologies", + ActionLogging.LogUserAction(username , "(GET) /pathologies", "Added dataset: " + dataset.getCode()); userPathologyDatasets.add(dataset); } } if (userPathologyDatasets.size() > 0) { - UserActionLogging.LogUserAction(username, "Load pathologies", + ActionLogging.LogUserAction(username , "(GET) /pathologies", "Added pathology '" + curPathology.getLabel() + "' with datasets: '" + userPathologyDatasets + "'"); diff --git a/src/main/java/eu/hbp/mip/utils/UserActionLogging.java b/src/main/java/eu/hbp/mip/utils/UserActionLogging.java deleted file mode 100644 index 18e27317a455cb8b87a605ef8495720a32bca889..0000000000000000000000000000000000000000 --- a/src/main/java/eu/hbp/mip/utils/UserActionLogging.java +++ /dev/null @@ -1,22 +0,0 @@ -package eu.hbp.mip.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class UserActionLogging { - - private static final Logger LOGGER = LoggerFactory.getLogger(UserActionLogging.class); - - public static void LogUserAction(String userName, String actionName, String actionInfo) { - LOGGER.info(" User : " - + userName - + " called endpoint: " + actionName - + ", info: " + actionInfo); - } - - // Usually, used from Threads because threads can't get userName. - // Also used when a user is not authorised yet - public static void LogAction(String actionName, String actionIdInfo) { - LOGGER.info("Action -->" + actionName + " info: " + actionIdInfo); - } -} diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index d4a1e4765b7d25b98ccaf68141e28784a6ff09cb..0726d82f41564d850f92eaa301010d39ea89b068 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -10,7 +10,8 @@ <logger name="eu.hbp.mip"> <appender-ref ref="FILE1" /> </logger> - <logger name="org.springframework"> + <include resource="org/springframework/boot/logging/logback/base.xml"/> + <logger name="org.springframework.web" level="ERROR"> <appender-ref ref="FILE1" /> </logger> <logger name="eu.hbp.mip.utils" level="INFO" additivity="false">