diff --git a/pom.xml b/pom.xml index 7278b9324..11becf139 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ eusurvey eusurvey war - 1.4.4 + 1.4.5 1.8 4.3.20.RELEASE diff --git a/sonar-project.properties b/sonar-project.properties index e5391deea..338bbf1d5 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,6 +1,6 @@ sonar.projectKey=EUSURVEY sonar.projectName=eusurvey -sonar.projectVersion=1.4.4 +sonar.projectVersion=1.4.5 # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. # Since SonarQube 4.2, this property is optional if sonar.modules is set. diff --git a/src/main/java/com/ec/survey/controller/AddressBookController.java b/src/main/java/com/ec/survey/controller/AddressBookController.java index a822cae8e..922406944 100644 --- a/src/main/java/com/ec/survey/controller/AddressBookController.java +++ b/src/main/java/com/ec/survey/controller/AddressBookController.java @@ -316,7 +316,7 @@ public ModelAndView batchEdit(HttpServletRequest request) throws Exception { } @RequestMapping(value = "/batchEdit", method = RequestMethod.POST) - public ModelAndView batchEditPOST(HttpServletRequest request, Locale locale) throws IntrusionException, NotAgreedToTosException { + public ModelAndView batchEditPOST(HttpServletRequest request, Locale locale) throws IntrusionException, NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); boolean userChanged = false; @@ -1349,7 +1349,7 @@ public ModelAndView edit(@PathVariable("id") String id, HttpServletRequest reque } @RequestMapping( value = "/configureAttributes", method = RequestMethod.POST) - public String configureAttributes(HttpServletRequest request) throws NotAgreedToTosException { + public String configureAttributes(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); Map parameterMap = Ucs2Utf8.requestToHashMap(request); @@ -1389,7 +1389,7 @@ public String configureAttributes(HttpServletRequest request) throws NotAgreedTo } @RequestMapping(value = "/configureAttributesJSON", headers="Accept=*/*", method=RequestMethod.GET) - public @ResponseBody List configureAttributesJSON(HttpServletRequest request, HttpServletResponse response ) throws NotAgreedToTosException { + public @ResponseBody List configureAttributesJSON(HttpServletRequest request, HttpServletResponse response ) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); Map parameterMap = Ucs2Utf8.requestToHashMap(request); diff --git a/src/main/java/com/ec/survey/controller/AdministrationController.java b/src/main/java/com/ec/survey/controller/AdministrationController.java index 1530b3606..1b0c3c79e 100644 --- a/src/main/java/com/ec/survey/controller/AdministrationController.java +++ b/src/main/java/com/ec/survey/controller/AdministrationController.java @@ -12,6 +12,7 @@ import com.ec.survey.tools.RecreateAllOLAPTablesExecutor; import com.ec.survey.tools.Tools; import com.ec.survey.tools.UpdateAllOLAPTablesExecutor; +import com.ec.survey.tools.WeakAuthenticationException; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFRow; @@ -116,7 +117,7 @@ public class AdministrationController extends BasicController { } @RequestMapping(value = "/saveUserConfiguration", method = {RequestMethod.POST}) - public @ResponseBody String saveUserConfiguration(HttpServletRequest request) throws NotAgreedToTosException { + public @ResponseBody String saveUserConfiguration(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { int userId = sessionService.getCurrentUser(request).getId(); UsersConfiguration usersConfiguration = administrationService.getUsersConfiguration(userId); diff --git a/src/main/java/com/ec/survey/controller/BasicController.java b/src/main/java/com/ec/survey/controller/BasicController.java index d8985ba0b..851aab1ce 100644 --- a/src/main/java/com/ec/survey/controller/BasicController.java +++ b/src/main/java/com/ec/survey/controller/BasicController.java @@ -28,6 +28,7 @@ import org.springframework.web.servlet.ModelAndView; import com.ec.survey.exception.ForbiddenURLException; +import com.ec.survey.exception.FrozenSurveyException; import com.ec.survey.exception.InvalidURLException; import com.ec.survey.exception.MessageException; import com.ec.survey.exception.NoFormLoadedException; @@ -58,6 +59,7 @@ import com.ec.survey.tools.ConversionTools; import com.ec.survey.tools.InvalidXHTMLException; import com.ec.survey.tools.NotAgreedToTosException; +import com.ec.survey.tools.WeakAuthenticationException; import com.octo.captcha.service.CaptchaServiceException; import com.octo.captcha.service.multitype.MultiTypeCaptchaService; @@ -133,6 +135,8 @@ public class BasicController implements BeanFactoryAware { public @Value("${ecashost}") String ecashost; public @Value("${sender}") String sender; public @Value("${captcha.bypass:@null}") String bypassCaptcha; + public @Value("${ui.enablepublicsurveys}") String enablepublicsurveys; + //OCAS public @Value("${casoss}") String cassOss; protected @Value("${contextpath}") String contextpath; @@ -190,6 +194,22 @@ public boolean isByPassCaptcha(){ return bypassCaptcha !=null && bypassCaptcha.equalsIgnoreCase("true"); } + @ExceptionHandler(com.ec.survey.tools.Bad2faCredentialsException.class) + public ModelAndView handleBad2faCredentialsException(Exception e, HttpServletRequest request) { + logger.info(e.getLocalizedMessage(), e); + ModelAndView model = new ModelAndView("redirect:/errors/2fa.html"); + model.addObject("contextpath", contextpath); + return model; + } + + @ExceptionHandler(com.ec.survey.tools.FrozenCredentialsException.class) + public ModelAndView handleFrozenCredentialsException(Exception e, HttpServletRequest request) { + logger.info(e.getLocalizedMessage(), e); + ModelAndView model = new ModelAndView("redirect:/errors/frozen.html"); + model.addObject("contextpath", contextpath); + return model; + } + @ExceptionHandler(InvalidURLException.class) public ModelAndView handleInvalidURLException(Exception e, HttpServletRequest request) { logger.info(e.getLocalizedMessage(), e); @@ -199,6 +219,16 @@ public ModelAndView handleInvalidURLException(Exception e, HttpServletRequest re return model; } + @ExceptionHandler(FrozenSurveyException.class) + public ModelAndView handleFrozenSurveyException(Exception e, HttpServletRequest request, Locale locale) { + logger.error(e.getLocalizedMessage(), e); + ModelAndView model = new ModelAndView("error/generic"); + String message = resources.getMessage("error.FrozenSurvey", null, "This survey has been blocked due to an infringement to our policy. We are sorry for the inconvenience this may cause. Please try again later.", locale); + model.addObject("message", message); + model.addObject("contextpath", contextpath); + return model; + } + @ExceptionHandler(ForbiddenURLException.class) public ModelAndView handleForbiddenURLException(Exception e, HttpServletRequest request) { logger.info(e.getLocalizedMessage(), e); @@ -214,6 +244,16 @@ public ModelAndView handleNotAgreedToTosException(Exception e, HttpServletReques return model; } + @ExceptionHandler(WeakAuthenticationException.class) + public ModelAndView handleWeakAuthenticationException(Exception e, HttpServletRequest request, Locale locale) { + logger.error(e.getLocalizedMessage(), e); + ModelAndView model = new ModelAndView("error/generic"); + String message = resources.getMessage("error.WeakAuthentication", null, "Please log in using two factor authentication in order to access the system.", locale); + model.addObject("message", message); + model.addObject("contextpath", contextpath); + return model; + } + @ExceptionHandler(TooManyFiltersException.class) public ModelAndView handleTooManyFiltersException(Exception e, HttpServletRequest request, Locale locale) { logger.error(e.getLocalizedMessage(), e); diff --git a/src/main/java/com/ec/survey/controller/ContributionController.java b/src/main/java/com/ec/survey/controller/ContributionController.java index 76c7a39a7..af19f5aec 100644 --- a/src/main/java/com/ec/survey/controller/ContributionController.java +++ b/src/main/java/com/ec/survey/controller/ContributionController.java @@ -19,6 +19,8 @@ import com.ec.survey.tools.QuizHelper; import com.ec.survey.tools.SurveyHelper; import com.ec.survey.tools.Tools; +import com.ec.survey.tools.WeakAuthenticationException; + import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -57,7 +59,7 @@ public class ContributionController extends BasicController { private @Value("${export.fileDir}") String fileDir; private @Value("${server.prefix}") String serverPrefix; - public AnswerSet getAnswerSet(String code, HttpServletRequest request) throws NotAgreedToTosException + public AnswerSet getAnswerSet(String code, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { AnswerSet answerSet = null; User user = sessionService.getCurrentUser(request); diff --git a/src/main/java/com/ec/survey/controller/DashboardController.java b/src/main/java/com/ec/survey/controller/DashboardController.java index b6618d2c9..86fbe3d58 100644 --- a/src/main/java/com/ec/survey/controller/DashboardController.java +++ b/src/main/java/com/ec/survey/controller/DashboardController.java @@ -68,6 +68,8 @@ public ModelAndView dashboard(HttpServletRequest request, Locale locale, Model m archiveService.delete(archive); } + //check user (e.g. weak authentication) + sessionService.getCurrentUser(request); ModelAndView result = new ModelAndView("dashboard"); if (request.getParameter("archived") != null) @@ -82,6 +84,12 @@ public ModelAndView dashboard(HttpServletRequest request, Locale locale, Model m result.addObject("deleted", shortname); } + if (request.getParameter("frozen") != null) + { + String shortname = request.getParameter("frozen"); + result.addObject("frozen", shortname); + } + result.addObject("filter", new ArchiveFilter()); return result; @@ -281,8 +289,18 @@ public ModelAndView dashboard(HttpServletRequest request, Locale locale, Model m filter.setSortOrder(request.getParameter("asc") != null && request.getParameter("asc").equalsIgnoreCase("true") ? "ASC" : "DESC"); } + if (request.getParameter("reported") != null) + { + filter.setSurveys("REPORTED"); + } + + if (request.getParameter("frozen") != null) + { + filter.setSurveys("FROZEN"); + } + SqlPagination paging = new SqlPagination(page, 10); - List result = surveyService.getSurveysIncludingTranslationLanguages(filter, paging, false); + List result = surveyService.getSurveysIncludingTranslationLanguages(filter, paging, false, false); surveyService.generateAccessInformation(result, u); diff --git a/src/main/java/com/ec/survey/controller/ExportsController.java b/src/main/java/com/ec/survey/controller/ExportsController.java index 00ed041c1..0e7e0a42f 100644 --- a/src/main/java/com/ec/survey/controller/ExportsController.java +++ b/src/main/java/com/ec/survey/controller/ExportsController.java @@ -13,6 +13,7 @@ import com.ec.survey.service.SurveyService; import com.ec.survey.tools.NotAgreedToTosException; import com.ec.survey.tools.Tools; +import com.ec.survey.tools.WeakAuthenticationException; import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.StringUtils; import org.apache.poi.util.IOUtils; @@ -225,7 +226,7 @@ public class ExportsController extends BasicController { @RequestMapping(value = "/list") - public ModelAndView root(HttpServletRequest request) throws NotAgreedToTosException { + public ModelAndView root(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { sessionService.getCurrentUser(request); //default @@ -251,7 +252,7 @@ public ModelAndView root(HttpServletRequest request) throws NotAgreedToTosExcept } @RequestMapping(value = "/exportsjson", method = {RequestMethod.GET, RequestMethod.HEAD}) - public @ResponseBody List exportsjson(HttpServletRequest request) throws NotAgreedToTosException { + public @ResponseBody List exportsjson(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { int itemsPerPage = -1; int page = -1; @@ -396,7 +397,7 @@ public ResponseEntity downloadExport(@PathVariable int exportId, HttpSer } @RequestMapping(value = "/recreate/{exportId}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView recreateExport(@PathVariable int exportId, HttpServletRequest request, Locale locale) throws NotAgreedToTosException { + public ModelAndView recreateExport(@PathVariable int exportId, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { Export export = exportService.getExport(exportId, true); if (export == null || !(sessionService.checkUser(export.getUserId(), request) || sessionService.getCurrentUser(request).getGlobalPrivileges().get(GlobalPrivilege.FormManagement).equals(2))) { return new ModelAndView("error/generic", "message", "Access denied"); @@ -406,7 +407,7 @@ public ModelAndView recreateExport(@PathVariable int exportId, HttpServletReques } @RequestMapping(value = "/recreateMany/{exportIdList}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView recreateExport(@PathVariable String exportIdList, HttpServletRequest request, Locale locale) throws NotAgreedToTosException { + public ModelAndView recreateExport(@PathVariable String exportIdList, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { String[] exportIds = exportIdList.split("-"); List exports = new ArrayList<>(); diff --git a/src/main/java/com/ec/survey/controller/HomeController.java b/src/main/java/com/ec/survey/controller/HomeController.java index 58759711a..e1460322d 100644 --- a/src/main/java/com/ec/survey/controller/HomeController.java +++ b/src/main/java/com/ec/survey/controller/HomeController.java @@ -1,5 +1,6 @@ package com.ec.survey.controller; +import com.ec.survey.exception.InvalidURLException; import com.ec.survey.model.*; import com.ec.survey.model.administration.User; import com.ec.survey.model.survey.Survey; @@ -626,7 +627,7 @@ public ModelAndView processSubmit(HttpServletRequest request, Locale locale) { Survey survey = surveyService.getSurvey(Integer.parseInt(request.getParameter("survey.id")), false, true); - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); AnswerSet answerSet = SurveyHelper.parseAndMergeAnswerSet(request, survey, fileDir, uniqueCode, oldAnswerSet, oldAnswerSet.getLanguageCode(), user, fileService); saveAnswerSet(answerSet, fileDir, null, -1); @@ -670,6 +671,11 @@ public ModelAndView publicsurveysrunner(HttpServletRequest request) throws Excep public ModelAndView publicsurveys(HttpServletRequest request) throws Exception { + if (!enablepublicsurveys.equalsIgnoreCase("true")) + { + throw new InvalidURLException(); + } + SurveyFilter filter = sessionService.getSurveyFilter(request, false); filter.setUser(null); String newPage = request.getParameter("newPage"); @@ -723,6 +729,11 @@ else if (sortKey.equalsIgnoreCase("popularity")) @RequestMapping(value = "/home/publicsurveysjson", method = {RequestMethod.GET, RequestMethod.HEAD}) public @ResponseBody List publicsurveysjson(HttpServletRequest request) throws Exception { + if (!enablepublicsurveys.equalsIgnoreCase("true")) + { + throw new InvalidURLException(); + } + int itemsPerPage = 10; int newPage = 1; @@ -753,7 +764,7 @@ else if (sortKey.equalsIgnoreCase("popularity")) SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lastPublicSurveyFilter"); SqlPagination sqlPagination = new SqlPagination(newPage, itemsPerPage); - return surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false); + return surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, false); } @RequestMapping(value = "/validate/{id}/{code}", method = {RequestMethod.GET, RequestMethod.HEAD}) @@ -811,4 +822,82 @@ public void notifyError(HttpServletRequest request, Locale locale, HttpServletRe machineTranslationService.saveErrorResponse(requestId,targetLanguage,errorCode,errorMessage); } + @RequestMapping(value = "/home/reportAbuse", method = RequestMethod.GET) + public String reportAbuse (HttpServletRequest request, Locale locale, Model model) throws InvalidURLException { + model.addAttribute("lang", locale.getLanguage()); + model.addAttribute("runnermode", true); + + String surveyid = request.getParameter("survey"); + if (surveyid == null || surveyid.trim().length() == 0) + { + throw new InvalidURLException(); + } + + try { + int id = Integer.parseInt(surveyid); + + Survey survey = surveyService.getSurvey(id); + + if (survey == null) + { + throw new InvalidURLException(); + } + + model.addAttribute("AbuseSurvey", survey.getUniqueId()); + model.addAttribute("AbuseType", ""); + model.addAttribute("AbuseText", ""); + model.addAttribute("AbuseEmail", ""); + + } catch (NumberFormatException e) + { + throw new InvalidURLException(); + } + + return "home/reportabuse"; + } + + @RequestMapping(value = "home/reportAbuse", method = RequestMethod.POST) + public ModelAndView reportAbusePOST(HttpServletRequest request, Locale locale, HttpServletResponse response) throws NumberFormatException, Exception { + ModelAndView model = new ModelAndView("home/reportabuse"); + + String uid = request.getParameter("abuseSurvey"); + String type = request.getParameter("abuseType"); + String text = request.getParameter("abuseText"); + String email = request.getParameter("abuseEmail"); + + Survey survey = surveyService.getSurveyByUniqueId(uid, false, true); + + if (survey == null) + { + throw new InvalidURLException(); + } + + if (!checkCaptcha(request)) { + model.addObject("wrongcaptcha", true); + model.addObject("contextpath", contextpath); + + model.addObject("AbuseSurvey", uid); + model.addObject("AbuseType", type); + model.addObject("AbuseText", text); + model.addObject("AbuseEmail", email); + + return model; + } + + logger.info("HomeController.reportAbuse called with abuseType " + type); + + surveyService.reportAbuse(survey, type, text, email); + + model = new ModelAndView("error/info"); + String message = resources.getMessage("info.ReportAbuseSent", null, "The abuse has been reported to the team in charge of the service.", locale); + + model.addObject("message", message); + model.addObject("contextpath", contextpath); + + String link = serverPrefix + "runner/" + survey.getShortname(); + model.addObject("SurveyLink", link); + + return model; + } + } diff --git a/src/main/java/com/ec/survey/controller/HttpErrorController.java b/src/main/java/com/ec/survey/controller/HttpErrorController.java index b80cdf3ae..f51175461 100644 --- a/src/main/java/com/ec/survey/controller/HttpErrorController.java +++ b/src/main/java/com/ec/survey/controller/HttpErrorController.java @@ -51,6 +51,18 @@ public ModelAndView handleException(HttpServletRequest request){ request.getSession().setAttribute("lastErrorTime", new Date()); request.getSession().setAttribute("lastErrorURL", request.getAttribute("javax.servlet.error.request_uri")); return new ModelAndView("error/500","error","exception" ); + } + + @RequestMapping(value = "/2fa.html") + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public ModelAndView handle2fa(HttpServletRequest request){ + return new ModelAndView("error/2fa","error","exception" ); + } + + @RequestMapping(value = "/frozen.html") + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public ModelAndView handlefrozen(HttpServletRequest request){ + return new ModelAndView("error/frozen","error","exception" ); } } diff --git a/src/main/java/com/ec/survey/controller/LoginLogoutController.java b/src/main/java/com/ec/survey/controller/LoginLogoutController.java index 8c925fa81..7653690cc 100644 --- a/src/main/java/com/ec/survey/controller/LoginLogoutController.java +++ b/src/main/java/com/ec/survey/controller/LoginLogoutController.java @@ -9,6 +9,7 @@ import com.ec.survey.service.SessionService; import com.ec.survey.tools.NotAgreedToTosException; import com.ec.survey.tools.Tools; +import com.ec.survey.tools.WeakAuthenticationException; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -76,7 +77,7 @@ public String getLoginPageRunnerMode(@RequestParam(value="error", required=false } @RequestMapping(value = "/auth/login", method = {RequestMethod.GET, RequestMethod.HEAD}) - public String getLoginPage(@RequestParam(value="error", required=false) boolean error, HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException { + public String getLoginPage(@RequestParam(value="error", required=false) boolean error, HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { if (isShowEcas()) model.put("showecas", true); if (isCasOss()) model.put("casoss", true); @@ -138,7 +139,7 @@ public void surveylogin(@RequestParam(value="error", required=false) boolean err } @RequestMapping(value = "/auth/logout", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView getLogoutPage(HttpServletRequest request) { + public ModelAndView getLogoutPage(HttpServletRequest request) throws WeakAuthenticationException { ModelAndView result = new ModelAndView("home/welcome"); result.addObject("page", "welcome"); User user = null; @@ -146,6 +147,8 @@ public ModelAndView getLogoutPage(HttpServletRequest request) { user = sessionService.getCurrentUser(request); } catch (NotAgreedToTosException e) { //ignore + } catch (WeakAuthenticationException e) { + //ignore } if (user != null && user.getType().equalsIgnoreCase(User.ECAS)) diff --git a/src/main/java/com/ec/survey/controller/ManagementController.java b/src/main/java/com/ec/survey/controller/ManagementController.java index 87218f9ce..e8f642e54 100644 --- a/src/main/java/com/ec/survey/controller/ManagementController.java +++ b/src/main/java/com/ec/survey/controller/ManagementController.java @@ -1,6 +1,7 @@ package com.ec.survey.controller; import com.ec.survey.exception.ForbiddenURLException; +import com.ec.survey.exception.FrozenSurveyException; import com.ec.survey.exception.InvalidURLException; import com.ec.survey.exception.NoFormLoadedException; import com.ec.survey.model.*; @@ -59,8 +60,7 @@ public class ManagementController extends BasicController { public @Value("${opc.users}") String opcusers; public @Value("${opc.department:@null}") String opcdepartments; public @Value("${opc.template}") String opctemplatesurvey; - public @Value("${ui.enablepublicsurveys}") String enablepublicsurveys; - + @InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(ConversionTools.DateFormat); @@ -194,6 +194,7 @@ public ModelAndView overview(@PathVariable String shortname, HttpServletRequest Survey survey = surveyService.getSurveyByShortname(shortname, true, user, request, false, true, true, false); survey.setNumberOfAnswerSetsPublished(surveyService.getNumberPublishedAnswersFromMaterializedView(survey.getUniqueId())); + survey.setNumberOfReports(surveyService.getAbuseReportsForSurvey(survey.getUniqueId())); form = new Form(resources); @@ -341,7 +342,7 @@ public ModelAndView exportSurvey(@PathVariable String answers, @PathVariable Str paging.moveTo("1"); SqlPagination sqlPagination = paginationMapper.toSqlPagination(paging); - List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false); + List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, false); paging.setItems(surveys); result = new ModelAndView("forms/forms", "paging", paging); @@ -2594,6 +2595,11 @@ public ModelAndView test(@PathVariable String shortname, HttpServletRequest requ User u = sessionService.getCurrentUser(request); Survey survey = surveyService.getSurveyByShortname(shortname, true, u, request, true, true, true, false); + if (survey.getIsFrozen()) + { + throw new FrozenSurveyException(); + } + sessionService.upgradePrivileges(survey, u, request); Form form = new Form(survey, translationService.getTranslationsForSurvey(survey.getId(), true), survey.getLanguage(), resources,contextpath); diff --git a/src/main/java/com/ec/survey/controller/PDFController.java b/src/main/java/com/ec/survey/controller/PDFController.java index 3ce56dff5..48a908ad5 100644 --- a/src/main/java/com/ec/survey/controller/PDFController.java +++ b/src/main/java/com/ec/survey/controller/PDFController.java @@ -14,6 +14,7 @@ import com.ec.survey.tools.NotAgreedToTosException; import com.ec.survey.tools.SurveyExecutor; import com.ec.survey.tools.Tools; +import com.ec.survey.tools.WeakAuthenticationException; import org.apache.catalina.connector.ClientAbortException; import org.apache.commons.lang.StringUtils; @@ -328,7 +329,7 @@ private void SendFile(Survey survey, HttpServletRequest request, Locale locale, } @RequestMapping(value = "/answer/{code}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView answer(@PathVariable String code, HttpServletRequest request, Locale locale, HttpServletResponse response) throws InvalidURLException, NotAgreedToTosException, ForbiddenURLException { + public ModelAndView answer(@PathVariable String code, HttpServletRequest request, Locale locale, HttpServletResponse response) throws InvalidURLException, NotAgreedToTosException, ForbiddenURLException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); if (user == null) diff --git a/src/main/java/com/ec/survey/controller/RunnerController.java b/src/main/java/com/ec/survey/controller/RunnerController.java index 450233c5b..6f8744e9e 100644 --- a/src/main/java/com/ec/survey/controller/RunnerController.java +++ b/src/main/java/com/ec/survey/controller/RunnerController.java @@ -1,6 +1,7 @@ package com.ec.survey.controller; import com.ec.survey.exception.ForbiddenURLException; +import com.ec.survey.exception.FrozenSurveyException; import com.ec.survey.exception.InvalidURLException; import com.ec.survey.exception.SmtpServerNotConfiguredException; import com.ec.survey.model.*; @@ -118,7 +119,7 @@ public ModelAndView confirmation(HttpServletRequest request, HttpServletResponse } @RequestMapping(value = "/invited/{group}/{unique}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView invited(@PathVariable String group, @PathVariable String unique, HttpServletRequest request, Locale locale, Integer draftSurveyId, Device device) { + public ModelAndView invited(@PathVariable String group, @PathVariable String unique, HttpServletRequest request, Locale locale, Integer draftSurveyId, Device device) throws WeakAuthenticationException { boolean readonlyMode = false; String p = request.getParameter("readonly"); @@ -230,9 +231,14 @@ public ModelAndView invited(@PathVariable String group, @PathVariable String uni if (draftSurvey.getIsDeleted() || draftSurvey.getArchived()) { throw new InvalidURLException(); } - + if (!readonlyMode) return getEscapePageModel(draftSurvey, request, device); } + + if (draftSurvey.getIsFrozen()) + { + throw new FrozenSurveyException(); + } Form f = new Form(survey, translationService.getTranslationsForSurvey(survey.getId(), true), survey.getLanguage(), resources, contextpath); @@ -367,7 +373,7 @@ public ModelAndView invited(@PathVariable String group, @PathVariable String uni } @RequestMapping(value = "/{shortname}/{token}", method = RequestMethod.POST) - public ModelAndView runnerTokenPost(@PathVariable String shortname, @PathVariable String token, HttpServletRequest request, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException { + public ModelAndView runnerTokenPost(@PathVariable String shortname, @PathVariable String token, HttpServletRequest request, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException, FrozenSurveyException { Survey survey = surveyService.getSurveyByShortname(shortname, false, null, request, true, true, true, true); //(shortname, false, true, false, false, null, true); @@ -387,6 +393,11 @@ public ModelAndView runnerTokenPost(@PathVariable String shortname, @PathVariabl } } + if (survey.getIsFrozen()) + { + throw new FrozenSurveyException(); + } + try { // check for token @@ -458,7 +469,7 @@ public ModelAndView invitedPOST(@PathVariable String group, @PathVariable String } - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); AnswerSet answerSet = SurveyHelper.parseAnswerSet(request, survey, fileDir, uniqueCode, false, lang, user, fileService); if (survey != null) { @@ -737,7 +748,7 @@ public ModelAndView preparesurvey(@PathVariable String id, HttpServletRequest re } @RequestMapping(value = "/{uidorshortname}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView runner(@PathVariable String uidorshortname, HttpServletRequest request, HttpServletResponse response, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException { + public ModelAndView runner(@PathVariable String uidorshortname, HttpServletRequest request, HttpServletResponse response, Locale locale, Device device) throws InvalidURLException, ForbiddenURLException, WeakAuthenticationException, FrozenSurveyException { ModelAndView modelReturn= new ModelAndView(); boolean internalUsersOnly = false; @@ -806,7 +817,7 @@ public ModelAndView runner(@PathVariable String uidorshortname, HttpServletReque { try { - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); boolean ecasauthenticated = request.getSession().getAttribute("ECASSURVEY") != null && request.getSession().getAttribute("ECASSURVEY").toString().startsWith(uidorshortname); @@ -953,7 +964,7 @@ private ModelAndView getEscapePageModel(Survey survey, HttpServletRequest reques } } - private ModelAndView loadSurvey(Survey survey, HttpServletRequest request, HttpServletResponse response, Locale locale, String action, boolean passwordauthenticated, Device device, boolean readonlyMode) throws ForbiddenURLException { + private ModelAndView loadSurvey(Survey survey, HttpServletRequest request, HttpServletResponse response, Locale locale, String action, boolean passwordauthenticated, Device device, boolean readonlyMode) throws ForbiddenURLException, WeakAuthenticationException { if (survey != null) { String draftid = request.getParameter("draftid"); @@ -1290,7 +1301,7 @@ public ModelAndView processDraftSubmit(@PathVariable String mode, HttpServletReq if (!mode.equalsIgnoreCase("preview")) { - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); String draftid = request.getParameter("draftid"); Draft draft = null; @@ -1401,7 +1412,7 @@ public ModelAndView processDraftSubmit(@PathVariable String mode, HttpServletReq } else if (mode.equalsIgnoreCase("test")) { url = serverPrefix + survey.getShortname() + "/management/test?draftid=" + uid; } else if (mode.equalsIgnoreCase("runner")) { - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); if (survey.getEcasSecurity() && user != null) { url = serverPrefix + "runner/" + survey.getUniqueId(); @@ -1459,7 +1470,7 @@ public ModelAndView DraftSubmit(@PathVariable String draftid, HttpServletRequest String invitationId = draft.getAnswerSet().getInvitationId(); String uniqueCode = draft.getAnswerSet().getUniqueCode(); String lang = draft.getAnswerSet().getLanguageCode(); - String url = answerService.getDraftURL(draft.getAnswerSet(), draftid, sessionService.getCurrentUser(request, false)); + String url = answerService.getDraftURL(draft.getAnswerSet(), draftid, sessionService.getCurrentUser(request, false, false)); ModelAndView result = new ModelAndView("thanksdraftrunner", "url", url); @@ -1587,7 +1598,7 @@ public ModelAndView processSubmit(@PathVariable String uidorshortname, HttpServl ModelAndView err = testDraftAlreadySubmittedByUniqueCode(origsurvey, uniqueCode, locale); if (err != null) return err; - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); AnswerSet answerSet = SurveyHelper.parseAnswerSet(request, origsurvey, fileDir, uniqueCode, false, lang, user, fileService); String newlang = request.getParameter("newlang"); @@ -1959,7 +1970,7 @@ public ModelAndView processSubmit(@PathVariable String uidorshortname, HttpServl } @RequestMapping(value = "/elements/{id}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public @ResponseBody List element(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException { + public @ResponseBody List element(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException, WeakAuthenticationException { String ids = request.getParameter("ids"); if (ids == null) return null; @@ -1975,7 +1986,7 @@ public ModelAndView processSubmit(@PathVariable String uidorshortname, HttpServl boolean hasGlobalAdminRights = false; if (foreditor) { - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); if (user != null) { hasGlobalAdminRights = user.getGlobalPrivileges().get(GlobalPrivilege.FormManagement) == 2; diff --git a/src/main/java/com/ec/survey/controller/SettingsController.java b/src/main/java/com/ec/survey/controller/SettingsController.java index 33e13492d..d58444924 100644 --- a/src/main/java/com/ec/survey/controller/SettingsController.java +++ b/src/main/java/com/ec/survey/controller/SettingsController.java @@ -11,6 +11,8 @@ import com.ec.survey.tools.NotAgreedToTosException; import com.ec.survey.tools.Tools; import com.ec.survey.tools.Ucs2Utf8; +import com.ec.survey.tools.WeakAuthenticationException; + import org.apache.commons.validator.routines.EmailValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -50,19 +52,43 @@ public class SettingsController extends BasicController { @Autowired private LocaleResolver localeResolver; @RequestMapping(method = {RequestMethod.GET, RequestMethod.HEAD}) - public String root(Locale locale, Model model) { + public String root(HttpServletRequest request, Locale locale, Model model) throws NotAgreedToTosException, WeakAuthenticationException { + //check user (e.g. weak authentication) + sessionService.getCurrentUser(request); model.addAttribute("languages", surveyService.getLanguages()); return "settings/skin"; } @RequestMapping(value = "/myAccount", method = {RequestMethod.GET, RequestMethod.HEAD}) - public String myAccount(ModelMap model){ + public String myAccount(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ model.addAttribute("languages", surveyService.getLanguages()); + + String message = request.getParameter("message"); + if (message != null) + { + switch(message) + { + case "password": + model.addAttribute("message", resources.getMessage("info.PasswordChanged", null, "The password has been changed", locale)); + break; + case "email": + model.addAttribute("message", resources.getMessage("message.NewEmailAddressSend", null, "The email address will be changed after confirmation", locale)); + break; + case "language": + User user = sessionService.getCurrentUser(request); + model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", new Locale(user.getLanguage()))); + break; + case "pivot": + model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", locale)); + break; + } + } + return "settings/myAccount"; } @RequestMapping(value = "/changePassword", method = RequestMethod.POST) - public String changePassword(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException{ + public String changePassword(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ String oldPassword = request.getParameter("oldpassword"); String newPassword = request.getParameter("newpassword"); @@ -103,14 +129,13 @@ public String changePassword(HttpServletRequest request, ModelMap model, Locale user.setPassword(Tools.hash(newPassword + user.getPasswordSalt())); administrationService.updateUser(user); - sessionService.setCurrentUser(request, user); + sessionService.setCurrentUser(request, user); - model.addAttribute("message", resources.getMessage("info.PasswordChanged", null, "The password has been changed", locale)); - return "settings/myAccount"; + return "redirect:/settings/myAccount?message=password"; } @RequestMapping(value = "/changeEmail", method = RequestMethod.POST) - public String changeEmail(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException{ + public String changeEmail(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ String password = request.getParameter("password"); String email = request.getParameter("newemail"); @@ -157,12 +182,11 @@ public String changeEmail(HttpServletRequest request, ModelMap model, Locale loc return "settings/myAccount"; } - model.addAttribute("message", resources.getMessage("message.NewEmailAddressSend", null, "The email address will be changed after confirmation", locale)); - return "settings/myAccount"; + return "redirect:/settings/myAccount?message=email"; } @RequestMapping(value = "/changeLanguage", method = RequestMethod.POST) - public String changeLanguage(HttpServletRequest request, HttpServletResponse response, ModelMap model, Locale locale) throws NotAgreedToTosException{ + public String changeLanguage(HttpServletRequest request, HttpServletResponse response, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ String lang = request.getParameter("change-lang"); User user = sessionService.getCurrentUser(request); @@ -173,13 +197,12 @@ public String changeLanguage(HttpServletRequest request, HttpServletResponse res sessionService.setCurrentUser(request, user); localeResolver.setLocale(request, response, new Locale(user.getLanguage())); - model.addAttribute("languages", surveyService.getLanguages()); - model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", new Locale(user.getLanguage()))); - return "settings/myAccount"; + + return "redirect:/settings/myAccount?message=language"; } @RequestMapping(value = "/changePivotLanguage", method = RequestMethod.POST) - public String changePivotLanguage(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException{ + public String changePivotLanguage(HttpServletRequest request, ModelMap model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ String lang = request.getParameter("change-lang"); User user = sessionService.getCurrentUser(request); @@ -188,13 +211,11 @@ public String changePivotLanguage(HttpServletRequest request, ModelMap model, Lo administrationService.updateUser(user); sessionService.setCurrentUser(request, user); - model.addAttribute("languages", surveyService.getLanguages()); - model.addAttribute("message", resources.getMessage("message.LanguageChanged", null, "The language has been changed", locale)); - return "settings/myAccount"; + return "redirect:/settings/myAccount?message=pivot"; } @RequestMapping(value = "/shares") - public ModelAndView shares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException{ + public ModelAndView shares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ User user = sessionService.getCurrentUser(request); String delete = request.getParameter("delete"); @@ -230,7 +251,7 @@ public ModelAndView shares(HttpServletRequest request, Locale locale) throws Not } @RequestMapping(value = "/shareEdit/{pid}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView shareEdit(@PathVariable String pid, HttpServletRequest request, Locale locale) throws NotAgreedToTosException{ + public ModelAndView shareEdit(@PathVariable String pid, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ int id = Integer.parseInt(pid); User user = sessionService.getCurrentUser(request); Share share = attendeeService.getShare(id); @@ -280,7 +301,7 @@ public ModelAndView shareEdit(@PathVariable String pid, HttpServletRequest reque } @RequestMapping(value = "/createStaticShare", method = RequestMethod.POST) - public ModelAndView createShares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException{ + public ModelAndView createShares(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ User user = sessionService.getCurrentUser(request); diff --git a/src/main/java/com/ec/survey/controller/SkinController.java b/src/main/java/com/ec/survey/controller/SkinController.java index 4fa08e6b1..1817661a4 100644 --- a/src/main/java/com/ec/survey/controller/SkinController.java +++ b/src/main/java/com/ec/survey/controller/SkinController.java @@ -12,6 +12,8 @@ import com.ec.survey.tools.FileUtils; import com.ec.survey.tools.NotAgreedToTosException; import com.ec.survey.tools.Ucs2Utf8; +import com.ec.survey.tools.WeakAuthenticationException; + import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Controller; @@ -51,7 +53,7 @@ public class SkinController extends BasicController { private SessionFactory sessionFactory; @RequestMapping(value = "/skin", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView skins(HttpServletRequest request, Locale locale) throws NotAgreedToTosException{ + public ModelAndView skins(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException{ User user = sessionService.getCurrentUser(request); List skins = null; @@ -97,7 +99,7 @@ public ModelAndView skins(HttpServletRequest request, Locale locale) throws NotA } @RequestMapping(value = "/skin/new", method = {RequestMethod.GET, RequestMethod.HEAD}) - public String newSkin(Locale locale, Model model, HttpServletRequest request) throws NotAgreedToTosException { + public String newSkin(Locale locale, Model model, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { Survey demoSurvey = surveyService.getSurvey("SkinDemo", true, false, false, false, null, true, false); Form form = new Form(resources); @@ -111,7 +113,7 @@ public String newSkin(Locale locale, Model model, HttpServletRequest request) th } @RequestMapping(value = "/skin/edit/{id}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView editSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException { + public ModelAndView editSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); Survey demoSurvey = surveyService.getSurvey("SkinDemo", true, false, false, false, null, true, false); @@ -132,7 +134,7 @@ public ModelAndView editSkin(@PathVariable String id, Locale locale, HttpServlet } @RequestMapping(value = "/skin/delete/{id}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView deleteSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException { + public ModelAndView deleteSkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); @@ -156,7 +158,7 @@ public ModelAndView deleteSkin(@PathVariable String id, Locale locale, HttpServl } @RequestMapping(value = "/skin/copy/{id}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView copySkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException { + public ModelAndView copySkin(@PathVariable String id, Locale locale, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); Survey demoSurvey = surveyService.getSurvey("SkinDemo", true, false, false, false, null, true, false); @@ -185,7 +187,7 @@ public ModelAndView copySkin(@PathVariable String id, Locale locale, HttpServlet } @RequestMapping(value = "/skin/save", method = RequestMethod.POST) - public ModelAndView saveSkin(@ModelAttribute Skin skin, BindingResult bindingresult, HttpServletRequest request, Locale locale) throws NotAgreedToTosException { + public ModelAndView saveSkin(@ModelAttribute Skin skin, BindingResult bindingresult, HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); Map parameterMap = Ucs2Utf8.requestToHashMap(request); @@ -261,7 +263,7 @@ public ModelAndView saveSkin(@ModelAttribute Skin skin, BindingResult bindingres } @RequestMapping(value = "/skin/download/{id}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView download(@PathVariable String id, Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException { + public ModelAndView download(@PathVariable String id, Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); int skinId = Integer.parseInt(id); @@ -293,7 +295,7 @@ public ModelAndView download(@PathVariable String id, Locale locale, HttpServlet } @RequestMapping(value = "/skin/upload") - public void upload(Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException { + public void upload(Locale locale, HttpServletRequest request, HttpServletResponse response) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); String error = resources.getMessage("error.FileImportFailed", null, "The file could not be imported.", locale); diff --git a/src/main/java/com/ec/survey/controller/SurveyController.java b/src/main/java/com/ec/survey/controller/SurveyController.java index ae9bc2aa7..ef5c6e7f4 100644 --- a/src/main/java/com/ec/survey/controller/SurveyController.java +++ b/src/main/java/com/ec/survey/controller/SurveyController.java @@ -92,7 +92,7 @@ public ModelAndView surveys(HttpServletRequest request) throws NumberFormatExcep paging.moveTo(newPage); SqlPagination sqlPagination = paginationMapper.toSqlPagination(paging); - List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false); + List surveys = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, true); surveyService.generateAccessInformation(surveys, user); @@ -146,7 +146,7 @@ public ModelAndView surveys(HttpServletRequest request) throws NumberFormatExcep SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lastSurveyFilter"); SqlPagination sqlPagination = new SqlPagination(newPage, itemsPerPage); - List result = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false); + List result = surveyService.getSurveysIncludingTranslationLanguages(filter, sqlPagination, false, true); surveyService.generateAccessInformation(result, sessionService.getCurrentUser(request)); diff --git a/src/main/java/com/ec/survey/controller/SurveySearchController.java b/src/main/java/com/ec/survey/controller/SurveySearchController.java index 53b4d6eba..a5f8bf935 100644 --- a/src/main/java/com/ec/survey/controller/SurveySearchController.java +++ b/src/main/java/com/ec/survey/controller/SurveySearchController.java @@ -18,6 +18,7 @@ import com.ec.survey.tools.ConversionTools; import com.ec.survey.tools.NotAgreedToTosException; import com.ec.survey.tools.RestoreExecutor; +import com.ec.survey.tools.WeakAuthenticationException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -64,10 +65,8 @@ public class SurveySearchController extends BasicController { @RequestMapping(value = "/administration/surveysearch", method = {RequestMethod.GET, RequestMethod.HEAD}) public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale locale) { - ModelAndView result = new ModelAndView("administration/surveysearch"); - - SurveyFilter sfilter = new SurveyFilter(); - + ModelAndView result = new ModelAndView("administration/surveysearch"); + SurveyFilter sfilter = new SurveyFilter(); result.addObject("archivedfilter", new ArchiveFilter()); @@ -82,6 +81,28 @@ public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale result.addObject("deletedfilter", new DeletedSurveysFilter()); } + if (request.getParameter("reported") != null) + { + result.addObject("reported", true); + SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstreportedfilter"); + if (filter == null) filter = new SurveyFilter(); + result.addObject("reportedfilter", filter); + result.addObject("mode", "reported"); + } else { + result.addObject("reportedfilter", new SurveyFilter()); + } + + if (request.getParameter("frozen") != null) + { + result.addObject("frozen", true); + SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstfrozenfilter"); + if (filter == null) filter = new SurveyFilter(); + result.addObject("frozenfilter", filter); + result.addObject("mode", "frozen"); + } else { + result.addObject("frozenfilter", new SurveyFilter()); + } + if (request.getParameter("normaldeleted") != null) { String shortname = request.getParameter("normaldeleted"); @@ -102,6 +123,28 @@ public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale } } + if (request.getParameter("frozen") != null) + { + try { + result.addObject("frozen", true); + sfilter = (SurveyFilter) request.getSession().getAttribute("surveysearchfilter"); + result.addObject("mode", "existing"); + } catch (Exception e){ + //ignore + } + } + + if (request.getParameter("unfrozen") != null) + { + try { + result.addObject("unfrozen", true); + sfilter = (SurveyFilter) request.getSession().getAttribute("surveysearchfilter"); + result.addObject("mode", "existing"); + } catch (Exception e){ + //ignore + } + } + result.addObject("filter", sfilter); List domains = ldapDBService.getDomains(true, true, resources, locale); @@ -111,11 +154,13 @@ public ModelAndView surveysearch(HttpServletRequest request, Model model, Locale } @RequestMapping(value = "/administration/surveysearch", method = {RequestMethod.POST}) - public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException { + public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { String mode = request.getParameter("surveys"); SurveyFilter filter = new SurveyFilter(); + SurveyFilter reportedFilter = new SurveyFilter(); + SurveyFilter frozenFilter = new SurveyFilter(); ArchiveFilter archivedFilter = new ArchiveFilter(); DeletedSurveysFilter deletedSurveysFilter = new DeletedSurveysFilter(); @@ -141,6 +186,30 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo deletedSurveysFilter.setDeletedTo(ConversionTools.getDate(request.getParameter("deleteddeletedTo"))); request.getSession().setAttribute("lstdeletedfilter", deletedSurveysFilter); + } else if (mode.equalsIgnoreCase("reported")) + { + reportedFilter.setUser(sessionService.getCurrentUser(request)); + reportedFilter.setShortname(request.getParameter("reportedshortname")); + reportedFilter.setUid(request.getParameter("reporteduid")); + reportedFilter.setTitle(request.getParameter("reportedtitle")); + reportedFilter.setOwner(request.getParameter("reportedowner")); + reportedFilter.setPublishedFrom(ConversionTools.getDate(request.getParameter("reportedpublishedFrom"))); + reportedFilter.setPublishedTo(ConversionTools.getDate(request.getParameter("reportedpublishedTo"))); + reportedFilter.setFirstPublishedFrom(ConversionTools.getDate(request.getParameter("reportedfirstPublishedFrom"))); + reportedFilter.setFirstPublishedTo(ConversionTools.getDate(request.getParameter("reportedfirstPublishedTo"))); + request.getSession().setAttribute("lstreportedfilter", reportedFilter); + } else if (mode.equalsIgnoreCase("frozen")) + { + frozenFilter.setUser(sessionService.getCurrentUser(request)); + frozenFilter.setShortname(request.getParameter("frozenshortname")); + frozenFilter.setUid(request.getParameter("frozenuid")); + frozenFilter.setTitle(request.getParameter("frozentitle")); + frozenFilter.setOwner(request.getParameter("frozenowner")); + frozenFilter.setPublishedFrom(ConversionTools.getDate(request.getParameter("frozenpublishedFrom"))); + frozenFilter.setPublishedTo(ConversionTools.getDate(request.getParameter("frozenpublishedTo"))); + frozenFilter.setFirstPublishedFrom(ConversionTools.getDate(request.getParameter("frozenfirstPublishedFrom"))); + frozenFilter.setFirstPublishedTo(ConversionTools.getDate(request.getParameter("frozenfirstPublishedTo"))); + request.getSession().setAttribute("lstfrozenfilter", frozenFilter); } else { filter.setUser(sessionService.getCurrentUser(request)); filter.setShortname(request.getParameter("shortname")); @@ -159,6 +228,8 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo result.addObject("filter", filter); result.addObject("archivedfilter", archivedFilter); result.addObject("deletedfilter", deletedSurveysFilter); + result.addObject("reportedfilter", reportedFilter); + result.addObject("frozenfilter", frozenFilter); List domains = ldapDBService.getDomains(true, true, resources, locale); result.addObject("domains", domains); @@ -166,6 +237,35 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo return result; } + @RequestMapping(value = "/administration/freezesurvey", method = {RequestMethod.POST}) + public ModelAndView freezesurvey(HttpServletRequest request, Model model, Locale locale) throws Exception { + String surveyId = request.getParameter("surveyId"); + String emailText = request.getParameter("emailText"); + + if (surveyId == null || surveyId.length() == 0 || emailText == null || emailText.length() == 0) + { + throw new Exception("invalid parameters"); + } + + surveyService.freeze(surveyId, emailText); + + return new ModelAndView("redirect:/administration/surveysearch?frozen=1"); + } + + @RequestMapping(value = "/administration/unfreezesurvey", method = {RequestMethod.POST}) + public ModelAndView unfreezesurvey(HttpServletRequest request, Model model, Locale locale) throws Exception { + String surveyId = request.getParameter("surveyId"); + + if (surveyId == null || surveyId.length() == 0) + { + throw new Exception("invalid parameters"); + } + + surveyService.unfreeze(surveyId); + + return new ModelAndView("redirect:/administration/surveysearch?unfrozen=1"); + } + @RequestMapping(value = "/administration/surveysearchJSON", method = {RequestMethod.GET, RequestMethod.HEAD}) public @ResponseBody List resultsJSON(HttpServletRequest request) { @@ -269,8 +369,76 @@ public ModelAndView surveysearchPOST(HttpServletRequest request, Model model, Lo return surveys; } + @RequestMapping(value = "/administration/reportedsurveysjson", method = {RequestMethod.GET, RequestMethod.HEAD}) + public @ResponseBody List reportedsurveysjson(HttpServletRequest request) throws Exception { + try { + + String rows = request.getParameter("rows"); + if (rows == null) return null; + String page = request.getParameter("page"); + if (page == null) return null; + + SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstreportedfilter"); + if (filter == null) return null; + + filter.setSurveys("REPORTED"); + + SqlPagination sqlPagination = new SqlPagination(Integer.parseInt(page), Integer.parseInt(rows)); + List surveys = surveyService.getSurveysIncludingPublicationDates(filter, sqlPagination); + + for (Survey survey: surveys) + { + survey.setTitle(survey.cleanTitle()); + survey.setNumberOfDrafts(answerService.getNumberOfDrafts(survey.getId())); + survey.setNumberOfReports(surveyService.getAbuseReportsForSurvey(survey.getUniqueId())); + } + + return surveys; + } + catch (Exception e) + { + logger.error(e.getLocalizedMessage(), e); + } + + return null; + } + + @RequestMapping(value = "/administration/frozensurveysjson", method = {RequestMethod.GET, RequestMethod.HEAD}) + public @ResponseBody List frozensurveysjson(HttpServletRequest request) throws Exception { + try { + + String rows = request.getParameter("rows"); + if (rows == null) return null; + String page = request.getParameter("page"); + if (page == null) return null; + + SurveyFilter filter = (SurveyFilter) request.getSession().getAttribute("lstfrozenfilter"); + if (filter == null) return null; + + filter.setSurveys("FROZEN"); + + SqlPagination sqlPagination = new SqlPagination(Integer.parseInt(page), Integer.parseInt(rows)); + List surveys = surveyService.getSurveysIncludingPublicationDates(filter, sqlPagination); + + for (Survey survey: surveys) + { + survey.setTitle(survey.cleanTitle()); + survey.setNumberOfDrafts(answerService.getNumberOfDrafts(survey.getId())); + survey.setNumberOfReports(surveyService.getAbuseReportsForSurvey(survey.getUniqueId())); + } + + return surveys; + } + catch (Exception e) + { + logger.error(e.getLocalizedMessage(), e); + } + + return null; + } + @RequestMapping(value = "/administration/changeowner", method = {RequestMethod.POST}) - public @ResponseBody boolean changeowner(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException { + public @ResponseBody boolean changeowner(HttpServletRequest request, Model model, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { User u = sessionService.getCurrentUser(request); if (u.getGlobalPrivileges().get(GlobalPrivilege.SystemManagement) < 2) diff --git a/src/main/java/com/ec/survey/controller/SystemController.java b/src/main/java/com/ec/survey/controller/SystemController.java index f5d8f83ed..4176720b6 100644 --- a/src/main/java/com/ec/survey/controller/SystemController.java +++ b/src/main/java/com/ec/survey/controller/SystemController.java @@ -6,10 +6,14 @@ import com.ec.survey.model.administration.ComplexityParameters; import com.ec.survey.model.administration.GlobalPrivilege; import com.ec.survey.model.administration.User; +import com.ec.survey.service.MailService; import com.ec.survey.service.SessionService; import com.ec.survey.service.SettingsService; import com.ec.survey.service.SystemService; import com.ec.survey.tools.NotAgreedToTosException; +import com.ec.survey.tools.Tools; +import com.ec.survey.tools.WeakAuthenticationException; + import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @@ -40,7 +44,7 @@ public class SystemController extends BasicController { private SettingsService settingsService; @RequestMapping(value = "/message", method = {RequestMethod.GET, RequestMethod.HEAD}) - public @ResponseBody Message getSystemMessage(HttpServletRequest request) throws NotAgreedToTosException { + public @ResponseBody Message getSystemMessage(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); Message message; @@ -79,7 +83,7 @@ public class SystemController extends BasicController { } @RequestMapping(value = "/deletemessage", method = {RequestMethod.GET, RequestMethod.HEAD}) - public @ResponseBody String deleteMessage(HttpServletRequest request) throws NotAgreedToTosException + public @ResponseBody String deleteMessage(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { User user = sessionService.getCurrentUser(request); String sid = request.getParameter("id"); @@ -94,16 +98,16 @@ public class SystemController extends BasicController { } @RequestMapping(value = "/messages/runner", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView getSystemMessagesRunner(HttpServletRequest request) throws NotAgreedToTosException { + public ModelAndView getSystemMessagesRunner(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { return getSystemMessages(request, true); } @RequestMapping(value = "/messages", method = {RequestMethod.GET, RequestMethod.HEAD}) - public ModelAndView getSystemMessages(HttpServletRequest request) throws NotAgreedToTosException { + public ModelAndView getSystemMessages(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { return getSystemMessages(request, false); } - private ModelAndView getSystemMessages(HttpServletRequest request, boolean runnermode) throws NotAgreedToTosException { + private ModelAndView getSystemMessages(HttpServletRequest request, boolean runnermode) throws NotAgreedToTosException, WeakAuthenticationException { Message message = systemService.getMessage(); User user = sessionService.getCurrentUser(request); @@ -146,10 +150,197 @@ public ModelAndView system(HttpServletRequest request, Model model) { complexityParameterList.put(cp.getKey(), settingsService.get(cp.getKey())); } m.addObject("complexityParameters", complexityParameterList); + + m.addObject("reportMaxNumber", settingsService.get(Setting.MaxReports)); + m.addObject("reportMessageText", settingsService.get(Setting.ReportText)); + m.addObject("reportRecipients", settingsService.get(Setting.ReportRecipients)); + + m.addObject("banUserMessageText", settingsService.get(Setting.FreezeUserTextAdminBan)); + m.addObject("unbanUserMessageText", settingsService.get(Setting.FreezeUserTextAdminUnban)); + m.addObject("bannedUserRecipients", settingsService.get(Setting.BannedUserRecipients)); + + m.addObject("bannedUserMessageText", settingsService.get(Setting.FreezeUserTextBan)); + m.addObject("unbannedUserMessageText", settingsService.get(Setting.FreezeUserTextUnban)); + + m.addObject("trustIndicatorCreatorInternal", settingsService.get(Setting.TrustValueCreatorInternal)); + m.addObject("trustIndicatorMinimumPassMark", settingsService.get(Setting.TrustValueMinimumPassMark)); + m.addObject("trustIndicatorPastSurveys", settingsService.get(Setting.TrustValuePastSurveys)); + m.addObject("trustIndicatorPrivilegedUser", settingsService.get(Setting.TrustValuePrivilegedUser)); + m.addObject("trustIndicatorNbContributions", settingsService.get(Setting.TrustValueNbContributions)); return m; } + @RequestMapping(value ="/configureBanUsers", method = RequestMethod.POST) + public ModelAndView configureBanUsers( HttpServletRequest request, Locale locale) throws Exception { + String banUserMessageText = request.getParameter("banUserMessageText"); + + if (banUserMessageText == null || banUserMessageText.length() == 0) + { + throw new Exception("banUserMessageText must not be empty"); + } + + String unbanUserMessageText = request.getParameter("unbanUserMessageText"); + + if (unbanUserMessageText == null || unbanUserMessageText.length() == 0) + { + throw new Exception("unbanUserMessageText must not be empty"); + } + + String bannedUserMessageText = request.getParameter("bannedUserMessageText"); + + if (bannedUserMessageText == null || bannedUserMessageText.length() == 0) + { + throw new Exception("bannedUserMessageText must not be empty"); + } + + String unbannedUserMessageText = request.getParameter("unbannedUserMessageText"); + + if (unbannedUserMessageText == null || unbannedUserMessageText.length() == 0) + { + throw new Exception("unbannedUserMessageText must not be empty"); + } + + String[] emails = request.getParameterValues("messageEmail"); + String recipients = ""; + if (emails != null) + { + for (String email : emails) { + if (email.trim().length() > 0) + { + if (!MailService.isValidEmailAddress(email)) + { + throw new Exception("invalid email address:" + email); + } + + if (recipients.length() > 0) + { + recipients += ";"; + } + recipients += email; + } + } + } + + settingsService.update(Setting.BannedUserRecipients, recipients); + settingsService.update(Setting.FreezeUserTextAdminBan, banUserMessageText); + settingsService.update(Setting.FreezeUserTextAdminUnban, unbanUserMessageText); + settingsService.update(Setting.FreezeUserTextBan, bannedUserMessageText); + settingsService.update(Setting.FreezeUserTextUnban, unbannedUserMessageText); + + return new ModelAndView("redirect:/administration/system"); + } + + @RequestMapping(value ="/configureTrustIndicator", method = RequestMethod.POST) + public ModelAndView configureTrustIndicator( HttpServletRequest request, Locale locale) throws Exception { + String trustIndicatorCreatorInternal = request.getParameter("trustIndicatorCreatorInternal"); + + if (trustIndicatorCreatorInternal == null || trustIndicatorCreatorInternal.length() == 0) + { + throw new Exception("trustIndicatorCreatorInternal must not be empty"); + } + if (!Tools.isInteger(trustIndicatorCreatorInternal)) + { + throw new Exception("trustIndicatorCreatorInternal must be an integer"); + } + + String trustIndicatorMinimumPassMark = request.getParameter("trustIndicatorMinimumPassMark"); + + if (trustIndicatorMinimumPassMark == null || trustIndicatorMinimumPassMark.length() == 0) + { + throw new Exception("trustIndicatorMinimumPassMark must not be empty"); + } + if (!Tools.isInteger(trustIndicatorMinimumPassMark)) + { + throw new Exception("trustIndicatorMinimumPassMark must be an integer"); + } + + String trustIndicatorPastSurveys = request.getParameter("trustIndicatorPastSurveys"); + + if (trustIndicatorPastSurveys == null || trustIndicatorPastSurveys.length() == 0) + { + throw new Exception("trustIndicatorPastSurveys must not be empty"); + } + if (!Tools.isInteger(trustIndicatorPastSurveys)) + { + throw new Exception("trustIndicatorPastSurveys must be an integer"); + } + + String trustIndicatorPrivilegedUser = request.getParameter("trustIndicatorPrivilegedUser"); + + if (trustIndicatorPrivilegedUser == null || trustIndicatorPrivilegedUser.length() == 0) + { + throw new Exception("trustIndicatorPrivilegedUser must not be empty"); + } + if (!Tools.isInteger(trustIndicatorPrivilegedUser)) + { + throw new Exception("trustIndicatorPrivilegedUser must be an integer"); + } + + String trustIndicatorNbContributions = request.getParameter("trustIndicatorNbContributions"); + + if (trustIndicatorNbContributions == null || trustIndicatorNbContributions.length() == 0) + { + throw new Exception("trustIndicatorNbContributions must not be empty"); + } + if (!Tools.isInteger(trustIndicatorNbContributions)) + { + throw new Exception("trustIndicatorNbContributions must be an integer"); + } + + settingsService.update(Setting.TrustValueCreatorInternal, trustIndicatorCreatorInternal); + settingsService.update(Setting.TrustValuePastSurveys, trustIndicatorPastSurveys); + settingsService.update(Setting.TrustValuePrivilegedUser, trustIndicatorPrivilegedUser); + settingsService.update(Setting.TrustValueMinimumPassMark, trustIndicatorMinimumPassMark); + settingsService.update(Setting.TrustValueNbContributions, trustIndicatorNbContributions); + + return new ModelAndView("redirect:/administration/system"); + } + + @RequestMapping(value ="/configureReports", method = RequestMethod.POST) + public ModelAndView configureReports( HttpServletRequest request, Locale locale) throws Exception { + String number = request.getParameter("maxNumber"); + + if (number == null || !Tools.isInteger(number)) + { + throw new Exception("Invalid number"); + } + + String text = request.getParameter("messageText"); + + if (text == null || text.length() == 0) + { + throw new Exception("text must not be empty"); + } + + String[] emails = request.getParameterValues("messageEmail"); + String recipients = ""; + if (emails != null) + { + for (String email : emails) { + if (email.trim().length() > 0) + { + if (!MailService.isValidEmailAddress(email)) + { + throw new Exception("invalid email address:" + email); + } + + if (recipients.length() > 0) + { + recipients += ";"; + } + recipients += email; + } + } + } + + settingsService.update(Setting.MaxReports, number); + settingsService.update(Setting.ReportText, text); + settingsService.update(Setting.ReportRecipients, recipients); + + return new ModelAndView("redirect:/administration/system"); + } + @RequestMapping(value ="/configureLogging", method = RequestMethod.POST) public ModelAndView configureLogging(@RequestParam("enabled") String enabled, HttpServletRequest request, Locale locale) { settingsService.update(Setting.ActivityLoggingEnabled, enabled); diff --git a/src/main/java/com/ec/survey/controller/TranslationController.java b/src/main/java/com/ec/survey/controller/TranslationController.java index 39473a03d..e4a90a2ef 100644 --- a/src/main/java/com/ec/survey/controller/TranslationController.java +++ b/src/main/java/com/ec/survey/controller/TranslationController.java @@ -398,7 +398,7 @@ public void deletetranslations(HttpServletRequest request, Locale locale, HttpSe } @RequestMapping(value = "/translatetranslations", method = RequestMethod.GET) - public void translateTranslations(HttpServletRequest request, Locale locale, HttpServletResponse response) throws NotAgreedToTosException, ForbiddenURLException { + public void translateTranslations(HttpServletRequest request, Locale locale, HttpServletResponse response) throws NotAgreedToTosException, ForbiddenURLException, WeakAuthenticationException { String idsString = request.getParameter("translationIds"); String[] ids = idsString.split("\\|"); User user = sessionService.getCurrentUser(request); @@ -454,7 +454,7 @@ public void cancelTranslation(HttpServletRequest request, Locale locale, HttpSer } @RequestMapping(value = "/activatetranslation", method = RequestMethod.POST) - public @ResponseBody SimpleResult activatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException { + public @ResponseBody SimpleResult activatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { String id = request.getParameter("id"); SimpleResult result = new SimpleResult(); @@ -484,7 +484,7 @@ public void cancelTranslation(HttpServletRequest request, Locale locale, HttpSer } @RequestMapping(value = "/deactivatetranslation", method = RequestMethod.POST) - public @ResponseBody SimpleResult deactivatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException { + public @ResponseBody SimpleResult deactivatetranslations(HttpServletRequest request, Locale locale) throws NotAgreedToTosException, WeakAuthenticationException { String id = request.getParameter("id"); SimpleResult result = new SimpleResult(); @@ -824,7 +824,7 @@ public ModelAndView addtranslations(@PathVariable String shortname, HttpServletR } @RequestMapping(value = "/importtranslation", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8") - public @ResponseBody String importtranslation(@PathVariable String shortname, HttpServletRequest request, HttpServletResponse response, Locale locale) throws IOException, NotAgreedToTosException, ForbiddenURLException { + public @ResponseBody String importtranslation(@PathVariable String shortname, HttpServletRequest request, HttpServletResponse response, Locale locale) throws IOException, NotAgreedToTosException, ForbiddenURLException, WeakAuthenticationException { ImportTranslationResult result = new ImportTranslationResult(); ObjectMapper mapper = new ObjectMapper(); diff --git a/src/main/java/com/ec/survey/controller/UserController.java b/src/main/java/com/ec/survey/controller/UserController.java index 7c0bf7e84..5f81c7054 100644 --- a/src/main/java/com/ec/survey/controller/UserController.java +++ b/src/main/java/com/ec/survey/controller/UserController.java @@ -1,6 +1,7 @@ package com.ec.survey.controller; import com.ec.survey.model.Paging; +import com.ec.survey.model.Setting; import com.ec.survey.model.SqlPagination; import com.ec.survey.model.UserFilter; import com.ec.survey.model.UsersConfiguration; @@ -79,7 +80,36 @@ public ModelAndView users(HttpServletRequest request, Model model) throws Except if (usersConfiguration == null) usersConfiguration = new UsersConfiguration(); m.addObject("usersConfiguration", usersConfiguration); - return m; + m.addObject("freezeusertext", settingsService.get(Setting.FreezeUserTextBan)); + m.addObject("unfreezeusertext", settingsService.get(Setting.FreezeUserTextUnban)); + + return m; + } + + @RequestMapping(value = "/banuser", method = RequestMethod.POST) + public ModelAndView banuser(@RequestParam("userId") String userId, @RequestParam("emailText") String emailText, HttpServletRequest request, Model model) throws Exception { + + if (userId == null || userId.length() == 0 || emailText == null || emailText.length() == 0) + { + throw new Exception("invalid input data"); + } + + administrationService.banUser(userId, emailText); + + return new ModelAndView("redirect:/administration/users?frozen=1"); + } + + @RequestMapping(value = "/unbanuser", method = RequestMethod.POST) + public ModelAndView unbanuser(@RequestParam("userId") String userId, HttpServletRequest request, Model model) throws Exception { + + if (userId == null || userId.length() == 0) + { + throw new Exception("invalid input data"); + } + + administrationService.unbanUser(userId); + + return new ModelAndView("redirect:/administration/users?unfrozen=1"); } @RequestMapping(value = "/createUser", method = RequestMethod.POST) @@ -100,7 +130,7 @@ public ModelAndView createUser(@RequestParam("add-login") String login, @Request if (Tools.isPasswordWeak(password)) { model.addAttribute("error", resources.getMessage("error.PasswordWeak", null, "This password does not fit our password policy. Please choose a password between 8 and 16 characters with at least one digit and one non-alphanumeric characters (e.g. !?$&%...).", locale)); - } else { + } else { User user = new User(); user.setValidated(true); user.setLogin(login); @@ -114,19 +144,24 @@ public ModelAndView createUser(@RequestParam("add-login") String login, @Request user.setLanguage(language); user.setType(User.SYSTEM); - if (roles != null && roles.length() > 0) + if (!administrationService.checkEmailsNotBanned(user.getAllEmailAddresses())) { - String[] ids = roles.split(";"); - Map rolesById = administrationService.getAllRolesAsMap(); - for (String id : ids) { - if (rolesById.containsKey(Integer.parseInt(id))) - { - user.getRoles().add(rolesById.get(Integer.parseInt(id))); - } - } + model.addAttribute("error", resources.getMessage("error.EmailBanned", null, "This email adress belongs to a banned user.", locale)); + } else { + if (roles != null && roles.length() > 0) + { + String[] ids = roles.split(";"); + Map rolesById = administrationService.getAllRolesAsMap(); + for (String id : ids) { + if (rolesById.containsKey(Integer.parseInt(id))) + { + user.getRoles().add(rolesById.get(Integer.parseInt(id))); + } + } + } + + administrationService.createUser(user); } - - administrationService.createUser(user); } } else { model.addAttribute("error", resources.getMessage("error.LoginExists", null, "This login already exists. Please choose a unique login.", locale)); @@ -201,5 +236,5 @@ public ModelAndView deleteUser(@RequestParam("id") String id, HttpServletRequest } return users(request, model); } - + } diff --git a/src/main/java/com/ec/survey/exception/FrozenSurveyException.java b/src/main/java/com/ec/survey/exception/FrozenSurveyException.java new file mode 100644 index 000000000..a998a6d8f --- /dev/null +++ b/src/main/java/com/ec/survey/exception/FrozenSurveyException.java @@ -0,0 +1,11 @@ +package com.ec.survey.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class FrozenSurveyException extends Exception { + + private static final long serialVersionUID = 1L; + +} diff --git a/src/main/java/com/ec/survey/model/Abuse.java b/src/main/java/com/ec/survey/model/Abuse.java new file mode 100644 index 000000000..5cb9cb6d9 --- /dev/null +++ b/src/main/java/com/ec/survey/model/Abuse.java @@ -0,0 +1,93 @@ +package com.ec.survey.model; + +import org.apache.log4j.Logger; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; +import org.springframework.format.annotation.DateTimeFormat; + +import com.ec.survey.tools.ConversionTools; + +import java.util.Date; + +import javax.persistence.*; + +/** + * Represents a abuse information for + * a survey + */ +@Entity +@Table(name = "SURABUSE", indexes = {@Index(name="IDX_SURABUSE",columnList = "SURABUSE_SURVEY, SURABUSE_DATE")}) +@Cacheable +@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) +public class Abuse { + + private int id; + private String surveyUid; + private String type; + private String text; + private String email; + private Date created; + + protected static final Logger logger = Logger.getLogger(Abuse.class); + + public Abuse(String surveyUid, String type, String text, String email) + { + this.surveyUid = surveyUid; + this.type = type; + this.text = text; + this.email = email; + this.created = new Date(); + } + + @Id + @Column(name = "SURABUSE_ID") + @GeneratedValue + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + + @Temporal(TemporalType.TIMESTAMP) + @DateTimeFormat(pattern=ConversionTools.DateTimeFormat) + @Column(name = "SURABUSE_DATE") + public Date getCreated() { + return created; + } + public void setCreated(Date created) { + this.created = created; + } + + @Column(name = "SURABUSE_SURVEY") + public String getSurveyUid() { + return surveyUid; + } + public void setSurveyUid(String surveyUid) { + this.surveyUid = surveyUid; + } + + @Column(name = "SURABUSE_TYPE") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + @Column(name = "SURABUSE_TEXT") + public String getText() { + return text; + } + public void setText(String text) { + this.text = text; + } + + @Column(name = "SURABUSE_EMAIL") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } +} diff --git a/src/main/java/com/ec/survey/model/Setting.java b/src/main/java/com/ec/survey/model/Setting.java index 50fbd4a31..212f284bf 100644 --- a/src/main/java/com/ec/survey/model/Setting.java +++ b/src/main/java/com/ec/survey/model/Setting.java @@ -38,7 +38,24 @@ public class Setting { public final static String ReportingMigrationStart = "ReportingMigrationStart"; public final static String ReportingMigrationTime = "ReportingMigrationTime"; public final static String ReportingMigrationSurveyToMigrate = "ReportingMigrationSurveyToMigrate"; - + + public final static String WeakAuthenticationDisabled = "WeakAuthenticationDisabled"; + public final static String MaxReports = "MaxReports"; + public final static String ReportText = "ReportText"; + public final static String ReportRecipients = "ReportRecipients"; + + public final static String FreezeUserTextAdminBan = "FreezeUserTextAdminBan"; + public final static String FreezeUserTextAdminUnban = "FreezeUserTextAdminUnban"; + public final static String FreezeUserTextBan = "FreezeUserTextBan"; + public final static String FreezeUserTextUnban = "FreezeUserTextUnban"; + public final static String BannedUserRecipients = "BannedUserRecipients"; + + public final static String TrustValueCreatorInternal = "TrustValueCreatorInternal"; + public final static String TrustValuePastSurveys = "TrustValuePastSurveys"; + public final static String TrustValuePrivilegedUser = "TrustValuePrivilegedUser"; + public final static String TrustValueNbContributions = "TrustValueNbContributions"; + public final static String TrustValueMinimumPassMark = "TrustValueMinimumPassMark"; + @Id @Column(name = "SETTINGS_ID") @GeneratedValue diff --git a/src/main/java/com/ec/survey/model/UserFilter.java b/src/main/java/com/ec/survey/model/UserFilter.java index ec9ef4d86..419eef37d 100644 --- a/src/main/java/com/ec/survey/model/UserFilter.java +++ b/src/main/java/com/ec/survey/model/UserFilter.java @@ -4,6 +4,8 @@ public class UserFilter { private String login; private String email; private String comment; + private Boolean banned; + private Boolean unbanned; private Boolean ECAS; private Boolean system; private Boolean ECASaccess; @@ -115,4 +117,17 @@ public Boolean getNoECaccess() { public void setNoECaccess(Boolean noECaccess) { NoECaccess = noECaccess; } + + public Boolean getBanned() { + return banned; + } + public void setBanned(Boolean banned) { + this.banned = banned; + } + public Boolean getUnbanned() { + return this.unbanned; + } + public void setUnbanned(Boolean unbanned) { + this.unbanned = unbanned; + } } diff --git a/src/main/java/com/ec/survey/model/UsersConfiguration.java b/src/main/java/com/ec/survey/model/UsersConfiguration.java index 5b4f5dcfb..e2bc5b034 100644 --- a/src/main/java/com/ec/survey/model/UsersConfiguration.java +++ b/src/main/java/com/ec/survey/model/UsersConfiguration.java @@ -25,6 +25,7 @@ public class UsersConfiguration implements java.io.Serializable { private boolean showLanguage = true; private boolean showRoles = false; private boolean showComment = false; + private boolean showBanned = true; @Id @Column(name = "UC_ID") @@ -92,4 +93,12 @@ public void setShowComment(boolean showComment) { this.showComment = showComment; } + @Column(name = "UC_BANNED") + public boolean getShowBanned() { + return showBanned; + } + public void setShowBanned(Boolean showBanned) { + this.showBanned = showBanned != null ? showBanned : true; + } + } diff --git a/src/main/java/com/ec/survey/model/administration/User.java b/src/main/java/com/ec/survey/model/administration/User.java index 17b0bfce0..2c3ccb9ea 100644 --- a/src/main/java/com/ec/survey/model/administration/User.java +++ b/src/main/java/com/ec/survey/model/administration/User.java @@ -49,6 +49,7 @@ public class User implements java.io.Serializable { private boolean agreedToToS; private Integer lastEditedSurvey; private boolean canCreateSurveys = true; + private boolean isFrozen = false; public static final String ECAS = "ECAS"; public static final String SYSTEM = "SYSTEM"; @@ -290,6 +291,14 @@ public void setLastEditedSurvey(Integer lastEditedSurvey) { this.lastEditedSurvey = lastEditedSurvey; } + @Column(name = "USER_FROZEN") + public boolean isFrozen() { + return isFrozen; + } + public void setFrozen(Boolean isFrozen) { + this.isFrozen = isFrozen != null ? isFrozen : false; + } + @Transient public String getName() { @@ -442,7 +451,7 @@ public boolean isCanCreateSurveys() { public void setCanCreateSurveys(boolean canCreateSurveys) { this.canCreateSurveys = canCreateSurveys; } - + @Transient public List getAllEmailAddresses() { List result = new ArrayList(); diff --git a/src/main/java/com/ec/survey/model/survey/Survey.java b/src/main/java/com/ec/survey/model/survey/Survey.java index 19afe7dd9..0477a37d4 100644 --- a/src/main/java/com/ec/survey/model/survey/Survey.java +++ b/src/main/java/com/ec/survey/model/survey/Survey.java @@ -91,6 +91,7 @@ public class Survey implements java.io.Serializable { private int numberOfDrafts; private int numberOfInvitations; private int numberOfAnswerSetsPublished; + private int numberOfReports; private int compulsoryStyle; private boolean isActive; // true if the survey is accessible on the web, isActive is valid for draft and survey objects private boolean isDraft; @@ -121,6 +122,7 @@ public class Survey implements java.io.Serializable { private boolean wcagCompliance; private boolean isArchived; private Boolean isDeleted; + private Boolean isFrozen; private boolean ecasSecurity; private String ecasMode; private Boolean logoInInfo; @@ -138,6 +140,7 @@ public class Survey implements java.io.Serializable { private boolean accessResultsRights = true; private Integer allowedContributionsPerUser = 1; private boolean canCreateSurveys = true; + private Integer trustScore; @Id @Column(name = "SURVEY_ID", nullable = false) @@ -1126,6 +1129,14 @@ public void setNumberOfAnswerSetsPublished(int numberOfAnswerSetsPublished) { this.numberOfAnswerSetsPublished = numberOfAnswerSetsPublished; } + @Transient + public int getNumberOfReports() { + return numberOfReports; + } + public void setNumberOfReports(int numberOfReports) { + this.numberOfReports = numberOfReports; + } + //this property is not used anymore but has to stay because of backward compatibility @Column(name = "COMPULSORYSTYLE") public Integer getCompulsoryStyle() { @@ -1154,6 +1165,14 @@ public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted != null ? isDeleted : false; } + @Column(name = "FROZEN") + public Boolean getIsFrozen() { + return isFrozen != null ? isFrozen : false; + } + public void setIsFrozen(Boolean isFrozen) { + this.isFrozen = isFrozen != null ? isFrozen : false; + } + @Column(name = "ECASSEC") public Boolean getEcasSecurity() { return ecasSecurity; @@ -1260,6 +1279,14 @@ public void setAllowedContributionsPerUser(Integer allowedContributionsPerUser) this.allowedContributionsPerUser = allowedContributionsPerUser; } + @Column(name = "TRUSTSCORE") + public Integer getTrustScore() { + return trustScore; + } + public void setTrustScore(Integer trustScore) { + this.trustScore = trustScore; + } + @Transient public String serialize(boolean elementOrderOnly) { StringBuilder result = new StringBuilder(); @@ -2104,13 +2131,11 @@ public void setAccessResultsRights(boolean accessResultsRights) { this.accessResultsRights = accessResultsRights; } - @Transient public boolean isCanCreateSurveys() { return canCreateSurveys; } public void setCanCreateSurveys(boolean canCreateSurveys) { this.canCreateSurveys = canCreateSurveys; - } - + } } \ No newline at end of file diff --git a/src/main/java/com/ec/survey/model/survey/base/File.java b/src/main/java/com/ec/survey/model/survey/base/File.java index d53cbd410..d9f7fdbe0 100644 --- a/src/main/java/com/ec/survey/model/survey/base/File.java +++ b/src/main/java/com/ec/survey/model/survey/base/File.java @@ -123,4 +123,10 @@ public Integer getAnswerId() { public void setAnswerId(Integer answerId) { this.answerId = answerId; } + + @Transient + public String getNameForExport() + { + return getName().replace(";", "").replace("|", ""); + } } diff --git a/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java b/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java index 2fc71ea77..bb6b4a51e 100644 --- a/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java +++ b/src/main/java/com/ec/survey/security/CustomAuthenticationManager.java @@ -6,8 +6,10 @@ import com.ec.survey.service.AdministrationService; import com.ec.survey.service.LdapService; import com.ec.survey.service.SessionService; +import com.ec.survey.tools.Bad2faCredentialsException; import com.ec.survey.tools.BadSurveyCredentialsException; import com.ec.survey.tools.EcasHelper; +import com.ec.survey.tools.FrozenCredentialsException; import com.ec.survey.tools.Tools; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Value; @@ -72,126 +74,148 @@ public Authentication authenticate(Authentication auth) logger.debug("authenticate".toUpperCase() +" GET THE TICKET TO CHECK VALUE " + ValidationURL +" THE TICKET IS " + ticket); - try{ + boolean weakAuthentication = false; + sessionService.initializeProxy(); + logger.debug("authenticate".toUpperCase() +" PROXY INITIALZED"); + String xmlValidationAnswer = EcasHelper.getSourceContents(ValidationURL); + logger.info("authenticate".toUpperCase() +" GET THE SOURCE CONTENT " + xmlValidationAnswer); + if (xmlValidationAnswer.contains("")) { + String username = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:user"); + String type = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:employeeType"); + String strength = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:strength"); - sessionService.initializeProxy(); - logger.debug("authenticate".toUpperCase() +" PROXY INITIALZED"); - String xmlValidationAnswer = EcasHelper.getSourceContents(ValidationURL); - logger.info("authenticate".toUpperCase() +" GET THE SOURCE CONTENT " + xmlValidationAnswer); - if (xmlValidationAnswer.contains("")) { - String username = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:user"); - String type = EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:employeeType"); - - if (auth.getName() != null && auth.getName().startsWith("oldLogin:")) + if (auth.getName() != null && auth.getName().startsWith("oldLogin:")) + { + String oldlogin = auth.getName().substring(9); + if (!oldlogin.equals(username)) { - String oldlogin = auth.getName().substring(9); - if (!oldlogin.equals(username)) - { - logger.warn("replacing user " + oldlogin + " by user " + username); - } + logger.warn("replacing user " + oldlogin + " by user " + username); } + } + + try { + logger.debug("authenticate".toUpperCase() +" START TO GET USER INFORMATION FROM DB FOR USERNAME " + username); + user = administrationService.getUserForLogin(username, true); + } catch (Exception e) + { + //if an ecas user logs in for the first time there is no db entry for him yes + } + + logger.debug("authenticate".toUpperCase() +" Get All Roles From AdminService"); + List Roles = administrationService.getAllRoles(); + Role ecRole = null; + Role intRole = null; + for (Role role : Roles) { + if (role.getName().equalsIgnoreCase("Form Manager (EC)")) ecRole = role; + if (role.getName().equalsIgnoreCase("Form Manager")) intRole = role; + } + + if (user == null) + { + user = new User(); + user.setLogin(username); + user.setType(User.ECAS); + user.setLanguage("EN"); + user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email")); + user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName")); + user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName")); - try { - logger.debug("authenticate".toUpperCase() +" START TO GET USER INFORMATION FROM DB FOR USERNAME " + username); - user = administrationService.getUserForLogin(username, true); - } catch (Exception e) - { - //if an ecas user logs in for the first time there is no db entry for him yes - } + if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c")) + { + user.getRoles().add(ecRole); + } else { + if (strength.equalsIgnoreCase("PASSWORD") || strength.equalsIgnoreCase("STRONG")) + { + weakAuthentication = true; + if (!surveyLoginMode) + { + throw new Bad2faCredentialsException("Ecas user does not use two factor authentication!"); + } + } + + user.getRoles().add(intRole); + } - logger.debug("authenticate".toUpperCase() +" Get All Roles From AdminService"); - List Roles = administrationService.getAllRoles(); - Role ecRole = null; - Role intRole = null; - for (Role role : Roles) { - if (role.getName().equalsIgnoreCase("Form Manager (EC)")) ecRole = role; - if (role.getName().equalsIgnoreCase("Form Manager")) intRole = role; - } + try { + administrationService.createUser(user); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new BadCredentialsException("Ecas user cannot be created!"); + } + } else { + String oldEmail = user.getEmail(); - if (user == null) - { - user = new User(); - user.setLogin(username); - user.setType(User.ECAS); - user.setLanguage("EN"); - user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email")); - user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName")); - user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName")); - - if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c")) + user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email")); + user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName")); + user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName")); + + if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c")) + { + if (ecRole != null) { - user.getRoles().add(ecRole); - } else { - user.getRoles().add(intRole); + if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), ecRole.getId())) + { + user.getRoles().clear(); + user.getRoles().add(ecRole); + administrationService.updateUser(user); + } } - - administrationService.createUser(user); } else { - String oldEmail = user.getEmail(); - - user.setEmail(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:email")); - user.setGivenName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:firstName")); - user.setSurName(EcasHelper.getXmlTagValue(xmlValidationAnswer, "cas:lastName")); - - if (type.equalsIgnoreCase("f") || type.equalsIgnoreCase("x") || type.equalsIgnoreCase("i") || type.equalsIgnoreCase("c")) + if (intRole != null) { - if (ecRole != null) - { - if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), ecRole.getId())) - { - user.getRoles().clear(); - user.getRoles().add(ecRole); - administrationService.updateUser(user); - } + if (strength.equalsIgnoreCase("PASSWORD") || strength.equalsIgnoreCase("STRONG")) + { + weakAuthentication = true; + if (!surveyLoginMode) + { + throw new Bad2faCredentialsException("Ecas user does not use two factor authentication!"); + } } - } else { - if (intRole != null) + + if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), intRole.getId())) { - if (user.getRoles().size() != 1 || !Objects.equals(user.getRoles().get(0).getId(), intRole.getId())) - { - user.getRoles().clear(); - user.getRoles().add(intRole); - administrationService.updateUser(user); - } + user.getRoles().clear(); + user.getRoles().add(intRole); + administrationService.updateUser(user); } } - - if (!oldEmail.equalsIgnoreCase(user.getEmail())) + } + + if (!oldEmail.equalsIgnoreCase(user.getEmail())) + { + if (user.getOtherEmail() == null) { - if (user.getOtherEmail() == null) + user.setOtherEmail(oldEmail); + } else { + if (!user.getOtherEmail().endsWith(";")) { - user.setOtherEmail(oldEmail); + user.setOtherEmail(user.getOtherEmail() + ";" + oldEmail); } else { - if (!user.getOtherEmail().endsWith(";")) - { - user.setOtherEmail(user.getOtherEmail() + ";" + oldEmail); - } else { - user.setOtherEmail(user.getOtherEmail() + oldEmail); - } + user.setOtherEmail(user.getOtherEmail() + oldEmail); } - administrationService.updateUser(user); } + administrationService.updateUser(user); } - - Collection authorities = getAuthorities(user, true); - - if (surveyLoginMode) - { - authorities.add(new SimpleGrantedAuthority("ROLE_ECAS_SURVEY_" + survey)); - } - - return new UsernamePasswordAuthenticationToken( - username, - "", - authorities); + } + + Collection authorities = getAuthorities(user, true, weakAuthentication); + + if (surveyLoginMode) + { + authorities.add(new SimpleGrantedAuthority("ROLE_ECAS_SURVEY_" + survey)); + } + + checkUserNotBanned(user); + + return new UsernamePasswordAuthenticationToken( + username, + "", + authorities); } else{ logger.error("cas:authenticationSuccess NOT FOUND IN XMLVALIDATION"); } - } catch (Exception e) - { - logger.error("error on getValidation "+e.getLocalizedMessage(), e); - } + logger.error("Ecas user cannot be validated!"); @@ -233,13 +257,27 @@ public Authentication authenticate(Authentication auth) throw new BadCredentialsException("User not validated!"); } + checkUserNotBanned(user); + user.setBadLoginAttempts(0); administrationService.updateUser(user); return new UsernamePasswordAuthenticationToken( auth.getName(), auth.getCredentials(), - getAuthorities(user, false)); + getAuthorities(user, false, false)); + } + + private void checkUserNotBanned(User user) + { + if (user.isFrozen()) { + throw new FrozenCredentialsException("User is banned!"); + } + + if (!administrationService.checkEmailsNotBanned(user.getAllEmailAddresses())) + { + throw new FrozenCredentialsException("User is banned!"); + } } /** @@ -249,8 +287,13 @@ public Authentication authenticate(Authentication auth) * @param ecas * @return */ - public Collection getAuthorities(User user, boolean ecas) { + public Collection getAuthorities(User user, boolean ecas, boolean weakAuthentication) { List authList = new ArrayList<>(); + + if (weakAuthentication) + { + authList.add(new SimpleGrantedAuthority("ROLE_WEAK_AUTHENTICATION")); + } authList.add(new SimpleGrantedAuthority("ROLE_USER")); diff --git a/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java b/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java index bc969cb2c..2da46ded9 100644 --- a/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java +++ b/src/main/java/com/ec/survey/security/CustomAuthenticationSuccessHandler.java @@ -50,6 +50,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo User user = null; try { boolean ecas = false; + boolean weakAuthentication = false; for (GrantedAuthority auth: securityContext.getAuthentication().getAuthorities()) { if (auth.getAuthority().equalsIgnoreCase("ROLE_ECAS_USER")) @@ -57,6 +58,11 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo ecas = true; } + if (auth.getAuthority().equalsIgnoreCase("ROLE_WEAK_AUTHENTICATION")) + { + weakAuthentication = true; + } + if (auth.getAuthority().startsWith("ROLE_ECAS_SURVEY_")) { request.getSession().setAttribute("ECASSURVEY", auth.getAuthority().substring(17)); @@ -93,6 +99,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo } request.getSession().setAttribute("USER", user); + request.getSession().setAttribute("WEAKAUTHENTICATION", weakAuthentication); localeResolver.setLocale(request, response, new Locale(user.getLanguage())); } catch (Exception e) { diff --git a/src/main/java/com/ec/survey/service/ActivityService.java b/src/main/java/com/ec/survey/service/ActivityService.java index a305afed7..7d2dccdcc 100644 --- a/src/main/java/com/ec/survey/service/ActivityService.java +++ b/src/main/java/com/ec/survey/service/ActivityService.java @@ -56,6 +56,9 @@ public void log(Map activitiesToLog, Integer userId, String s activity.setLogID(logId); activity.setOldValue(oldnew[counter++]); activity.setNewValue(oldnew[counter++]); + + checkValueSizes(activity); + activity.setUserId(userId); activity.setSurveyUID(surveyUID); session.save(activity); @@ -89,6 +92,9 @@ public void logTranslations(int activityCode, String code, Map o activity.setLogID(activityCode); activity.setOldValue(code + " " + key + ": " + oldValue); activity.setNewValue(code + " " + key + ": " + newValue); + + checkValueSizes(activity); + activity.setUserId(userId); activity.setSurveyUID(surveyUID); session.save(activity); @@ -105,6 +111,9 @@ public void logTranslations(int activityCode, String code, Map o activity.setLogID(activityCode); activity.setOldValue(code + " " + key + ":"); activity.setNewValue(code + " " + key + ": " + info.get(key)); + + checkValueSizes(activity); + activity.setUserId(userId); activity.setSurveyUID(surveyUID); session.save(activity); @@ -146,6 +155,9 @@ public void log(int activityCode, String oldValue, String newValue, int userId, activity.setLogID(activityCode); activity.setOldValue(oldValue); activity.setNewValue(newValue); + + checkValueSizes(activity); + activity.setUserId(userId); activity.setSurveyUID(surveyUID); activity.setType(type); @@ -163,15 +175,30 @@ public void log(int activityCode, String oldValue, String newValue, int userId, activity.setLogID(activityCode); activity.setOldValue(oldValue); activity.setNewValue(newValue); + + checkValueSizes(activity); + activity.setUserId(userId); activity.setSurveyUID(surveyUID); activity.setType(type); session.save(activity); } } + } + } + + private void checkValueSizes(Activity activity) + { + if (activity.getOldValue() != null && activity.getOldValue().length() > 65000) + { + activity.setOldValue(activity.getOldValue().substring(0, 65000) + "..."); } - } + if (activity.getNewValue() != null && activity.getNewValue().length() > 65000) + { + activity.setNewValue(activity.getNewValue().substring(0, 65000) + "..."); + } + } @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) public void log(int activityCode, String oldValue, String newValue, int userId, String surveyUID) diff --git a/src/main/java/com/ec/survey/service/AdministrationService.java b/src/main/java/com/ec/survey/service/AdministrationService.java index 437dc8cfe..9733f2d67 100644 --- a/src/main/java/com/ec/survey/service/AdministrationService.java +++ b/src/main/java/com/ec/survey/service/AdministrationService.java @@ -3,6 +3,7 @@ import com.ec.survey.model.*; import com.ec.survey.model.administration.*; import com.ec.survey.model.survey.Survey; +import com.ec.survey.tools.ConversionTools; import com.ec.survey.tools.LoginAlreadyExistsException; import com.ec.survey.tools.Tools; @@ -25,46 +26,42 @@ @Service("administrationService") public class AdministrationService extends BasicService { - - @Resource(name="sessionService") - private SessionService sessionService; - - @Resource(name="mailService") + + @Resource(name = "sessionService") + private SessionService sessionService; + + @Resource(name = "mailService") private MailService mailService; - + @Autowired private SqlQueryService sqlQueryService; - + private @Value("${admin.user}") String adminuser; private @Value("${admin.password}") String adminpassword; private @Value("${stress.user}") String stressuser; - private @Value("${stress.password}") String stresspassword; + private @Value("${stress.password}") String stresspassword; - private @Value("${smtpserver}") String smtpServer; + private @Value("${smtpserver}") String smtpServer; private @Value("${smtp.port}") String smtpPort; - private @Value("${sender}") String sender; + private @Value("${sender}") String sender; private @Value("${server.prefix}") String host; - - public String getAdminUser() - { + + public String getAdminUser() { return adminuser; } - - public String getAdminPassword() - { + + public String getAdminPassword() { return adminpassword; } - - public String getStressUser() - { + + public String getStressUser() { return stressuser; } - - public String getStressPassword() - { + + public String getStressPassword() { return stresspassword; } - + @SuppressWarnings("unchecked") @Transactional(readOnly = true) public List getAllRoles() { @@ -115,7 +112,7 @@ public List getAllUsers() { Query query = session.createQuery("FROM User"); return query.list(); } - + @SuppressWarnings("unchecked") @Transactional(readOnly = true) public List getAllUserIDs() { @@ -123,16 +120,16 @@ public List getAllUserIDs() { Query query = session.createQuery("SELECT u.id FROM User u"); return query.list(); } - + @SuppressWarnings("unchecked") @Transactional(readOnly = true) public List getUsers(UserFilter filter, SqlPagination sqlPagination) throws Exception { Session session = sessionFactory.getCurrentSession(); - + HashMap parameters = new HashMap<>(); Query query = session.createQuery(getHql(filter, parameters)); sqlQueryService.setParameters(query, parameters); - + return query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).setFirstResult(sqlPagination.getFirstResult()).setMaxResults(sqlPagination.getMaxResult()).list(); } @@ -145,47 +142,46 @@ public User getUser(Integer id) { @Transactional public void createUser(User user) throws Exception { Session session = sessionFactory.getCurrentSession(); - + Query query = session.createQuery("FROM User u where u.login = :login").setString("login", user.getLogin()); @SuppressWarnings("unchecked") List list = query.list(); - - if (list.size() > 0) throw new LoginAlreadyExistsException(); - + + if (list.size() > 0) + throw new LoginAlreadyExistsException(); + session.save(user); } - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public void updateUser(User user) { Session session = sessionFactory.getCurrentSession(); user = (User) session.merge(user); - + String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled); - if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0) - { + if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0) { user.setCanCreateSurveys(false); } - + session.setReadOnly(user, false); session.update(user); } - + @Transactional - public boolean checkUserPassword(User user, String rawPassword) - { - logger.debug("CHECKUSERPASSWORD CALLED " +user.getPassword() +" " + rawPassword); - + public boolean checkUserPassword(User user, String rawPassword) { + logger.debug("CHECKUSERPASSWORD CALLED " + user.getPassword() + " " + rawPassword); + String md5hash = Tools.md5hash(rawPassword); - + if (user.getPassword().equals(md5hash)) { - //replace md5 hash by salted SHA-512 hash - Session session = sessionFactory.getCurrentSession(); + // replace md5 hash by salted SHA-512 hash + Session session = sessionFactory.getCurrentSession(); user.setPasswordSalt(Tools.newSalt()); user.setPassword(Tools.hash(rawPassword + user.getPasswordSalt())); session.update(user); return true; } - + return false; } @@ -201,25 +197,25 @@ public String deleteUser(int id) { @Transactional(readOnly = true) public String[] getLoginsForPrefix(String term, String emailterm, boolean forPrivileges) { Session session = sessionFactory.getCurrentSession(); - + Query query = null; - if (term.length() > 0 && (emailterm != null && emailterm.length() > 0 )) - { - query = session.createQuery("FROM User u where u.login like :login and u.email like :email and u.type = :type order by u.login asc").setString("type", User.SYSTEM).setString("login", "%" + term + "%").setString("email", "%" + emailterm + "%"); + if (term.length() > 0 && (emailterm != null && emailterm.length() > 0)) { + query = session.createQuery("FROM User u where u.login like :login and u.email like :email and u.type = :type order by u.login asc").setString("type", User.SYSTEM) + .setString("login", "%" + term + "%").setString("email", "%" + emailterm + "%"); } else if (emailterm != null && emailterm.length() > 0) { query = session.createQuery("FROM User u where u.email like :email and u.type = :type order by u.login asc").setString("type", User.SYSTEM).setString("email", "%" + emailterm + "%"); } else { query = session.createQuery("FROM User u where u.login like :login and u.type = :type order by u.login asc").setString("type", User.SYSTEM).setString("login", "%" + term + "%"); } - + @SuppressWarnings("unchecked") List list = query.setMaxResults(100).list(); String[] result = new String[list.size()]; int counter = 0; for (User user : list) { - if (forPrivileges) - { - result[counter++] = "" + user.getLogin() + "" + (user.getGivenName() == null ? " " : user.getGivenName()) + "" + (user.getSurName() == null ? " " : user.getSurName()) + " "; + if (forPrivileges) { + result[counter++] = "" + user.getLogin() + "" + + (user.getGivenName() == null ? " " : user.getGivenName()) + "" + (user.getSurName() == null ? " " : user.getSurName()) + " "; } else { result[counter++] = user.getLogin(); } @@ -227,69 +223,67 @@ public String[] getLoginsForPrefix(String term, String emailterm, boolean forPri return result; } - + @Transactional(readOnly = true) public User getUserForLogin(String login) { Session session = sessionFactory.getCurrentSession(); - + String hql = "FROM User u where u.login = :login"; - - Query query = session.createQuery(hql).setString("login", login); + + Query query = session.createQuery(hql).setString("login", login); @SuppressWarnings("unchecked") List list = query.list(); if (list.size() > 0) - return list.get(0); - + return list.get(0); + return null; } - + @Transactional(readOnly = true) public Map getECASUserLoginsByEmail() { Session session = sessionFactory.getCurrentSession(); - - Query query = session.createSQLQuery("SELECT USER_EMAIL, USER_LOGIN FROM USERS WHERE USER_TYPE = 'ECAS'"); + + Query query = session.createSQLQuery("SELECT USER_EMAIL, USER_LOGIN FROM USERS WHERE USER_TYPE = 'ECAS'"); @SuppressWarnings("rawtypes") List res = query.list(); - + HashMap result = new HashMap<>(); - - for (Object o: res) - { + + for (Object o : res) { Object[] a = (Object[]) o; if (!result.containsKey((String) a[0])) { result.put((String) a[0], (String) a[1]); } } - + return result; } @Transactional(readOnly = true) public User getUserForLogin(String login, boolean ecas) throws Exception { - logger.debug("getUserForLogin".toUpperCase() +" START CHECK USER " + login +" IS ECAS " + ecas ); + logger.debug("getUserForLogin".toUpperCase() + " START CHECK USER " + login + " IS ECAS " + ecas); Session session = sessionFactory.getCurrentSession(); - + String hql = "FROM User u where u.login = :login AND u.type = :type"; - - Query query = session.createQuery(hql).setString("login", login); - - if (ecas) - { + + Query query = session.createQuery(hql).setString("login", login); + + if (ecas) { query.setString("type", User.ECAS); } else { query.setString("type", User.SYSTEM); } - logger.debug("getUserForLogin".toUpperCase() +" START CHECK USER LAUNCH QUERY "); + logger.debug("getUserForLogin".toUpperCase() + " START CHECK USER LAUNCH QUERY "); @SuppressWarnings("unchecked") List list = query.list(); - - logger.debug("getUserForLogin".toUpperCase() +" START CHECK USER QUERY EXECUTED WITH RESULT SIZE " + list.size()); + + logger.debug("getUserForLogin".toUpperCase() + " START CHECK USER QUERY EXECUTED WITH RESULT SIZE " + list.size()); if (list.size() == 0) throw new Exception("No user found for login " + login); @@ -298,114 +292,108 @@ public User getUserForLogin(String login, boolean ecas) throws Exception { return list.get(0); } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) - public void save(UsersConfiguration userConfiguration) - { + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) + public void save(UsersConfiguration userConfiguration) { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(userConfiguration); } - + @Transactional(readOnly = true) - public UsersConfiguration getUsersConfiguration(int userId) - { + public UsersConfiguration getUsersConfiguration(int userId) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("FROM UsersConfiguration c where c.userId = :userId").setInteger("userId", userId); - + @SuppressWarnings("unchecked") List list = query.list(); if (list.size() == 0) return null; - + return list.get(0); } @Transactional(readOnly = false) public void sendValidationEmail(User user) throws NumberFormatException, Exception { Session session = sessionFactory.getCurrentSession(); - + user.setValidationCode(UUID.randomUUID().toString()); user.setValidationCodeGeneration(new Date()); session.update(user); - + String link = host + "validate/" + user.getId() + "/" + user.getValidationCode(); - + String body = "Dear " + user.getLogin() + ",

