public String addQuestionThroughForm() throws IOException { if (idTaskAddQuestion < 1) { addFieldError("warning", "Select task and then add questions"); return INPUT; } SessionFactory sessionFactory = (SessionFactory) servletContext.getAttribute("SessionFactory"); try { task = new TaskDaoImpl(sessionFactory).getTask(idTaskAddQuestion); } catch (Exception e) { e.printStackTrace(); return INPUT; } if (hasFieldErrors()) { return ERROR; } if (fileImage != null) { Path imagePath = Paths.get(fileImage.getAbsolutePath()); InputStream io = Files.newInputStream(imagePath); question.setImage(IOUtils.toByteArray(io)); } question.setTask(task); ValidatorFactory validatorFactory = (ValidatorFactory) servletContext.getAttribute("ValidatorFactory"); Validator validator = validatorFactory.getValidator(); Set<ConstraintViolation<Question>> constraintViolations = validator.validate(question); if (!constraintViolations.isEmpty()) { for (ConstraintViolation item : constraintViolations) { addFieldError("warning", "Question validate error. " + item.getMessage()); } return ERROR; } if (!parseVariants(question)) { return ERROR; } try { task = new TaskDaoImpl(sessionFactory).addQuestion(idTaskAddQuestion, question); addFieldError("success", "Question was added!"); question = null; return SUCCESS; } catch (Exception e) { addFieldError("warning", e.getMessage()); return ERROR; } }
private boolean parseVariants(Question question) { if (question.getType().equals(QuestionType.SINGLE_SELECT) || question.getType().equals(QuestionType.MULTI_SELECT)) { int emptyVariant = 0; if (question.getVariant1().equals("")) { emptyVariant++; question.setVariant1(null); } if (question.getVariant2().equals("")) { emptyVariant++; question.setVariant2(null); } if (question.getVariant3().equals("")) { emptyVariant++; question.setVariant3(null); } if (question.getVariant4().equals("")) { emptyVariant++; question.setVariant4(null); } if (question.getVariant5().equals("")) { emptyVariant++; question.setVariant5(null); } if (question.getVariant6().equals("")) { emptyVariant++; question.setVariant6(null); } if (question.getVariant7().equals("")) { emptyVariant++; question.setVariant7(null); } if (question.getVariant8().equals("")) { emptyVariant++; question.setVariant8(null); } if (emptyVariant > 6) { addFieldError( "warning", "At least two variants for the question types " + "'SINGLE SELECT' and 'MULTI SELECT' should be"); return false; } } if (question.getType().equals(QuestionType.MULTI_SELECT)) { if (question.getAnswerRight().contains("@@@@@@@@") || question.getAnswerRight().endsWith("@@@@") || question.getAnswerRight().startsWith("@@@@") || question.getAnswerRight().length() == 0) { addFieldError("warning", "One of answers is empty"); return false; } } return true; }