From 1a0a5fce954f91304159f4e27e4d3dd5056b79bb Mon Sep 17 00:00:00 2001 From: kfilippopolitis <kostasfilippop@gmail.com> Date: Tue, 13 Oct 2020 08:34:15 -0700 Subject: [PATCH 1/4] Refactored all logs. 1) Disabled spring boot framework logs. 2) Added 2 logs at every endpoint, when entering and returning, with useful information. 3) Unified the logs output. --- build.sh | 2 +- .../configuration/SecurityConfiguration.java | 4 +- .../eu/hbp/mip/controllers/AlgorithmsApi.java | 36 +-- .../eu/hbp/mip/controllers/ArticlesApi.java | 22 +- .../eu/hbp/mip/controllers/ExperimentApi.java | 284 +++++++++--------- .../java/eu/hbp/mip/controllers/FilesAPI.java | 10 +- .../eu/hbp/mip/controllers/MiningApi.java | 25 +- .../eu/hbp/mip/controllers/ModelsApi.java | 26 +- .../hbp/mip/controllers/PathologiesApi.java | 7 +- .../eu/hbp/mip/controllers/SecurityApi.java | 10 +- .../java/eu/hbp/mip/controllers/StatsApi.java | 5 +- .../java/eu/hbp/mip/controllers/UsersApi.java | 4 +- .../java/eu/hbp/mip/utils/ActionLogging.java | 38 +++ .../java/eu/hbp/mip/utils/ClaimUtils.java | 18 +- .../eu/hbp/mip/utils/UserActionLogging.java | 22 -- src/main/resources/logback.xml | 3 +- 16 files changed, 281 insertions(+), 235 deletions(-) create mode 100644 src/main/java/eu/hbp/mip/utils/ActionLogging.java delete mode 100644 src/main/java/eu/hbp/mip/utils/UserActionLogging.java diff --git a/build.sh b/build.sh index ef4f10565..6a18d98ec 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 adc3df815..90d05b9d3 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 27e9b8e5d..f495c5d8f 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 2e5fb3dc5..467e558d2 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 a800711b5..9d1635122 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 3b4ec96ab..74d8c8093 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 75369d0b4..e05b4ca94 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 633c01783..de5c7f5d4 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 7b6b3e650..41518bd11 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 397f1ae6c..852e7e12c 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 56d256793..7fb491ee8 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 0620c34e4..9485f99fe 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 000000000..8e9757276 --- /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 eeceb5d21..bad70279e 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 18e27317a..000000000 --- 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 d4a1e4765..0726d82f4 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"> -- GitLab From 32658797bfc2cfac53ffb10119954eb6a8379f78 Mon Sep 17 00:00:00 2001 From: kfilippopolitis <kostasfilippop@gmail.com> Date: Tue, 13 Oct 2020 08:43:35 -0700 Subject: [PATCH 2/4] Identation fixes on the whole solution. --- src/main/java/eu/hbp/mip/MIPApplication.java | 6 +- .../PersistenceConfiguration.java | 2 +- .../configuration/PortalErrorAttributes.java | 2 +- .../eu/hbp/mip/controllers/AlgorithmsApi.java | 34 +++---- .../eu/hbp/mip/controllers/ArticlesApi.java | 83 +++++++--------- .../eu/hbp/mip/controllers/ExperimentApi.java | 50 +++++----- .../java/eu/hbp/mip/controllers/FilesAPI.java | 8 +- .../eu/hbp/mip/controllers/MiningApi.java | 11 ++- .../eu/hbp/mip/controllers/ModelsApi.java | 96 ++++++++----------- .../hbp/mip/controllers/PathologiesApi.java | 8 +- .../eu/hbp/mip/controllers/SecurityApi.java | 8 +- .../java/eu/hbp/mip/controllers/StatsApi.java | 4 +- .../java/eu/hbp/mip/controllers/UsersApi.java | 2 +- src/main/java/eu/hbp/mip/model/Article.java | 4 +- src/main/java/eu/hbp/mip/model/Config.java | 6 +- src/main/java/eu/hbp/mip/model/Dataset.java | 4 +- .../java/eu/hbp/mip/model/Experiment.java | 24 +++-- .../java/eu/hbp/mip/model/GeneralStats.java | 4 +- src/main/java/eu/hbp/mip/model/Group.java | 6 +- src/main/java/eu/hbp/mip/model/Model.java | 4 +- .../java/eu/hbp/mip/model/PathologyDTO.java | 6 +- src/main/java/eu/hbp/mip/model/Query.java | 42 ++++---- src/main/java/eu/hbp/mip/model/Tag.java | 4 +- src/main/java/eu/hbp/mip/model/User.java | 7 +- src/main/java/eu/hbp/mip/model/Variable.java | 4 +- .../eu/hbp/mip/model/galaxy/WorkflowDTO.java | 22 ++--- .../mip/repositories/ArticleRepository.java | 2 + .../repositories/ExperimentRepository.java | 1 + .../hbp/mip/repositories/ModelRepository.java | 2 + .../java/eu/hbp/mip/utils/ActionLogging.java | 6 +- .../java/eu/hbp/mip/utils/ClaimUtils.java | 4 +- src/main/java/eu/hbp/mip/utils/HTTPUtil.java | 2 +- 32 files changed, 219 insertions(+), 249 deletions(-) diff --git a/src/main/java/eu/hbp/mip/MIPApplication.java b/src/main/java/eu/hbp/mip/MIPApplication.java index e6ccd8e1e..9af69bdd9 100644 --- a/src/main/java/eu/hbp/mip/MIPApplication.java +++ b/src/main/java/eu/hbp/mip/MIPApplication.java @@ -13,13 +13,11 @@ import org.slf4j.LoggerFactory; @SpringBootApplication public class MIPApplication { - private static final Logger LOGGER = LoggerFactory.getLogger(MIPApplication.class); - + private static final Logger LOGGER = LoggerFactory.getLogger(MIPApplication.class); + public static void main(String[] args) { SpringApplication.run(MIPApplication.class, args); } - - } diff --git a/src/main/java/eu/hbp/mip/configuration/PersistenceConfiguration.java b/src/main/java/eu/hbp/mip/configuration/PersistenceConfiguration.java index 6b973dc65..c8024e1bf 100644 --- a/src/main/java/eu/hbp/mip/configuration/PersistenceConfiguration.java +++ b/src/main/java/eu/hbp/mip/configuration/PersistenceConfiguration.java @@ -23,7 +23,7 @@ public class PersistenceConfiguration { @Primary @Bean(name = "portalDatasource") - @ConfigurationProperties(prefix="spring.portalDatasource") + @ConfigurationProperties(prefix = "spring.portalDatasource") public DataSource portalDataSource() { return DataSourceBuilder.create().build(); } diff --git a/src/main/java/eu/hbp/mip/configuration/PortalErrorAttributes.java b/src/main/java/eu/hbp/mip/configuration/PortalErrorAttributes.java index aba509034..352b1d156 100644 --- a/src/main/java/eu/hbp/mip/configuration/PortalErrorAttributes.java +++ b/src/main/java/eu/hbp/mip/configuration/PortalErrorAttributes.java @@ -20,7 +20,7 @@ public class PortalErrorAttributes extends DefaultErrorAttributes { Throwable throwable = getError(requestAttributes); StringBuilder sb = new StringBuilder("["); - for (String attr: requestAttributes.getAttributeNames(RequestAttributes.SCOPE_REQUEST)) { + for (String attr : requestAttributes.getAttributeNames(RequestAttributes.SCOPE_REQUEST)) { Object v = requestAttributes.getAttribute(attr, RequestAttributes.SCOPE_REQUEST); sb.append(attr).append(" = ").append(v).append('\n'); } diff --git a/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java b/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java index f495c5d8f..db9b7d124 100644 --- a/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/AlgorithmsApi.java @@ -57,24 +57,24 @@ public class AlgorithmsApi { @ApiOperation(value = "List all algorithms", response = String.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<AlgorithmDTO>> getAlgorithms() { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Executing..."); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Executing..."); LinkedList<AlgorithmDTO> exaremeAlgorithms = getExaremeAlgorithms(); - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Loaded "+ exaremeAlgorithms.size() +" exareme algorithms"); + 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"); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Loaded " + galaxyAlgorithms.size() + " galaxy algorithms"); LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); if (exaremeAlgorithms != null) { algorithms.addAll(exaremeAlgorithms); } else { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Getting exareme algorithms failed and returned null"); } if (galaxyAlgorithms != null) { algorithms.addAll(galaxyAlgorithms); } else { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Getting galaxy workflows failed and returned null"); } @@ -82,7 +82,7 @@ public class AlgorithmsApi { try { disabledAlgorithms = getDisabledAlgorithms(); } catch (IOException e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", disabledAlgorithmsCouldNotBeLoaded); } @@ -93,8 +93,8 @@ public class AlgorithmsApi { allowedAlgorithms.add(algorithm); } } - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", - "Successfully listed "+ allowedAlgorithms.size() +" algorithms"); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", + "Successfully listed " + allowedAlgorithms.size() + " algorithms"); return ResponseEntity.ok(allowedAlgorithms); } @@ -116,11 +116,11 @@ public class AlgorithmsApi { }.getType() ); } catch (IOException e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "An exception occurred: " + e.getMessage()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "An exception occurred: " + e.getMessage()); return null; } - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Completed, returned " + algorithms.size() + " algorithms."); return algorithms; } @@ -140,7 +140,7 @@ public class AlgorithmsApi { workflowList = new ArrayList<>(workflowsClient.getWorkflows()); } catch (Exception e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "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()); - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Error Response: " + msgErr); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Error Response: " + msgErr); return null; } } catch (Exception e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "An exception occurred: " + e.getMessage()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "An exception occurred: " + e.getMessage()); return null; } } - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "Converting workflow: " + workflow); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Converting workflow: " + workflow); algorithms.add(workflow.convertToAlgorithmDTO()); - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Converted algorithm: " + algorithms.get(algorithms.size() - 1)); } - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /algorithms", "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 467e558d2..e73b2d061 100644 --- a/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ArticlesApi.java @@ -12,8 +12,6 @@ import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.repositories.ArticleRepository; import eu.hbp.mip.utils.ActionLogging; import io.swagger.annotations.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -45,43 +43,38 @@ public class ArticlesApi { ) { User user = userInfo.getUser(); Iterable<Article> articles; - ActionLogging.LogUserAction(user.getUsername() , "(GET) /articles", "Loading articles..."); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /articles", "Loading articles..."); - if(own != null && own) - { - articles = articleRepository.findByCreatedBy(user); - } - else - { + if (own != null && own) { + articles = articleRepository.findByCreatedBy(user); + } else { articles = articleRepository.findByStatusOrCreatedBy("published", user); } int articlesSize = 0; - if(status != null) - { - for(Iterator<Article> i = articles.iterator(); i.hasNext();) - { + if (status != null) { + for (Iterator<Article> i = articles.iterator(); i.hasNext(); ) { Article a = i.next(); - if(!status.equals(a.getStatus())) - { + if (!status.equals(a.getStatus())) { i.remove(); } articlesSize++; } } - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /articles", "Successfully Loaded "+ articlesSize +" articles"); - + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles", "Successfully Loaded " + articlesSize + " articles"); + return ResponseEntity.ok(articles); } @ApiOperation(value = "Create an article") - @ApiResponses(value = { @ApiResponse(code = 201, message = "Article created") }) + @ApiResponses(value = {@ApiResponse(code = 201, message = "Article created")}) @RequestMapping(method = RequestMethod.POST) 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..."); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /articles", "Creating article..."); article.setCreatedAt(new Date()); if ("published".equals(article.getStatus())) { @@ -90,16 +83,13 @@ public class ArticlesApi { article.setCreatedBy(user); long count = 1; - for(int i = 1; count > 0; i++) - { + for (int i = 1; count > 0; i++) { count = articleRepository.countByTitle(article.getTitle()); - if(count > 0) - { + if (count > 0) { String title = article.getTitle(); - if(i > 1) - { - title = title.substring(0, title.length()-4); + if (i > 1) { + title = title.substring(0, title.length() - 4); } article.setTitle(title + " (" + i + ")"); } @@ -114,22 +104,19 @@ public class ArticlesApi { } boolean alreadyExists = true; - for(int i = 1; alreadyExists; i++) - { + for (int i = 1; alreadyExists; i++) { alreadyExists = articleRepository.exists(slug); - if(alreadyExists) - { - if(i > 1) - { - slug = slug.substring(0, slug.length()-2); + if (alreadyExists) { + if (i > 1) { + slug = slug.substring(0, slug.length() - 2); } - slug += "-"+i; + slug += "-" + i; } article.setSlug(slug); } articleRepository.save(article); - ActionLogging.LogUserAction(user.getUsername() , "(POST) /articles", "Successfully created article with id : " + article.getSlug()); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /articles", "Successfully created article with id : " + article.getSlug()); return new ResponseEntity<>(HttpStatus.CREATED); } @@ -139,45 +126,42 @@ public class ArticlesApi { public ResponseEntity<Article> getAnArticle( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /articles/{slug}", "Loading article with id : " + slug); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles/{slug}", "Loading article with id : " + slug); User user = userInfo.getUser(); Article article; article = articleRepository.findOne(slug); - if(article == null) - { + if (article == null) { //LOGGER.warn("Cannot find article : " + slug); - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /articles/{slug}", "Article not found"); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles/{slug}", "Article not found"); return ResponseEntity.badRequest().body(null); } - if (!"published".equals(article.getStatus()) && !article.getCreatedBy().getUsername().equals(user.getUsername())) - { + if (!"published".equals(article.getStatus()) && !article.getCreatedBy().getUsername().equals(user.getUsername())) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } - ActionLogging.LogUserAction(user.getUsername() , "(GET) /articles/{slug}", "Successfully Loaded article with id : " + slug); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /articles/{slug}", "Successfully Loaded article with id : " + slug); return ResponseEntity.ok(article); } @ApiOperation(value = "Update an article") - @ApiResponses(value = { @ApiResponse(code = 204, message = "Article updated") }) + @ApiResponses(value = {@ApiResponse(code = 204, message = "Article updated")}) @RequestMapping(value = "/{slug}", method = RequestMethod.PUT) public ResponseEntity<Void> updateAnArticle( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug, @RequestBody @ApiParam(value = "Article to update", required = true) @Valid Article article ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(PUT) /articles/{slug}", "Updating article with id : " + slug); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(PUT) /articles/{slug}", "Updating article with id : " + slug); User user = userInfo.getUser(); String author = articleRepository.findOne(slug).getCreatedBy().getUsername(); - if(!user.getUsername().equals(author)) - { + if (!user.getUsername().equals(author)) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } @@ -185,10 +169,9 @@ public class ArticlesApi { String newTitle = article.getTitle(); - if(!newTitle.equals(oldTitle)) { + if (!newTitle.equals(oldTitle)) { long count = 1; - for(int i = 1; count > 0 && !newTitle.equals(oldTitle); i++) - { + for (int i = 1; count > 0 && !newTitle.equals(oldTitle); i++) { newTitle = article.getTitle(); count = articleRepository.countByTitle(newTitle); if (count > 0 && !newTitle.equals(oldTitle)) { @@ -202,7 +185,7 @@ public class ArticlesApi { articleRepository.save(article); - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(PUT) /articles/{slug}", "Successfully pdated article with id : " + slug); + 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 9d1635122..b4a7d2bbd 100644 --- a/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java @@ -92,7 +92,7 @@ public class ExperimentApi { UUID experimentUuid; User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Loading Experiment with uuid : "+uuid); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Loading Experiment with uuid : " + uuid); try { experimentUuid = UUID.fromString(uuid); @@ -113,7 +113,7 @@ public class ExperimentApi { return new ResponseEntity<>("You don't have access to the experiment.", HttpStatus.UNAUTHORIZED); } - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment was Loaded with uuid : " + uuid +"."); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment was Loaded with uuid : " + uuid + "."); return new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -153,10 +153,10 @@ public class ExperimentApi { // Run with the appropriate engine if (algorithmType.equals("workflow")) { - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm","Algorithm runs on Galaxy."); + 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."); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Algorithm runs on Exareme."); return runExaremeAlgorithm(experimentExecutionDTO); } } @@ -180,7 +180,7 @@ public class ExperimentApi { } experiment = experimentRepository.findOne(experimentUuid); - if (!experiment.getCreatedBy().getUsername().equals(user.getUsername())){ + 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); } @@ -229,7 +229,7 @@ public class ExperimentApi { public ResponseEntity<String> listExperiments(@ApiParam(value = "slug") @RequestParam("slug") String modelSlug, @ApiParam(value = "maxResultCount") @RequestParam("maxResultCount") int maxResultCount) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Listing experiments with a maximum amount of :" + maxResultCount +"with 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)) { return new ResponseEntity<>("You must provide at least a slug or a limit of result", @@ -356,7 +356,7 @@ public class ExperimentApi { Experiment experiment = createExperiment(experimentExecutionDTO); User user = userInfo.getUser(); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :"+ experiment.getUuid()); + 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(); @@ -377,20 +377,20 @@ public class ExperimentApi { "Starting exareme execution thread"); new Thread(() -> { // 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!"); + ActionLogging.LogExperimentAction(experiment.getName(), "Thread named :" + Thread.currentThread().getName() + " with id :" + Thread.currentThread().getId() + " started!"); try { StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, body, results); - ActionLogging.LogExperimentAction(experiment.getName(),"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) { - ActionLogging.LogExperimentAction(experiment.getName(),"There was an exception: " + e.getMessage()); + ActionLogging.LogExperimentAction(experiment.getName(), "There was an exception: " + e.getMessage()); experiment.setHasError(true); experiment.setHasServerError(true); @@ -398,7 +398,7 @@ public class ExperimentApi { } finishExperiment(experiment); - ActionLogging.LogExperimentAction(experiment.getName(),"Finished the experiment: " + experiment.toString()); + ActionLogging.LogExperimentAction(experiment.getName(), "Finished the experiment: " + experiment.toString()); }).start(); return response; @@ -417,7 +417,7 @@ public class ExperimentApi { 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()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :" + experiment.getUuid()); User user = userInfo.getUser(); @@ -544,10 +544,10 @@ public class ExperimentApi { try { sleep(2000); } catch (InterruptedException e) { - ActionLogging.LogExperimentAction(experiment.getName(),"Sleep was disrupted: " + e.getMessage()); + ActionLogging.LogExperimentAction(experiment.getName(), "Sleep was disrupted: " + e.getMessage()); } - ActionLogging.LogExperimentAction(experiment.getName(),"Fetching status for experiment Id: " + experiment.getUuid()); + ActionLogging.LogExperimentAction(experiment.getName(), "Fetching status for experiment Id: " + experiment.getUuid()); String state = getWorkflowStatus(experiment.getWorkflowHistoryId(), experiment.getName()); ActionLogging.LogExperimentAction(experiment.getName(), "State is: " + state); @@ -555,22 +555,22 @@ public class ExperimentApi { switch (state) { case "running": // Do nothing, when the experiment is created the status is set to running - ActionLogging.LogExperimentAction(experiment.getName(),"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); - ActionLogging.LogExperimentAction(experiment.getName(),"Results are: " + workflowJobsResults.toString()); + ActionLogging.LogExperimentAction(experiment.getName(), "Results are: " + workflowJobsResults.toString()); boolean resultFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getVisible()) { - ActionLogging.LogExperimentAction(experiment.getName(),"Visible result are: " + jobResult.getId()); + ActionLogging.LogExperimentAction(experiment.getName(), "Visible result are: " + jobResult.getId()); String result = getWorkflowResultBody(experiment, jobResult.getId()); - ActionLogging.LogExperimentAction(experiment.getName(),"Result: " + result); + ActionLogging.LogExperimentAction(experiment.getName(), "Result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -582,7 +582,7 @@ public class ExperimentApi { } if (!resultFound) { // If there is no visible result - ActionLogging.LogExperimentAction(experiment.getName(),"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); @@ -594,16 +594,16 @@ public class ExperimentApi { case "error": // Get the job result that failed workflowJobsResults = getWorkflowResults(experiment); - ActionLogging.LogExperimentAction(experiment.getName(),"Error results are: " + workflowJobsResults.toString()); + ActionLogging.LogExperimentAction(experiment.getName(), "Error results are: " + workflowJobsResults.toString()); boolean failedJobFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getState().equals("error")) { - ActionLogging.LogExperimentAction(experiment.getName(),"Failed job is: " + jobResult.getId()); + ActionLogging.LogExperimentAction(experiment.getName(), "Failed job is: " + jobResult.getId()); String result = getWorkflowJobError(jobResult.getId(), experiment.getName()); - ActionLogging.LogExperimentAction(experiment.getName(),"Job result: " + result); + ActionLogging.LogExperimentAction(experiment.getName(), "Job result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -615,7 +615,7 @@ public class ExperimentApi { } if (!failedJobFound) { // If there is no visible failed job - ActionLogging.LogExperimentAction(experiment.getName(),"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); @@ -633,7 +633,7 @@ public class ExperimentApi { // If result exists return if (experiment.getResult() != null) { - ActionLogging.LogExperimentAction(experiment.getName(),"Result exists: " + experiment.getResult()); + ActionLogging.LogExperimentAction(experiment.getName(), "Result exists: " + experiment.getResult()); return; } } @@ -736,7 +736,7 @@ public class ExperimentApi { /** * @param experiment The experiment of the workflow - * @param contentId the id of the job result that we want + * @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(Experiment experiment, String contentId) { diff --git a/src/main/java/eu/hbp/mip/controllers/FilesAPI.java b/src/main/java/eu/hbp/mip/controllers/FilesAPI.java index 74d8c8093..34f64984c 100644 --- a/src/main/java/eu/hbp/mip/controllers/FilesAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/FilesAPI.java @@ -28,20 +28,20 @@ import java.time.LocalDateTime; @Api(value = "/protected", description = "the protected files API") public class FilesAPI { - + @Autowired private UserInfo userInfo; @ApiOperation(value = "Get protected files") - @RequestMapping(value = "/{filename:.+}" , method = RequestMethod.GET) + @RequestMapping(value = "/{filename:.+}", method = RequestMethod.GET) public ResponseEntity<Void> getProtectedFile( @ApiParam(value = "filename", required = true) @PathVariable("filename") String filename ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername() , "(GET) /protected/{filename:.+}", "Loading protected file with filename : " + filename); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /protected/{filename:.+}", "Loading protected file with filename : " + filename); String filepath = "/protected/" + filename; - ActionLogging.LogUserAction(user.getUsername() , "(GET) /protected/{filename:.+}" + filepath, "Downloaded protected file"); + 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 e05b4ca94..a5fc94b78 100644 --- a/src/main/java/eu/hbp/mip/controllers/MiningApi.java +++ b/src/main/java/eu/hbp/mip/controllers/MiningApi.java @@ -1,4 +1,5 @@ package eu.hbp.mip.controllers; + import eu.hbp.mip.utils.HTTPUtil; import com.google.gson.Gson; @@ -36,7 +37,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; * Created by mirco on 06.01.17. */ @RestController -@RequestMapping(value = "/mining", produces = { APPLICATION_JSON_VALUE }) +@RequestMapping(value = "/mining", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/mining", description = "the mining API") public class MiningApi { @@ -51,7 +52,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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(POST) /mining/histogram", "Executing histogram..."); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Executing histogram..."); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "MULTIPLE_HISTOGRAMS"; @@ -60,10 +61,10 @@ 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()); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Executed histogram with result :" + results.toString()); return ResponseEntity.ok(gson.toJson(results.toString())); - } catch (IOException e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(POST) /mining/histogram", "Histogram algorithm was not found"); + } catch (IOException e) { + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Histogram algorithm was not found"); return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } } diff --git a/src/main/java/eu/hbp/mip/controllers/ModelsApi.java b/src/main/java/eu/hbp/mip/controllers/ModelsApi.java index de5c7f5d4..08f5199ea 100644 --- a/src/main/java/eu/hbp/mip/controllers/ModelsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ModelsApi.java @@ -53,28 +53,22 @@ public class ModelsApi { 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 - ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /models","Loading models ..."); + ) { + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /models", "Loading models ..."); User user = userInfo.getUser(); Iterable<Model> models; - if(own != null && own) - { + if (own != null && own) { models = modelRepository.findByCreatedByOrderByCreatedAt(user); - } - else - { + } else { models = modelRepository.findByValidOrCreatedByOrderByCreatedAt(true, user); } - if(valid != null && models != null) - { - for (Iterator<Model> i = models.iterator(); i.hasNext(); ) - { + if (valid != null && models != null) { + for (Iterator<Model> i = models.iterator(); i.hasNext(); ) { Model m = i.next(); - if(valid != m.getValid()) - { + if (valid != m.getValid()) { i.remove(); } } @@ -86,27 +80,26 @@ 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."); + + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /models", "Successfully loaded " + modelsList.size() + " models."); return ResponseEntity.ok(modelsList); } @ApiOperation(value = "Create a model", response = Model.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Model created") }) + @ApiResponses(value = {@ApiResponse(code = 201, message = "Model created")}) @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Model> addAModel( @RequestBody @ApiParam(value = "Model to create", required = true) Model model - ) { + ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername() , "(POST) /models","Creating a model"); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /models", "Creating a model"); model.setTitle(model.getConfig().getTitle().get("text")); model.setCreatedBy(user); model.setCreatedAt(new Date()); - if(model.getValid() == null) - { + if (model.getValid() == null) { model.setValid(false); } @@ -120,7 +113,7 @@ public class ModelsApi { saveVariables(model.getQuery().getVariables()); saveVariables(model.getQuery().getCovariables()); saveVariables(model.getQuery().getGrouping()); - saveVariables(model.getQuery().getTrainingDatasets()); + saveVariables(model.getQuery().getTrainingDatasets()); configRepository.save(model.getConfig()); queryRepository.save(model.getQuery()); @@ -129,14 +122,13 @@ public class ModelsApi { } modelRepository.save(model); - ActionLogging.LogUserAction(user.getUsername() , "(POST) /models","Created model with id : " + model.getSlug()+ ", model.config and model.query"); + ActionLogging.LogUserAction(user.getUsername(), "(POST) /models", "Created model with id : " + model.getSlug() + ", model.config and model.query"); return ResponseEntity.status(HttpStatus.CREATED).body(model); } private void saveVariables(@RequestBody @ApiParam(value = "Model to create", required = true) List<Variable> variables) { - for (Variable var : variables) - { + for (Variable var : variables) { variableRepository.save(var); } } @@ -144,16 +136,13 @@ public class ModelsApi { private void ensureSlugUniqueness(@RequestBody @ApiParam(value = "Model to create", required = true) Model model) { String slug = createSlug(model.getTitle()); boolean slugExists = true; - for(int i = 1; slugExists; i++) - { + for (int i = 1; slugExists; i++) { slugExists = modelRepository.exists(slug); - if(slugExists) - { - if(i > 1) - { - slug = slug.substring(0, slug.length()-2); + if (slugExists) { + if (i > 1) { + slug = slug.substring(0, slug.length() - 2); } - slug += "-"+i; + slug += "-" + i; } model.setSlug(slug); } @@ -172,15 +161,12 @@ public class ModelsApi { private void ensureTitleUniqueness(@RequestBody @ApiParam(value = "Model to create", required = true) Model model) { boolean titleExists = true; - for(int i = 1; titleExists; i++) - { + for (int i = 1; titleExists; i++) { String title = model.getTitle(); titleExists = modelRepository.countByTitle(title) > 0; - if(titleExists) - { - if(i > 1) - { - title = title.substring(0, title.length()-4); + if (titleExists) { + if (i > 1) { + title = title.substring(0, title.length() - 4); } model.setTitle(title + " (" + i + ")"); } @@ -191,23 +177,21 @@ public class ModelsApi { @RequestMapping(value = "/{slug}", method = RequestMethod.GET) public ResponseEntity<Model> getAModel( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug - ) { + ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername() , "(GET) /models/{slug}", "Loading model with id : " + slug); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /models/{slug}", "Loading model with id : " + slug); Model model = modelRepository.findOne(slug); - if(model == null) - { + if (model == null) { //LOGGER.warn("Cannot find model : " + slug); - ActionLogging.LogUserAction(user.getUsername() , "(GET) /models/{slug}", "Model was not found"); + 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. "); + 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); } @@ -215,24 +199,23 @@ 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); + ActionLogging.LogUserAction(user.getUsername(), "(GET) /models/{slug}", "Loaded model with id : " + slug); return ResponseEntity.ok(model); } @ApiOperation(value = "Update a model", response = Void.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "Model updated") }) + @ApiResponses(value = {@ApiResponse(code = 204, message = "Model updated")}) @RequestMapping(value = "/{slug}", method = RequestMethod.PUT) public ResponseEntity<Void> updateAModel( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug, @RequestBody @ApiParam(value = "Model to update", required = true) Model model - ) { + ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername() , "(PUT) /models/{slug}", "Updating model with id : "+ slug); + ActionLogging.LogUserAction(user.getUsername(), "(PUT) /models/{slug}", "Updating model with id : " + slug); Model oldModel = modelRepository.findOne(slug); - if(!user.getUsername().equals(oldModel.getCreatedBy().getUsername())) - { + if (!user.getUsername().equals(oldModel.getCreatedBy().getUsername())) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } @@ -242,10 +225,9 @@ public class ModelsApi { String newTitle = model.getTitle(); // If title has been updated, ensure it is unique - if(!newTitle.equals(oldTitle)) { + if (!newTitle.equals(oldTitle)) { boolean newTitleExists = true; - for(int i = 1; newTitleExists && !newTitle.equals(oldTitle); i++) - { + for (int i = 1; newTitleExists && !newTitle.equals(oldTitle); i++) { newTitle = model.getTitle(); newTitleExists = modelRepository.countByTitle(newTitle) > 0; if (newTitleExists && !newTitle.equals(oldTitle)) { @@ -271,7 +253,7 @@ public class ModelsApi { datasetRepository.save(model.getDataset()); modelRepository.save(model); - ActionLogging.LogUserAction(user.getUsername() , "(PUT) /models/{slug}", "Updated model and saved/updated model.config and model.query"); + 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 41518bd11..0469056a8 100644 --- a/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java +++ b/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java @@ -48,7 +48,7 @@ public class PathologiesApi { @RequestMapping(name = "/pathologies", method = RequestMethod.GET) public ResponseEntity<String> getPathologies(Authentication authentication) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /pathologies", "Loading pathologies ..."); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /pathologies", "Loading pathologies ..."); // Load pathologies from file Resource resource = resourceLoader.getResource("file:/opt/portal/api/pathologies.json"); @@ -57,17 +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"); + 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"); + 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"); + 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 852e7e12c..a1eb3e8b7 100644 --- a/src/main/java/eu/hbp/mip/controllers/SecurityApi.java +++ b/src/main/java/eu/hbp/mip/controllers/SecurityApi.java @@ -45,7 +45,7 @@ public class SecurityApi { public Object user(Principal principal, HttpServletResponse response) { ObjectMapper mapper = new ObjectMapper(); - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /user", "Loading user : " + userInfo.getUser().getUsername()); + 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); } - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(POST) /user", "User has agreed on the NDA"); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /user", "User has agreed on the NDA"); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @@ -86,7 +86,7 @@ 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."); + ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /user/login/hbp", "Unathorized login."); httpServletResponse.sendRedirect(securityConfiguration.getFrontendRedirectAfterLogin()); } @@ -114,7 +114,7 @@ public class SecurityApi { JsonObject object = new JsonObject(); object.addProperty("authorization", stringEncoded); object.addProperty("context", galaxyContext); - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /user/galaxy", "Successfully Loaded 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 7fb491ee8..77ef125db 100644 --- a/src/main/java/eu/hbp/mip/controllers/StatsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/StatsApi.java @@ -36,14 +36,14 @@ public class StatsApi { @ApiOperation(value = "Get general statistics", response = GeneralStats.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<GeneralStats> getGeneralStatistics() { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /stats", "Loading general statistics"); + 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."); + 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 9485f99fe..4dc7de343 100644 --- a/src/main/java/eu/hbp/mip/controllers/UsersApi.java +++ b/src/main/java/eu/hbp/mip/controllers/UsersApi.java @@ -36,7 +36,7 @@ public class UsersApi { public ResponseEntity<User> getAUser( @ApiParam(value = "username", required = true) @PathVariable("username") String username ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername() , "(GET) /users/{username}", "Loaded a user with username : " + userInfo.getUser().getUsername()); + 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/model/Article.java b/src/main/java/eu/hbp/mip/model/Article.java index 4fdfc40b8..95c7cbbae 100644 --- a/src/main/java/eu/hbp/mip/model/Article.java +++ b/src/main/java/eu/hbp/mip/model/Article.java @@ -58,8 +58,8 @@ public class Article { public Article() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ title = ""; } diff --git a/src/main/java/eu/hbp/mip/model/Config.java b/src/main/java/eu/hbp/mip/model/Config.java index d950d5074..2362194b2 100644 --- a/src/main/java/eu/hbp/mip/model/Config.java +++ b/src/main/java/eu/hbp/mip/model/Config.java @@ -16,7 +16,7 @@ import java.util.Map; @Entity @Table(name = "`config`") @ApiModel -@JsonIgnoreProperties(value = { "id" }) +@JsonIgnoreProperties(value = {"id"}) public class Config { @Id @@ -42,8 +42,8 @@ public class Config { public Config() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } diff --git a/src/main/java/eu/hbp/mip/model/Dataset.java b/src/main/java/eu/hbp/mip/model/Dataset.java index d7d1e486a..d920571d9 100644 --- a/src/main/java/eu/hbp/mip/model/Dataset.java +++ b/src/main/java/eu/hbp/mip/model/Dataset.java @@ -47,8 +47,8 @@ public class Dataset { public Dataset() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } diff --git a/src/main/java/eu/hbp/mip/model/Experiment.java b/src/main/java/eu/hbp/mip/model/Experiment.java index 902cf37da..c40d91d34 100644 --- a/src/main/java/eu/hbp/mip/model/Experiment.java +++ b/src/main/java/eu/hbp/mip/model/Experiment.java @@ -20,11 +20,11 @@ public class Experiment { @Id @Column(columnDefinition = "uuid") - @org.hibernate.annotations.Type(type="pg-uuid") + @org.hibernate.annotations.Type(type = "pg-uuid") @Expose private UUID uuid; - @Column(columnDefinition="TEXT") + @Column(columnDefinition = "TEXT") @Expose private String name; @@ -38,22 +38,22 @@ public class Experiment { @Expose private Model model; - @Column(columnDefinition="TEXT") + @Column(columnDefinition = "TEXT") @Expose private String algorithms; - @Column(columnDefinition="TEXT") + @Column(columnDefinition = "TEXT") private String validations; - @Column(columnDefinition="TEXT") + @Column(columnDefinition = "TEXT") @Expose private String workflowHistoryId; - @Column(columnDefinition="TEXT") + @Column(columnDefinition = "TEXT") @Expose private String workflowStatus; - @Column(columnDefinition="TEXT") + @Column(columnDefinition = "TEXT") @Expose private String result; @@ -78,8 +78,8 @@ public class Experiment { public Experiment() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } @@ -87,15 +87,13 @@ public class Experiment { JsonObject exp = gson.toJsonTree(this).getAsJsonObject(); JsonParser parser = new JsonParser(); - if (this.algorithms != null) - { + if (this.algorithms != null) { exp.remove("algorithms"); JsonArray jsonAlgorithms = parser.parse(this.algorithms).getAsJsonArray(); exp.add("algorithms", jsonAlgorithms); } - if (this.validations != null) - { + if (this.validations != null) { exp.remove("validations"); JsonArray jsonValidations = parser.parse(this.validations).getAsJsonArray(); exp.add("validations", jsonValidations); diff --git a/src/main/java/eu/hbp/mip/model/GeneralStats.java b/src/main/java/eu/hbp/mip/model/GeneralStats.java index 302cf8edd..4253ae7dd 100644 --- a/src/main/java/eu/hbp/mip/model/GeneralStats.java +++ b/src/main/java/eu/hbp/mip/model/GeneralStats.java @@ -17,8 +17,8 @@ public class GeneralStats { public GeneralStats() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } diff --git a/src/main/java/eu/hbp/mip/model/Group.java b/src/main/java/eu/hbp/mip/model/Group.java index 3cf2a0706..abb195a93 100644 --- a/src/main/java/eu/hbp/mip/model/Group.java +++ b/src/main/java/eu/hbp/mip/model/Group.java @@ -15,7 +15,7 @@ import javax.persistence.Table; @Entity @Table(name = "`group`") @ApiModel -@JsonIgnoreProperties(value = { "parent" }) +@JsonIgnoreProperties(value = {"parent"}) @JsonInclude(JsonInclude.Include.NON_NULL) public class Group { @@ -25,8 +25,8 @@ public class Group { public Group() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } diff --git a/src/main/java/eu/hbp/mip/model/Model.java b/src/main/java/eu/hbp/mip/model/Model.java index 8b25b7410..b15908037 100644 --- a/src/main/java/eu/hbp/mip/model/Model.java +++ b/src/main/java/eu/hbp/mip/model/Model.java @@ -57,8 +57,8 @@ public class Model { public Model() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } diff --git a/src/main/java/eu/hbp/mip/model/PathologyDTO.java b/src/main/java/eu/hbp/mip/model/PathologyDTO.java index cc407e7f2..c58238b62 100644 --- a/src/main/java/eu/hbp/mip/model/PathologyDTO.java +++ b/src/main/java/eu/hbp/mip/model/PathologyDTO.java @@ -73,10 +73,12 @@ public class PathologyDTO { this.label = label; } - public String toString(){ return code;} + public String toString() { + return code; + } } - public String toString(){ + public String toString() { return code; } diff --git a/src/main/java/eu/hbp/mip/model/Query.java b/src/main/java/eu/hbp/mip/model/Query.java index 0e4a59850..8e4d78dcb 100644 --- a/src/main/java/eu/hbp/mip/model/Query.java +++ b/src/main/java/eu/hbp/mip/model/Query.java @@ -16,7 +16,7 @@ import java.util.List; @Entity @ApiModel @Table(name = "`query`") -@JsonIgnoreProperties(value = { "id" }) +@JsonIgnoreProperties(value = {"id"}) @JsonInclude(JsonInclude.Include.NON_NULL) public class Query { @@ -26,44 +26,44 @@ public class Query { @ManyToMany @JoinTable(name = "query_variable", joinColumns = { - @JoinColumn(name = "id", nullable = false, updatable = false) }, - inverseJoinColumns = { @JoinColumn(name = "code", - nullable = false, updatable = false) }) + @JoinColumn(name = "id", nullable = false, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "code", + nullable = false, updatable = false)}) private List<Variable> variables = new LinkedList<>(); @ManyToMany @JoinTable(name = "query_covariable", joinColumns = { - @JoinColumn(name = "id", nullable = false, updatable = false) }, - inverseJoinColumns = { @JoinColumn(name = "code", - nullable = false, updatable = false) }) + @JoinColumn(name = "id", nullable = false, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "code", + nullable = false, updatable = false)}) private List<Variable> covariables = new LinkedList<>(); @ManyToMany @JoinTable(name = "query_grouping", joinColumns = { - @JoinColumn(name = "id", nullable = false, updatable = false) }, - inverseJoinColumns = { @JoinColumn(name = "code", - nullable = false, updatable = false) }) + @JoinColumn(name = "id", nullable = false, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "code", + nullable = false, updatable = false)}) private List<Variable> grouping = new LinkedList<>(); @ManyToMany @JoinTable(name = "query_training_datasets", joinColumns = { - @JoinColumn(name = "id", nullable = false, updatable = false) }, - inverseJoinColumns = { @JoinColumn(name = "code", - nullable = false, updatable = false) }) + @JoinColumn(name = "id", nullable = false, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "code", + nullable = false, updatable = false)}) private List<Variable> trainingDatasets = new LinkedList<>(); @ManyToMany @JoinTable(name = "query_testing_datasets", joinColumns = { - @JoinColumn(name = "id", nullable = false, updatable = false) }, - inverseJoinColumns = { @JoinColumn(name = "code", - nullable = false, updatable = false) }) + @JoinColumn(name = "id", nullable = false, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "code", + nullable = false, updatable = false)}) private List<Variable> testingDatasets = new LinkedList<>(); @ManyToMany @JoinTable(name = "query_validation_datasets", joinColumns = { - @JoinColumn(name = "id", nullable = false, updatable = false) }, - inverseJoinColumns = { @JoinColumn(name = "code", - nullable = false, updatable = false) }) + @JoinColumn(name = "id", nullable = false, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "code", + nullable = false, updatable = false)}) private List<Variable> validationDatasets = new LinkedList<>(); @Column(columnDefinition = "text") @@ -75,8 +75,8 @@ public class Query { public Query() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } diff --git a/src/main/java/eu/hbp/mip/model/Tag.java b/src/main/java/eu/hbp/mip/model/Tag.java index 3e1fbccbc..693c98656 100644 --- a/src/main/java/eu/hbp/mip/model/Tag.java +++ b/src/main/java/eu/hbp/mip/model/Tag.java @@ -23,8 +23,8 @@ public class Tag { public Tag() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } diff --git a/src/main/java/eu/hbp/mip/model/User.java b/src/main/java/eu/hbp/mip/model/User.java index d95be07d0..64fee4b67 100644 --- a/src/main/java/eu/hbp/mip/model/User.java +++ b/src/main/java/eu/hbp/mip/model/User.java @@ -19,7 +19,7 @@ import java.util.stream.Collectors; @Table(name = "`user`") @ApiModel @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(value = { "appsVotes" }) +@JsonIgnoreProperties(value = {"appsVotes"}) public class User { @Id @@ -86,13 +86,14 @@ public class User { public User() { /* - * Empty constructor is needed by Hibernate - */ + * Empty constructor is needed by Hibernate + */ } /** * Create a user using OpenID user profile + * * @param userInfo info from OpenID UserInfo endpoint */ public User(String userInfo) { diff --git a/src/main/java/eu/hbp/mip/model/Variable.java b/src/main/java/eu/hbp/mip/model/Variable.java index 1fcce2e48..596be8d77 100644 --- a/src/main/java/eu/hbp/mip/model/Variable.java +++ b/src/main/java/eu/hbp/mip/model/Variable.java @@ -17,7 +17,7 @@ import java.util.List; @Entity @Table(name = "`variable`") @ApiModel -@JsonIgnoreProperties(value = { "queries" }) +@JsonIgnoreProperties(value = {"queries"}) @JsonInclude(JsonInclude.Include.NON_NULL) public class Variable { @@ -26,7 +26,7 @@ public class Variable { private String code = null; /** - * Empty constructor is needed by Hibernate + * Empty constructor is needed by Hibernate */ public Variable() { } diff --git a/src/main/java/eu/hbp/mip/model/galaxy/WorkflowDTO.java b/src/main/java/eu/hbp/mip/model/galaxy/WorkflowDTO.java index de537a1dc..fa0cb4b33 100644 --- a/src/main/java/eu/hbp/mip/model/galaxy/WorkflowDTO.java +++ b/src/main/java/eu/hbp/mip/model/galaxy/WorkflowDTO.java @@ -103,7 +103,7 @@ public class WorkflowDTO { } } - public AlgorithmDTO convertToAlgorithmDTO(){ + public AlgorithmDTO convertToAlgorithmDTO() { AlgorithmDTO algorithmDTO = new AlgorithmDTO(); @@ -120,10 +120,10 @@ public class WorkflowDTO { // Convert the annotation to algorithm Parameter AlgorithmDTO.AlgorithmParamDTO algorithmParam; - if(steps.get(workflowInput.getKey()).getAnnotation() != null) { + if (steps.get(workflowInput.getKey()).getAnnotation() != null) { algorithmParam = gson.fromJson(steps.get(workflowInput.getKey()).getAnnotation(), - AlgorithmDTO.AlgorithmParamDTO.class); - }else{ + AlgorithmDTO.AlgorithmParamDTO.class); + } else { // If annotation is not provided, auto-fill some information algorithmParam = new AlgorithmDTO.AlgorithmParamDTO(); // When the constraints are not known, set the most relaxed constraints @@ -134,17 +134,17 @@ public class WorkflowDTO { algorithmParam.setDefaultValue(""); algorithmParam.setDefaultValue("true"); // If label is dataset/pathology/filter/formula the type should be the same - if(workflowInput.getValue().getLabel().equals("dataset") || - workflowInput.getValue().getLabel().equals("pathology")|| - workflowInput.getValue().getLabel().equals("filter")|| - workflowInput.getValue().getLabel().equals("formula")){ + if (workflowInput.getValue().getLabel().equals("dataset") || + workflowInput.getValue().getLabel().equals("pathology") || + workflowInput.getValue().getLabel().equals("filter") || + workflowInput.getValue().getLabel().equals("formula")) { algorithmParam.setType(workflowInput.getValue().getLabel()); - }else if(workflowInput.getValue().getLabel().equals("x") || - workflowInput.getValue().getLabel().equals("y")){ + } else if (workflowInput.getValue().getLabel().equals("x") || + workflowInput.getValue().getLabel().equals("y")) { algorithmParam.setType("column"); algorithmParam.setColumnValuesSQLType("text,real,integer"); algorithmParam.setColumnValuesIsCategorical(""); - }else{ + } else { algorithmParam.setType("other"); } } diff --git a/src/main/java/eu/hbp/mip/repositories/ArticleRepository.java b/src/main/java/eu/hbp/mip/repositories/ArticleRepository.java index 4ad0e3942..1a93186ff 100644 --- a/src/main/java/eu/hbp/mip/repositories/ArticleRepository.java +++ b/src/main/java/eu/hbp/mip/repositories/ArticleRepository.java @@ -10,6 +10,8 @@ import org.springframework.data.repository.CrudRepository; public interface ArticleRepository extends CrudRepository<Article, String> { Long countByTitle(String title); + Iterable<Article> findByCreatedBy(User user); + Iterable<Article> findByStatusOrCreatedBy(String status, User user); } diff --git a/src/main/java/eu/hbp/mip/repositories/ExperimentRepository.java b/src/main/java/eu/hbp/mip/repositories/ExperimentRepository.java index 6609d6450..2f6ae857d 100644 --- a/src/main/java/eu/hbp/mip/repositories/ExperimentRepository.java +++ b/src/main/java/eu/hbp/mip/repositories/ExperimentRepository.java @@ -12,5 +12,6 @@ import java.util.UUID; public interface ExperimentRepository extends CrudRepository<Experiment, UUID> { Iterable<Experiment> findByCreatedBy(User user); + Iterable<Experiment> findByShared(Boolean shared); } diff --git a/src/main/java/eu/hbp/mip/repositories/ModelRepository.java b/src/main/java/eu/hbp/mip/repositories/ModelRepository.java index de44afc6c..c25b1e5bb 100644 --- a/src/main/java/eu/hbp/mip/repositories/ModelRepository.java +++ b/src/main/java/eu/hbp/mip/repositories/ModelRepository.java @@ -10,6 +10,8 @@ import org.springframework.data.repository.CrudRepository; public interface ModelRepository extends CrudRepository<Model, String> { Long countByTitle(String Title); + Iterable<Model> findByCreatedByOrderByCreatedAt(User user); + Iterable<Model> findByValidOrCreatedByOrderByCreatedAt(Boolean valid, User user); } diff --git a/src/main/java/eu/hbp/mip/utils/ActionLogging.java b/src/main/java/eu/hbp/mip/utils/ActionLogging.java index 8e9757276..7004fb89e 100644 --- a/src/main/java/eu/hbp/mip/utils/ActionLogging.java +++ b/src/main/java/eu/hbp/mip/utils/ActionLogging.java @@ -12,8 +12,8 @@ public class ActionLogging { 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); + 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 @@ -25,7 +25,7 @@ public class ActionLogging { // Used from Threads because threads can't get userName. public static void LogExperimentAction(String experimentName, String actionInfo) { - LOGGER.info(" Experiment -> "+ experimentName + LOGGER.info(" Experiment -> " + experimentName + " , Info -> " + actionInfo); } diff --git a/src/main/java/eu/hbp/mip/utils/ClaimUtils.java b/src/main/java/eu/hbp/mip/utils/ClaimUtils.java index bad70279e..2749a96d6 100644 --- a/src/main/java/eu/hbp/mip/utils/ClaimUtils.java +++ b/src/main/java/eu/hbp/mip/utils/ClaimUtils.java @@ -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()))) { - ActionLogging.LogUserAction(username , "(GET) /pathologies", + ActionLogging.LogUserAction(username, "(GET) /pathologies", "Added dataset: " + dataset.getCode()); userPathologyDatasets.add(dataset); } } if (userPathologyDatasets.size() > 0) { - ActionLogging.LogUserAction(username , "(GET) /pathologies", + ActionLogging.LogUserAction(username, "(GET) /pathologies", "Added pathology '" + curPathology.getLabel() + "' with datasets: '" + userPathologyDatasets + "'"); diff --git a/src/main/java/eu/hbp/mip/utils/HTTPUtil.java b/src/main/java/eu/hbp/mip/utils/HTTPUtil.java index 5c5043463..cd3778a00 100644 --- a/src/main/java/eu/hbp/mip/utils/HTTPUtil.java +++ b/src/main/java/eu/hbp/mip/utils/HTTPUtil.java @@ -27,7 +27,7 @@ public class HTTPUtil { } public static int sendAuthorizedHTTP(String url, String query, StringBuilder resp, String httpVerb, - String authorization) throws IOException { + String authorization) throws IOException { return sendHTTP(url, query, resp, httpVerb, authorization); } -- GitLab From 2a8732d7f49810f2db1a47f73ade22d2d8dcccfa Mon Sep 17 00:00:00 2001 From: kfilippopolitis <kostasfilippop@gmail.com> Date: Tue, 13 Oct 2020 09:05:56 -0700 Subject: [PATCH 3/4] Renamed ActionLogging to Logging. --- build.sh | 2 +- .../configuration/SecurityConfiguration.java | 4 +- .../eu/hbp/mip/controllers/AlgorithmsApi.java | 34 ++-- .../eu/hbp/mip/controllers/ArticlesApi.java | 20 +- .../eu/hbp/mip/controllers/ExperimentApi.java | 184 +++++++++--------- .../java/eu/hbp/mip/controllers/FilesAPI.java | 10 +- .../eu/hbp/mip/controllers/MiningApi.java | 30 ++- .../eu/hbp/mip/controllers/ModelsApi.java | 24 ++- .../hbp/mip/controllers/PathologiesApi.java | 11 +- .../eu/hbp/mip/controllers/SecurityApi.java | 11 +- .../java/eu/hbp/mip/controllers/StatsApi.java | 6 +- .../java/eu/hbp/mip/controllers/UsersApi.java | 4 +- .../java/eu/hbp/mip/utils/ClaimUtils.java | 14 +- .../{ActionLogging.java => Logging.java} | 6 +- 14 files changed, 171 insertions(+), 189 deletions(-) rename src/main/java/eu/hbp/mip/utils/{ActionLogging.java => Logging.java} (92%) diff --git a/build.sh b/build.sh index 6a18d98ec..ef4f10565 100755 --- a/build.sh +++ b/build.sh @@ -26,7 +26,7 @@ else DOCKER="sudo docker" fi -IMAGE="kfilippopolitis/portal-backend" +IMAGE="hbpmip/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 90d05b9d3..7836edf94 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ã™ã‚‹ãƒªã‚¯ã‚¨ã‚¹ãƒˆãƒ‘ãƒ©ãƒ¡ãƒ¼ã‚¿ãƒ¼ã‚’ä½œæˆ - ActionLogging.LogAction("refresh token ", this.oauth2ClientContext.getAccessToken().getRefreshToken().getValue()); + Logging.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); // ãƒªã‚¯ã‚¨ã‚¹ãƒˆã‚’ä½œæˆ - ActionLogging.LogAction("logoutUri is ", logoutUri); + Logging.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 db9b7d124..8310973a3 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.ActionLogging; +import eu.hbp.mip.utils.Logging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; @@ -57,24 +57,24 @@ public class AlgorithmsApi { @ApiOperation(value = "List all algorithms", response = String.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<AlgorithmDTO>> getAlgorithms() { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Executing..."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Executing..."); LinkedList<AlgorithmDTO> exaremeAlgorithms = getExaremeAlgorithms(); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Loaded " + exaremeAlgorithms.size() + " exareme algorithms"); + Logging.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"); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Loaded " + galaxyAlgorithms.size() + " galaxy algorithms"); LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); if (exaremeAlgorithms != null) { algorithms.addAll(exaremeAlgorithms); } else { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Getting exareme algorithms failed and returned null"); } if (galaxyAlgorithms != null) { algorithms.addAll(galaxyAlgorithms); } else { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Getting galaxy workflows failed and returned null"); } @@ -82,7 +82,7 @@ public class AlgorithmsApi { try { disabledAlgorithms = getDisabledAlgorithms(); } catch (IOException e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", disabledAlgorithmsCouldNotBeLoaded); } @@ -93,7 +93,7 @@ public class AlgorithmsApi { allowedAlgorithms.add(algorithm); } } - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Successfully listed " + allowedAlgorithms.size() + " algorithms"); return ResponseEntity.ok(allowedAlgorithms); } @@ -116,11 +116,11 @@ public class AlgorithmsApi { }.getType() ); } catch (IOException e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "An exception occurred: " + e.getMessage()); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "An exception occurred: " + e.getMessage()); return null; } - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Completed, returned " + algorithms.size() + " algorithms."); return algorithms; } @@ -140,7 +140,7 @@ public class AlgorithmsApi { workflowList = new ArrayList<>(workflowsClient.getWorkflows()); } catch (Exception e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Error when calling list galaxy workflows: " + e.getMessage()); + Logging.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()); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Error Response: " + msgErr); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Error Response: " + msgErr); return null; } } catch (Exception e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "An exception occurred: " + e.getMessage()); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "An exception occurred: " + e.getMessage()); return null; } } - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Workflows fetched: " + workflows.size()); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Workflows fetched: " + workflows.size()); // Convert the workflows to algorithms LinkedList<AlgorithmDTO> algorithms = new LinkedList<>(); for (WorkflowDTO workflow : workflows) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Converting workflow: " + workflow); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Converting workflow: " + workflow); algorithms.add(workflow.convertToAlgorithmDTO()); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Converted algorithm: " + algorithms.get(algorithms.size() - 1)); } - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /algorithms", "Completed!"); + Logging.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 e73b2d061..d4eb46e9f 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.ActionLogging; +import eu.hbp.mip.utils.Logging; import io.swagger.annotations.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -43,7 +43,7 @@ public class ArticlesApi { ) { User user = userInfo.getUser(); Iterable<Article> articles; - ActionLogging.LogUserAction(user.getUsername(), "(GET) /articles", "Loading articles..."); + Logging.LogUserAction(user.getUsername(), "(GET) /articles", "Loading articles..."); if (own != null && own) { articles = articleRepository.findByCreatedBy(user); @@ -60,7 +60,7 @@ public class ArticlesApi { articlesSize++; } } - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles", "Successfully Loaded " + articlesSize + " articles"); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles", "Successfully Loaded " + articlesSize + " articles"); return ResponseEntity.ok(articles); } @@ -74,7 +74,7 @@ public class ArticlesApi { ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /articles", "Creating article..."); + Logging.LogUserAction(user.getUsername(), "(POST) /articles", "Creating article..."); article.setCreatedAt(new Date()); if ("published".equals(article.getStatus())) { @@ -116,7 +116,7 @@ public class ArticlesApi { } articleRepository.save(article); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /articles", "Successfully created article with id : " + article.getSlug()); + Logging.LogUserAction(user.getUsername(), "(POST) /articles", "Successfully created article with id : " + article.getSlug()); return new ResponseEntity<>(HttpStatus.CREATED); } @@ -126,7 +126,7 @@ public class ArticlesApi { public ResponseEntity<Article> getAnArticle( @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles/{slug}", "Loading article with id : " + slug); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles/{slug}", "Loading article with id : " + slug); User user = userInfo.getUser(); Article article; @@ -134,7 +134,7 @@ public class ArticlesApi { if (article == null) { //LOGGER.warn("Cannot find article : " + slug); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles/{slug}", "Article not found"); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /articles/{slug}", "Article not found"); return ResponseEntity.badRequest().body(null); } @@ -142,7 +142,7 @@ public class ArticlesApi { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } - ActionLogging.LogUserAction(user.getUsername(), "(GET) /articles/{slug}", "Successfully Loaded article with id : " + slug); + Logging.LogUserAction(user.getUsername(), "(GET) /articles/{slug}", "Successfully Loaded article with id : " + slug); return ResponseEntity.ok(article); } @@ -155,7 +155,7 @@ public class ArticlesApi { @ApiParam(value = "slug", required = true) @PathVariable("slug") String slug, @RequestBody @ApiParam(value = "Article to update", required = true) @Valid Article article ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(PUT) /articles/{slug}", "Updating article with id : " + slug); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(PUT) /articles/{slug}", "Updating article with id : " + slug); User user = userInfo.getUser(); @@ -185,7 +185,7 @@ public class ArticlesApi { articleRepository.save(article); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(PUT) /articles/{slug}", "Successfully pdated article with id : " + slug); + Logging.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 b4a7d2bbd..e81d2ee5b 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.ActionLogging; +import eu.hbp.mip.utils.Logging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -92,28 +92,28 @@ public class ExperimentApi { UUID experimentUuid; User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Loading Experiment with uuid : " + uuid); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Loading Experiment with uuid : " + uuid); try { experimentUuid = UUID.fromString(uuid); } catch (IllegalArgumentException iae) { - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Invalid Experiment UUID."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Invalid Experiment UUID."); return ResponseEntity.badRequest().body("Invalid Experiment UUID"); } experiment = experimentRepository.findOne(experimentUuid); if (experiment == null) { - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment Not found."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment Not found."); return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } if (!experiment.isShared() && !experiment.getCreatedBy().getUsername().equals(user.getUsername())) { - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Accessing Experiment is unauthorized."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Accessing Experiment is unauthorized."); return new ResponseEntity<>("You don't have access to the experiment.", HttpStatus.UNAUTHORIZED); } - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment was Loaded with uuid : " + uuid + "."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}", "Experiment was Loaded with uuid : " + uuid + "."); return new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -127,7 +127,7 @@ public class ExperimentApi { 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 + "."); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Executing " + algorithmName + " with algorithmType : " + algorithmType + "."); if (authenticationIsEnabled) { // Getting the dataset from the experiment parameters @@ -140,7 +140,7 @@ public class ExperimentApi { } if (experimentDatasets == null || experimentDatasets.equals("")) { - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", + Logging.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."); } @@ -153,10 +153,10 @@ public class ExperimentApi { // Run with the appropriate engine if (algorithmType.equals("workflow")) { - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Algorithm runs on Galaxy."); + Logging.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."); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Algorithm runs on Exareme."); return runExaremeAlgorithm(experimentExecutionDTO); } } @@ -170,24 +170,24 @@ public class ExperimentApi { UUID experimentUuid; User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Marking as viewed the experiment with uuid : " + uuid + "."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Marking as viewed the experiment with uuid : " + uuid + "."); try { experimentUuid = UUID.fromString(uuid); } catch (IllegalArgumentException iae) { - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Invalid Experiment UUID" + uuid + "."); + Logging.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())) { - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "You're not the owner of this experiment"); + Logging.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); - ActionLogging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Experiment with uuid: " + uuid + " was marked as viewed."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{uuid}/markAsViewed", "Experiment with uuid: " + uuid + " was marked as viewed."); return new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -197,7 +197,7 @@ public class ExperimentApi { public ResponseEntity<String> markExperimentAsShared( @ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{uuid}/markAsShared", "Marking as shared the experiment with uuid : " + uuid + "."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{uuid}/markAsShared", "Marking as shared the experiment with uuid : " + uuid + "."); return doMarkExperimentAsShared(uuid, true); } @@ -206,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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{uuid}/markAs/Unshared", "Marking as unshared the experiment with uuid : " + uuid + "."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{uuid}/markAs/Unshared", "Marking as unshared the experiment with uuid : " + uuid + "."); return doMarkExperimentAsShared(uuid, false); } @@ -216,10 +216,10 @@ public class ExperimentApi { public ResponseEntity<String> listExperiments( @ApiParam(value = "maxResultCount") @RequestParam int maxResultCount) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Listing experiments with a maximum amount of : " + maxResultCount + "."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Listing experiments with a maximum amount of : " + maxResultCount + "."); List<Experiment> expList = doListExperiments(false, null); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Successfully listed experiments."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Successfully listed experiments."); return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); } @@ -229,7 +229,7 @@ public class ExperimentApi { public ResponseEntity<String> listExperiments(@ApiParam(value = "slug") @RequestParam("slug") String modelSlug, @ApiParam(value = "maxResultCount") @RequestParam("maxResultCount") int maxResultCount) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Listing experiments with a maximum amount of :" + maxResultCount + "with modelSlug : " + modelSlug + "."); + Logging.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)) { return new ResponseEntity<>("You must provide at least a slug or a limit of result", @@ -237,16 +237,16 @@ public class ExperimentApi { } List<Experiment> expList = doListExperiments(false, null); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Successfully listed my experiments."); + Logging.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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{mine}", "Listing my experiments."); + Logging.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."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{mine}", "Successfully listed my experiments."); return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); } @@ -285,7 +285,7 @@ public class ExperimentApi { } 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."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "List my experiments", "Listing my experiments."); return ResponseEntity.badRequest().body("Invalid Experiment UUID"); } @@ -297,7 +297,7 @@ public class ExperimentApi { experiment.setShared(shared); experimentRepository.save(experiment); - ActionLogging.LogUserAction(user.getUsername(), "Experiment updated (marked as shared)", ""); + Logging.LogUserAction(user.getUsername(), "Experiment updated (marked as shared)", ""); return new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -316,26 +316,26 @@ public class ExperimentApi { experiment.setName(experimentExecutionDTO.getName()); experimentRepository.save(experiment); - 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()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " id : " + experiment.getUuid()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " algorithms : " + experiment.getAlgorithms()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " model : " + experiment.getModel().getSlug()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " name : " + experiment.getName()); return experiment; } private void saveExperiment(Experiment experiment) { 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()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " id : " + experiment.getUuid()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " algorithms : " + experiment.getAlgorithms()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " model : " + experiment.getModel().getSlug()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " name : " + experiment.getName()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " historyId : " + experiment.getWorkflowHistoryId()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " status : " + experiment.getWorkflowStatus()); experimentRepository.save(experiment); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Saved experiment"); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Saved experiment"); } private void finishExperiment(Experiment experiment) { @@ -352,11 +352,11 @@ public class ExperimentApi { * @return the response to be returned */ public ResponseEntity<String> runExaremeAlgorithm(ExperimentExecutionDTO experimentExecutionDTO) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Running the algorithm..."); + Logging.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()); + Logging.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(); @@ -367,30 +367,30 @@ public class ExperimentApi { String body = gson.toJson(algorithmParameters); String url = queryExaremeUrl + "/" + algorithmName; - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "url: " + url + ", body: " + body); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "url: " + url + ", body: " + body); ResponseEntity<String> response = new ResponseEntity<>(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Completed, returning: " + experiment.toString()); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Starting exareme execution thread"); new Thread(() -> { // 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!"); + Logging.LogExperimentAction(experiment.getName(), "Thread named :" + Thread.currentThread().getName() + " with id :" + Thread.currentThread().getId() + " started!"); try { StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, body, results); - ActionLogging.LogExperimentAction(experiment.getName(), "Algorithm finished with code: " + code); + Logging.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) { - ActionLogging.LogExperimentAction(experiment.getName(), "There was an exception: " + e.getMessage()); + Logging.LogExperimentAction(experiment.getName(), "There was an exception: " + e.getMessage()); experiment.setHasError(true); experiment.setHasServerError(true); @@ -398,7 +398,7 @@ public class ExperimentApi { } finishExperiment(experiment); - ActionLogging.LogExperimentAction(experiment.getName(), "Finished the experiment: " + experiment.toString()); + Logging.LogExperimentAction(experiment.getName(), "Finished the experiment: " + experiment.toString()); }).start(); return response; @@ -414,10 +414,10 @@ public class ExperimentApi { * @return the response to be returned */ public ResponseEntity<String> runGalaxyWorkflow(ExperimentExecutionDTO experimentExecutionDTO) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Running a workflow..."); + Logging.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()); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :" + experiment.getUuid()); User user = userInfo.getUser(); @@ -447,7 +447,7 @@ public class ExperimentApi { } } if (workflow == null) { - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", + Logging.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()); @@ -466,7 +466,7 @@ public class ExperimentApi { // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Running Galaxy workflow with id: " + workflow.getId()); + Logging.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); @@ -475,7 +475,7 @@ public class ExperimentApi { if (response.code() == 200) { // Call succeeded String responseBody = gson.toJson(response.body()); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Response: " + responseBody); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Response: " + responseBody); String historyId = (String) new JSONObject(responseBody).get("history_id"); experiment.setWorkflowHistoryId(historyId); @@ -485,7 +485,7 @@ public class ExperimentApi { } else { // Something unexpected happened String msgErr = gson.toJson(response.errorBody()); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Error Response: " + msgErr); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Error Response: " + msgErr); // Values are read from streams. JSONObject jObjectError = new JSONObject(msgErr); @@ -497,7 +497,7 @@ public class ExperimentApi { } } catch (Exception e) { - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "An exception occurred: " + e.getMessage()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "An exception occurred: " + e.getMessage()); experiment.setHasError(true); experiment.setHasServerError(true); experiment.setResult(e.getMessage()); @@ -507,7 +507,7 @@ public class ExperimentApi { // Start the process of fetching the status updateWorkflowExperiment(experiment); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Run workflow completed!"); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Run workflow completed!"); return new ResponseEntity(gsonOnlyExposed.toJson(experiment.jsonify()), HttpStatus.OK); } @@ -524,53 +524,53 @@ public class ExperimentApi { User user = userInfo.getUser(); if (experiment == null) { - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "The experiment does not exist."); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "The experiment does not exist."); return; } - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", " Experiment id : " + experiment.getUuid()); if (experiment.getWorkflowHistoryId() == null) { - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "History Id does not exist."); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "History Id does not exist."); return; } - ActionLogging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Starting Thread..."); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Starting Thread..."); new Thread(() -> { while (true) { // ATTENTION: Inside the Thread only LogExperimentAction should be used, not LogExperimentAction! - ActionLogging.LogExperimentAction(experiment.getName(), "Thread is running..."); + Logging.LogExperimentAction(experiment.getName(), "Thread is running..."); try { sleep(2000); } catch (InterruptedException e) { - ActionLogging.LogExperimentAction(experiment.getName(), "Sleep was disrupted: " + e.getMessage()); + Logging.LogExperimentAction(experiment.getName(), "Sleep was disrupted: " + e.getMessage()); } - ActionLogging.LogExperimentAction(experiment.getName(), "Fetching status for experiment Id: " + experiment.getUuid()); + Logging.LogExperimentAction(experiment.getName(), "Fetching status for experiment Id: " + experiment.getUuid()); String state = getWorkflowStatus(experiment.getWorkflowHistoryId(), experiment.getName()); - ActionLogging.LogExperimentAction(experiment.getName(), "State is: " + state); + Logging.LogExperimentAction(experiment.getName(), "State is: " + state); switch (state) { case "running": // Do nothing, when the experiment is created the status is set to running - ActionLogging.LogExperimentAction(experiment.getName(), "Workflow is still running."); + Logging.LogExperimentAction(experiment.getName(), "Workflow is still running."); break; case "completed": // Get only the job result that is visible List<GalaxyWorkflowResult> workflowJobsResults = getWorkflowResults(experiment); - ActionLogging.LogExperimentAction(experiment.getName(), "Results are: " + workflowJobsResults.toString()); + Logging.LogExperimentAction(experiment.getName(), "Results are: " + workflowJobsResults.toString()); boolean resultFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getVisible()) { - ActionLogging.LogExperimentAction(experiment.getName(), "Visible result are: " + jobResult.getId()); + Logging.LogExperimentAction(experiment.getName(), "Visible result are: " + jobResult.getId()); String result = getWorkflowResultBody(experiment, jobResult.getId()); - ActionLogging.LogExperimentAction(experiment.getName(), "Result: " + result); + Logging.LogExperimentAction(experiment.getName(), "Result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -582,7 +582,7 @@ public class ExperimentApi { } if (!resultFound) { // If there is no visible result - ActionLogging.LogExperimentAction(experiment.getName(), "No visible result"); + Logging.LogExperimentAction(experiment.getName(), "No visible result"); experiment.setResult("[" + new ErrorResponse("The workflow has no visible result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -594,16 +594,16 @@ public class ExperimentApi { case "error": // Get the job result that failed workflowJobsResults = getWorkflowResults(experiment); - ActionLogging.LogExperimentAction(experiment.getName(), "Error results are: " + workflowJobsResults.toString()); + Logging.LogExperimentAction(experiment.getName(), "Error results are: " + workflowJobsResults.toString()); boolean failedJobFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getState().equals("error")) { - ActionLogging.LogExperimentAction(experiment.getName(), "Failed job is: " + jobResult.getId()); + Logging.LogExperimentAction(experiment.getName(), "Failed job is: " + jobResult.getId()); String result = getWorkflowJobError(jobResult.getId(), experiment.getName()); - ActionLogging.LogExperimentAction(experiment.getName(), "Job result: " + result); + Logging.LogExperimentAction(experiment.getName(), "Job result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -615,7 +615,7 @@ public class ExperimentApi { } if (!failedJobFound) { // If there is no visible failed job - ActionLogging.LogExperimentAction(experiment.getName(), "No failed result"); + Logging.LogExperimentAction(experiment.getName(), "No failed result"); experiment.setResult("[" + new ErrorResponse("The workflow has no failed result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -633,7 +633,7 @@ public class ExperimentApi { // If result exists return if (experiment.getResult() != null) { - ActionLogging.LogExperimentAction(experiment.getName(), "Result exists: " + experiment.getResult()); + Logging.LogExperimentAction(experiment.getName(), "Result exists: " + experiment.getResult()); return; } } @@ -650,7 +650,7 @@ public class ExperimentApi { */ 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); + Logging.LogExperimentAction(experimentName, " History Id : " + historyId); // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); @@ -660,15 +660,15 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - ActionLogging.LogExperimentAction(experimentName, " Response code: " + Logging.LogExperimentAction(experimentName, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return "internalError"; } result = new Gson().toJson(response.body()); - ActionLogging.LogExperimentAction(experimentName, " Result: " + result); + Logging.LogExperimentAction(experimentName, " Result: " + result); } catch (IOException e) { - ActionLogging.LogExperimentAction(experimentName + Logging.LogExperimentAction(experimentName , " An exception happened: " + e.getMessage()); return "internalError"; } @@ -678,12 +678,12 @@ public class ExperimentApi { JSONObject resultJson = new JSONObject(result); state = resultJson.getString("state"); } catch (JSONException e) { - ActionLogging.LogExperimentAction(experimentName + Logging.LogExperimentAction(experimentName , " An exception happened: " + e.getMessage()); return "internalError"; } - ActionLogging.LogExperimentAction(experimentName, " Completed!"); + Logging.LogExperimentAction(experimentName, " Completed!"); switch (state) { case "ok": return "completed"; @@ -707,7 +707,7 @@ public class ExperimentApi { String historyId = experiment.getWorkflowHistoryId(); String experimentName = experiment.getName(); - ActionLogging.LogExperimentAction(experimentName, " historyId : " + historyId); + Logging.LogExperimentAction(experimentName, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<List<GalaxyWorkflowResult>> call = service.getWorkflowResultsFromGalaxy(historyId, galaxyApiKey); @@ -716,20 +716,20 @@ public class ExperimentApi { try { Response<List<GalaxyWorkflowResult>> response = call.execute(); if (response.code() >= 400) { - ActionLogging.LogExperimentAction(experimentName, " Response code: " + Logging.LogExperimentAction(experimentName, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } getGalaxyWorkflowResultList = response.body(); - ActionLogging.LogExperimentAction(experimentName, " Result: " + response.body()); + Logging.LogExperimentAction(experimentName, " Result: " + response.body()); } catch (IOException e) { - ActionLogging.LogExperimentAction(experimentName + Logging.LogExperimentAction(experimentName , " An exception happened: " + e.getMessage()); return null; } - ActionLogging.LogExperimentAction(experimentName, " Completed!"); + Logging.LogExperimentAction(experimentName, " Completed!"); return getGalaxyWorkflowResultList; } @@ -744,7 +744,7 @@ public class ExperimentApi { String historyId = experiment.getWorkflowHistoryId(); String experimentName = experiment.getName(); - ActionLogging.LogExperimentAction(experimentName, " historyId : " + historyId); + Logging.LogExperimentAction(experimentName, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> call = @@ -754,20 +754,20 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - ActionLogging.LogExperimentAction(experimentName, " Response code: " + Logging.LogExperimentAction(experimentName, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } resultJson = new Gson().toJson(response.body()); - ActionLogging.LogExperimentAction(experimentName, " Result: " + resultJson); + Logging.LogExperimentAction(experimentName, " Result: " + resultJson); } catch (IOException e) { - ActionLogging.LogExperimentAction(experimentName, + Logging.LogExperimentAction(experimentName, " An exception happened: " + e.getMessage()); return null; } - ActionLogging.LogExperimentAction(experimentName, " Completed!"); + Logging.LogExperimentAction(experimentName, " Completed!"); return resultJson; } @@ -777,7 +777,7 @@ public class ExperimentApi { * @return the error that was produced or null if an error occurred */ public String getWorkflowJobError(String jobId, String experimentName) { - ActionLogging.LogExperimentAction(experimentName, " jobId : " + jobId); + Logging.LogExperimentAction(experimentName, " jobId : " + jobId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> callError = service.getErrorMessageOfWorkflowFromGalaxy(jobId, galaxyApiKey); @@ -786,7 +786,7 @@ public class ExperimentApi { try { Response<Object> response = callError.execute(); if (response.code() >= 400) { - ActionLogging.LogExperimentAction(experimentName, "Response code: " + Logging.LogExperimentAction(experimentName, "Response code: " + response.code() + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } @@ -796,19 +796,19 @@ public class ExperimentApi { JsonElement jsonElement = new JsonParser().parse(jsonString); JsonObject rootObject = jsonElement.getAsJsonObject(); fullError = rootObject.get("stderr").getAsString(); - ActionLogging.LogExperimentAction(experimentName, "Error: " + fullError); + Logging.LogExperimentAction(experimentName, "Error: " + fullError); String[] arrOfStr = fullError.split("ValueError", 0); String specError = arrOfStr[arrOfStr.length - 1]; returnError = specError.substring(1); - ActionLogging.LogExperimentAction(experimentName, "Parsed Error: " + returnError); + Logging.LogExperimentAction(experimentName, "Parsed Error: " + returnError); } catch (IOException e) { - ActionLogging.LogExperimentAction(experimentName, "Exception: " + e.getMessage()); + Logging.LogExperimentAction(experimentName, "Exception: " + e.getMessage()); return null; } - ActionLogging.LogExperimentAction(experimentName, "Completed successfully!"); + Logging.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 34f64984c..69e7f3ba9 100644 --- a/src/main/java/eu/hbp/mip/controllers/FilesAPI.java +++ b/src/main/java/eu/hbp/mip/controllers/FilesAPI.java @@ -5,8 +5,6 @@ import eu.hbp.mip.model.UserInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -15,9 +13,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.ActionLogging; - -import java.time.LocalDateTime; +import eu.hbp.mip.utils.Logging; /** * Created by mirco on 08.05.17. @@ -38,10 +34,10 @@ public class FilesAPI { @ApiParam(value = "filename", required = true) @PathVariable("filename") String filename ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(GET) /protected/{filename:.+}", "Loading protected file with filename : " + filename); + Logging.LogUserAction(user.getUsername(), "(GET) /protected/{filename:.+}", "Loading protected file with filename : " + filename); String filepath = "/protected/" + filename; - ActionLogging.LogUserAction(user.getUsername(), "(GET) /protected/{filename:.+}" + filepath, "Downloaded protected file"); + Logging.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 a5fc94b78..6a198cc0d 100644 --- a/src/main/java/eu/hbp/mip/controllers/MiningApi.java +++ b/src/main/java/eu/hbp/mip/controllers/MiningApi.java @@ -4,18 +4,12 @@ import eu.hbp.mip.utils.HTTPUtil; import com.google.gson.Gson; -import eu.hbp.mip.model.Mining; -import eu.hbp.mip.model.User; import eu.hbp.mip.model.UserInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.cache.annotation.Cacheable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; @@ -23,9 +17,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.ActionLogging; - -import org.springframework.web.bind.annotation.*; +import eu.hbp.mip.utils.Logging; import java.util.*; @@ -52,7 +44,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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Executing histogram..."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Executing histogram..."); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "MULTIPLE_HISTOGRAMS"; @@ -61,10 +53,10 @@ 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()); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Executed histogram with result :" + results.toString()); return ResponseEntity.ok(gson.toJson(results.toString())); } catch (IOException e) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Histogram algorithm was not found"); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /mining/histogram", "Histogram algorithm was not found"); return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } } @@ -72,7 +64,7 @@ public class MiningApi { @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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats", "Executing Exareme descriptive stats..."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats", "Executing Exareme descriptive stats..."); String query = gson.toJson(queryList); String url = queryExaremeUrl + "/" + "DESCRIPTIVE_STATS"; @@ -80,10 +72,10 @@ 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()); + Logging.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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats", "Descriptive stats algorithm was not found"); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats", "Descriptive stats algorithm was not found"); return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } } @@ -91,7 +83,7 @@ public class MiningApi { @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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats_v2", "Executing an Exareme descriptive stats v2"); + Logging.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"; @@ -100,10 +92,10 @@ 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()); + Logging.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) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats_v2", "Descriptive stats v2 algorithm was not found"); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/descriptive_stats_v2", "Descriptive stats v2 algorithm was not found"); return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND); } } @@ -111,7 +103,7 @@ public class MiningApi { @ApiOperation(value = "Check if a formula is valid", response = String.class) @RequestMapping(value = "/checkFormula", method = RequestMethod.POST) public ResponseEntity checkFormulaValidity(String formula) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/checkFormula", "Executing checkFormula ..."); + Logging.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 08f5199ea..6f013ee33 100644 --- a/src/main/java/eu/hbp/mip/controllers/ModelsApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ModelsApi.java @@ -11,13 +11,11 @@ import eu.hbp.mip.model.UserInfo; import eu.hbp.mip.model.Variable; import eu.hbp.mip.repositories.*; import io.swagger.annotations.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; 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.ActionLogging; +import eu.hbp.mip.utils.Logging; import java.io.IOException; import java.util.*; @@ -54,7 +52,7 @@ public class ModelsApi { @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 ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /models", "Loading models ..."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /models", "Loading models ..."); User user = userInfo.getUser(); @@ -81,7 +79,7 @@ public class ModelsApi { modelsList.add(m); } - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /models", "Successfully loaded " + modelsList.size() + " models."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /models", "Successfully loaded " + modelsList.size() + " models."); return ResponseEntity.ok(modelsList); } @@ -94,7 +92,7 @@ public class ModelsApi { @RequestBody @ApiParam(value = "Model to create", required = true) Model model ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /models", "Creating a model"); + Logging.LogUserAction(user.getUsername(), "(POST) /models", "Creating a model"); model.setTitle(model.getConfig().getTitle().get("text")); model.setCreatedBy(user); @@ -122,7 +120,7 @@ public class ModelsApi { } modelRepository.save(model); - ActionLogging.LogUserAction(user.getUsername(), "(POST) /models", "Created model with id : " + model.getSlug() + ", model.config and model.query"); + Logging.LogUserAction(user.getUsername(), "(POST) /models", "Created model with id : " + model.getSlug() + ", model.config and model.query"); return ResponseEntity.status(HttpStatus.CREATED).body(model); } @@ -181,17 +179,17 @@ public class ModelsApi { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(GET) /models/{slug}", "Loading model with id : " + slug); + Logging.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"); + Logging.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. "); + Logging.LogUserAction(user.getUsername(), "(GET) /models/{slug}", "You are not authorized to retrieve models. "); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } @@ -199,7 +197,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); + Logging.LogUserAction(user.getUsername(), "(GET) /models/{slug}", "Loaded model with id : " + slug); return ResponseEntity.ok(model); } @@ -212,7 +210,7 @@ public class ModelsApi { @RequestBody @ApiParam(value = "Model to update", required = true) Model model ) { User user = userInfo.getUser(); - ActionLogging.LogUserAction(user.getUsername(), "(PUT) /models/{slug}", "Updating model with id : " + slug); + Logging.LogUserAction(user.getUsername(), "(PUT) /models/{slug}", "Updating model with id : " + slug); Model oldModel = modelRepository.findOne(slug); if (!user.getUsername().equals(oldModel.getCreatedBy().getUsername())) { @@ -253,7 +251,7 @@ public class ModelsApi { datasetRepository.save(model.getDataset()); modelRepository.save(model); - ActionLogging.LogUserAction(user.getUsername(), "(PUT) /models/{slug}", "Updated model and saved/updated model.config and model.query"); + Logging.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 0469056a8..779169814 100644 --- a/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java +++ b/src/main/java/eu/hbp/mip/controllers/PathologiesApi.java @@ -11,10 +11,9 @@ 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.ActionLogging; +import eu.hbp.mip.utils.Logging; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; @@ -48,7 +47,7 @@ public class PathologiesApi { @RequestMapping(name = "/pathologies", method = RequestMethod.GET) public ResponseEntity<String> getPathologies(Authentication authentication) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /pathologies", "Loading pathologies ..."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /pathologies", "Loading pathologies ..."); // Load pathologies from file Resource resource = resourceLoader.getResource("file:/opt/portal/api/pathologies.json"); @@ -57,17 +56,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"); + Logging.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"); + Logging.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"); + Logging.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 a1eb3e8b7..4e412aea0 100644 --- a/src/main/java/eu/hbp/mip/controllers/SecurityApi.java +++ b/src/main/java/eu/hbp/mip/controllers/SecurityApi.java @@ -8,14 +8,13 @@ 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.ActionLogging; +import eu.hbp.mip.utils.Logging; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; @@ -45,7 +44,7 @@ public class SecurityApi { public Object user(Principal principal, HttpServletResponse response) { ObjectMapper mapper = new ObjectMapper(); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /user", "Loading user : " + userInfo.getUser().getUsername()); + Logging.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 +76,7 @@ public class SecurityApi { userRepository.save(user); } - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /user", "User has agreed on the NDA"); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /user", "User has agreed on the NDA"); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @@ -86,7 +85,7 @@ 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."); + Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /user/login/hbp", "Unathorized login."); httpServletResponse.sendRedirect(securityConfiguration.getFrontendRedirectAfterLogin()); } @@ -114,7 +113,7 @@ public class SecurityApi { JsonObject object = new JsonObject(); object.addProperty("authorization", stringEncoded); object.addProperty("context", galaxyContext); - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /user/galaxy", "Successfully Loaded galaxy information."); + Logging.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 77ef125db..8bd109e53 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.ActionLogging; +import eu.hbp.mip.utils.Logging; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; @@ -36,14 +36,14 @@ public class StatsApi { @ApiOperation(value = "Get general statistics", response = GeneralStats.class) @RequestMapping(method = RequestMethod.GET) public ResponseEntity<GeneralStats> getGeneralStatistics() { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /stats", "Loading general statistics"); + Logging.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."); + Logging.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 4dc7de343..b791a7858 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.ActionLogging; +import eu.hbp.mip.utils.Logging; 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 ) { - ActionLogging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /users/{username}", "Loaded a user with username : " + userInfo.getUser().getUsername()); + Logging.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/ClaimUtils.java b/src/main/java/eu/hbp/mip/utils/ClaimUtils.java index 2749a96d6..e71d3f190 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(",")); - ActionLogging.LogUserAction(username, "(POST) /experiments/runAlgorithm", userClaims.toString()); + Logging.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())) { - ActionLogging.LogUserAction(username, "(POST) /experiments/runAlgorithm", + Logging.LogUserAction(username, "(POST) /experiments/runAlgorithm", "You are not allowed to use dataset: " + dataset); return false; } } - ActionLogging.LogUserAction(username, "(POST) /experiments/runAlgorithm", + Logging.LogUserAction(username, "(POST) /experiments/runAlgorithm", "User is authorized to use the datasets: " + experimentDatasets); } return true; @@ -49,13 +49,13 @@ 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 --- - ActionLogging.LogUserAction(username, + Logging.LogUserAction(username, "(GET) /pathologies", "Filter out the unauthorised datasets."); List<String> userClaims = Arrays.asList(authorities.toString().toLowerCase() .replaceAll("[\\s+\\]\\[]", "").split(",")); - ActionLogging.LogUserAction(username, + Logging.LogUserAction(username, "(GET) /pathologies", "User Claims: " + userClaims); // If the "dataset_all" claim exists then return everything @@ -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()))) { - ActionLogging.LogUserAction(username, "(GET) /pathologies", + Logging.LogUserAction(username, "(GET) /pathologies", "Added dataset: " + dataset.getCode()); userPathologyDatasets.add(dataset); } } if (userPathologyDatasets.size() > 0) { - ActionLogging.LogUserAction(username, "(GET) /pathologies", + Logging.LogUserAction(username, "(GET) /pathologies", "Added pathology '" + curPathology.getLabel() + "' with datasets: '" + userPathologyDatasets + "'"); diff --git a/src/main/java/eu/hbp/mip/utils/ActionLogging.java b/src/main/java/eu/hbp/mip/utils/Logging.java similarity index 92% rename from src/main/java/eu/hbp/mip/utils/ActionLogging.java rename to src/main/java/eu/hbp/mip/utils/Logging.java index 7004fb89e..892181108 100644 --- a/src/main/java/eu/hbp/mip/utils/ActionLogging.java +++ b/src/main/java/eu/hbp/mip/utils/Logging.java @@ -3,11 +3,9 @@ package eu.hbp.mip.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.UUID; +public class Logging { -public class ActionLogging { - - private static final Logger LOGGER = LoggerFactory.getLogger(ActionLogging.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Logging.class); private static Integer maxEndpointLen = 5; private static Integer maxInfoLen = 5; -- GitLab From ac9030d2cbd8609d3ba2f47a9f314d8e649362b0 Mon Sep 17 00:00:00 2001 From: kfilippopolitis <kostasfilippop@gmail.com> Date: Wed, 14 Oct 2020 11:11:45 -0700 Subject: [PATCH 4/4] Update logs on /experiments/runAlgorithm to output the parameters of the algorithm --- .../eu/hbp/mip/controllers/ExperimentApi.java | 144 ++++++++++-------- src/main/java/eu/hbp/mip/utils/Logging.java | 34 +++-- 2 files changed, 99 insertions(+), 79 deletions(-) diff --git a/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java b/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java index e81d2ee5b..f05151474 100644 --- a/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java +++ b/src/main/java/eu/hbp/mip/controllers/ExperimentApi.java @@ -127,7 +127,16 @@ public class ExperimentApi { String algorithmType = experimentExecutionDTO.getAlgorithms().get(0).getType(); String algorithmName = experimentExecutionDTO.getAlgorithms().get(0).getName(); - Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Executing " + algorithmName + " with algorithmType : " + algorithmType + "."); + StringBuilder parametersLogMessage = new StringBuilder(", Parameters:\n"); + for (ExperimentExecutionDTO.AlgorithmExecutionDTO.AlgorithmExecutionParamDTO params : experimentExecutionDTO.getAlgorithms().get(0).getParameters()) { + parametersLogMessage + .append(" ") + .append(params.getLabel()) + .append(" -> ") + .append(params.getValue()) + .append("\n"); + } + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Executing " + algorithmName + parametersLogMessage); if (authenticationIsEnabled) { // Getting the dataset from the experiment parameters @@ -215,11 +224,11 @@ public class ExperimentApi { @RequestMapping(method = RequestMethod.GET, params = {"maxResultCount"}) public ResponseEntity<String> listExperiments( @ApiParam(value = "maxResultCount") @RequestParam int maxResultCount) { - - Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Listing experiments with a maximum amount of : " + maxResultCount + "."); + User user = userInfo.getUser(); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{maxResultCount}", "Listing experiments with a maximum amount of : " + maxResultCount + "."); List<Experiment> expList = doListExperiments(false, null); - Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{maxResultCount}", "Successfully listed experiments."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{maxResultCount}", "Successfully listed experiments."); return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); } @@ -228,8 +237,8 @@ public class ExperimentApi { @RequestMapping(method = RequestMethod.GET, params = {"slug", "maxResultCount"}) public ResponseEntity<String> listExperiments(@ApiParam(value = "slug") @RequestParam("slug") String modelSlug, @ApiParam(value = "maxResultCount") @RequestParam("maxResultCount") int maxResultCount) { - - Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Listing experiments with a maximum amount of :" + maxResultCount + "with modelSlug : " + modelSlug + "."); + User user = userInfo.getUser(); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Listing experiments with a maximum amount of :" + maxResultCount + "with modelSlug : " + modelSlug + "."); if (maxResultCount <= 0 || modelSlug == null || "".equals(modelSlug)) { return new ResponseEntity<>("You must provide at least a slug or a limit of result", @@ -237,16 +246,17 @@ public class ExperimentApi { } List<Experiment> expList = doListExperiments(false, null); - Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{slug}/{maxResultCount}", "Successfully listed my experiments."); + Logging.LogUserAction(user.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) { - Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{mine}", "Listing my experiments."); + User user = userInfo.getUser(); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{mine}", "Listing my experiments."); List<Experiment> expList = doListExperiments(true, null); - Logging.LogUserAction(userInfo.getUser().getUsername(), "(GET) /experiments/{mine}", "Successfully listed my experiments."); + Logging.LogUserAction(user.getUsername(), "(GET) /experiments/{mine}", "Successfully listed my experiments."); return new ResponseEntity<>(gsonOnlyExposed.toJson(expList), HttpStatus.OK); } @@ -285,7 +295,7 @@ public class ExperimentApi { } catch (IllegalArgumentException iae) { //LOGGER.trace("Invalid UUID", iae); //LOGGER.warn("An invalid Experiment UUID was received !"); - Logging.LogUserAction(userInfo.getUser().getUsername(), "List my experiments", "Listing my experiments."); + Logging.LogUserAction(user.getUsername(), "List my experiments", "Listing my experiments."); return ResponseEntity.badRequest().body("Invalid Experiment UUID"); } @@ -352,11 +362,11 @@ public class ExperimentApi { * @return the response to be returned */ public ResponseEntity<String> runExaremeAlgorithm(ExperimentExecutionDTO experimentExecutionDTO) { - Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Running the algorithm..."); + User user = userInfo.getUser(); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Running the algorithm..."); Experiment experiment = createExperiment(experimentExecutionDTO); - User user = userInfo.getUser(); - Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :" + experiment.getUuid()); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :" + experiment.getUuid()); // Run the 1st algorithm from the list String algorithmName = experimentExecutionDTO.getAlgorithms().get(0).getName(); @@ -377,20 +387,20 @@ public class ExperimentApi { "Starting exareme execution thread"); new Thread(() -> { // ATTENTION: Inside the Thread only LogExperimentAction should be used, not LogUserAction! - Logging.LogExperimentAction(experiment.getName(), "Thread named :" + Thread.currentThread().getName() + " with id :" + Thread.currentThread().getId() + " started!"); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Thread named :" + Thread.currentThread().getName() + " with id :" + Thread.currentThread().getId() + " started!"); try { StringBuilder results = new StringBuilder(); int code = HTTPUtil.sendPost(url, body, results); - Logging.LogExperimentAction(experiment.getName(), "Algorithm finished with code: " + code); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "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) { - Logging.LogExperimentAction(experiment.getName(), "There was an exception: " + e.getMessage()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "There was an exception: " + e.getMessage()); experiment.setHasError(true); experiment.setHasServerError(true); @@ -398,7 +408,7 @@ public class ExperimentApi { } finishExperiment(experiment); - Logging.LogExperimentAction(experiment.getName(), "Finished the experiment: " + experiment.toString()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Finished the experiment: " + experiment.toString()); }).start(); return response; @@ -414,11 +424,11 @@ public class ExperimentApi { * @return the response to be returned */ public ResponseEntity<String> runGalaxyWorkflow(ExperimentExecutionDTO experimentExecutionDTO) { - Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Running a workflow..."); + User user = userInfo.getUser(); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Running a workflow..."); Experiment experiment = createExperiment(experimentExecutionDTO); - Logging.LogUserAction(userInfo.getUser().getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :" + experiment.getUuid()); - User user = userInfo.getUser(); + Logging.LogUserAction(user.getUsername(), "(POST) /experiments/runAlgorithm", "Created experiment with uuid :" + experiment.getUuid()); // Run the 1st algorithm from the list @@ -539,38 +549,38 @@ public class ExperimentApi { new Thread(() -> { while (true) { // ATTENTION: Inside the Thread only LogExperimentAction should be used, not LogExperimentAction! - Logging.LogExperimentAction(experiment.getName(), "Thread is running..."); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Thread is running..."); try { sleep(2000); } catch (InterruptedException e) { - Logging.LogExperimentAction(experiment.getName(), "Sleep was disrupted: " + e.getMessage()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Sleep was disrupted: " + e.getMessage()); } - Logging.LogExperimentAction(experiment.getName(), "Fetching status for experiment Id: " + experiment.getUuid()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Fetching status for experiment Id: " + experiment.getUuid()); - String state = getWorkflowStatus(experiment.getWorkflowHistoryId(), experiment.getName()); - Logging.LogExperimentAction(experiment.getName(), "State is: " + state); + String state = getWorkflowStatus(experiment); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "State is: " + state); switch (state) { case "running": // Do nothing, when the experiment is created the status is set to running - Logging.LogExperimentAction(experiment.getName(), "Workflow is still running."); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Workflow is still running."); break; case "completed": // Get only the job result that is visible List<GalaxyWorkflowResult> workflowJobsResults = getWorkflowResults(experiment); - Logging.LogExperimentAction(experiment.getName(), "Results are: " + workflowJobsResults.toString()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Results are: " + workflowJobsResults.toString()); boolean resultFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getVisible()) { - Logging.LogExperimentAction(experiment.getName(), "Visible result are: " + jobResult.getId()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Visible result are: " + jobResult.getId()); String result = getWorkflowResultBody(experiment, jobResult.getId()); - Logging.LogExperimentAction(experiment.getName(), "Result: " + result); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -582,7 +592,7 @@ public class ExperimentApi { } if (!resultFound) { // If there is no visible result - Logging.LogExperimentAction(experiment.getName(), "No visible result"); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "No visible result"); experiment.setResult("[" + new ErrorResponse("The workflow has no visible result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -594,16 +604,16 @@ public class ExperimentApi { case "error": // Get the job result that failed workflowJobsResults = getWorkflowResults(experiment); - Logging.LogExperimentAction(experiment.getName(), "Error results are: " + workflowJobsResults.toString()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Error results are: " + workflowJobsResults.toString()); boolean failedJobFound = false; for (GalaxyWorkflowResult jobResult : workflowJobsResults) { if (jobResult.getState().equals("error")) { - Logging.LogExperimentAction(experiment.getName(), "Failed job is: " + jobResult.getId()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Failed job is: " + jobResult.getId()); - String result = getWorkflowJobError(jobResult.getId(), experiment.getName()); + String result = getWorkflowJobError(jobResult.getId(), experiment); - Logging.LogExperimentAction(experiment.getName(), "Job result: " + result); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Job result: " + result); if (result == null) { experiment.setHasError(true); experiment.setHasServerError(true); @@ -615,7 +625,7 @@ public class ExperimentApi { } if (!failedJobFound) { // If there is no visible failed job - Logging.LogExperimentAction(experiment.getName(), "No failed result"); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "No failed result"); experiment.setResult("[" + new ErrorResponse("The workflow has no failed result.").toString() + "]"); experiment.setHasError(true); experiment.setHasServerError(true); @@ -633,7 +643,7 @@ public class ExperimentApi { // If result exists return if (experiment.getResult() != null) { - Logging.LogExperimentAction(experiment.getName(), "Result exists: " + experiment.getResult()); + Logging.LogExperimentAction(experiment.getName(), experiment.getUuid(), "Result exists: " + experiment.getResult()); return; } } @@ -642,15 +652,19 @@ public class ExperimentApi { /** - * @param historyId The historyId of the workflow + * @param experiment The experiment of the workflow * @return "running" -> When the workflow is still running * "internalError" -> When an exception or a bad request occurred * "error" -> When the workflow produced an error * "completed" -> When the workflow completed successfully */ - public String getWorkflowStatus(String historyId, String experimentName) { + public String getWorkflowStatus(Experiment experiment) { + String historyId = experiment.getWorkflowHistoryId(); + String experimentName = experiment.getName(); + UUID experimentId = experiment.getUuid(); + // ATTENTION: This function is used from a Thread. Only LogExperimentAction should be used, not LogUserAction! - Logging.LogExperimentAction(experimentName, " History Id : " + historyId); + Logging.LogExperimentAction(experimentName, experimentId, " History Id : " + historyId); // Create the request client RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); @@ -660,16 +674,15 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, " Response code: " + Logging.LogExperimentAction(experimentName, experimentId, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return "internalError"; } result = new Gson().toJson(response.body()); - Logging.LogExperimentAction(experimentName, " Result: " + result); + Logging.LogExperimentAction(experimentName, experimentId, " Result: " + result); } catch (IOException e) { - Logging.LogExperimentAction(experimentName - , " An exception happened: " + e.getMessage()); + Logging.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return "internalError"; } @@ -678,12 +691,11 @@ public class ExperimentApi { JSONObject resultJson = new JSONObject(result); state = resultJson.getString("state"); } catch (JSONException e) { - Logging.LogExperimentAction(experimentName - , " An exception happened: " + e.getMessage()); + Logging.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return "internalError"; } - Logging.LogExperimentAction(experimentName, " Completed!"); + Logging.LogExperimentAction(experimentName, experimentId, " Completed!"); switch (state) { case "ok": return "completed"; @@ -707,7 +719,8 @@ public class ExperimentApi { String historyId = experiment.getWorkflowHistoryId(); String experimentName = experiment.getName(); - Logging.LogExperimentAction(experimentName, " historyId : " + historyId); + UUID experimentId = experiment.getUuid(); + Logging.LogExperimentAction(experimentName, experimentId, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<List<GalaxyWorkflowResult>> call = service.getWorkflowResultsFromGalaxy(historyId, galaxyApiKey); @@ -716,20 +729,19 @@ public class ExperimentApi { try { Response<List<GalaxyWorkflowResult>> response = call.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, " Response code: " + Logging.LogExperimentAction(experimentName, experimentId, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } getGalaxyWorkflowResultList = response.body(); - Logging.LogExperimentAction(experimentName, " Result: " + response.body()); + Logging.LogExperimentAction(experimentName, experimentId, " Result: " + response.body()); } catch (IOException e) { - Logging.LogExperimentAction(experimentName - , " An exception happened: " + e.getMessage()); + Logging.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return null; } - Logging.LogExperimentAction(experimentName, " Completed!"); + Logging.LogExperimentAction(experimentName, experimentId, " Completed!"); return getGalaxyWorkflowResultList; } @@ -743,8 +755,9 @@ public class ExperimentApi { String historyId = experiment.getWorkflowHistoryId(); String experimentName = experiment.getName(); + UUID experimentId = experiment.getUuid(); - Logging.LogExperimentAction(experimentName, " historyId : " + historyId); + Logging.LogExperimentAction(experimentName, experimentId, " historyId : " + historyId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> call = @@ -754,20 +767,20 @@ public class ExperimentApi { try { Response<Object> response = call.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, " Response code: " + Logging.LogExperimentAction(experimentName, experimentId, " Response code: " + response.code() + "" + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } resultJson = new Gson().toJson(response.body()); - Logging.LogExperimentAction(experimentName, " Result: " + resultJson); + Logging.LogExperimentAction(experimentName, experimentId, " Result: " + resultJson); } catch (IOException e) { - Logging.LogExperimentAction(experimentName, + Logging.LogExperimentAction(experimentName, experimentId, " An exception happened: " + e.getMessage()); return null; } - Logging.LogExperimentAction(experimentName, " Completed!"); + Logging.LogExperimentAction(experimentName, experimentId, " Completed!"); return resultJson; } @@ -776,8 +789,11 @@ 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, String experimentName) { - Logging.LogExperimentAction(experimentName, " jobId : " + jobId); + public String getWorkflowJobError(String jobId, Experiment experiment) { + String experimentName = experiment.getName(); + UUID experimentId = experiment.getUuid(); + + Logging.LogExperimentAction(experimentName, experimentId, " jobId : " + jobId); RetroFitGalaxyClients service = RetrofitClientInstance.getRetrofitInstance().create(RetroFitGalaxyClients.class); Call<Object> callError = service.getErrorMessageOfWorkflowFromGalaxy(jobId, galaxyApiKey); @@ -786,7 +802,7 @@ public class ExperimentApi { try { Response<Object> response = callError.execute(); if (response.code() >= 400) { - Logging.LogExperimentAction(experimentName, "Response code: " + Logging.LogExperimentAction(experimentName, experimentId, "Response code: " + response.code() + " with body: " + (response.errorBody() != null ? response.errorBody().string() : " ")); return null; } @@ -796,19 +812,19 @@ public class ExperimentApi { JsonElement jsonElement = new JsonParser().parse(jsonString); JsonObject rootObject = jsonElement.getAsJsonObject(); fullError = rootObject.get("stderr").getAsString(); - Logging.LogExperimentAction(experimentName, "Error: " + fullError); + Logging.LogExperimentAction(experimentName, experimentId, "Error: " + fullError); String[] arrOfStr = fullError.split("ValueError", 0); String specError = arrOfStr[arrOfStr.length - 1]; returnError = specError.substring(1); - Logging.LogExperimentAction(experimentName, "Parsed Error: " + returnError); + Logging.LogExperimentAction(experimentName, experimentId, "Parsed Error: " + returnError); } catch (IOException e) { - Logging.LogExperimentAction(experimentName, "Exception: " + e.getMessage()); + Logging.LogExperimentAction(experimentName, experimentId, "Exception: " + e.getMessage()); return null; } - Logging.LogExperimentAction(experimentName, "Completed successfully!"); + Logging.LogExperimentAction(experimentName, experimentId, "Completed successfully!"); return returnError; } diff --git a/src/main/java/eu/hbp/mip/utils/Logging.java b/src/main/java/eu/hbp/mip/utils/Logging.java index 892181108..f3ed45e83 100644 --- a/src/main/java/eu/hbp/mip/utils/Logging.java +++ b/src/main/java/eu/hbp/mip/utils/Logging.java @@ -3,34 +3,38 @@ package eu.hbp.mip.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.UUID; + public class Logging { private static final Logger LOGGER = LoggerFactory.getLogger(Logging.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); + LOGGER.info(" User -> " + userName + " ," + + calculateAdditionalSpacing(userName.length(), 8) + + "Endpoint -> " + endpoint + " ," + + calculateAdditionalSpacing(endpoint.length(), 32) + + "Info -> " + actionInfo); } // Used from Threads because threads can't get userName. - public static void LogExperimentAction(String experimentName, String actionInfo) { + public static void LogExperimentAction(String experimentName, UUID experimentId, String actionInfo) { LOGGER.info(" Experiment -> " + experimentName - + " , Info -> " + actionInfo); + + "(" + experimentId + ") ," + + calculateAdditionalSpacing(experimentName.length() + experimentId.toString().length() + 2, 20) + + "Info -> " + actionInfo); } // Used when a user is not authorised yet public static void LogAction(String actionName, String actionIdInfo) { - LOGGER.info(" Action -> " + actionName - + " , Info -> " + actionIdInfo); + LOGGER.info(" Action -> " + actionName + " ," + + calculateAdditionalSpacing(actionName.length() + 2, 20) + + "Info -> " + actionIdInfo); } + // Calculates the spacing that is needed to create consistent logs. + private static String calculateAdditionalSpacing(Integer currentLen, Integer maxLen) { + int additionalSpacing = (maxLen > currentLen ? maxLen - currentLen + 2 : 2); + return String.format("%" + additionalSpacing + "s", ""); + } } -- GitLab