Please validate your account by clicking the link below:

" + link + ""; - + mailService.SendHtmlMail(user.getEmail(), sender, sender, "EUSurvey Registration", body, smtpServer, Integer.parseInt(smtpPort), null); } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public boolean sendNewEmailAdressValidationEmail(User user) { - try { + try { Session session = sessionFactory.getCurrentSession(); user.setValidationCode(UUID.randomUUID().toString()); user.setValidationCodeGeneration(new Date()); session.update(user); - + String link = host + "validateNewEmail/" + user.getId() + "/" + user.getValidationCode(); - + String body = "Dear " + user.getLogin() + ",

Please confirm your email change by clicking the link below:

" + link + ""; - + InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/Content/mailtemplateeusurvey.html"); - String text = IOUtils.toString(inputStream, "UTF-8").replace("[CONTENT]", body).replace("[HOST]", host); - + String text = IOUtils.toString(inputStream, "UTF-8").replace("[CONTENT]", body).replace("[HOST]", host); + mailService.SendHtmlMail(user.getEmailToValidate(), sender, sender, "EUSurvey Confirmation", text, smtpServer, Integer.parseInt(smtpPort), null); - } catch (Exception ex) { - logger.error(ex.getLocalizedMessage(), ex); - return false; - } + } catch (Exception ex) { + logger.error(ex.getLocalizedMessage(), ex); + return false; + } return true; } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public boolean validateUser(int id, String code) { Session session = sessionFactory.getCurrentSession(); User user = (User) session.get(User.class, id); - - if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code)) - { + + if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code)) { user.setValidated(true); session.update(user); - + return true; } - + return false; } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public boolean validateNewEmail(HttpServletRequest request, int id, String code) { Session session = sessionFactory.getCurrentSession(); User user = (User) session.get(User.class, id); - - if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code) && user.getEmailToValidate() != null) - { + + if (user != null && user.getValidationCode() != null && user.getValidationCode().equalsIgnoreCase(code) && user.getEmailToValidate() != null) { String oldEmail = user.getEmail(); - if (user.getOtherEmail() == null) - { + if (user.getOtherEmail() == null) { user.setOtherEmail(oldEmail); } else { - if (!user.getOtherEmail().endsWith(";")) - { + if (!user.getOtherEmail().endsWith(";")) { user.setOtherEmail(user.getOtherEmail() + ";" + oldEmail); } else { user.setOtherEmail(user.getOtherEmail() + oldEmail); } } - + user.setEmail(user.getEmailToValidate()); user.setEmailToValidate(null); user.setValidationCode(null); - session.update(user); + session.update(user); sessionService.setCurrentUser(request, user); return true; } - + return false; } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public OneTimePasswordResetCode createOneTimePasswordResetCode(User user) { OneTimePasswordResetCode code = new OneTimePasswordResetCode(user); Session session = sessionFactory.getCurrentSession(); @@ -416,7 +404,7 @@ public OneTimePasswordResetCode createOneTimePasswordResetCode(User user) { @Transactional(readOnly = true) public OneTimePasswordResetCode getOneTimePasswordResetCode(String code) throws Exception { Session session = sessionFactory.getCurrentSession(); - + Query query = session.createQuery("FROM OneTimePasswordResetCode c where c.code = :code").setString("code", code); @SuppressWarnings("unchecked") List list = query.list(); @@ -428,40 +416,36 @@ public OneTimePasswordResetCode getOneTimePasswordResetCode(String code) throws return list.get(0); } - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public void add(EcasUser eu) { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(eu); } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public void removeUserGroups(Integer id) { Session session = sessionFactory.getCurrentSession(); Query query = session.createSQLQuery("DELETE FROM ECASGROUPS where eg_id = :id").setInteger("id", id); query.executeUpdate(); } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) - public void deactivateEcasUser(int id) - { + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) + public void deactivateEcasUser(int id) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("UPDATE EcasUser u SET u.deactivated = true WHERE u.id = :id").setInteger("id", id); - query.executeUpdate(); + query.executeUpdate(); } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) - public void deactivateEcasUsers(List ids) - { + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) + public void deactivateEcasUsers(List ids) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("UPDATE EcasUser u SET u.deactivated = true WHERE u.id = :id"); int counter = 0; - for (int id : ids) - { + for (int id : ids) { query.setInteger("id", id); query.executeUpdate(); - counter+=1; - if (counter % 10000 == 0) - { + counter += 1; + if (counter % 10000 == 0) { logger.info(counter + " EcasUsers deactivated"); } } @@ -470,193 +454,254 @@ public void deactivateEcasUsers(List ids) @Transactional(readOnly = true) public int getNumberOfUsers(UserFilter filter) { Session session = sessionFactory.getCurrentSession(); - + HashMap parameters = new HashMap<>(); Query query = session.createQuery(getHql(filter, parameters)); - + for (String attrib : parameters.keySet()) { Object value = parameters.get(attrib); - if (value instanceof String) - { - query.setString(attrib, (String)parameters.get(attrib)); - } else if (value instanceof Integer) - { - query.setInteger(attrib, (Integer)parameters.get(attrib)); - } else if (value instanceof Date) - { - query.setDate(attrib, (Date)parameters.get(attrib)); + if (value instanceof String) { + query.setString(attrib, (String) parameters.get(attrib)); + } else if (value instanceof Integer) { + query.setInteger(attrib, (Integer) parameters.get(attrib)); + } else if (value instanceof Date) { + query.setDate(attrib, (Date) parameters.get(attrib)); } } - + return query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).list().size(); } - - private String getHql(UserFilter filter, HashMap parameters) - { + + private String getHql(UserFilter filter, HashMap parameters) { StringBuilder hql = new StringBuilder("SELECT DISTINCT u FROM User u LEFT JOIN u.roles as r WHERE u.id > 0"); - - if (filter.getLogin() != null && filter.getLogin().length() > 0) - { + + if (filter.getLogin() != null && filter.getLogin().length() > 0) { hql.append(" AND u.login like :login"); parameters.put("login", "%" + filter.getLogin() + "%"); } - - if (filter.getEmail() != null && filter.getEmail().length() > 0) - { + + if (filter.getEmail() != null && filter.getEmail().length() > 0) { hql.append(" AND u.email like :email"); parameters.put("email", "%" + filter.getEmail() + "%"); } - - if (filter.getComment() != null && filter.getComment().length() > 0) - { + + if (filter.getComment() != null && filter.getComment().length() > 0) { hql.append(" AND u.comment like :comment"); parameters.put("comment", "%" + filter.getComment() + "%"); } - - if (filter.getLanguages() != null) - { + + if (filter.getLanguages() != null) { int i = 0; hql.append(" AND ("); - for (String lang : filter.getLanguages()) - { - if (lang.trim().length() > 0) - { + for (String lang : filter.getLanguages()) { + if (lang.trim().length() > 0) { String l = "lang" + i++; - - if (i > 1) - { + + if (i > 1) { hql.append(" OR"); } - + hql.append(" ( u.language like :").append(l).append(")"); parameters.put(l, lang.trim()); } } hql.append(" )"); } - - if (filter.getECAS() != null && filter.getSystem() != null) - if (filter.getECAS() && !filter.getSystem()) - { - hql.append(" AND u.type = 'ECAS'"); - } else if (!filter.getECAS() && filter.getSystem()) - { - hql.append(" AND u.type = 'SYSTEM'"); + + if (filter.getECAS() != null && filter.getSystem() != null) { + if (filter.getECAS() && !filter.getSystem()) { + hql.append(" AND u.type = 'ECAS'"); + } else if (!filter.getECAS() && filter.getSystem()) { + hql.append(" AND u.type = 'SYSTEM'"); + } } - if (filter.getRoles() != null) - { + if (filter.getBanned() != null && filter.getBanned() && filter.getUnbanned() != null && filter.getUnbanned()) { + //show all + } else if (filter.getBanned() != null && filter.getBanned()) { + hql.append(" AND u.frozen = true"); + } else if (filter.getUnbanned() != null && filter.getUnbanned()) { + hql.append(" AND u.frozen = false"); + } + + if (filter.getRoles() != null) { int i = 0; hql.append(" AND ("); - for (String role : filter.getRoles()) - { - if (role.trim().length() > 0) - { + for (String role : filter.getRoles()) { + if (role.trim().length() > 0) { String l = "role" + i++; - - if (i > 1) - { + + if (i > 1) { hql.append(" OR"); } - + hql.append(" r.id like :").append(l); - + parameters.put(l, Integer.parseInt(role.trim())); } } hql.append(" )"); } - - if (filter.getECASaccess() != null && filter.getNoECASaccess() != null) - if (filter.getECASaccess() && !filter.getNoECASaccess()) - { - hql.append(" AND u.canAccessEcasFunctionality = true"); - } else if (!filter.getECASaccess() && filter.getNoECASaccess()) - { - hql.append(" AND u.canAccessEcasFunctionality = false"); - } - - if (filter.getECaccess() != null && filter.getNoECaccess() != null) - if (filter.getECaccess() && !filter.getNoECaccess()) - { - hql.append(" AND u.canAccessECFunctionality = true"); - } else if (!filter.getECaccess() && filter.getNoECaccess()) - { - hql.append(" AND u.canAccessECFunctionality = false"); - } - - if (filter.getSortKey() != null && filter.getSortKey().length() > 0) - { - + + if (filter.getECASaccess() != null && filter.getNoECASaccess() != null) + if (filter.getECASaccess() && !filter.getNoECASaccess()) { + hql.append(" AND u.canAccessEcasFunctionality = true"); + } else if (!filter.getECASaccess() && filter.getNoECASaccess()) { + hql.append(" AND u.canAccessEcasFunctionality = false"); + } + + if (filter.getECaccess() != null && filter.getNoECaccess() != null) + if (filter.getECaccess() && !filter.getNoECaccess()) { + hql.append(" AND u.canAccessECFunctionality = true"); + } else if (!filter.getECaccess() && filter.getNoECaccess()) { + hql.append(" AND u.canAccessECFunctionality = false"); + } + + if (filter.getSortKey() != null && filter.getSortKey().length() > 0) { + hql.append(" ORDER BY u.").append(filter.getSortKey()); - - if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) - { + + if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) { hql.append(" ").append(filter.getSortOrder()); } else { hql.append(" DESC"); } - + } - + return hql.toString(); } - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public void createDummyEcasUsers(int counter) { Session session = sessionFactory.getCurrentSession(); - - for (int i = 0; i < 100000; i++) - { + + for (int i = 0; i < 100000; i++) { EcasUser eu = new EcasUser(); eu.setDepartmentNumber("Department1"); - eu.setEcMoniker("newuserz"+counter+"#"+i); + eu.setEcMoniker("newuserz" + counter + "#" + i); eu.setEmail("test@clam.dialogika.de"); - eu.setName("newnamez"+counter+"#"+i); + eu.setName("newnamez" + counter + "#" + i); eu.setUserLDAPGroups(new HashSet<>()); eu.getUserLDAPGroups().add("Department1"); session.saveOrUpdate(eu); } } - - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public void createDummySurAccess() throws Exception { Session session = sessionFactory.getCurrentSession(); - + User user = getUser(8); - + SurveyFilter filter = new SurveyFilter(); filter.setUser(getUser(1)); - SqlPagination sqlPagination = new SqlPagination(0, 5000); + SqlPagination sqlPagination = new SqlPagination(0, 5000); List surveys = surveyService.getSurveys(filter, sqlPagination); - + for (Survey survey : surveys) { - Access a = new Access(); - a.setSurvey(survey); - a.setUser(user); - a.getLocalPrivileges().put(LocalPrivilege.FormManagement, 1); - session.saveOrUpdate(a); + Access a = new Access(); + a.setSurvey(survey); + a.setUser(user); + a.getLocalPrivileges().put(LocalPrivilege.FormManagement, 1); + session.saveOrUpdate(a); } } - public boolean isSmtpServerConfigured() { - return !StringUtils.isEmpty(smtpServer); - } + public boolean isSmtpServerConfigured() { + return !StringUtils.isEmpty(smtpServer); + } - @Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW) + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public User setLastEditedSurvey(User user, Integer surveyid) { - Session session = sessionFactory.getCurrentSession(); - user = (User)session.merge(user); - - String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled); - if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0) - { + Session session = sessionFactory.getCurrentSession(); + user = (User) session.merge(user); + + String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled); + if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0) { user.setCanCreateSurveys(false); } - - user.setLastEditedSurvey(surveyid); + + user.setLastEditedSurvey(surveyid); session.saveOrUpdate(user); return user; } + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) + public void banUser(String userId, String mailText) throws Exception { + Session session = sessionFactory.getCurrentSession(); + User user = getUser(Integer.parseInt(userId)); + + if (user == null) { + throw new Exception("user does not exist"); + } + + user.setFrozen(true); + session.saveOrUpdate(user); + + // send email to user + InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/Content/mailtemplateeusurvey.html"); + String mailtemplate = IOUtils.toString(inputStream, "UTF-8"); + String mailtext = mailtemplate.replace("[CONTENT]", mailText).replace("[HOST]", host); + mailService.SendHtmlMail(user.getEmail(), sender, sender, "Your account has been banned", mailtext, smtpServer, Integer.parseInt(smtpPort), null); + + // send email to admins + String recipients = settingsService.get(Setting.BannedUserRecipients); + mailtext = settingsService.get(Setting.FreezeUserTextAdminBan).replace("[LOGIN]", user.getLogin()).replace("[EMAIL]", user.getEmail()); + mailtext = mailtemplate.replace("[CONTENT]", mailtext).replace("[HOST]", host); + + String[] emails = recipients.split(";"); + for (String recipient : emails) { + if (recipient.trim().length() > 0) { + mailService.SendHtmlMail(recipient, sender, sender, "User banned", mailtext, smtpServer, Integer.parseInt(smtpPort), null); + } + } + } + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) + public void unbanUser(String userId) throws Exception { + Session session = sessionFactory.getCurrentSession(); + User user = getUser(Integer.parseInt(userId)); + + if (user == null) { + throw new Exception("user does not exist"); + } + + user.setFrozen(false); + session.saveOrUpdate(user); + + // send email to user + InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/Content/mailtemplateeusurvey.html"); + String mailtemplate = IOUtils.toString(inputStream, "UTF-8"); + + String content = settingsService.get(Setting.FreezeUserTextUnban); + + String mailtext = mailtemplate.replace("[CONTENT]", content).replace("[HOST]", host); + mailService.SendHtmlMail(user.getEmail(), sender, sender, "Your account has been unbanned", mailtext, smtpServer, Integer.parseInt(smtpPort), null); + + // send email to admins + String recipients = settingsService.get(Setting.BannedUserRecipients); + mailtext = settingsService.get(Setting.FreezeUserTextAdminUnban).replace("[LOGIN]", user.getLogin()).replace("[EMAIL]", user.getEmail()); + mailtext = mailtemplate.replace("[CONTENT]", mailtext).replace("[HOST]", host); + + String[] emails = recipients.split(";"); + for (String recipient : emails) { + if (recipient.trim().length() > 0) { + mailService.SendHtmlMail(recipient, sender, sender, "User unbanned", mailtext, smtpServer, Integer.parseInt(smtpPort), null); + } + } + } + + @Transactional(readOnly = true) + public boolean checkEmailsNotBanned(List allEmailAddresses) { + Session session = sessionFactory.getCurrentSession(); + + Query query = session.createQuery("SELECT COUNT(u.id) FROM User u WHERE u.frozen = true AND u.email IN (:emails)"); + query.setParameterList("emails", allEmailAddresses); + + int count = ConversionTools.getValue(query.uniqueResult()); + + return count == 0; + } + } diff --git a/src/main/java/com/ec/survey/service/AnswerService.java b/src/main/java/com/ec/survey/service/AnswerService.java index 24836e5b7..d9ad7e5dd 100644 --- a/src/main/java/com/ec/survey/service/AnswerService.java +++ b/src/main/java/com/ec/survey/service/AnswerService.java @@ -17,6 +17,7 @@ import com.ec.survey.tools.InvalidEmailException; import com.ec.survey.tools.NotAgreedToTosException; import com.ec.survey.tools.Tools; +import com.ec.survey.tools.WeakAuthenticationException; import com.ec.survey.tools.export.StatisticsCreator; import org.apache.commons.lang3.time.DateUtils; @@ -1736,11 +1737,11 @@ public List getAnswersAndDrafts(int surveyId) { return result; } - public String getDraftForEcasLogin(Survey survey, HttpServletRequest request) throws NotAgreedToTosException { + public String getDraftForEcasLogin(Survey survey, HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { Session session = sessionFactory.getCurrentSession(); String sql = "SELECT d.DRAFT_UID FROM DRAFTS d JOIN ANSWERS_SET a ON d.answerSet_ANSWER_SET_ID = a.ANSWER_SET_ID WHERE (a.RESPONDER_EMAIL = :email or a.RESPONDER_EMAIL = :email2) AND a.SURVEY_ID IN (:ids)"; SQLQuery query = session.createSQLQuery(sql); - User user = sessionService.getCurrentUser(request, false); + User user = sessionService.getCurrentUser(request, false, false); if (user == null) return null; diff --git a/src/main/java/com/ec/survey/service/FtpClient.java b/src/main/java/com/ec/survey/service/FtpClient.java index ad73ca4f7..77be49c72 100644 --- a/src/main/java/com/ec/survey/service/FtpClient.java +++ b/src/main/java/com/ec/survey/service/FtpClient.java @@ -18,7 +18,6 @@ @Service("ftpClient") public class FtpClient { - protected static final Logger logger = Logger.getLogger(FtpClient.class); private final ProducerTemplate producerTemplate; private final ConsumerTemplate consumerTemplate; diff --git a/src/main/java/com/ec/survey/service/ReportingService.java b/src/main/java/com/ec/survey/service/ReportingService.java index 961b315d2..06407d48f 100644 --- a/src/main/java/com/ec/survey/service/ReportingService.java +++ b/src/main/java/com/ec/survey/service/ReportingService.java @@ -115,7 +115,7 @@ public ToDoItem(int id, int type, String uid, String code) } } - private String getWhereClause(ResultFilter filter, Map values, Survey survey) throws TooManyFiltersException + public String getWhereClause(ResultFilter filter, Map values, Survey survey) throws TooManyFiltersException { String where = ""; Map elementsByUniqueID = survey.getQuestionMapByUniqueId(); @@ -582,7 +582,7 @@ public List> getAnswerSets(Survey survey, ResultFilter filter, SqlP { v += answerid; } else { - v += answer.getStrippedTitle(); + v += answer.getTitle(); } } } @@ -601,7 +601,7 @@ public List> getAnswerSets(Survey survey, ResultFilter filter, SqlP { v += answerid; } else { - v += answer.getStrippedTitle(); + v += answer.getTitle(); } } } @@ -634,11 +634,11 @@ public List> getAnswerSets(Survey survey, ResultFilter filter, SqlP { if (addlinks) { - v += "" + file.getName() + "
"; + v += "" + file.getNameForExport() + "
"; } else if (forexport) { - v += file.getUid() + "|" + file.getName() + ";"; + v += file.getUid() + "|" + file.getNameForExport() + ";"; } else { - v += file.getName() + "
"; + v += file.getNameForExport() + "
"; } } } @@ -738,7 +738,7 @@ public void deleteOLAPTable(String uid, boolean draftversion, boolean publishedv while (OLAPTableExists(uid + "_" + counter, true)) { - query = sessionReporting.createSQLQuery("DROP TABLE IF EXISTS T" + uid.replace("-", "") + "_" + counter); + query = sessionReporting.createSQLQuery("DROP TABLE IF EXISTS TD" + uid.replace("-", "") + "_" + counter); query.executeUpdate(); counter++; } @@ -1331,16 +1331,42 @@ public void removeFromOLAPTable(String uid, String code, boolean publishedSurvey } @Transactional(readOnly = true, transactionManager = "transactionManagerReporting") - public int getCount(Survey survey) { + public int getCount(Survey survey, String where, Map values) { if (!isReportingDatabaseEnabled()) return -1; Session sessionReporting = sessionFactoryReporting.getCurrentSession(); - SQLQuery query = sessionReporting.createSQLQuery("SELECT COUNT(*) FROM " + GetOLAPTableName(survey)); + + String sql = "SELECT COUNT(*) FROM " + GetOLAPTableName(survey); + + if (where != null) + { + sql += where; + } + + SQLQuery query = sessionReporting.createSQLQuery(sql); + + if (where != null) + { + for (String attrib : values.keySet()) { + Object value = values.get(attrib); + if (value instanceof String) + { + query.setString(attrib, (String)values.get(attrib)); + } else if (value instanceof Integer) + { + query.setInteger(attrib, (Integer)values.get(attrib)); + } else if (value instanceof Date) + { + query.setTimestamp(attrib, (Date)values.get(attrib)); + } + } + } + return ConversionTools.getValue(query.uniqueResult()); } @Transactional(readOnly = true, transactionManager = "transactionManagerReporting") - public int getCount(Survey survey, String quid, String auid, boolean noPrefixSearch) { + public int getCount(Survey survey, String quid, String auid, boolean noPrefixSearch, String where, Map values) { if (!isReportingDatabaseEnabled()) return -1; Session sessionReporting = sessionFactoryReporting.getCurrentSession(); @@ -1354,7 +1380,30 @@ public int getCount(Survey survey, String quid, String auid, boolean noPrefixSea sql += " LIKE '%" + auid + "%'"; } + if (where != null) + { + sql += " AND QANSWERSETID IN (SELECT QANSWERSETID FROM " + GetOLAPTableName(survey) + " " + where + ")"; + } + SQLQuery query = sessionReporting.createSQLQuery(sql); + + if (where != null) + { + for (String attrib : values.keySet()) { + Object value = values.get(attrib); + if (value instanceof String) + { + query.setString(attrib, (String)values.get(attrib)); + } else if (value instanceof Integer) + { + query.setInteger(attrib, (Integer)values.get(attrib)); + } else if (value instanceof Date) + { + query.setTimestamp(attrib, (Date)values.get(attrib)); + } + } + } + return ConversionTools.getValue(query.uniqueResult()); } diff --git a/src/main/java/com/ec/survey/service/SchedulerService.java b/src/main/java/com/ec/survey/service/SchedulerService.java index 69868819b..0ac4d5070 100644 --- a/src/main/java/com/ec/survey/service/SchedulerService.java +++ b/src/main/java/com/ec/survey/service/SchedulerService.java @@ -32,6 +32,7 @@ import com.ec.survey.tools.EcasUserUpdater; import com.ec.survey.tools.ExportUpdater; import com.ec.survey.tools.FileUpdater; +import com.ec.survey.tools.SendReportedSurveysWorker; import com.ec.survey.tools.SurveyUpdater; import com.ec.survey.tools.ValidCodesRemover; @@ -72,6 +73,9 @@ public class SchedulerService extends BasicService { @Resource(name = "deleteInvalidStatisticsWorker") private DeleteInvalidStatisticsWorker deleteInvalidStatisticsWorker; + @Resource(name = "sendReportedSurveysWorker") + private SendReportedSurveysWorker sendReportedSurveysWorker; + @Resource(name = "surveyWorker") private SurveyUpdater surveyWorker; @@ -472,7 +476,7 @@ public void migrateReportingSchedule() { } } - @Scheduled(fixedDelay=1200000) //every 20 minutes + @Scheduled(fixedDelay=10000) //wait for 10 seconds between calls public void doToDosSchedule() throws Exception { if (!isReportingDatabaseEnabled()) return; @@ -525,6 +529,7 @@ public void doNightlySchedule() { deleteDraftsWorker.run(); deleteTemporaryFoldersWorker.run(); deleteInvalidStatisticsWorker.run(); + sendReportedSurveysWorker.run(); logger.debug("End nightly schedule"); } diff --git a/src/main/java/com/ec/survey/service/SchemaService.java b/src/main/java/com/ec/survey/service/SchemaService.java index 1fd273829..4e306b43c 100644 --- a/src/main/java/com/ec/survey/service/SchemaService.java +++ b/src/main/java/com/ec/survey/service/SchemaService.java @@ -58,6 +58,118 @@ public boolean isOss() @Resource(name = "domainWorker") private DomainUpdater domaintWorker; + @Transactional + public void step93() { + Session session = sessionFactory.getCurrentSession(); + Status status = getStatus(); + + settingsService.add(Setting.TrustValueCreatorInternal, "500", "int"); + settingsService.add(Setting.TrustValuePastSurveys, "500", "int"); + settingsService.add(Setting.TrustValuePrivilegedUser, "100", "int"); + settingsService.add(Setting.TrustValueNbContributions, "50", "int"); + settingsService.add(Setting.TrustValueMinimumPassMark, "100", "int"); + + status.setDbversion(93); + session.saveOrUpdate(status); + } + + @Transactional + public void step92() { + Session session = sessionFactory.getCurrentSession(); + Status status = getStatus(); + + String text = "

Please be informed that the following user [LOGIN] having the email address: [EMAIL] has been banned from EUSurvey.

For more information please contact the EUSurvey team.

"; + settingsService.add(Setting.FreezeUserTextAdminBan, text, "text"); + + text = "

Please be informed that the following user [LOGIN] having the email address: [EMAIL] has been unbanned from EUSurvey.

For more information please contact the EUSurvey team.

"; + settingsService.add(Setting.FreezeUserTextAdminUnban, text, "text"); + + text = "

Dear Sir or Madam,

You have been banned from EUSurvey application due to infrigiment to our policy.

Reason: to specify

Please refer to our Terms of Service for more information.

Kind regards,
The EUSurvey Team

"; + settingsService.add(Setting.FreezeUserTextBan, text, "text"); + + text = "

Dear Sir or Madam,

You have just been unbanned and got back your access to the EUSurvey application. You can now connect to EUSurvey

Kind regards,
The EUSurvey Team

"; + settingsService.add(Setting.FreezeUserTextUnban, text, "text"); + + Setting s = new Setting(); + s.setKey(Setting.BannedUserRecipients); + s.setValue(""); + s.setFormat("email addresses separated by ;"); + session.saveOrUpdate(s); + + status.setDbversion(92); + session.saveOrUpdate(status); + } + + @Transactional + public void step91() { + Session session = sessionFactory.getCurrentSession(); + Status status = getStatus(); + + SQLQuery query = session.createSQLQuery("ALTER TABLE SETTINGS MODIFY SETTINGS.SETTINGS_VALUE TEXT"); + query.executeUpdate(); + + String newReportText = "

The following survey:
" + + "" + + "" + + "" + + "" + + "
Published survey link:[LINK]
Alias:[ALIAS]
Title:[TITLE]
" + + "has been reported as infringing our policy by [EMAIL] at [DATE].

" + + "

The reason provided is the following: [TYPE].

" + + "

So far, it has been reported [COUNT] time(s).

"; + + settingsService.update(Setting.ReportText, newReportText); + + status.setDbversion(91); + session.saveOrUpdate(status); + } + + @Transactional + public void step90() { + Session session = sessionFactory.getCurrentSession(); + Status status = getStatus(); + String existing = settingsService.get(Setting.MaxReports); + if (existing == null) + { + Setting s = new Setting(); + s.setKey(Setting.MaxReports); + s.setValue("5"); + s.setFormat("int"); + session.saveOrUpdate(s); + + s = new Setting(); + s.setKey(Setting.ReportText); + s.setValue("Survey [ALIAS]
[TITLE] has been reported as infringing our policy by [EMAIL] at [DATE]. The reason provided is the following: [TYPE].
So far, it has been reported [COUNT] time(s)."); + s.setFormat("text"); + session.saveOrUpdate(s); + + s = new Setting(); + s.setKey(Setting.ReportRecipients); + s.setValue(""); + s.setFormat("email addresses separated by ;"); + session.saveOrUpdate(s); + } + status.setDbversion(90); + session.saveOrUpdate(status); + } + + @Transactional + public void step89() { + Session session = sessionFactory.getCurrentSession(); + Status status = getStatus(); + String existing = settingsService.get(Setting.WeakAuthenticationDisabled); + if (existing == null) + { + Setting s = new Setting(); + s.setKey(Setting.WeakAuthenticationDisabled); + s.setValue("true"); + s.setFormat("true / false"); + session.saveOrUpdate(s); + } + status.setDbversion(89); + session.saveOrUpdate(status); + } + @Transactional public void step88() { Session session = sessionFactory.getCurrentSession(); diff --git a/src/main/java/com/ec/survey/service/SessionService.java b/src/main/java/com/ec/survey/service/SessionService.java index 8e70588f5..943e61194 100644 --- a/src/main/java/com/ec/survey/service/SessionService.java +++ b/src/main/java/com/ec/survey/service/SessionService.java @@ -15,6 +15,8 @@ import com.ec.survey.model.survey.Text; import com.ec.survey.tools.ConversionTools; import com.ec.survey.tools.NotAgreedToTosException; +import com.ec.survey.tools.WeakAuthenticationException; + import org.apache.commons.lang3.StringUtils; import org.hibernate.Hibernate; import org.hibernate.Query; @@ -57,22 +59,30 @@ public class SessionService extends BasicService { private @Value("${pdfserver.prefix}") String pdfServerPrefix; private @Value("${proxy.nonProxyHosts}") String proxyNonProxyHosts; - public User getCurrentUser(HttpServletRequest request) throws NotAgreedToTosException { - return getCurrentUser(request, true); + public User getCurrentUser(HttpServletRequest request) throws NotAgreedToTosException, WeakAuthenticationException { + return getCurrentUser(request, true, true); } - public User getCurrentUser(HttpServletRequest request, boolean checkTOS) throws NotAgreedToTosException { + public User getCurrentUser(HttpServletRequest request, boolean checkTOS, boolean checkWeakAuthentication) throws NotAgreedToTosException, WeakAuthenticationException { if (request == null) return null; User user = (User) request.getSession().getAttribute("USER"); + Boolean weakAuthentication = (Boolean) request.getSession().getAttribute("WEAKAUTHENTICATION"); if (user != null) { Session session = sessionFactory.getCurrentSession(); user = (User) session.merge(user); + String weakAuthenticationDisabled = settingsService.get(Setting.WeakAuthenticationDisabled); + + if (weakAuthenticationDisabled.equalsIgnoreCase("true") && checkWeakAuthentication && user.getType().equalsIgnoreCase(User.ECAS) && user.isExternal() && weakAuthentication) + { + throw new WeakAuthenticationException(); + } + String disabled = settingsService.get(Setting.CreateSurveysForExternalsDisabled); - if (disabled.equalsIgnoreCase("true") && user.getGlobalPrivileges().get(GlobalPrivilege.ECAccess) == 0) + if (disabled.equalsIgnoreCase("true") && user.isExternal()) { user.setCanCreateSurveys(false); } @@ -294,7 +304,7 @@ public void updateSessionInfo(Survey survey, User user, HttpServletRequest reque request.getSession().setAttribute("sessioninfo", new SessionInfo(survey.getId(), user.getId(), survey.getOwner().getId(), survey.getLanguage().getCode(),survey.getShortname())); } - public SurveyFilter getSurveyFilter(HttpServletRequest request, boolean forms) throws NotAgreedToTosException { + public SurveyFilter getSurveyFilter(HttpServletRequest request, boolean forms) throws NotAgreedToTosException, WeakAuthenticationException { SurveyFilter filter = new SurveyFilter(); filter.setUser(getCurrentUser(request)); @@ -513,6 +523,9 @@ public UserFilter getUserFilter(HttpServletRequest request) { filter.setLanguages(request.getParameterValues("languages")); + filter.setBanned(request.getParameter("banned") != null && request.getParameter("banned").equalsIgnoreCase("true")); + filter.setUnbanned(request.getParameter("unbanned") != null && request.getParameter("unbanned").equalsIgnoreCase("true")); + String roles[] = request.getParameterValues("roles"); if (roles != null && roles.length > 0) { diff --git a/src/main/java/com/ec/survey/service/SurveyService.java b/src/main/java/com/ec/survey/service/SurveyService.java index 8f75885d9..45731997c 100644 --- a/src/main/java/com/ec/survey/service/SurveyService.java +++ b/src/main/java/com/ec/survey/service/SurveyService.java @@ -38,60 +38,61 @@ @Service("surveyService") public class SurveyService extends BasicService { - + private @Value("${publicsurveynotification}") String publicsurveynotification; private @Value("${smtpserver}") String smtpServer; private @Value("${smtp.port}") String smtpPort; private @Value("${sender}") String sender; private @Value("${server.prefix}") String host; public @Value("${opc.notify}") String opcnotify; - + private @Value("${monitoring.recipient}") String monitoringEmail; + @Autowired protected SqlQueryService sqlQueryService; - + + @Autowired + protected LdapService ldapDBService; + @Transactional(readOnly = true) - public int getNumberPublishedAnswersFromMaterializedView(String uid) - { + public int getNumberPublishedAnswersFromMaterializedView(String uid) { Session session = sessionFactory.getCurrentSession(); String sql = "SELECT npa.PUBLISHEDANSWERS FROM MV_SURVEYS_NUMBERPUBLISHEDANSWERS npa WHERE npa.SURVEYUID = :uid"; SQLQuery query = session.createSQLQuery(sql); query.setString("uid", uid); List res = (List) query.list(); - if (res.size() > 0) return ConversionTools.getValue(res.get(0)); + if (res.size() > 0) + return ConversionTools.getValue(res.get(0)); return 0; } - + private Map getLanguageMap() { - return getLanguages() - .stream() - .collect(Collectors.toMap(Language::getId, l -> l)); + return getLanguages().stream().collect(Collectors.toMap(Language::getId, l -> l)); } - + @SuppressWarnings("unchecked") private List loadSurveysfromDatabase(String sql, HashMap parameters, SqlPagination sqlPagination) throws Exception { Session session = sessionFactory.getCurrentSession(); - SQLQuery query = session.createSQLQuery(sql); + SQLQuery query = session.createSQLQuery(sql); sqlQueryService.setParameters(query, parameters); - + return query.setFirstResult(sqlPagination.getFirstResult()).setMaxResults(sqlPagination.getMaxResult()).list(); } - + @Transactional(readOnly = true) public List getSurveys(SurveyFilter filter, SqlPagination sqlPagination) throws Exception { String sql = "SELECT s.SURVEY_ID, s.SURVEY_UID, s.SURVEYNAME, s.TITLE, s.SURVEY_CREATED, s.SURVEY_END_DATE, s.SURVEY_START_DATE, s.ISPUBLISHED, s.LANGUAGE" - + " , npa.PUBLISHEDANSWERS as replies, s.ACTIVE, s.OWNER, s.CONTACT" - + " , (SELECT USER_LOGIN FROM USERS u WHERE u.USER_ID = s.OWNER) as ownerlogin, (SELECT USER_DISPLAYNAME FROM USERS u WHERE u.USER_ID = s.OWNER) as ownername, s.AUTOMATICPUBLISHING, s.CONTACTLABEL, s.SURVEYSECURITY, s.QUIZ, s.OPC, s.HASPENDINGCHANGES" - + " from SURVEYS s LEFT JOIN MV_SURVEYS_NUMBERPUBLISHEDANSWERS npa on s.SURVEY_UID = npa.SURVEYUID where s.ISDRAFT = 1 and (s.ARCHIVED = 0 or s.ARCHIVED is null) and (s.DELETED = 0 or s.DELETED is null)"; - + + " , npa.PUBLISHEDANSWERS as replies, s.ACTIVE, s.OWNER, s.CONTACT" + + " , (SELECT USER_LOGIN FROM USERS u WHERE u.USER_ID = s.OWNER) as ownerlogin, (SELECT USER_DISPLAYNAME FROM USERS u WHERE u.USER_ID = s.OWNER) as ownername, s.AUTOMATICPUBLISHING, s.CONTACTLABEL, s.SURVEYSECURITY, s.QUIZ, s.OPC, s.HASPENDINGCHANGES" + + " from SURVEYS s LEFT JOIN MV_SURVEYS_NUMBERPUBLISHEDANSWERS npa on s.SURVEY_UID = npa.SURVEYUID where s.ISDRAFT = 1 and (s.ARCHIVED = 0 or s.ARCHIVED is null) and (s.DELETED = 0 or s.DELETED is null)"; + HashMap parameters = new HashMap<>(); sql += getSql(filter, parameters, false); - - List surveys = new ArrayList<>(); - Map languageMap = getLanguageMap(); - for (Object[] row: loadSurveysfromDatabase(sql, parameters, sqlPagination)) - { + + List surveys = new ArrayList<>(); + Map languageMap = getLanguageMap(); + for (Object[] row : loadSurveysfromDatabase(sql, parameters, sqlPagination)) { Survey survey = new Survey(); - + survey.setId(ConversionTools.getValue(row[0])); survey.setUniqueId((String) row[1]); survey.setShortname((String) row[2]); @@ -118,96 +119,98 @@ public List getSurveys(SurveyFilter filter, SqlPagination sqlPagination) survey.setSecurity((String) row[17]); survey.setIsQuiz((Boolean) row[18]); survey.setIsOPC((Boolean) row[19]); - + survey.setHasPendingChanges((Boolean) row[20]); - + surveys.add(survey); } return surveys; } - - public List getSurveysIncludingTranslationLanguages(SurveyFilter filter, SqlPagination sqlPagination, boolean addInvitedAndDrafts) throws Exception { + + public List getSurveysIncludingTranslationLanguages(SurveyFilter filter, SqlPagination sqlPagination, boolean addInvitedAndDrafts, boolean addNumberOfReports) throws Exception { List surveys = getSurveys(filter, sqlPagination); for (Survey survey : surveys) { - survey.setTranslations(translationService.getTranslationLanguagesForSurvey(survey.getId(), false)); - survey.setCompleteTranslations(getCompletedTranslations(survey)); - - if (addInvitedAndDrafts) - { - survey.setNumberOfInvitations(participationService.getNumberOfInvitations(survey.getUniqueId())); - survey.setNumberOfDrafts(answerService.getNumberOfDrafts(survey.getId())); - } else { - survey.setNumberOfInvitations(-1); - survey.setNumberOfDrafts(-1); - } + survey.setTranslations(translationService.getTranslationLanguagesForSurvey(survey.getId(), false)); + survey.setCompleteTranslations(getCompletedTranslations(survey)); + + if (addInvitedAndDrafts) { + survey.setNumberOfInvitations(participationService.getNumberOfInvitations(survey.getUniqueId())); + survey.setNumberOfDrafts(answerService.getNumberOfDrafts(survey.getId())); + } else { + survey.setNumberOfInvitations(-1); + survey.setNumberOfDrafts(-1); + } + + if (addNumberOfReports) + { + survey.setNumberOfReports(surveyService.getAbuseReportsForSurvey(survey.getUniqueId())); + } } return surveys; } - + private List getCompletedTranslations(Survey survey) { - return translationService.getTranslationsForSurvey(survey.getId(), false) - .stream() - .filter(Translations::getActive) - .map(t -> t.getLanguage().getCode()) - .collect(toList()); + return translationService.getTranslationsForSurvey(survey.getId(), false).stream().filter(Translations::getActive).map(t -> t.getLanguage().getCode()).collect(toList()); } - + public List getSurveysIncludingPublicationDates(SurveyFilter filter, SqlPagination sqlPagination) throws Exception { - String sql = "SELECT s.SURVEY_ID, s.SURVEY_UID, s.SURVEYNAME, s.TITLE, s.OWNER, (SELECT USER_LOGIN FROM USERS u WHERE u.USER_ID = s.OWNER) as ownerlogin,(SELECT USER_DISPLAYNAME FROM USERS u WHERE u.USER_ID = s.OWNER) as ownername, npa.PUBLISHEDANSWERS as replies, SUBSTRING(GROUP_CONCAT(s.survey_created),21, 19), SUBSTRING(GROUP_CONCAT(s.survey_created),-19), s.SURVEYSECURITY, s.ACTIVE from SURVEYS s LEFT JOIN MV_SURVEYS_NUMBERPUBLISHEDANSWERS npa on s.SURVEY_UID = npa.SURVEYUID where "; - - if (filter.getSurveys() != null && filter.getSurveys().equalsIgnoreCase("ARCHIVED")) - { + String sql = "SELECT s.SURVEY_ID, s.SURVEY_UID, s.SURVEYNAME, s.TITLE, s.OWNER, (SELECT USER_LOGIN FROM USERS u WHERE u.USER_ID = s.OWNER) as ownerlogin,(SELECT USER_DISPLAYNAME FROM USERS u WHERE u.USER_ID = s.OWNER) as ownername, npa.PUBLISHEDANSWERS as replies, SUBSTRING(GROUP_CONCAT(s.survey_created),21, 19), SUBSTRING(GROUP_CONCAT(s.survey_created),-19), s.SURVEYSECURITY, s.ACTIVE, s.FROZEN from SURVEYS s LEFT JOIN MV_SURVEYS_NUMBERPUBLISHEDANSWERS npa on s.SURVEY_UID = npa.SURVEYUID where "; + + if (filter.getSurveys() != null && filter.getSurveys().equalsIgnoreCase("ARCHIVED")) { sql += "(s.ARCHIVED = 1)"; } else if (filter.getSurveys() != null && filter.getSurveys().equalsIgnoreCase("DELETED")) { sql += "(s.DELETED = 1)"; + } else if (filter.getSurveys() != null && filter.getSurveys().equalsIgnoreCase("REPORTED")) { + sql += "(s.SURVEY_ID > 0)"; + // handled inside getSql } else { sql += "(s.ARCHIVED = 0 or s.ARCHIVED is null) and (s.DELETED = 0 or s.DELETED is null)"; } - + HashMap parameters = new HashMap<>(); sql += getSql(filter, parameters, true); - + List surveys = new ArrayList<>(); - for (Object[] row: loadSurveysfromDatabase(sql, parameters, sqlPagination)) - { + for (Object[] row : loadSurveysfromDatabase(sql, parameters, sqlPagination)) { Survey survey = new Survey(); survey.setId(ConversionTools.getValue(row[0])); survey.setUniqueId((String) row[1]); survey.setShortname((String) row[2]); survey.setTitle((String) row[3]); - - User user = new User(); + + User user = new User(); user.setId(ConversionTools.getValue(row[4])); user.setLogin((String) row[5]); user.setDisplayName((String) row[6]); survey.setOwner(user); - - survey.setNumberOfAnswerSetsPublished(ConversionTools.getValue(row[7])); + + survey.setNumberOfAnswerSetsPublished(ConversionTools.getValue(row[7])); survey.setFirstPublished(ConversionTools.getDate((String) row[9])); survey.setPublished(ConversionTools.getDate((String) row[9])); survey.setSecurity((String) row[10]); survey.setIsActive((Boolean) row[11]); + survey.setIsFrozen((Boolean) row[12]); surveys.add(survey); } - + return surveys; - } + } public List getPopularSurveys(SurveyFilter filter) throws Exception { - filter.setSortKey("replies"); - SqlPagination sqlPagination = new SqlPagination(1, 5); - return getSurveys(filter, sqlPagination); + filter.setSortKey("replies"); + SqlPagination sqlPagination = new SqlPagination(1, 5); + return getSurveys(filter, sqlPagination); } - + private String getSql(SurveyFilter filter, HashMap oQueryParameters, boolean loadpublicationdates) { - + StringBuilder sql = new StringBuilder(); - + if (filter == null) { return sql.toString(); } - + if (filter.getUid() != null && filter.getUid().length() > 0) { sql.append(" AND s.SURVEY_UID like :uid"); oQueryParameters.put("uid", "%" + filter.getUid().trim() + "%"); @@ -222,155 +225,148 @@ private String getSql(SurveyFilter filter, HashMap oQueryParamet sql.append(" AND s.TITLE COLLATE UTF8_GENERAL_CI like :title"); oQueryParameters.put("title", "%" + filter.getTitle().trim() + "%"); } - + if (filter.getAccess() != null && filter.getAccess().length() > 0) { sql.append(" AND s.SURVEYSECURITY like :access"); oQueryParameters.put("access", filter.getAccess()); } - - if (filter.getStatus() != null) - { + + if (filter.getStatus() != null) { boolean unpublished = filter.getStatus().contains("Unpublished"); boolean published = filter.getStatus().contains("Published"); - - if (published && unpublished) - { - //return everything - } - else if (published) - { + + if (published && unpublished) { + // return everything + } else if (published) { sql.append(" AND s.ISPUBLISHED = 1 AND s.ACTIVE = 1"); - } else if (unpublished) - { + } else if (unpublished) { sql.append(" AND NOT(s.ISPUBLISHED = 1 AND s.ACTIVE = 1)"); } } - + if (filter.getGeneratedFrom() != null) { sql.append(" AND s.SURVEY_CREATED >= :generatedFrom"); oQueryParameters.put("generatedFrom", filter.getGeneratedFrom()); } - + if (filter.getGeneratedTo() != null) { sql.append(" AND s.SURVEY_CREATED <= :generatedTo"); oQueryParameters.put("generatedTo", Tools.getFollowingDay(filter.getGeneratedTo())); } - + if (filter.getStartFrom() != null) { sql.append(" AND s.SURVEY_START_DATE >= :startFrom"); oQueryParameters.put("startFrom", filter.getStartFrom()); } - + if (filter.getStartTo() != null) { sql.append(" AND s.SURVEY_START_DATE <= :startTo"); oQueryParameters.put("startTo", Tools.getFollowingDay(filter.getStartTo())); } - + if (filter.getEndFrom() != null) { sql.append(" AND s.SURVEY_END_DATE >= :endFrom"); oQueryParameters.put("endFrom", filter.getEndFrom()); } - + if (filter.getEndTo() != null) { sql.append(" AND s.SURVEY_END_DATE <= :endTo"); oQueryParameters.put("endTo", Tools.getFollowingDay(filter.getEndTo())); } - - if (filter.getOwner() != null && filter.getOwner().length() > 0 && filter.getUser() != null && (filter.getUser().getLogin().equals(filter.getOwner()) || filter.getUser().getGlobalPrivileges().get(GlobalPrivilege.FormManagement) == 2)) - { + + if (filter.getOwner() != null && filter.getOwner().length() > 0 && filter.getUser() != null + && (filter.getUser().getLogin().equals(filter.getOwner()) || filter.getUser().getGlobalPrivileges().get(GlobalPrivilege.FormManagement) == 2)) { sql.append(" AND (s.OWNER in (SELECT USER_ID FROM USERS WHERE USER_LOGIN = :ownername OR USER_DISPLAYNAME = :ownername))"); oQueryParameters.put("ownername", filter.getOwner()); - } else if (filter.getUser() == null) - { - sql.append(" AND s.LISTFORM = 1 AND s.LISTFORMVALIDATED = 1 AND s.ISPUBLISHED = true AND s.ACTIVE = true AND (s.SURVEYSECURITY = 'open' or s.SURVEYSECURITY = 'openanonymous') AND (s.SURVEY_END_DATE IS NULL OR s.SURVEY_END_DATE > :now)"); + } else if (filter.getUser() == null) { + sql.append( + " AND s.LISTFORM = 1 AND s.LISTFORMVALIDATED = 1 AND s.ISPUBLISHED = true AND s.ACTIVE = true AND (s.SURVEYSECURITY = 'open' or s.SURVEYSECURITY = 'openanonymous') AND (s.SURVEY_END_DATE IS NULL OR s.SURVEY_END_DATE > :now)"); oQueryParameters.put("now", new Date()); - } else if (filter.getUser() != null) - { - if (filter.getSelector() != null && filter.getSelector().equalsIgnoreCase("my")) - { + } else if (filter.getUser() != null) { + if (filter.getSelector() != null && filter.getSelector().equalsIgnoreCase("my")) { sql.append(" AND (s.OWNER = :ownerId)"); oQueryParameters.put("ownerId", filter.getUser().getId()); - } else if (filter.getSelector() != null && filter.getSelector().equalsIgnoreCase("shared")) - { - if (filter.getUser().getType().equalsIgnoreCase("ECAS")) - { - sql.append(" AND (s.SURVEY_ID in (Select a.SURVEY FROM SURACCESS a WHERE (a.ACCESS_USER = :ownerId OR a.ACCESS_DEPARTMENT IN (SELECT GRPS FROM ECASGROUPS WHERE eg_ID = (SELECT USER_ID FROM ECASUSERS WHERE USER_LOGIN = :login))) AND (a.ACCESS_PRIVILEGES like '%2%' or a.ACCESS_PRIVILEGES like '%1%')))"); + } else if (filter.getSelector() != null && filter.getSelector().equalsIgnoreCase("shared")) { + if (filter.getUser().getType().equalsIgnoreCase("ECAS")) { + sql.append( + " AND (s.SURVEY_ID in (Select a.SURVEY FROM SURACCESS a WHERE (a.ACCESS_USER = :ownerId OR a.ACCESS_DEPARTMENT IN (SELECT GRPS FROM ECASGROUPS WHERE eg_ID = (SELECT USER_ID FROM ECASUSERS WHERE USER_LOGIN = :login))) AND (a.ACCESS_PRIVILEGES like '%2%' or a.ACCESS_PRIVILEGES like '%1%')))"); oQueryParameters.put("ownerId", filter.getUser().getId()); oQueryParameters.put("login", filter.getUser().getLogin()); } else { sql.append(" AND (s.SURVEY_ID in (Select a.SURVEY FROM SURACCESS a WHERE a.ACCESS_USER = :ownerId AND (a.ACCESS_PRIVILEGES like '%2%' or a.ACCESS_PRIVILEGES like '%1%')))"); oQueryParameters.put("ownerId", filter.getUser().getId()); } - } else if (filter.getUser().getGlobalPrivileges().get(GlobalPrivilege.FormManagement) < 2) - { - if (filter.getUser().getType().equalsIgnoreCase("ECAS")) - { - sql.append(" AND (s.OWNER = :ownerId OR s.SURVEY_ID in (Select a.SURVEY FROM SURACCESS a WHERE (a.ACCESS_USER = :ownerId OR a.ACCESS_DEPARTMENT IN (SELECT GRPS FROM ECASGROUPS WHERE eg_ID = (SELECT USER_ID FROM ECASUSERS WHERE USER_LOGIN = :login))) AND (a.ACCESS_PRIVILEGES like '%2%' or a.ACCESS_PRIVILEGES like '%1%')))"); + } else if (filter.getUser().getGlobalPrivileges().get(GlobalPrivilege.FormManagement) < 2) { + if (filter.getUser().getType().equalsIgnoreCase("ECAS")) { + sql.append( + " AND (s.OWNER = :ownerId OR s.SURVEY_ID in (Select a.SURVEY FROM SURACCESS a WHERE (a.ACCESS_USER = :ownerId OR a.ACCESS_DEPARTMENT IN (SELECT GRPS FROM ECASGROUPS WHERE eg_ID = (SELECT USER_ID FROM ECASUSERS WHERE USER_LOGIN = :login))) AND (a.ACCESS_PRIVILEGES like '%2%' or a.ACCESS_PRIVILEGES like '%1%')))"); oQueryParameters.put("ownerId", filter.getUser().getId()); oQueryParameters.put("login", filter.getUser().getLogin()); } else { - sql.append(" AND (s.OWNER = :ownerId OR s.SURVEY_ID in (Select a.SURVEY FROM SURACCESS a WHERE a.ACCESS_USER = :ownerId AND (a.ACCESS_PRIVILEGES like '%2%' or a.ACCESS_PRIVILEGES like '%1%')))"); + sql.append( + " AND (s.OWNER = :ownerId OR s.SURVEY_ID in (Select a.SURVEY FROM SURACCESS a WHERE a.ACCESS_USER = :ownerId AND (a.ACCESS_PRIVILEGES like '%2%' or a.ACCESS_PRIVILEGES like '%1%')))"); oQueryParameters.put("ownerId", filter.getUser().getId()); } - } - } + } + } if (filter.getKeywords() != null && filter.getKeywords().trim().length() > 0) { int i = 0; sql.append(" AND ("); for (String word : filter.getKeywords().split(" ")) { - if (word.trim().length() > 0) - { + if (word.trim().length() > 0) { String w = "word" + i++; - - if (i > 1) - { + + if (i > 1) { sql.append(" OR"); } - + sql.append(" ( s.SURVEYNAME COLLATE UTF8_GENERAL_CI like :").append(w).append(" OR s.TITLE COLLATE UTF8_GENERAL_CI like :").append(w).append(")"); oQueryParameters.put(w, "%" + word.trim() + "%"); } } sql.append(" )"); } - - if (filter.getLanguages() != null) - { + + if (filter.getLanguages() != null) { int i = 0; sql.append(" AND ("); - for (String lang : filter.getLanguages()) - { - if (lang.trim().length() > 0) - { + for (String lang : filter.getLanguages()) { + if (lang.trim().length() > 0) { String l = "lang" + i++; - - if (i > 1) - { + + if (i > 1) { sql.append(" OR"); } - - sql.append(" ( s.LANGUAGE = :").append(l).append(" or s.SURVEY_ID in (Select distinct t.SURVEY_ID FROM TRANSLATIONS t WHERE t.SURVEY_ACTIVE = 1 AND t.LANGUAGE = :").append(l).append("))"); + + sql.append(" ( s.LANGUAGE = :").append(l).append(" or s.SURVEY_ID in (Select distinct t.SURVEY_ID FROM TRANSLATIONS t WHERE t.SURVEY_ACTIVE = 1 AND t.LANGUAGE = :").append(l) + .append("))"); oQueryParameters.put(l, lang.trim()); } } sql.append(" )"); } + + if (filter.getSurveys() != null && filter.getSurveys().equalsIgnoreCase("REPORTED")) { + sql.append(" AND (s.SURVEY_UID IN (SELECT DISTINCT SURABUSE_SURVEY FROM SURABUSE))"); + } - if (loadpublicationdates) - { + if (filter.getSurveys() != null && filter.getSurveys().equalsIgnoreCase("FROZEN")) { + sql.append(" AND (s.FROZEN = 1)"); + } + + if (loadpublicationdates) { sql.append(" GROUP BY s.SURVEY_UID"); - + boolean having = false; if (filter.getPublishedFrom() != null) { sql.append(" HAVING STR_TO_DATE(SUBSTRING(GROUP_CONCAT(s.survey_created),-19), '%Y-%m-%d') >= :publishedFrom"); having = true; oQueryParameters.put("publishedFrom", filter.getPublishedFrom()); } - + if (filter.getPublishedTo() != null) { - if (having) - { + if (having) { sql.append(" AND "); } else { sql.append(" HAVING "); @@ -378,11 +374,10 @@ else if (published) } sql.append("STR_TO_DATE(SUBSTRING(GROUP_CONCAT(s.survey_created),-19), '%Y-%m-%d') <= :publishedTo"); oQueryParameters.put("publishedTo", filter.getPublishedTo()); - } - + } + if (filter.getFirstPublishedFrom() != null) { - if (having) - { + if (having) { sql.append(" AND "); } else { sql.append(" HAVING "); @@ -391,10 +386,9 @@ else if (published) sql.append("STR_TO_DATE(SUBSTRING(GROUP_CONCAT(s.survey_created),21, 19), '%Y-%m-%d') >= :firstPublishedFrom"); oQueryParameters.put("firstPublishedFrom", filter.getFirstPublishedFrom()); } - + if (filter.getFirstPublishedTo() != null) { - if (having) - { + if (having) { sql.append(" AND "); } else { sql.append(" HAVING "); @@ -402,292 +396,253 @@ else if (published) } sql.append("STR_TO_DATE(SUBSTRING(GROUP_CONCAT(s.survey_created),21, 19), '%Y-%m-%d') <= :firstPublishedTo"); oQueryParameters.put("firstPublishedTo", filter.getFirstPublishedTo()); - } + } } - - if (filter.getSortKey() != null && filter.getSortKey().length() > 0) - { - if (filter.getSortKey().equalsIgnoreCase("replies")) - { + + if (filter.getSortKey() != null && filter.getSortKey().length() > 0) { + if (filter.getSortKey().equalsIgnoreCase("replies")) { sql.append(" ORDER BY npa.PUBLISHEDANSWERS"); - - if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) - { + + if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) { sql.append(" ").append(filter.getSortOrder().toUpperCase()); } - } else if (filter.getSortKey().equalsIgnoreCase("created")) - { + } else if (filter.getSortKey().equalsIgnoreCase("created")) { sql.append(" ORDER BY s.SURVEY_CREATED"); - - if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) - { + + if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) { sql.append(" ").append(filter.getSortOrder().toUpperCase()); } - } else { + } else { sql.append(" ORDER BY s.").append(filter.getSortKey()); - - if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) - { + + if (filter.getSortOrder() != null && filter.getSortOrder().length() > 0) { sql.append(" ").append(filter.getSortOrder().toUpperCase()); } else { sql.append(" DESC"); - } - } + } + } } - + return sql.toString(); } - - private void synchronizeSurvey(Survey survey, String languageCode, boolean setSurvey) - { + + private void synchronizeSurvey(Survey survey, String languageCode, boolean setSurvey) { SurveyHelper.synchronizeSurvey(survey, languageCode, translationService, getLanguage(languageCode), setSurvey); } - + @Transactional - public Survey getSurvey(int id) - { + public Survey getSurvey(int id) { Session session = sessionFactory.getCurrentSession(); return (Survey) session.get(Survey.class, id); } - + @Transactional - public Survey getSurvey(int id, boolean readonly) - { - Session session = sessionFactory.getCurrentSession(); + public Survey getSurvey(int id, boolean readonly) { + Session session = sessionFactory.getCurrentSession(); Survey survey = (Survey) session.get(Survey.class, id); - + if (survey != null) { session.setReadOnly(survey, readonly); for (Element e : survey.getElementsRecursive(true)) { - e = (Element)session.merge(e); + e = (Element) session.merge(e); session.setReadOnly(e, readonly); } } - + return survey; } - + @Transactional(readOnly = true) public Survey getSurveyReadOnly(int id, boolean loadTranslations, boolean setSurvey) { return getSurvey(id, loadTranslations, true, true, setSurvey); } - + @Transactional public Survey getSurvey(int id, boolean loadTranslations, boolean readonly) { return getSurvey(id, loadTranslations, readonly, true, true); } - + @Transactional public Survey getSurvey(int id, boolean loadTranslations, boolean readonly, boolean synchronizeSurvey, boolean setSurvey) { - Session session = sessionFactory.getCurrentSession(); + Session session = sessionFactory.getCurrentSession(); Survey survey = (Survey) session.get(Survey.class, id); - - if (survey != null && survey.getIsDraft()) - { + + if (survey != null && survey.getIsDraft()) { List translations = translationService.getTranslationLanguagesForSurvey(survey.getId()); survey.setTranslations(translations); - } else if (survey != null && loadTranslations) - { + } else if (survey != null && loadTranslations) { List translations = translationService.getTranslationLanguagesForSurvey(survey.getId()); survey.setTranslations(translations); } if (survey != null && synchronizeSurvey) { synchronizeSurvey(survey, survey.getLanguage().getCode(), setSurvey); - + session.setReadOnly(survey, readonly); for (Element e : survey.getElementsRecursive(true)) { - e = (Element)session.merge(e); + e = (Element) session.merge(e); session.setReadOnly(e, readonly); } } - + return survey; } - + @Transactional - public Survey getSurveyByUniqueIdToWrite(String uid) - { + public Survey getSurveyByUniqueIdToWrite(String uid) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("SELECT id FROM Survey s WHERE s.uniqueId = :uid AND s.isDraft = :draft ORDER BY s.id DESC").setString("uid", uid); query.setBoolean("draft", true); - + @SuppressWarnings("unchecked") List list = query.setReadOnly(true).setMaxResults(1).list(); - if (list.size() > 0) - { + if (list.size() > 0) { Survey survey = getSurvey(ConversionTools.getValue(list.get(0))); return survey; } return null; } - + @Transactional(readOnly = true) - public Survey getSurveyByUniqueId(String uid, boolean loadTranslations, boolean draft) - { + public Survey getSurveyByUniqueId(String uid, boolean loadTranslations, boolean draft) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("SELECT id FROM Survey s WHERE s.uniqueId = :uid AND s.isDraft = :draft ORDER BY s.id DESC").setString("uid", uid); query.setBoolean("draft", draft); - + @SuppressWarnings("unchecked") List list = query.setReadOnly(true).setMaxResults(1).list(); - if (list.size() > 0) - { + if (list.size() > 0) { Survey survey = getSurvey(ConversionTools.getValue(list.get(0))); - - if (survey != null && loadTranslations) - { + + if (survey != null && loadTranslations) { List translations = translationService.getTranslationLanguagesForSurvey(survey.getId()); survey.setTranslations(translations); } - if (survey != null){ + if (survey != null) { synchronizeSurvey(survey, survey.getLanguage().getCode(), true); } - + session.setReadOnly(survey, true); for (Element e : survey.getElementsRecursive(true)) { session.setReadOnly(e, true); } - + return survey; } return null; } @Transactional - public Survey initializeAndMergeSurvey(Survey survey) - { + public Survey initializeAndMergeSurvey(Survey survey) { Session session = sessionFactory.getCurrentSession(); Survey s = (Survey) session.merge(survey); initializeSurvey(s); return s; } - - public void initializeSkin(Survey survey) - { - if (survey.getSkin() != null) - { + + public void initializeSkin(Survey survey) { + if (survey.getSkin() != null) { Hibernate.initialize(survey.getSkin().getElements()); - } + } } - - public void initializeSurvey(Survey survey) - { + + public void initializeSurvey(Survey survey) { Hibernate.initialize(survey.getBackgroundDocuments()); Hibernate.initialize(survey.getUsefulLinks()); Hibernate.initialize(survey.getPublication().getFilter().getVisibleQuestions()); Hibernate.initialize(survey.getPublication().getFilter().getExportedQuestions()); Hibernate.initialize(survey.getPublication().getFilter().getFilterValues()); Hibernate.initialize(survey.getPublication().getFilter().getLanguages()); - - if (survey.getSkin() != null) - { + + if (survey.getSkin() != null) { Hibernate.initialize(survey.getSkin().getElements()); - } - + } + for (Element element : survey.getElementsRecursive(true)) { - - if (element instanceof Question) - { + + if (element instanceof Question) { Question q = (Question) element; Hibernate.initialize(q.getScoringItems()); } - - if (element instanceof ChoiceQuestion) - { + + if (element instanceof ChoiceQuestion) { ChoiceQuestion question = (ChoiceQuestion) element; - for (PossibleAnswer answer: question.getPossibleAnswers()) - { + for (PossibleAnswer answer : question.getPossibleAnswers()) { Hibernate.initialize(answer.getDependentElements()); - if (answer.getDependentElements() != null) - { + if (answer.getDependentElements() != null) { Hibernate.initialize(answer.getDependentElements().getDependentElements()); } else { logger.warn("answer.getDependentElements() null for answer " + answer.getId()); } } - } else if (element instanceof Matrix) - { + } else if (element instanceof Matrix) { Matrix matrix = (Matrix) element; Hibernate.initialize(matrix.getDependentElements()); Hibernate.initialize(matrix.getChildElements()); - for (DependencyItem dep: matrix.getDependentElements()) - { + for (DependencyItem dep : matrix.getDependentElements()) { Hibernate.initialize(dep.getDependentElements()); } - } else if (element instanceof RatingQuestion) - { + } else if (element instanceof RatingQuestion) { RatingQuestion rating = (RatingQuestion) element; Hibernate.initialize(rating.getChildElements()); - } else if (element instanceof Table) - { + } else if (element instanceof Table) { Table table = (Table) element; - Hibernate.initialize(table.getChildElements()); - } else if (element instanceof Download) - { + Hibernate.initialize(table.getChildElements()); + } else if (element instanceof Download) { Download download = (Download) element; Hibernate.initialize(download.getFiles()); - } else if (element instanceof Confirmation) - { + } else if (element instanceof Confirmation) { Confirmation confirmation = (Confirmation) element; Hibernate.initialize(confirmation.getFiles()); - } else if (element instanceof GalleryQuestion) - { + } else if (element instanceof GalleryQuestion) { GalleryQuestion gallery = (GalleryQuestion) element; Hibernate.initialize(gallery.getFiles()); } } } - + @Transactional(readOnly = true) public Survey getSurvey(int id, String language) { Survey survey = getSurvey(id, false, true, false, true); synchronizeSurvey(survey, language, true); return survey; } - + @Transactional(readOnly = true) - public Survey getSurveyByShortname(String shortname, boolean isDraft, User u, HttpServletRequest request, boolean initElements, boolean checkNotArchived, boolean checkNotDeleted, boolean synchronize) throws InvalidURLException { - - if (shortname.equals("noform")) - { + public Survey getSurveyByShortname(String shortname, boolean isDraft, User u, HttpServletRequest request, boolean initElements, boolean checkNotArchived, boolean checkNotDeleted, + boolean synchronize) throws InvalidURLException { + + if (shortname.equals("noform")) { SessionInfo info = (SessionInfo) request.getSession().getAttribute("sessioninfo"); - - if (info != null) - { + + if (info != null) { Survey survey = getSurvey(info.getSurvey(), info.getLanguage()); - if (survey != null) return survey; + if (survey != null) + return survey; } - + throw new InvalidURLException(); } - + Survey survey = surveyService.getSurvey(shortname, isDraft, false, false, false, null, true, checkNotDeleted, true, synchronize); - + if (survey != null) { - List translations = translationService.getTranslationLanguagesForSurvey(survey.getId()); + List translations = translationService.getTranslationLanguagesForSurvey(survey.getId()); survey.setTranslations(translations); - - if (u != null) - { + + if (u != null) { boolean allowed = false; - if (!survey.getOwner().getId().equals(u.getId())) - { - if (u.getGlobalPrivileges().get(GlobalPrivilege.FormManagement) < 2) - { - if (u.getLocalPrivileges().get(LocalPrivilege.FormManagement) < 1) - { - if (u.getLocalPrivileges().get(LocalPrivilege.AccessDraft) > 0) - { + if (!survey.getOwner().getId().equals(u.getId())) { + if (u.getGlobalPrivileges().get(GlobalPrivilege.FormManagement) < 2) { + if (u.getLocalPrivileges().get(LocalPrivilege.FormManagement) < 1) { + if (u.getLocalPrivileges().get(LocalPrivilege.AccessDraft) > 0) { allowed = true; - } - if (u.getLocalPrivileges().get(LocalPrivilege.AccessResults) > 0) - { + } + if (u.getLocalPrivileges().get(LocalPrivilege.AccessResults) > 0) { allowed = true; - } - if (u.getLocalPrivileges().get(LocalPrivilege.ManageInvitations) > 0) - { + } + if (u.getLocalPrivileges().get(LocalPrivilege.ManageInvitations) > 0) { allowed = true; - } + } } } else { allowed = true; @@ -695,119 +650,113 @@ public Survey getSurveyByShortname(String shortname, boolean isDraft, User u, Ht } else { allowed = true; } - - if (allowed) sessionService.updateSessionInfo(survey, u, request); + + if (allowed) + sessionService.updateSessionInfo(survey, u, request); } - + if (initElements) - for (Element element: survey.getElementsRecursive()) - { - element.setSurvey(survey); - } - - if (checkNotArchived && (survey.getArchived() || survey.getIsDeleted())) - { + for (Element element : survey.getElementsRecursive()) { + element.setSurvey(survey); + } + + if (checkNotArchived && (survey.getArchived() || survey.getIsDeleted())) { throw new InvalidURLException(); } - + return survey; } throw new InvalidURLException(); } - + @Transactional - public Survey getSurveyWithMissingElements(String uidorshortname, boolean isDraft, boolean checkActive, boolean readReplies, boolean useEagerLoading, String language, boolean readonly, boolean synchronize) { + public Survey getSurveyWithMissingElements(String uidorshortname, boolean isDraft, boolean checkActive, boolean readReplies, boolean useEagerLoading, String language, boolean readonly, + boolean synchronize) { Survey survey = getSurvey(uidorshortname, isDraft, checkActive, readReplies, useEagerLoading, language, readonly, false, false, synchronize); - if (survey != null) CheckAndRecreateMissingElements(survey, null); + if (survey != null) + CheckAndRecreateMissingElements(survey, null); return survey; } - + @Transactional public Survey getSurvey(String uidorshortname, boolean isDraft, boolean checkActive, boolean readReplies, boolean useEagerLoading, String language, boolean readonly, boolean synchronize) { return getSurvey(uidorshortname, isDraft, checkActive, readReplies, useEagerLoading, language, readonly, false, false, synchronize); } - + @Transactional - public Survey getSurvey(String uidorshortname, boolean isDraft, boolean checkActive, boolean readReplies, boolean useEagerLoading, String language, boolean readonly, boolean checkNotDeleted, boolean shortnamefirst, boolean synchronize) { + public Survey getSurvey(String uidorshortname, boolean isDraft, boolean checkActive, boolean readReplies, boolean useEagerLoading, String language, boolean readonly, boolean checkNotDeleted, + boolean shortnamefirst, boolean synchronize) { Session session = sessionFactory.getCurrentSession(); String sql; - - if (shortnamefirst) - { + + if (shortnamefirst) { sql = "SELECT max(s.id) FROM Survey s WHERE (s.shortname = :uid OR s.uniqueId = :uid) AND s.isDraft = :draft"; } else { sql = "SELECT max(s.id) FROM Survey s WHERE (s.uniqueId = :uid OR s.shortname = :uid) AND s.isDraft = :draft"; } - - if (checkNotDeleted) - { + + if (checkNotDeleted) { sql += " AND (s.isDeleted is null OR s.isDeleted = false)"; } - + Query query = session.createQuery(sql).setString("uid", uidorshortname).setBoolean("draft", isDraft).setReadOnly(true); - + int id = ConversionTools.getValue(query.uniqueResult()); - + if (id > 0) { - + Survey survey = (Survey) session.get(Survey.class, id); - //logger.info("Refreshing survey " + id); - //session.refresh(survey); - - if (useEagerLoading) - { + // logger.info("Refreshing survey " + id); + // session.refresh(survey); + + if (useEagerLoading) { initializeSurvey(survey); } - - //used e.g. in form runner to check whether disclaimer has to be displayed + + // used e.g. in form runner to check whether disclaimer has to be displayed Hibernate.initialize(survey.getOwner().getRoles()); - - if (readReplies) - { - survey.setNumberOfAnswerSetsPublished(answerService.getNumberOfAnswerSetsPublished(uidorshortname, survey.getUniqueId())); + + if (readReplies) { + survey.setNumberOfAnswerSetsPublished(answerService.getNumberOfAnswerSetsPublished(uidorshortname, survey.getUniqueId())); } - - if (survey.getIsActive() && survey.getAutomaticPublishing() && survey.getEnd() != null && survey.getEnd().before(new Date())) - { + + if (survey.getIsActive() && survey.getAutomaticPublishing() && survey.getEnd() != null && survey.getEnd().before(new Date())) { survey.setIsActive(false); session.update(survey); - } else if (!survey.getIsActive() && survey.getAutomaticPublishing() && survey.getStart() != null && survey.getStart().before(new Date())) - { - if (survey.getEnd() == null || survey.getEnd().after(new Date())) - { + } else if (!survey.getIsActive() && survey.getAutomaticPublishing() && survey.getStart() != null && survey.getStart().before(new Date())) { + if (survey.getEnd() == null || survey.getEnd().after(new Date())) { survey.setIsActive(true); survey.setIsPublished(true); session.update(survey); } } - - if (checkActive && !isDraft) - { + + if (checkActive && !isDraft) { query = session.createQuery(sql).setString("uid", uidorshortname).setBoolean("draft", true); id = ConversionTools.getValue(query.uniqueResult()); - - if (id == 0) return null; - + + if (id == 0) + return null; + Survey draft = (Survey) session.get(Survey.class, id); - if (!draft.getIsActive()) return null; + if (!draft.getIsActive()) + return null; } - + session.setReadOnly(survey, readonly); for (Element e : survey.getElementsRecursive(true)) { - e = (Element)session.merge(e); + e = (Element) session.merge(e); session.setReadOnly(e, readonly); } - - if (synchronize) - { - if (language == null) - { + + if (synchronize) { + if (language == null) { synchronizeSurvey(survey, survey.getLanguage().getCode(), true); } else { synchronizeSurvey(survey, language, true); } } - List translations = translationService.getTranslationLanguagesForSurvey(survey.getId()); + List translations = translationService.getTranslationLanguagesForSurvey(survey.getId()); survey.setTranslations(translations); return survey; } @@ -817,7 +766,7 @@ public Survey getSurvey(String uidorshortname, boolean isDraft, boolean checkAct @Transactional public Survey add(Survey survey, int userId) { return add(survey, true, userId); - } + } @Transactional public Survey add(Survey survey, boolean synchronize, int userId) { @@ -827,32 +776,28 @@ public Survey add(Survey survey, boolean synchronize, int userId) { survey.setCreated(new Date()); survey.setUpdated(survey.getCreated()); } - if (survey.getUniqueId() == null || survey.getUniqueId().length() == 0) - { + if (survey.getUniqueId() == null || survey.getUniqueId().length() == 0) { survey.setUniqueId(UUID.randomUUID().toString()); } Session session = sessionFactory.getCurrentSession(); int id = (Integer) session.save(survey); Survey result = (Survey) session.get(Survey.class, id); - + UpdatePossibleAnswers(result); session.update(result); - - if (synchronize) synchronizeTranslation(survey, userId); - + + if (synchronize) + synchronizeTranslation(survey, userId); + reportingService.addToDo(ToDo.CHANGEDDRAFTSURVEY, survey.getUniqueId(), null); - + return result; - } - - private void UpdatePossibleAnswers(Survey survey) - { - for (Element element: survey.getElements()) - { - if (element instanceof ChoiceQuestion) - { - for (PossibleAnswer pa: ((ChoiceQuestion)element).getPossibleAnswers()) - { + } + + private void UpdatePossibleAnswers(Survey survey) { + for (Element element : survey.getElements()) { + if (element instanceof ChoiceQuestion) { + for (PossibleAnswer pa : ((ChoiceQuestion) element).getPossibleAnswers()) { pa.setQuestionId(element.getId()); } } @@ -860,47 +805,122 @@ private void UpdatePossibleAnswers(Survey survey) } @Transactional - public Survey publish(Survey survey, int pnumberOfAnswerSets, int pnumberOfAnswerSetsPublished, boolean deactivateAutoPublishing, int userId, boolean resetSourceIds, boolean resetSurvey) throws Exception + private void computeTrustScore(Survey survey) throws Exception { - //this means to create a copy of the survey and save it as non-draft survey - Session session = sessionFactory.getCurrentSession(); - boolean alreadyPublished = survey.getIsPublished(); + Session session = sessionFactory.getCurrentSession(); + int score = 0; + + int trustValueCreatorInternal = Integer.parseInt(settingsService.get(Setting.TrustValueCreatorInternal)); + int trustValuePastSurveys = Integer.parseInt(settingsService.get(Setting.TrustValuePastSurveys)); + int trustValuePrivilegedUser = Integer.parseInt(settingsService.get(Setting.TrustValuePrivilegedUser)); + int trustValueNbContributions = Integer.parseInt(settingsService.get(Setting.TrustValueNbContributions)); + + //Rule 0: if the Form Manager is internal + if (!survey.getOwner().isExternal()) + { + score += trustValueCreatorInternal; + } + + //Rule 1: if the Form Manager has published in the past 3 or more surveys: + //- having all reached 10 contributions or more ; and + //- including at least one survey having been published for one month or more + + SurveyFilter filter = new SurveyFilter(); + filter.setUser(survey.getOwner()); + filter.setOwner(survey.getOwner().getLogin()); + SqlPagination pagination = new SqlPagination(1, 1000); + List surveys = getSurveysIncludingPublicationDates(filter, pagination); + + int countSurveysWith10Contributions = 0; + boolean found = false; + Calendar c = Calendar.getInstance(); + c.setTime(new Date()); + c.add(Calendar.MONTH, -1); + Date lastmonth = c.getTime(); + for (Survey candidate: surveys) { + int candidateanswers = answerService.getNumberOfAnswerSetsPublished(candidate.getShortname(), candidate.getUniqueId()); + if (candidateanswers >= 10) + { + countSurveysWith10Contributions++; + } + + if (candidate.getFirstPublished() != null && candidate.getFirstPublished().before(lastmonth)) + { + found = true; + } + + if (found && countSurveysWith10Contributions >= 3) { + break; + } + } + if (found && countSurveysWith10Contributions >= 3) { + score += trustValuePastSurveys; + } + + //Rule 2: if a privileged user is internal + List accesses = this.getAccesses(survey.getId()); + for (Access access : accesses) { + if (access.getUser() != null && !access.getUser().isExternal()) + { + score += trustValuePrivilegedUser; + break; + } + } + + int answers = answerService.getNumberOfAnswerSetsPublished(survey.getShortname(), survey.getUniqueId()); + + //Rule 3: when the survey is reaching 10 contributions + if (answers >= 10) + { + score += trustValueNbContributions; + } - if (resetSurvey) + //Rule 4: when the survey is reaching 100 contributions + if (answers >= 100) { + score += trustValueNbContributions; + } + + survey.setTrustScore(score); + session.saveOrUpdate(survey); + } + + @Transactional + public Survey publish(Survey survey, int pnumberOfAnswerSets, int pnumberOfAnswerSetsPublished, boolean deactivateAutoPublishing, int userId, boolean resetSourceIds, boolean resetSurvey) + throws Exception { + // this means to create a copy of the survey and save it as non-draft survey + Session session = sessionFactory.getCurrentSession(); + boolean alreadyPublished = survey.getIsPublished(); + + if (resetSurvey) { session.evict(survey); survey = (Survey) session.merge(survey); } - + Survey published = survey.copy(this, survey.getOwner(), fileDir, true, pnumberOfAnswerSets, pnumberOfAnswerSetsPublished, true, resetSourceIds, true, null, null); - published.setIsDraft(false); //this means it is not a draft - if (deactivateAutoPublishing) - { + published.setIsDraft(false); // this means it is not a draft + if (deactivateAutoPublishing) { published.setAutomaticPublishing(false); } - published = update(published, false, true, false, userId); - - //copy translations + published = update(published, false, true, false, userId); + + computeTrustScore(survey); + + // copy translations Map keys = new HashMap<>(); - for (Element element: published.getElementsRecursive()) - { + for (Element element : published.getElementsRecursive()) { keys.put(element.getUniqueId(), element.getUniqueId()); keys.put(element.getSourceId().toString(), element.getId().toString()); - if (element instanceof ChoiceQuestion) - { - for (PossibleAnswer answer: ((ChoiceQuestion)element).getPossibleAnswers()) - { + if (element instanceof ChoiceQuestion) { + for (PossibleAnswer answer : ((ChoiceQuestion) element).getPossibleAnswers()) { keys.put(answer.getUniqueId(), answer.getUniqueId()); keys.put(answer.getSourceId().toString(), answer.getId().toString()); } } - if (element instanceof Question) - { + if (element instanceof Question) { Question question = (Question) element; - if (question.getScoringItems() != null) - { - for (ScoringItem scoringItem: question.getScoringItems()) - { + if (question.getScoringItems() != null) { + for (ScoringItem scoringItem : question.getScoringItems()) { keys.put(scoringItem.getUniqueId(), scoringItem.getUniqueId()); keys.put(scoringItem.getSourceId().toString(), scoringItem.getId().toString()); } @@ -908,10 +928,8 @@ public Survey publish(Survey survey, int pnumberOfAnswerSets, int pnumberOfAnswe } } List translations = translationService.getTranslationsForSurvey(survey.getId(), true); - for (Translations translation: translations) - { - if (!translation.getLanguage().getCode().equalsIgnoreCase(survey.getLanguage().getCode())) - { + for (Translations translation : translations) { + if (!translation.getLanguage().getCode().equalsIgnoreCase(survey.getLanguage().getCode())) { Translations tcopy = new Translations(); tcopy.setActive(translation.getActive()); tcopy.setLanguage(translation.getLanguage()); @@ -919,95 +937,79 @@ public Survey publish(Survey survey, int pnumberOfAnswerSets, int pnumberOfAnswe tcopy.setSurveyUid(published.getUniqueId()); tcopy.setTitle(translation.getTitle()); tcopy.setComplete(translation.getComplete()); - - for (Translation t: translation.getTranslations()) - { + + for (Translation t : translation.getTranslations()) { Translation tc = new Translation(); tc.setLabel(t.getLabel()); tc.setLanguage(t.getLanguage()); tc.setSurveyId(published.getId()); tc.setTranslations(tcopy); - if (t.getKey().equalsIgnoreCase(Survey.TITLE) || t.getKey().equalsIgnoreCase(Survey.INTRODUCTION) || t.getKey().equalsIgnoreCase(Survey.ESCAPEPAGE) || t.getKey().equalsIgnoreCase(Survey.ESCAPELINK) || t.getKey().equalsIgnoreCase(Survey.CONFIRMATIONPAGE) || t.getKey().equalsIgnoreCase(Survey.CONFIRMATIONLINK) || t.getKey().equalsIgnoreCase(Survey.HELP) || t.getKey().equalsIgnoreCase(Survey.QUIZWELCOMEMESSAGE) || t.getKey().equalsIgnoreCase(Survey.QUIZRESULTSMESSAGE)) - { + if (t.getKey().equalsIgnoreCase(Survey.TITLE) || t.getKey().equalsIgnoreCase(Survey.INTRODUCTION) || t.getKey().equalsIgnoreCase(Survey.ESCAPEPAGE) + || t.getKey().equalsIgnoreCase(Survey.ESCAPELINK) || t.getKey().equalsIgnoreCase(Survey.CONFIRMATIONPAGE) || t.getKey().equalsIgnoreCase(Survey.CONFIRMATIONLINK) + || t.getKey().equalsIgnoreCase(Survey.HELP) || t.getKey().equalsIgnoreCase(Survey.QUIZWELCOMEMESSAGE) || t.getKey().equalsIgnoreCase(Survey.QUIZRESULTSMESSAGE)) { tc.setKey(t.getKey()); tcopy.getTranslations().add(tc); } else { - if (t.getKey().endsWith("help")) - { + if (t.getKey().endsWith("help")) { String k = t.getKey().replace("help", ""); - if (keys.containsKey(k)) - { + if (keys.containsKey(k)) { tc.setKey(keys.get(k) + "help"); tcopy.getTranslations().add(tc); } else { logger.info("key " + t.getKey() + " not found in key map for translation"); } - } else if (t.getKey().endsWith("FEEDBACK")) - { + } else if (t.getKey().endsWith("FEEDBACK")) { String k = t.getKey().replace("FEEDBACK", ""); - if (keys.containsKey(k)) - { + if (keys.containsKey(k)) { tc.setKey(keys.get(k) + "FEEDBACK"); tcopy.getTranslations().add(tc); } else { logger.info("key " + t.getKey() + " not found in key map for translation"); } - } else if (t.getKey().endsWith("UNIT")) - { + } else if (t.getKey().endsWith("UNIT")) { String k = t.getKey().replace("UNIT", ""); - if (keys.containsKey(k)) - { + if (keys.containsKey(k)) { tc.setKey(keys.get(k) + "UNIT"); tcopy.getTranslations().add(tc); } else { logger.info("key " + t.getKey() + " not found in key map for translation"); } - } else if (t.getKey().endsWith("CONFIRMATIONTEXT")) - { + } else if (t.getKey().endsWith("CONFIRMATIONTEXT")) { String k = t.getKey().replace("CONFIRMATIONTEXT", ""); - if (keys.containsKey(k)) - { + if (keys.containsKey(k)) { tc.setKey(keys.get(k) + "CONFIRMATIONTEXT"); tcopy.getTranslations().add(tc); } else { logger.info("key " + t.getKey() + " not found in key map for translation"); } - } else if (t.getKey().endsWith("CONFIRMATIONLABEL")) - { + } else if (t.getKey().endsWith("CONFIRMATIONLABEL")) { String k = t.getKey().replace("CONFIRMATIONLABEL", ""); - if (keys.containsKey(k)) - { + if (keys.containsKey(k)) { tc.setKey(keys.get(k) + "CONFIRMATIONLABEL"); tcopy.getTranslations().add(tc); } else { logger.info("key " + t.getKey() + " not found in key map for translation"); } - } else if (t.getKey().endsWith("TABTITLE")) - { + } else if (t.getKey().endsWith("TABTITLE")) { String k = t.getKey().replace("TABTITLE", ""); - if (keys.containsKey(k)) - { + if (keys.containsKey(k)) { tc.setKey(keys.get(k) + "TABTITLE"); tcopy.getTranslations().add(tc); } else { logger.info("key " + t.getKey() + " not found in key map for translation"); } - } else if (t.getKey().endsWith("shortname")) - { - String k = t.getKey().replace("shortname", ""); - if (keys.containsKey(k)) - { - tc.setKey(keys.get(k) + "shortname"); - tcopy.getTranslations().add(tc); - } else { - logger.info("key " + t.getKey() + " not found in key map for translation"); - } - } else if (t.getKey().endsWith("#backgrounddocument") || t.getKey().endsWith("#usefullink")) - { + } else if (t.getKey().endsWith("shortname")) { + String k = t.getKey().replace("shortname", ""); + if (keys.containsKey(k)) { + tc.setKey(keys.get(k) + "shortname"); + tcopy.getTranslations().add(tc); + } else { + logger.info("key " + t.getKey() + " not found in key map for translation"); + } + } else if (t.getKey().endsWith("#backgrounddocument") || t.getKey().endsWith("#usefullink")) { tc.setKey(t.getKey()); tcopy.getTranslations().add(tc); - } else if (keys.containsKey(t.getKey())) - { + } else if (keys.containsKey(t.getKey())) { tc.setKey(keys.get(t.getKey())); tcopy.getTranslations().add(tc); } else { @@ -1018,49 +1020,46 @@ public Survey publish(Survey survey, int pnumberOfAnswerSets, int pnumberOfAnswe translationService.save(tcopy); } } - + Survey ob = null; ob = (Survey) session.get(Survey.class, survey.getId()); - + ob.setIsPublished(true); ob.setHasPendingChanges(false); - - if (deactivateAutoPublishing) - { + + if (deactivateAutoPublishing) { ob.setAutomaticPublishing(false); survey.setAutomaticPublishing(false); } - + survey.setHasPendingChanges(false); - + session.update(ob); survey.setIsPublished(true); - - if (!alreadyPublished) reportingService.addToDo(ToDo.NEWSURVEY, survey.getUniqueId(), null); - + + if (!alreadyPublished) + reportingService.addToDo(ToDo.NEWSURVEY, survey.getUniqueId(), null); + return published; } - + @Transactional - public Survey activate(Survey survey, boolean deactivateAutoPublishing, int userId) throws Exception - { - //this means to create a copy of the survey and save it as non-draft survey - Session session = sessionFactory.getCurrentSession(); - + public Survey activate(Survey survey, boolean deactivateAutoPublishing, int userId) throws Exception { + // this means to create a copy of the survey and save it as non-draft survey + Session session = sessionFactory.getCurrentSession(); + Survey published = getSurvey(survey.getShortname(), false, false, false, false, null, false, false); - - if (published != null) - { + + if (published != null) { published.setIsActive(true); - if (deactivateAutoPublishing) - { + if (deactivateAutoPublishing) { published.setAutomaticPublishing(false); } - update(published, false, false, false, userId); + update(published, false, false, false, userId); } else { throw new Exception("Survey does not exist"); } - + // hibernate: transactional change of local variable Survey ob = null; ob = (Survey) session.get(Survey.class, survey.getId()); @@ -1068,29 +1067,30 @@ public Survey activate(Survey survey, boolean deactivateAutoPublishing, int user ob.setIsActive(true); ob.setIsPublished(true); ob.setNotified(false); - if (deactivateAutoPublishing) - { + if (deactivateAutoPublishing) { ob.setAutomaticPublishing(false); survey.setAutomaticPublishing(false); } session.update(ob); - + survey.setIsPublished(true); - survey.setIsActive(true); + survey.setIsActive(true); + computeTrustScore(survey); + return published; } - + @Transactional public Survey clearChanges(String shortname, int userId) throws Exception { Session session = sessionFactory.getCurrentSession(); - + Survey survey = this.getSurvey(shortname, true, false, false, false, null, false, false); - + boolean active = survey.getIsActive(); - + Survey publishedSurvey = this.getSurvey(shortname, false, false, false, false, null, true, false); - + // hibernate: transactional change of local variable Survey newDraft = publish(publishedSurvey, survey.getNumberOfAnswerSets(), survey.getNumberOfAnswerSetsPublished(), false, userId, true, false); newDraft.setCreated(survey.getCreated()); @@ -1098,140 +1098,125 @@ public Survey clearChanges(String shortname, int userId) throws Exception { newDraft.setIsPublished(true); newDraft.setIsActive(active); session.update(newDraft); - + AdaptIDs(survey, newDraft, true, survey.getUniqueIDsByID()); - //delete original - deleteSurveyData(survey.getId(), false, false, survey.getUniqueId(), false); - session.delete(survey); - + // delete original + deleteSurveyData(survey.getId(), false, false, survey.getUniqueId(), false); + session.delete(survey); + return newDraft; } @Transactional - public void unpublish(Survey survey, boolean deactivateAutoPublishing, int userId) - { + public void unpublish(Survey survey, boolean deactivateAutoPublishing, int userId) { Session session = sessionFactory.getCurrentSession(); - + Survey publishedSurvey = this.getSurvey(survey.getShortname(), false, false, false, false, null, false, false); - - if (publishedSurvey == null) - { + + if (publishedSurvey == null) { publishedSurvey = this.getSurvey(survey.getUniqueId(), false, false, false, false, null, false, false); } - - if (publishedSurvey != null) - { + + if (publishedSurvey != null) { publishedSurvey.setIsActive(false); - if (deactivateAutoPublishing) - { + if (deactivateAutoPublishing) { publishedSurvey.setAutomaticPublishing(false); publishedSurvey.setNotificationValue(null); publishedSurvey.setNotificationUnit(null); } update(publishedSurvey, false, false, false, userId); } - - Survey ob = null; - ob = (Survey) session.get(Survey.class, survey.getId()); - session.setReadOnly(ob, false); - - ob.setIsActive(false); - - if (deactivateAutoPublishing) - { - ob.setAutomaticPublishing(false); - ob.setNotificationValue(null); - ob.setNotificationUnit(null); - survey.setAutomaticPublishing(false); - survey.setNotificationValue(null); - survey.setNotificationUnit(null); - } - - survey.setIsActive(false); - - session.update(ob); + + Survey ob = null; + ob = (Survey) session.get(Survey.class, survey.getId()); + session.setReadOnly(ob, false); + + ob.setIsActive(false); + + if (deactivateAutoPublishing) { + ob.setAutomaticPublishing(false); + ob.setNotificationValue(null); + ob.setNotificationUnit(null); + survey.setAutomaticPublishing(false); + survey.setNotificationValue(null); + survey.setNotificationUnit(null); } - - public static HashMap getUniqueIdsById(Survey publishedSurvey) - { + + survey.setIsActive(false); + + session.update(ob); + } + + public static HashMap getUniqueIdsById(Survey publishedSurvey) { HashMap oldUniqueIdsById = new HashMap<>(); for (Element element : publishedSurvey.getElementsRecursive(true)) { oldUniqueIdsById.put(element.getId(), element.getUniqueId()); - } + } return oldUniqueIdsById; } - - private HashMap getSourceIdsById(Survey publishedSurvey) - { + + private HashMap getSourceIdsById(Survey publishedSurvey) { HashMap oldSourceIdsById = new HashMap<>(); for (Element element : publishedSurvey.getElementsRecursive()) { oldSourceIdsById.put(element.getId(), element.getSourceId()); - } + } return oldSourceIdsById; } - - - private void AdaptIDs(Survey oldSurvey, Survey newSurvey, boolean isDraft, Map draftUniqueIDsByID) throws Exception - { + + private void AdaptIDs(Survey oldSurvey, Survey newSurvey, boolean isDraft, Map draftUniqueIDsByID) throws Exception { Session session = sessionFactory.getCurrentSession(); - - if (isDraft) - { - //get existing answers and change survey reference - List answers = answerService.getAnswersAndDrafts(oldSurvey.getId()); + + if (isDraft) { + // get existing answers and change survey reference + List answers = answerService.getAnswersAndDrafts(oldSurvey.getId()); for (AnswerSet answerSet : answers) { answerSet.setSurvey(newSurvey); answerSet.setSurveyId(newSurvey.getId()); - + session.update(answerSet); } - - //also update draft-specific data - - //update privileges + + // also update draft-specific data + + // update privileges List accesses = getAccesses(oldSurvey.getId()); - for (Access access: accesses) - { + for (Access access : accesses) { access.setSurvey(newSurvey); session.update(access); } } } - + public void updateAnswerUids(int id, String uid, boolean pa) throws Exception { boolean saved = false; - + int counter = 1; - - while(!saved) - { + + while (!saved) { try { internalUpdateAnswerUids(id, uid, pa); saved = true; - } catch (org.hibernate.exception.LockAcquisitionException ex) - { + } catch (org.hibernate.exception.LockAcquisitionException ex) { logger.info("lock on answerSet table catched; retry counter: " + counter); counter++; - - if (counter > 60) - { + + if (counter > 60) { logger.error(ex.getLocalizedMessage(), ex); throw ex; } - + Thread.sleep(1000); } - } + } } - + @Transactional private void internalUpdateAnswerUids(int id, String uid, boolean pa) { Session session = sessionFactory.getCurrentSession(); Query query; - - if (pa) - { + + if (pa) { query = session.createSQLQuery("UPDATE ANSWERS SET PA_UID = :uid WHERE PA_UID IS NULL AND PA_ID = :id"); } else { query = session.createSQLQuery("UPDATE ANSWERS SET QUESTION_UID = :uid WHERE QUESTION_UID IS NULL AND QUESTION_ID = :id"); @@ -1241,24 +1226,22 @@ private void internalUpdateAnswerUids(int id, String uid, boolean pa) { } @Transactional - public int applyChanges(Survey survey, boolean deactivateAutoPublishing, int userId, boolean resetSurey) throws Exception - { - if (resetSurey) - { + public int applyChanges(Survey survey, boolean deactivateAutoPublishing, int userId, boolean resetSurey) throws Exception { + if (resetSurey) { Session session = sessionFactory.getCurrentSession(); session.evict(survey); survey = (Survey) session.merge(survey); initializeSurvey(survey); } - + boolean sendListFormMail = survey.isListFormValidated(); - + Map uniqueIDSByID = survey.getUniqueIDsByID(); - + Survey publishedSurvey = getSurvey(survey.getShortname(), false, false, false, true, null, true, false); - + Survey newPublishedSurvey = publish(survey, -1, -1, deactivateAutoPublishing, userId, false, false); - newPublishedSurvey.setVersion(publishedSurvey.getVersion()+1); + newPublishedSurvey.setVersion(publishedSurvey.getVersion() + 1); newPublishedSurvey.setIsActive(publishedSurvey.getIsActive()); newPublishedSurvey.setNotified(publishedSurvey.getNotified()); newPublishedSurvey.setListFormValidated(false); @@ -1273,377 +1256,329 @@ public int applyChanges(Survey survey, boolean deactivateAutoPublishing, int use survey.setHasPendingChanges(false); survey.setListFormValidated(false); survey.setPublicationRequestedDate(new Date()); + + computeTrustScore(survey); - //copy result filters + // copy result filters List filters = sessionService.getAllResultFilter(publishedSurvey.getId()); - if (filters != null) - { - for (ResultFilter filter: filters) - { - //do not copy filters of exports + if (filters != null) { + for (ResultFilter filter : filters) { + // do not copy filters of exports Export export = exportService.getExportByResultFilterID(filter.getId()); - if (export == null) - { + if (export == null) { ResultFilter newFilter = filter.copy(); - - if (filter.getDefaultQuestions() == null || !filter.getDefaultQuestions()) - { + + if (filter.getDefaultQuestions() == null || !filter.getDefaultQuestions()) { Map uidsById = publishedSurvey.getUniqueIDsByID(); Map idsByUid = newPublishedSurvey.getIDsByUniqueID(); Set newids = new HashSet(); - for (String sid : filter.getVisibleQuestions()) - { + for (String sid : filter.getVisibleQuestions()) { String uid = uidsById.get(sid); - if (uid != null) - { + if (uid != null) { String id = idsByUid.get(uid); - if (id != null) - { + if (id != null) { newids.add(id); } } } newFilter.setVisibleQuestions(newids); - + newids = new HashSet(); - for (String sid : filter.getExportedQuestions()) - { + for (String sid : filter.getExportedQuestions()) { String uid = uidsById.get(sid); - if (uid != null) - { + if (uid != null) { String id = idsByUid.get(uid); - if (id != null) - { + if (id != null) { newids.add(id); } } } newFilter.setExportedQuestions(newids); } - + newFilter.setSurveyId(newPublishedSurvey.getId()); - if (filter.getUserId() != null) - { + if (filter.getUserId() != null) { sessionService.internalSetLastResultFilter(newFilter, filter.getUserId(), newFilter.getSurveyId()); } } } } - + update(survey, true); - - if (sendListFormMail) - { + + if (sendListFormMail) { sendListFormMail(survey); } - - if (survey.getIsOPC()) - { + + if (survey.getIsOPC()) { sendOPCApplyChangesMail(survey, userId); } - + fileService.deleteOldSurveyPDFs(publishedSurvey.getUniqueId(), publishedSurvey.getId()); answerService.deleteStatisticsForSurvey(publishedSurvey.getId()); - + reportingService.addToDo(ToDo.CHANGEDSURVEY, survey.getUniqueId(), null); - + return newPublishedSurvey.getId(); } - + @Transactional - public void makeDirty(int id) - { + public void makeDirty(int id) { Session session = sessionFactory.getCurrentSession(); Survey survey = (Survey) session.get(Survey.class, id); session.setReadOnly(survey, false); survey.setHasPendingChanges(true); session.update(survey); } - + @Transactional(readOnly = false) - public void makeClean(int id) - { + public void makeClean(int id) { Session session = sessionFactory.getCurrentSession(); - + Query query = session.createQuery("UPDATE Survey s SET s.hasPendingChanges = false WHERE s.id = :id"); query.setInteger("id", id); query.executeUpdate(); } - + @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) - public Survey editSave(Survey oldsurvey, HttpServletRequest request) throws Exception - { + public Survey editSave(Survey oldsurvey, HttpServletRequest request) throws Exception { Session session = sessionFactory.getCurrentSession(); - + Map referencedFiles = oldsurvey.getReferencedFileUIDs(contextpath); - Map fileIDsByUID = new HashMap<>(); - - //File and dependent elements are recreated during parsing - for (Element element : oldsurvey.getElements()) - { - if (element instanceof Download) - { - Download download = (Download)element; - - for (File file : download.getFiles()) - { + Map fileIDsByUID = new HashMap<>(); + + // File and dependent elements are recreated during parsing + for (Element element : oldsurvey.getElements()) { + if (element instanceof Download) { + Download download = (Download) element; + + for (File file : download.getFiles()) { fileIDsByUID.put(file.getUid(), file.getId()); } - + download.getFiles().clear(); - } else if (element instanceof Confirmation) - { - Confirmation confirmation = (Confirmation)element; - - for (File file : confirmation.getFiles()) - { + } else if (element instanceof Confirmation) { + Confirmation confirmation = (Confirmation) element; + + for (File file : confirmation.getFiles()) { fileIDsByUID.put(file.getUid(), file.getId()); } - + confirmation.getFiles().clear(); - } else if (element instanceof GalleryQuestion) - { - GalleryQuestion gallery = (GalleryQuestion)element; - - for (File file : gallery.getFiles()) - { + } else if (element instanceof GalleryQuestion) { + GalleryQuestion gallery = (GalleryQuestion) element; + + for (File file : gallery.getFiles()) { fileIDsByUID.put(file.getUid(), file.getId()); } - + gallery.getFiles().clear(); } - } - - oldsurvey = (Survey)session.merge(oldsurvey); + } + + oldsurvey = (Survey) session.merge(oldsurvey); session.update(oldsurvey); - + Survey survey = SurveyHelper.parseSurvey(request, this, true, fileService, servletContext, activityService.isEnabled(217), activityService.isEnabled(220), fileIDsByUID); - + Map pendingChanges = surveyService.getPendingChanges(survey); - + update(survey, pendingChanges.size() > 0, true, false, sessionService.getCurrentUser(request).getId()); - + Map referencedFilesNew = survey.getReferencedFileUIDs(contextpath); - - for (String fileuid : referencedFiles.keySet()) - { - if (!referencedFilesNew.containsKey(fileuid)) - { + + for (String fileuid : referencedFiles.keySet()) { + if (!referencedFilesNew.containsKey(fileuid)) { fileService.delete(referencedFiles.get(fileuid)); fileService.deleteIfNotReferenced(fileuid, survey.getUniqueId()); } } - + activityService.log(survey.getActivitiesToLog(), sessionService.getCurrentUser(request).getId(), survey.getUniqueId()); - + survey = getSurvey(survey.getId(), false, false); - + return survey; } - + @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class) public Survey update(Survey survey, boolean hasPendingChanges, boolean synchronizeTranslations, boolean mergeFirst, int userId) { Session session = sessionFactory.getCurrentSession(); survey.setHasPendingChanges(hasPendingChanges); survey.setUpdated(new Date()); - - if (survey.getRegistrationForm()) - { + + if (survey.getRegistrationForm()) { boolean[] result = checkRegistrationFormElements(survey); - if (!result[0] || !result[1]) - { + if (!result[0] || !result[1]) { survey.setRegistrationForm(false); } - } - - if (mergeFirst) - { + } + + if (mergeFirst) { Survey existing = (Survey) session.get(Survey.class, survey.getId()); session.evict(existing); survey = (Survey) session.merge(survey); session.setReadOnly(survey, false); } session.update(survey); - + session.flush(); - + UpdatePossibleAnswers(survey); session.update(survey); - + session.flush(); - - if (synchronizeTranslations) synchronizeTranslation(survey, userId); - + + if (synchronizeTranslations) + synchronizeTranslation(survey, userId); + if (survey.getTranslations() != null) - for (String lang : survey.getTranslations()) { - try - { - java.io.File target = fileService.getSurveyPDFFile(survey.getUniqueId(), survey.getId(), lang); - if (target.exists()) target.delete(); - } catch (Exception e) - { - logger.error(e.getLocalizedMessage(), e); - } - } - + for (String lang : survey.getTranslations()) { + try { + java.io.File target = fileService.getSurveyPDFFile(survey.getUniqueId(), survey.getId(), lang); + if (target.exists()) + target.delete(); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + } + return survey; } - - public boolean[] checkRegistrationFormElements(Survey survey) - { + + public boolean[] checkRegistrationFormElements(Survey survey) { boolean[] result = new boolean[2]; result[0] = false; result[1] = false; - - //check if name and email questions exist - for (Element element: survey.getElements()) - { - if (element instanceof Question) - { - Question question = (Question)element; - - if (question.getIsAttribute() && !question.getOptional()) - { - if (question.getAttributeName().equalsIgnoreCase("name")) result[0] = true; - if (question.getAttributeName().equalsIgnoreCase("email")) result[1] = true; - if (result[0] && result[1]) break; - } + + // check if name and email questions exist + for (Element element : survey.getElements()) { + if (element instanceof Question) { + Question question = (Question) element; + + if (question.getIsAttribute() && !question.getOptional()) { + if (question.getAttributeName().equalsIgnoreCase("name")) + result[0] = true; + if (question.getAttributeName().equalsIgnoreCase("email")) + result[1] = true; + if (result[0] && result[1]) + break; + } } } - + return result; } - + @Transactional public Survey update(Survey survey, boolean evict) { Session session = sessionFactory.getCurrentSession(); - if (evict) - { + if (evict) { session.evict(survey); - survey = (Survey)session.merge(survey); + survey = (Survey) session.merge(survey); } session.update(survey); return survey; } - + private void synchronizeTranslation(Survey survey, int userId) { - Map oldInfo = null; + Map oldInfo = null; Translations translations = TranslationsHelper.getTranslations(survey, false); - if (translations != null) - { + if (translations != null) { Translations originalTranslations = translationService.getTranslations(survey.getId(), survey.getLanguage().getCode()); - if (originalTranslations != null) - { + if (originalTranslations != null) { oldInfo = originalTranslations.getInfo(); - Map originalTranslationsMap = originalTranslations.getTranslationsByKey(); - Map newTranslationsMap = translations.getTranslationsByKey(); + Map originalTranslationsMap = originalTranslations.getTranslationsByKey(); + Map newTranslationsMap = translations.getTranslationsByKey(); boolean structureChanges = false; - for (Translation translation: translations.getTranslations()) - { - if (!originalTranslationsMap.containsKey(translation.getKey())) - { - if (!translation.getKey().endsWith("help") && !translation.getKey().endsWith("UNIT") && !translation.getKey().endsWith("TABTITLE")) - { + for (Translation translation : translations.getTranslations()) { + if (!originalTranslationsMap.containsKey(translation.getKey())) { + if (!translation.getKey().endsWith("help") && !translation.getKey().endsWith("UNIT") && !translation.getKey().endsWith("TABTITLE")) { structureChanges = true; break; } } } - + List deletedElements = new ArrayList<>(); - for (Translation translation: originalTranslations.getTranslations()) - { - if (!newTranslationsMap.containsKey(translation.getKey())) - { - if (!translation.getKey().endsWith("help") && !translation.getKey().endsWith("UNIT") && !translation.getKey().endsWith("TABTITLE")) - { - if (!deletedElements.contains(translation.getKey())) - { + for (Translation translation : originalTranslations.getTranslations()) { + if (!newTranslationsMap.containsKey(translation.getKey())) { + if (!translation.getKey().endsWith("help") && !translation.getKey().endsWith("UNIT") && !translation.getKey().endsWith("TABTITLE")) { + if (!deletedElements.contains(translation.getKey())) { deletedElements.add(translation.getKey()); } } } } - + List allTranslations = translationService.getTranslationsForSurvey(survey.getId(), false); - - if (structureChanges) - { - //invalidate all other translations - for (Translations invalidTranslations: allTranslations) - { - if (invalidTranslations.getActive() && !invalidTranslations.getLanguage().getCode().equalsIgnoreCase(survey.getLanguage().getCode())) - { + + if (structureChanges) { + // invalidate all other translations + for (Translations invalidTranslations : allTranslations) { + if (invalidTranslations.getActive() && !invalidTranslations.getLanguage().getCode().equalsIgnoreCase(survey.getLanguage().getCode())) { invalidTranslations.setActive(false); translationService.save(invalidTranslations); } } } - - for (Translations existingTranslations: allTranslations) - { + + for (Translations existingTranslations : allTranslations) { boolean changed = false; - for (String key: deletedElements) - { - if (!existingTranslations.getLanguage().getCode().equalsIgnoreCase(survey.getLanguage().getCode())) - { + for (String key : deletedElements) { + if (!existingTranslations.getLanguage().getCode().equalsIgnoreCase(survey.getLanguage().getCode())) { changed = changed || existingTranslations.removeTranslationByKey(key); } } - if (changed) - { + if (changed) { translationService.save(existingTranslations); } } } - + translationService.deleteTranslations(survey.getId(), survey.getLanguage().getCode()); translations.setComplete(TranslationsHelper.isComplete(translations, survey)); translationService.save(translations); - + activityService.logTranslations(227, translations.getLanguage().getCode(), oldInfo, translations.getInfo(), userId, survey.getUniqueId()); } } - private void deleteSurveyData(int id, boolean deleteAnswers, boolean deleteAccesses, String uid, boolean deleteLogs) - { + private void deleteSurveyData(int id, boolean deleteAnswers, boolean deleteAccesses, String uid, boolean deleteLogs) { Session session = sessionFactory.getCurrentSession(); - - if (deleteAnswers) - { - Query query0 = session.createSQLQuery("SELECT fi.FILE_UID from FILES fi JOIN ANSWERS_FILES f ON fi.FILE_ID = f.files_FILE_ID JOIN ANSWERS a ON f.ANSWERS_ANSWER_ID = a.ANSWER_ID JOIN ANSWERS_SET an ON a.AS_ID = an.ANSWER_SET_ID WHERE an.SURVEY_ID = :id"); + + if (deleteAnswers) { + Query query0 = session.createSQLQuery( + "SELECT fi.FILE_UID from FILES fi JOIN ANSWERS_FILES f ON fi.FILE_ID = f.files_FILE_ID JOIN ANSWERS a ON f.ANSWERS_ANSWER_ID = a.ANSWER_ID JOIN ANSWERS_SET an ON a.AS_ID = an.ANSWER_SET_ID WHERE an.SURVEY_ID = :id"); @SuppressWarnings("unchecked") - List fileuids = query0.setInteger("id", id).list(); - + List fileuids = query0.setInteger("id", id).list(); + Query query = session.createSQLQuery("DELETE d.* from DRAFTS d INNER JOIN ANSWERS_SET an ON d.answerSet_ANSWER_SET_ID = an.ANSWER_SET_ID where an.SURVEY_ID = :id"); query.setInteger("id", id).executeUpdate(); - - Query query1 = session.createSQLQuery("DELETE f.* from ANSWERS_FILES f JOIN ANSWERS a ON f.ANSWERS_ANSWER_ID = a.ANSWER_ID JOIN ANSWERS_SET an ON a.AS_ID = an.ANSWER_SET_ID WHERE an.SURVEY_ID = :id"); + + Query query1 = session + .createSQLQuery("DELETE f.* from ANSWERS_FILES f JOIN ANSWERS a ON f.ANSWERS_ANSWER_ID = a.ANSWER_ID JOIN ANSWERS_SET an ON a.AS_ID = an.ANSWER_SET_ID WHERE an.SURVEY_ID = :id"); query1.setInteger("id", id).executeUpdate(); - + Query query2 = session.createSQLQuery("DELETE a.* from ANSWERS a JOIN ANSWERS_SET an ON a.AS_ID = an.ANSWER_SET_ID WHERE an.SURVEY_ID = :id"); query2.setInteger("id", id).executeUpdate(); - + Query query3 = session.createQuery("DELETE from AnswerSet a where a.surveyId = :id"); - query3.setInteger("id", id).executeUpdate(); - - for (String fileuid : fileuids) - { - java.io.File file = fileService.getSurveyFile(uid, fileuid); - if (file.exists()) - { + query3.setInteger("id", id).executeUpdate(); + + for (String fileuid : fileuids) { + java.io.File file = fileService.getSurveyFile(uid, fileuid); + if (file.exists()) { file.delete(); } } - + Query query4 = session.createSQLQuery("SELECT v.VALIDCODE_CODE FROM VALIDCODE v WHERE v.VALIDCODE_SURVEYUID = :uid"); @SuppressWarnings("unchecked") - List codes = query4.setString("uid", uid).list(); - for (String code: codes) - { + List codes = query4.setString("uid", uid).list(); + for (String code : codes) { java.io.File folder = fileService.getSurveyFile(uid, code); - if (folder.exists() && folder.isDirectory()) - { + if (folder.exists() && folder.isDirectory()) { try { FileUtils.deleteDirectory(folder); } catch (IOException e) { @@ -1651,93 +1586,85 @@ private void deleteSurveyData(int id, boolean deleteAnswers, boolean deleteAcces } } } - + Query query5 = session.createSQLQuery("DELETE FROM VALIDCODE WHERE VALIDCODE_SURVEYUID = :uid"); query5.setString("uid", uid).executeUpdate(); } - + List translations = translationService.getTranslationsForSurvey(id, false); - for (Translations translation: translations) - { + for (Translations translation : translations) { if (translation.getId() > 0) - session.delete(translation); - } - - if (deleteAccesses) - { + session.delete(translation); + } + + if (deleteAccesses) { List accesses = getAccesses(id); - for (Access access: accesses) - { + for (Access access : accesses) { if (access.getId() > 0) - session.delete(access); + session.delete(access); } } - + exportService.deleteSurveyExports(id); - - if (deleteLogs) - { + + if (deleteLogs) { activityService.deleteLogsForSurvey(uid); } - + List groups = participationService.getAll(id); - for (ParticipationGroup group : groups) - { + for (ParticipationGroup group : groups) { Query query6 = session.createSQLQuery("DELETE FROM INVITATIONS WHERE PARTICIPATIONGROUP_ID = :id"); query6.setInteger("id", group.getId()).executeUpdate(); - + session.delete(group); } - - //remove dependencies (this is only needed for older surveys that have zombie dependencies + + // remove dependencies (this is only needed for older surveys that have zombie + // dependencies SQLQuery query = session.createSQLQuery("DELETE FROM POSSIBLEANSWER_ELEMENT where dependentElements_ID in (SELECT elements_ID from SURVEYS_ELEMENTS WHERE SURVEYS_SURVEY_ID = :id)"); query.setInteger("id", id); query.executeUpdate(); } - + @Transactional public void delete(int id, boolean deleteLogs, boolean deleteFileMappings) throws Exception { deleteNoTransaction(id, deleteLogs, deleteFileMappings); } - + public void deleteNoTransaction(int id, boolean deleteLogs, boolean deleteFileMappings) throws Exception { Session session = sessionFactory.getCurrentSession(); - Survey s = this.getSurvey(id, false, false); - + Survey s = this.getSurvey(id, false, false); + List surveyIDs = surveyService.getAllSurveyVersions(s.getShortname(), s.getUniqueId()); fileService.deleteFilesForSurveys(surveyIDs); - - if (contextpath == null || contextpath.trim().length() == 0) - { + + if (contextpath == null || contextpath.trim().length() == 0) { throw new Exception("contextpath empty"); } - + if (deleteFileMappings) { deleteFileMappings(surveyIDs); } - //delete draft - Map referencedFiles = s.getReferencedFileUIDs(contextpath); + // delete draft + Map referencedFiles = s.getReferencedFileUIDs(contextpath); deleteSurveyData(id, true, true, s.getUniqueId(), deleteLogs); session.flush(); session.delete(s); session.flush(); - - for (String uid : referencedFiles.keySet()) - { - if (referencedFiles.get(uid) == null) - { - //delete files belonging to images and background documents + + for (String uid : referencedFiles.keySet()) { + if (referencedFiles.get(uid) == null) { + // delete files belonging to images and background documents fileService.deleteIfNotReferenced(uid, s.getUniqueId()); - } - } - - //delete published versions + } + } + + // delete published versions Survey published = getSurveyByUniqueId(s.getUniqueId(), false, false); - if (published != null) - { + if (published != null) { surveyIDs = this.getAllSurveyVersions(published.getId()); for (Integer sid : surveyIDs) { s = this.getSurvey(sid, false, false); @@ -1746,27 +1673,25 @@ public void deleteNoTransaction(int id, boolean deleteLogs, boolean deleteFileMa session.flush(); session.delete(s); session.flush(); - for (String uid : referencedFiles.keySet()) - { - if (referencedFiles.get(uid) == null) - { - //delete files belonging to images and background documents + for (String uid : referencedFiles.keySet()) { + if (referencedFiles.get(uid) == null) { + // delete files belonging to images and background documents fileService.deleteIfNotReferenced(uid, s.getUniqueId()); } } } } - + java.io.File folder = fileService.getSurveyFolder(s.getUniqueId()); try { FileUtils.deleteDirectory(folder); } catch (Exception e) { logger.error(e.getLocalizedMessage(), e); - } - + } + reportingService.addToDo(ToDo.DELETEDSURVEY, s.getUniqueId(), null); } - + private void deleteFileMappings(List surveyIDs) { Session session = sessionFactory.getCurrentSession(); String sql = "delete from ELEMENTS_FILES" + @@ -1787,49 +1712,43 @@ private void deleteFileMappings(List surveyIDs) { } @Transactional(readOnly = true) - public List getLanguages() - { + public List getLanguages() { Session session = sessionFactory.getCurrentSession(); - Query query = session.createQuery("FROM Language l order by l.englishName asc"); + Query query = session.createQuery("FROM Language l order by l.englishName asc"); @SuppressWarnings("unchecked") List languages = query.list(); return languages; } - + @Transactional(readOnly = true) - public Language getLanguage(String code) - { + public Language getLanguage(String code) { return getLanguage(code, sessionFactory.getCurrentSession()); } - - public Language getLanguage(String code, Session session) - { + + public Language getLanguage(String code, Session session) { Query query = session.createQuery("FROM Language l WHERE l.code = :code").setString("code", code); - + @SuppressWarnings("rawtypes") List result = query.list(); - - if (result.size() == 0) - { + + if (result.size() == 0) { logger.error("ivalid language code: " + code); } - + return (Language) result.get(0); } @Transactional public void saveLanguages(List langs) { Session session = sessionFactory.getCurrentSession(); - for (Language l : langs) - { + for (Language l : langs) { try { - session.save(l); - } catch (Exception e) - { + session.save(l); + } catch (Exception e) { logger.error("language " + l.getEnglishName() + " could not be imported"); } } - + } public boolean getIsSurveyPublished(String shortname) { @@ -1840,54 +1759,45 @@ public boolean getIsSurveyPublished(String shortname) { @Transactional(readOnly = true) public List getLanguageCodes() { Session session = sessionFactory.getCurrentSession(); - Query query = session.createQuery("Select l.code FROM Language l"); + Query query = session.createQuery("Select l.code FROM Language l"); @SuppressWarnings("unchecked") List codes = query.list(); return codes; } - + @Transactional - private Map importDraftSurvey(Survey copy, ImportResult result, User user) - { - if (copy.getSkin() != null) - { + private Map importDraftSurvey(Survey copy, ImportResult result, User user) { + if (copy.getSkin() != null) { Skin skin = skinService.get(copy.getSkin().getId()); - if (skin == null) - { + if (skin == null) { copy.setSkin(null); } } - + Map oldToNewUniqueIds = new HashMap<>(); - oldToNewUniqueIds.put("", ""); //leave blank for old surveys that have no uniqueIds - - //recreate unique ids - for (Element elem: copy.getElementsRecursive(true)) - { + oldToNewUniqueIds.put("", ""); // leave blank for old surveys that have no uniqueIds + + // recreate unique ids + for (Element elem : copy.getElementsRecursive(true)) { String newUniqueId = UUID.randomUUID().toString(); - if (!oldToNewUniqueIds.containsKey(elem.getUniqueId())) - { + if (!oldToNewUniqueIds.containsKey(elem.getUniqueId())) { oldToNewUniqueIds.put(elem.getUniqueId(), newUniqueId); } elem.setUniqueId(newUniqueId); } - + Map elementsBySourceId = copy.getElementsBySourceId(); - if (result.isFromIPM()) - { - //recreate dependencies - for (int elem: result.getOriginalDependencies().keySet()) - { + if (result.isFromIPM()) { + // recreate dependencies + for (int elem : result.getOriginalDependencies().keySet()) { PossibleAnswer answer = (PossibleAnswer) elementsBySourceId.get(elem); - - for (String originalId: result.getOriginalDependencies().get(elem)) - { + + for (String originalId : result.getOriginalDependencies().get(elem)) { Element dependent = elementsBySourceId.get(result.getOriginalIdsToNewIds().get(originalId)); answer.getDependentElements().getDependentElements().add(dependent); - - if (result.getAdditionalElements().containsKey(dependent.getSourceId())) - { + + if (result.getAdditionalElements().containsKey(dependent.getSourceId())) { List ids = result.getAdditionalElements().get(dependent.getSourceId()); for (Integer id : ids) { Element upload = elementsBySourceId.get(id); @@ -1896,86 +1806,76 @@ private Map importDraftSurvey(Survey copy, ImportResult result, } } } - - for (String elems: result.getOriginalMatrixDependencies().keySet()) - { + + for (String elems : result.getOriginalMatrixDependencies().keySet()) { String[] data = elems.split("#"); int answerpos = Integer.parseInt(data[1]); String questionoriginal = data[0]; int question = elementsBySourceId.get(result.getOriginalIdsToNewIds().get(questionoriginal)).getId(); String matrix = data[2]; - + Matrix m = (Matrix) elementsBySourceId.get(result.getOriginalIdsToNewIds().get(matrix)); - - for (String originalId: result.getOriginalMatrixDependencies().get(elems)) - { + + for (String originalId : result.getOriginalMatrixDependencies().get(elems)) { Element dependent = elementsBySourceId.get(result.getOriginalIdsToNewIds().get(originalId)); - + DependencyItem dep = new DependencyItem(); - + int k = 0; - for (Element q : m.getQuestions()) - { - if (q.getId() == question) - { + for (Element q : m.getQuestions()) { + if (q.getId() == question) { k += answerpos; break; } - - k+= m.getAnswers().size(); + + k += m.getAnswers().size(); } - + dep.setPosition(k); dep.getDependentElements().add(dependent); - - if (result.getAdditionalElements().containsKey(dependent.getSourceId())) - { + + if (result.getAdditionalElements().containsKey(dependent.getSourceId())) { List ids = result.getAdditionalElements().get(dependent.getSourceId()); for (Integer id : ids) { Element upload = elementsBySourceId.get(id); dep.getDependentElements().add(upload); } } - + m.getDependentElements().add(dep); } } } - - if (result.getActiveSurvey() != null) - { + + if (result.getActiveSurvey() != null) { copy.setIsActive(false); copy.setIsPublished(true); } - + this.update(copy, false, true, false, user.getId()); - + return oldToNewUniqueIds; } - + @Transactional - private Survey importOldPublishedSurvey(Survey survey, User user, Map oldToNewUniqueIds) throws Exception - { - HashMap oldSourceIdsById2 = getSourceIdsById(survey); - + private Survey importOldPublishedSurvey(Survey survey, User user, Map oldToNewUniqueIds) throws Exception { + HashMap oldSourceIdsById2 = getSourceIdsById(survey); + Survey copyOld = survey.copy(this, user, fileDir, false, -1, -1, false, false, true, null, null); copyOld.setIsDraft(false); - - if (copyOld.getSkin() != null) - { + + if (copyOld.getSkin() != null) { Skin skin = skinService.get(copyOld.getSkin().getId()); - if (skin == null) - { + if (skin == null) { copyOld.setSkin(null); } } - - //update source_ids + + // update source_ids for (Element element : copyOld.getElementsRecursive(true)) { element.setSourceId(oldSourceIdsById2.get(element.getSourceId())); - - if (oldToNewUniqueIds.containsKey(element.getUniqueId())) - { + + if (oldToNewUniqueIds.containsKey(element.getUniqueId())) { element.setUniqueId(oldToNewUniqueIds.get(element.getUniqueId())); } else { String newUniqueId = UUID.randomUUID().toString(); @@ -1983,31 +1883,27 @@ private Survey importOldPublishedSurvey(Survey survey, User user, Map oldToNewUniqueIds, HashMap oldSourceIdsById) - { + private void importPublishedSurvey(Survey copyActive, ImportResult result, User user, Map oldToNewUniqueIds, HashMap oldSourceIdsById) { copyActive.setIsDraft(false); - - if (copyActive.getSkin() != null) - { + + if (copyActive.getSkin() != null) { Skin skin = skinService.get(copyActive.getSkin().getId()); - if (skin == null) - { + if (skin == null) { copyActive.setSkin(null); } } - - //update source_ids + + // update source_ids for (Element element : copyActive.getElementsRecursive(true)) { element.setSourceId(oldSourceIdsById.get(element.getSourceId())); - - if (oldToNewUniqueIds.containsKey(element.getUniqueId())) - { + + if (oldToNewUniqueIds.containsKey(element.getUniqueId())) { element.setUniqueId(oldToNewUniqueIds.get(element.getUniqueId())); } else { String newUniqueId = UUID.randomUUID().toString(); @@ -2015,16 +1911,15 @@ private void importPublishedSurvey(Survey copyActive, ImportResult result, User element.setUniqueId(newUniqueId); } } - - if (result.getActiveAnswerSets() != null && result.getActiveAnswerSets().size() > 0) - { + + if (result.getActiveAnswerSets() != null && result.getActiveAnswerSets().size() > 0) { copyActive.setIsActive(true); copyActive.setIsPublished(true); } - - this.update(copyActive, false, true, false, user.getId()); + + this.update(copyActive, false, true, false, user.getId()); } - + @Transactional public int importSurvey(ImportResult result, User user, boolean isRestore) throws Exception { Survey copy = result.getSurvey().copy(this, user, fileDir, false, -1, -1, false, false, true, null, null); @@ -2032,12 +1927,11 @@ public int importSurvey(ImportResult result, User user, boolean isRestore) throw try { Map missingfiles = new HashMap<>(); Map convertedUIDs = surveyService.copyFiles(copy, new HashMap<>(), true, missingfiles, result.getSurvey().getUniqueId()); - + Map oldToNewUniqueIds = importDraftSurvey(copy, result, user); importSurveyData(result, user, true, copy, oldToNewUniqueIds, result.getSurvey().getId()); - - if (result.getActiveSurvey() != null && result.getActiveAnswerSets() != null && result.getActiveAnswerSets().size() > 0) - { + + if (result.getActiveSurvey() != null && result.getActiveAnswerSets() != null && result.getActiveAnswerSets().size() > 0) { HashMap oldSourceIdsById = getSourceIdsById(result.getActiveSurvey()); for (int id : result.getOldSurveys().keySet()) { Survey copyOld = importOldPublishedSurvey(result.getOldSurveys().get(id), user, oldToNewUniqueIds); @@ -2045,38 +1939,35 @@ public int importSurvey(ImportResult result, User user, boolean isRestore) throw } copyActive = result.getActiveSurvey().copy(this, user, fileDir, false, -1, -1, false, false, true, null, null); surveyService.copyFiles(copyActive, convertedUIDs, true, missingfiles, result.getSurvey().getUniqueId()); - - importPublishedSurvey(copyActive, result, user, oldToNewUniqueIds, oldSourceIdsById); + + importPublishedSurvey(copyActive, result, user, oldToNewUniqueIds, oldSourceIdsById); importSurveyData(result, user, false, copyActive, oldToNewUniqueIds, result.getActiveSurvey().getId()); } - - for (String fileuid : convertedUIDs.keySet()) - { + + for (String fileuid : convertedUIDs.keySet()) { fileService.deleteIfNotReferenced(fileuid, copy.getUniqueId()); } - - if (missingfiles.size() > 0) - { + + if (missingfiles.size() > 0) { Locale locale = new Locale(user.getLanguage().toLowerCase()); - + StringBuilder text = new StringBuilder(); String link = "" + copy.getShortname() + ""; - text.append(resources.getMessage("error.ProblemDuringRestore", new Object[] {link}, "Error during operation", locale)); - + text.append(resources.getMessage("error.ProblemDuringRestore", new Object[] { link }, "Error during operation", locale)); + text.append(""); - - for (String name : missingfiles.keySet()) - { + + for (String name : missingfiles.keySet()) { text.append(""); } - + text.append("
File NameType
"); text.append(name); text.append(""); text.append(missingfiles.get(name)); text.append("
"); text.append(resources.getMessage("error.ProblemDuringRestore2", null, "Error during operation", locale)); - + Message m = new Message(); m.setType(4); m.setCriticality(3); @@ -2084,37 +1975,32 @@ public int importSurvey(ImportResult result, User user, boolean isRestore) throw m.setUserId(user.getId()); systemService.save(m); } - - } catch (Exception e) - { - if (isRestore && copy.getId() > 0) - { - //mark survey as archived so it is not visible + + } catch (Exception e) { + if (isRestore && copy.getId() > 0) { + // mark survey as archived so it is not visible copy.setArchived(true); surveyService.update(copy, true); } - - if (e instanceof ConstraintViolationException && copy != null && copy.getId() > 0) - { + + if (e instanceof ConstraintViolationException && copy != null && copy.getId() > 0) { logger.error(e.getLocalizedMessage(), e); throw new SurveyException(copy.getId()); } else { - throw e; + throw e; } } - - return copy.getId(); + + return copy.getId(); } - - private void importSurveyData(ImportResult result, User user, boolean draft, Survey survey, Map oldToNewUniqueIds, Integer surveyid) throws Exception - { + + private void importSurveyData(ImportResult result, User user, boolean draft, Survey survey, Map oldToNewUniqueIds, Integer surveyid) throws Exception { List translations = null; List answerSets = new ArrayList<>(); - Map> files = null; - - if (draft) - { - translations = result.getTranslations(); + Map> files = null; + + if (draft) { + translations = result.getTranslations(); answerSets = result.getAnswerSets(); files = result.getFiles(); } else { @@ -2123,138 +2009,117 @@ private void importSurveyData(ImportResult result, User user, boolean draft, Sur } else { translations = result.getOldTranslations().get(surveyid); } - + if (result.getActiveAnswerSets() != null) - for (List list : result.getActiveAnswerSets()) { - for (AnswerSet as : list) { - if (as.getSurveyId() == surveyid) { - answerSets.add(as); + for (List list : result.getActiveAnswerSets()) { + for (AnswerSet as : list) { + if (as.getSurveyId() == surveyid) { + answerSets.add(as); + } } } - } files = result.getActiveFiles(); } - - if (translations != null) - { - copyTranslations(translations, survey, oldToNewUniqueIds, result, false); + + if (translations != null) { + copyTranslations(translations, survey, oldToNewUniqueIds, result, false); } - - if (answerSets != null && answerSets.size() > 0) - { + + if (answerSets != null && answerSets.size() > 0) { logger.info("starting import of answers"); - + Map keys = new HashMap<>(); - for (Element element: survey.getElementsRecursive()) - { + for (Element element : survey.getElementsRecursive()) { keys.put(element.getSourceId().toString(), element.getId()); - if (element instanceof ChoiceQuestion) - { - for (PossibleAnswer answer: ((ChoiceQuestion)element).getPossibleAnswers()) - { - if (answer.getSourceId() != null) - { + if (element instanceof ChoiceQuestion) { + for (PossibleAnswer answer : ((ChoiceQuestion) element).getPossibleAnswers()) { + if (answer.getSourceId() != null) { keys.put(answer.getSourceId().toString(), answer.getId()); } } } } - + Set answerSets2 = new HashSet<>(); - - while (answerSets.size() > 0) - { - AnswerSet a = answerSets.remove(0); + + while (answerSets.size() > 0) { + AnswerSet a = answerSets.remove(0); AnswerSet b = a.copy(survey, files); - - for (Answer an: b.getAnswers()) - { - if (keys.containsKey(an.getQuestionId().toString())) - { + + for (Answer an : b.getAnswers()) { + if (keys.containsKey(an.getQuestionId().toString())) { an.setQuestionId(keys.get(an.getQuestionId().toString())); } - + an.setQuestionUniqueId(oldToNewUniqueIds.get(an.getQuestionUniqueId())); - - if (an.getPossibleAnswerId() > 0) - { - if (keys.containsKey(an.getPossibleAnswerId().toString())) - { + + if (an.getPossibleAnswerId() > 0) { + if (keys.containsKey(an.getPossibleAnswerId().toString())) { an.setValue(keys.get(an.getPossibleAnswerId().toString()).toString()); an.setPossibleAnswerId(keys.get(an.getPossibleAnswerId().toString())); } - + an.setPossibleAnswerUniqueId(oldToNewUniqueIds.get(an.getPossibleAnswerUniqueId())); } } - - answerSets2.add(b); - - if (answerSets2.size() > 1000) - { + + answerSets2.add(b); + + if (answerSets2.size() > 1000) { logger.info("1000 answers imported"); SaveAnswerSets(answerSets2, tempFileDir, null); answerSets2 = new HashSet<>(); - } + } } - + SaveAnswerSets(answerSets2, tempFileDir, null); logger.info("finished import of answers"); - } + } } - + @Transactional - public void SaveAnswerSets(Set answerSets, String fileDir, String draftid) throws Exception - { + public void SaveAnswerSets(Set answerSets, String fileDir, String draftid) throws Exception { Session session = sessionFactory.getCurrentSession(); - for (AnswerSet answerSet: answerSets) - { + for (AnswerSet answerSet : answerSets) { saveAnswerSet(answerSet, fileDir, draftid); session.evict(answerSet); } } - + public void saveAnswerSet(AnswerSet answerSet, String fileDir, String draftid) throws Exception { boolean saved = false; - + int counter = 1; - - while(!saved) - { + + while (!saved) { try { answerService.internalSaveAnswerSet(answerSet, fileDir, draftid, false, false); saved = true; - } catch (org.hibernate.exception.LockAcquisitionException ex) - { + } catch (org.hibernate.exception.LockAcquisitionException ex) { logger.info("lock on answerSet table catched; retry counter: " + counter); counter++; - - if (counter > 60) - { + + if (counter > 60) { logger.error(ex.getLocalizedMessage(), ex); throw ex; } - + Thread.sleep(1000); } - } + } } - - public void copyTranslations(List translations, Survey survey, Map oldToNewUniqueIds, ImportResult result, boolean newTitle) - { - Map elementsBySourceId = survey.getElementsBySourceId(); - - for (Translations tOriginal: translations) - { + + public void copyTranslations(List translations, Survey survey, Map oldToNewUniqueIds, ImportResult result, boolean newTitle) { + Map elementsBySourceId = survey.getElementsBySourceId(); + + for (Translations tOriginal : translations) { Translations t = new Translations(); t.setActive(tOriginal.getActive()); t.setLanguage(tOriginal.getLanguage()); - if (newTitle) - { - if (survey.getLanguage().getCode().equals(tOriginal.getLanguage().getCode())) - { + if (newTitle) { + if (survey.getLanguage().getCode().equals(tOriginal.getLanguage().getCode())) { t.setTitle(survey.getTitle()); } else { t.setTitle(""); @@ -2264,23 +2129,17 @@ public void copyTranslations(List translations, Survey survey, Map } t.setSurveyId(survey.getId()); t.setSurveyUid(survey.getUniqueId()); - for (Translation trOriginal: tOriginal.getTranslations()) - { - if (trOriginal.getLabel() != null) - { + for (Translation trOriginal : tOriginal.getTranslations()) { + if (trOriginal.getLabel() != null) { Translation tr = new Translation(); tr.setSurveyId(survey.getId()); - - if (result == null || !result.isFromIPM()) - { + + if (result == null || !result.isFromIPM()) { tr.setKey(translateKey(trOriginal.getKey(), elementsBySourceId, oldToNewUniqueIds)); } else { - if (trOriginal.getKey().equalsIgnoreCase(Survey.IPMINTRODUCTION)) - { - for (com.ec.survey.model.survey.Element element: survey.getElements()) - { - if (element instanceof Section && element.getPosition() == 0 && element.getShortname().equalsIgnoreCase("Introduction")) - { + if (trOriginal.getKey().equalsIgnoreCase(Survey.IPMINTRODUCTION)) { + for (com.ec.survey.model.survey.Element element : survey.getElements()) { + if (element instanceof Section && element.getPosition() == 0 && element.getShortname().equalsIgnoreCase("Introduction")) { Translation tr2 = new Translation(); tr2.setSurveyId(survey.getId()); tr2.setKey(element.getId().toString()); @@ -2288,22 +2147,19 @@ public void copyTranslations(List translations, Survey survey, Map tr2.setLanguage(trOriginal.getLanguage()); tr2.setTranslations(t); t.getTranslations().add(tr2); - } else if (element instanceof Text && element.getShortname() != null && element.getShortname().equalsIgnoreCase("introduction") && element.getPosition() < 2) - { + } else if (element instanceof Text && element.getShortname() != null && element.getShortname().equalsIgnoreCase("introduction") && element.getPosition() < 2) { tr.setKey(element.getUniqueId()); break; } } } else { - + tr.setKey(translateIPMKey(trOriginal.getKey(), elementsBySourceId, oldToNewUniqueIds, result)); - + if (trOriginal.getKey().endsWith("desc") && trOriginal.getKey().length() > 4) { - - for (com.ec.survey.model.survey.Element element: survey.getElements()) - { - if (element instanceof Text && element.getShortname() != null && element.getShortname().equals(trOriginal.getKey())) - { + + for (com.ec.survey.model.survey.Element element : survey.getElements()) { + if (element instanceof Text && element.getShortname() != null && element.getShortname().equals(trOriginal.getKey())) { tr.setKey(element.getUniqueId()); break; } @@ -2311,181 +2167,175 @@ public void copyTranslations(List translations, Survey survey, Map } } } - - if (newTitle && trOriginal.getKey().equalsIgnoreCase("TITLE")) - { - if (trOriginal.getLanguage().equalsIgnoreCase(survey.getLanguage().getCode())) - { + + if (newTitle && trOriginal.getKey().equalsIgnoreCase("TITLE")) { + if (trOriginal.getLanguage().equalsIgnoreCase(survey.getLanguage().getCode())) { tr.setLabel(survey.getTitle()); } - } else { + } else { tr.setLabel(trOriginal.getLabel()); } - + tr.setLanguage(trOriginal.getLanguage()); tr.setTranslations(t); t.getTranslations().add(tr); } } - - if (result != null && result.isFromIPM()) - { - - for (List ids : result.getAdditionalElements().values()) - for (Integer id : ids) { - Element upload = elementsBySourceId.get(id); - - if (upload instanceof Upload) - { - Translation tr = new Translation(); - tr.setSurveyId(survey.getId()); - tr.setKey(elementsBySourceId.get(id).getId().toString()); - tr.setLabel(""); - tr.setLanguage(tOriginal.getLanguage().getCode()); - t.getTranslations().add(tr); + + if (result != null && result.isFromIPM()) { + + for (List ids : result.getAdditionalElements().values()) + for (Integer id : ids) { + Element upload = elementsBySourceId.get(id); + + if (upload instanceof Upload) { + Translation tr = new Translation(); + tr.setSurveyId(survey.getId()); + tr.setKey(elementsBySourceId.get(id).getId().toString()); + tr.setLabel(""); + tr.setLanguage(tOriginal.getLanguage().getCode()); + t.getTranslations().add(tr); + } } - } } - + translationService.deleteTranslations(survey.getId(), t.getLanguage().getCode()); translationService.add(t, true); } } private String translateKey(String key, Map elementsBySourceId, Map oldToNewUniqueIds) { - - if (key == null) return key; - - if (key.equalsIgnoreCase(Survey.TITLE)) return key; - if (key.equalsIgnoreCase(Survey.INTRODUCTION)) return key; - if (key.equalsIgnoreCase(Survey.ESCAPEPAGE)) return key; - if (key.equalsIgnoreCase(Survey.ESCAPELINK)) return key; - if (key.equalsIgnoreCase(Survey.CONFIRMATIONPAGE)) return key; - if (key.equalsIgnoreCase(Survey.CONFIRMATIONLINK)) return key; - + + if (key == null) + return key; + + if (key.equalsIgnoreCase(Survey.TITLE)) + return key; + if (key.equalsIgnoreCase(Survey.INTRODUCTION)) + return key; + if (key.equalsIgnoreCase(Survey.ESCAPEPAGE)) + return key; + if (key.equalsIgnoreCase(Survey.ESCAPELINK)) + return key; + if (key.equalsIgnoreCase(Survey.CONFIRMATIONPAGE)) + return key; + if (key.equalsIgnoreCase(Survey.CONFIRMATIONLINK)) + return key; + Integer retVal; String uid; - try { - if (key.endsWith("help")) - { + try { + if (key.endsWith("help")) { uid = key.substring(0, key.indexOf("help")); - - if (oldToNewUniqueIds.containsKey(uid)) - { + + if (oldToNewUniqueIds.containsKey(uid)) { return oldToNewUniqueIds.get(uid) + "help"; - } - retVal = Integer.parseInt(uid); - if (elementsBySourceId.containsKey(retVal)) return elementsBySourceId.get(retVal).getUniqueId() + "help"; - } else if (key.endsWith(NumberQuestion.UNIT)) - { + } + retVal = Integer.parseInt(uid); + if (elementsBySourceId.containsKey(retVal)) + return elementsBySourceId.get(retVal).getUniqueId() + "help"; + } else if (key.endsWith(NumberQuestion.UNIT)) { uid = key.substring(0, key.indexOf(NumberQuestion.UNIT)); - if (oldToNewUniqueIds.containsKey(uid)) - { + if (oldToNewUniqueIds.containsKey(uid)) { return oldToNewUniqueIds.get(uid) + NumberQuestion.UNIT; } - - retVal = Integer.parseInt(uid); - if (elementsBySourceId.containsKey(retVal)) return elementsBySourceId.get(retVal).getUniqueId() + NumberQuestion.UNIT; - } else if (key.endsWith(Confirmation.LABEL)) - { + + retVal = Integer.parseInt(uid); + if (elementsBySourceId.containsKey(retVal)) + return elementsBySourceId.get(retVal).getUniqueId() + NumberQuestion.UNIT; + } else if (key.endsWith(Confirmation.LABEL)) { uid = key.substring(0, key.indexOf(Confirmation.LABEL)); - if (oldToNewUniqueIds.containsKey(uid)) - { + if (oldToNewUniqueIds.containsKey(uid)) { return oldToNewUniqueIds.get(uid) + Confirmation.LABEL; } - - retVal = Integer.parseInt(uid); - if (elementsBySourceId.containsKey(retVal)) return elementsBySourceId.get(retVal).getUniqueId() + Confirmation.LABEL; - } else if (key.endsWith(Confirmation.TEXT)) - { + + retVal = Integer.parseInt(uid); + if (elementsBySourceId.containsKey(retVal)) + return elementsBySourceId.get(retVal).getUniqueId() + Confirmation.LABEL; + } else if (key.endsWith(Confirmation.TEXT)) { uid = key.substring(0, key.indexOf(Confirmation.TEXT)); - if (oldToNewUniqueIds.containsKey(uid)) - { + if (oldToNewUniqueIds.containsKey(uid)) { return oldToNewUniqueIds.get(uid) + Confirmation.TEXT; } - - retVal = Integer.parseInt(uid); - if (elementsBySourceId.containsKey(retVal)) return elementsBySourceId.get(retVal).getUniqueId() + Confirmation.TEXT; - } else if (key.endsWith(Section.TABTITLE)) - { + + retVal = Integer.parseInt(uid); + if (elementsBySourceId.containsKey(retVal)) + return elementsBySourceId.get(retVal).getUniqueId() + Confirmation.TEXT; + } else if (key.endsWith(Section.TABTITLE)) { uid = key.substring(0, key.indexOf(Section.TABTITLE)); - if (oldToNewUniqueIds.containsKey(uid)) - { + if (oldToNewUniqueIds.containsKey(uid)) { return oldToNewUniqueIds.get(uid) + Section.TABTITLE; } - - retVal = Integer.parseInt(uid); - if (elementsBySourceId.containsKey(retVal)) return elementsBySourceId.get(retVal).getUniqueId() + Section.TABTITLE; - } else if (key.endsWith("shortname")) - { + + retVal = Integer.parseInt(uid); + if (elementsBySourceId.containsKey(retVal)) + return elementsBySourceId.get(retVal).getUniqueId() + Section.TABTITLE; + } else if (key.endsWith("shortname")) { uid = key.substring(0, key.indexOf("shortname")); - if (oldToNewUniqueIds.containsKey(uid)) - { + if (oldToNewUniqueIds.containsKey(uid)) { return oldToNewUniqueIds.get(uid) + "shortname"; } - - retVal = Integer.parseInt(uid); - - if (elementsBySourceId.containsKey(retVal)) return elementsBySourceId.get(retVal).getUniqueId() + "shortname"; - } else if (oldToNewUniqueIds.containsKey(key)) - { + + retVal = Integer.parseInt(uid); + + if (elementsBySourceId.containsKey(retVal)) + return elementsBySourceId.get(retVal).getUniqueId() + "shortname"; + } else if (oldToNewUniqueIds.containsKey(key)) { return oldToNewUniqueIds.get(key); - } else { - retVal = Integer.parseInt(key); - if (elementsBySourceId.containsKey(retVal)) return elementsBySourceId.get(retVal).getUniqueId(); + } else { + retVal = Integer.parseInt(key); + if (elementsBySourceId.containsKey(retVal)) + return elementsBySourceId.get(retVal).getUniqueId(); } } catch (NumberFormatException nfe) { logger.info("unknown key " + key + "found in translation"); } - + return key; } - + private String translateIPMKey(String key, Map elementsBySourceId, Map oldToNewUniqueIds, ImportResult result) { - if (key.equalsIgnoreCase(Survey.TITLE)) return key; - if (key.equalsIgnoreCase(Survey.INTRODUCTION)) return key; - if (key.equalsIgnoreCase(Survey.ESCAPEPAGE)) return key; - if (key.equalsIgnoreCase(Survey.CONFIRMATIONPAGE)) return key; - + if (key.equalsIgnoreCase(Survey.TITLE)) + return key; + if (key.equalsIgnoreCase(Survey.INTRODUCTION)) + return key; + if (key.equalsIgnoreCase(Survey.ESCAPEPAGE)) + return key; + if (key.equalsIgnoreCase(Survey.CONFIRMATIONPAGE)) + return key; + String key2 = key; - + try { - if (key.endsWith("help")) - { + if (key.endsWith("help")) { String id = key.substring(0, key.indexOf("help")); - if (result.getOriginalIdsToNewIds().containsKey(id)) - { + if (result.getOriginalIdsToNewIds().containsKey(id)) { key2 = result.getOriginalIdsToNewIds().get(id).toString() + "help"; } - } else if (key.endsWith(NumberQuestion.UNIT)) - { + } else if (key.endsWith(NumberQuestion.UNIT)) { String id = key.substring(0, key.indexOf(NumberQuestion.UNIT)); - if (result.getOriginalIdsToNewIds().containsKey(id)) - { + if (result.getOriginalIdsToNewIds().containsKey(id)) { key2 = result.getOriginalIdsToNewIds().get(id).toString() + NumberQuestion.UNIT; } - } else if (key.endsWith(Section.TABTITLE)) - { + } else if (key.endsWith(Section.TABTITLE)) { String id = key.substring(0, key.indexOf(Section.TABTITLE)); - if (result.getOriginalIdsToNewIds().containsKey(id)) - { + if (result.getOriginalIdsToNewIds().containsKey(id)) { key2 = result.getOriginalIdsToNewIds().get(id).toString() + Section.TABTITLE; } - } else { - if (result.getOriginalIdsToNewIds().containsKey(key)) - { + } else { + if (result.getOriginalIdsToNewIds().containsKey(key)) { key2 = result.getOriginalIdsToNewIds().get(key).toString(); } } } catch (Exception e) { - logger.info("unknown key " + key + "found in translation"); + logger.info("unknown key " + key + "found in translation"); } - + return translateKey(key2, elementsBySourceId, oldToNewUniqueIds); } @@ -2514,45 +2364,47 @@ public void deleteAccess(Access access) { Session session = sessionFactory.getCurrentSession(); session.delete(access); } - + @Transactional(readOnly = true) public Access getAccess(Integer id, Integer userId) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("FROM Access a WHERE a.survey.id = :id AND a.user.id = :userId").setInteger("id", id).setInteger("userId", userId); @SuppressWarnings("unchecked") List result = query.list(); - if (result.size() > 0) return result.get(0); + if (result.size() > 0) + return result.get(0); return null; } - + @Transactional(readOnly = true) public Access getGroupAccess(Integer id, String groupName) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("FROM Access a WHERE a.survey.id = :id AND a.department = :groupName").setInteger("id", id).setString("groupName", groupName); @SuppressWarnings("unchecked") List result = query.list(); - if (result.size() > 0) return result.get(0); + if (result.size() > 0) + return result.get(0); return null; } - + @Transactional public void save(Template template) { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(template); } - + @Transactional(readOnly = true) public Template getTemplate(int id) { Session session = sessionFactory.getCurrentSession(); return (Template) session.get(Template.class, id); } - + @Transactional public void deleteTemplate(Template template) { Session session = sessionFactory.getCurrentSession(); session.delete(template); } - + @SuppressWarnings("unchecked") @Transactional(readOnly = true) public List