@Post @Path("/reports/{errorEntry.id}/comments") public void addComment(ErrorEntry errorEntry, String newComment) { newComment = sanitizer.sanitize(newComment, true); ErrorEntry errorEntryFromDB = errorEntryDAO.retrieve(new Long(errorEntry.getId())); LOG.debug("errorEntry: " + errorEntryFromDB); LOG.debug("newComment: " + newComment); if (newComment.trim().isEmpty()) { validator.add( new ValidationMessage( ExceptionMessages.COMMENT_SHOULD_NOT_BE_EMPTY, ExceptionMessages.ERROR)); validator .onErrorUse(Results.logic()) .redirectTo(ErrorReportController.class) .details(errorEntryFromDB); } else if (newComment.trim().length() > COMMENT_MAX_SIZE) { validator.add( new ValidationMessage( ExceptionMessages.COMMENT_SHOULD_NOT_EXCEED_CHAR, ExceptionMessages.ERROR)); validator .onErrorUse(Results.logic()) .redirectTo(ErrorReportController.class) .details(errorEntryFromDB); } else { errorEntryLogic.addCommentToErrorEntry( errorEntryFromDB.getId(), loggedUser.getUser().getId(), newComment); } result.include("gaEventCommentAdded", true); result.redirectTo(ErrorReportController.class).details(errorEntryFromDB); }
public void adiciona(Pessoa pessoa, Endereco endereco, List<NumeroTelefone> telefone) { if (pessoa.getNome() == null || pessoa.getNome().length() < 3) { validator.add( new ValidationMessage( "Nome é obrigatório e precisa ter mais de 3 letras", "pessoa.nome")); } if (telefone.get(0).getNumero() == null) { validator.add( new ValidationMessage("Pelo menos um telefone deverá ser cadastrado", "telefone.numero")); } validator.onErrorUsePageOf(PessoaController.class).formulario(); pessoa.setEndereco(endereco); enderecoBanco.inserirEnderecoBanco(endereco); pessoaBanco.inserirPessoaBanco(pessoa); for (NumeroTelefone tel : telefone) { if (tel != null) { tel.setPessoa(pessoa); telefoneBanco.inserirTelefoneBanco(tel); } } result.redirectTo(this).listaContatos(); }
@Post("/products") public void create(Product product) { validator.validate(product); validator.onErrorUsePageOf(this).newProduct(); repository.create(product); result.redirectTo(this).index(); }
@Post("/projects/{project.id}/servers") public void addServer(final Server server, final Project project) { validator.checking( new Validations() { { if (server != null) { that(server.getDescription(), is(notEmpty()), "description", "invalid_description"); that(server.getIp(), is(notEmpty()), "ip", "invalid_ip"); } } }); validator.onErrorForwardTo(ProjectsController.class).addServer(server, project); Project p = projectDao.find(project.getId()); server.setCreation(Calendar.getInstance()); server.setOwner(userInfo.getUser()); p.addServer(server); projectDao.add(p); result.include("notice", server.getDescription() + " server added"); result.redirectTo(ProjectsController.class).view(project); }
@Path("/projeto/altera") public void altera(final Projeto projeto) { validator.validate(projeto); validator.onErrorForwardTo(this).altera_form(projeto.getIdProjeto()); dao.update(projeto); result.redirectTo(ProjetoController.class).index(); }
@Path("/projeto/cria") public void cria(final Projeto projeto) { validator.validate(projeto); validator.onErrorForwardTo(this).novo_form(); dao.save(projeto); result.redirectTo(ProjetoController.class).index(); }
@Post @Path("/apps") @Permission(value = {Role.ADMIN, Role.MEMBER}) public void create(Apps apps, UploadedFile war) { try { PropertiesUtil props = new PropertiesUtil("src/main/resources/path.properties"); String pathDeploy = props.getValor("tomcat.webapps"); if (war != null) apps.setNameWar(war.getFileName().substring(0, war.getFileName().indexOf("."))); validator.validate(apps); uploadValidate(war); validator.onErrorUsePageOf(this).newApps(); File warFile = new File(pathDeploy + war.getFileName()); IOUtils.copyLarge(war.getFile(), new FileOutputStream(warFile)); apps.setUser(this.userSession.getUser()); this.result.include("message", "Upload concluído com sucesso."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } repository.create(apps); result.redirectTo(this).index(); }
@Put("/products") public void update(Product product) { validator.validate(product); validator.onErrorUsePageOf(this).edit(product); repository.update(product); result.redirectTo(this).index(); }
@Post("/produtos") public void adiciona(Produto produto) { validator.validate(produto); validator.onErrorUsePageOf(ProdutosController.class).formulario(); dao.salva(produto); result.redirectTo(this).lista(); }
@Post("/login") public void login(Usuario usuario) { Usuario carrega = dao.carrega(usuario); if (carrega == null) { validator.add(new ValidationMessage("Login e/ou senha inválidos", "usuario.login")); } validator.onErrorUsePageOf(UsuariosController.class).loginForm(); usuarioWeb.login(carrega); result.redirectTo(ProdutosController.class).lista(); }
@Post("/usuarios") public void adiciona(Usuario usuario) { if (dao.existeUsuario(usuario)) { validator.add(new ValidationMessage("Login já existe", "usuario.login")); } validator.onErrorUsePageOf(UsuariosController.class).novo(); dao.adiciona(usuario); result.redirectTo(ProdutosController.class).lista(); }
@Post("/login") public void login(Administrador usuario) { Administrador carregado = dao.carregar(usuario); if (carregado == null) { validator.add(new ValidationMessage("Login ou Senha Incorretos", "usuario")); } validator.onErrorUsePageOf(this).loginForm(); userinfo.login(carregado); result.redirectTo(UsertwitterController.class).lista(); }
@Put @Path("/apps") @Permission(value = {Role.ADMIN, Role.MEMBER}) public void update(Apps apps) { checkPermission(apps); apps.setUser(this.userSession.getUser()); validator.validate(apps); validator.onErrorUsePageOf(this).edit(apps); repository.update(apps); result.redirectTo(this).index(); }
@Put @Path("/codes") public void update(Code code) { CodeValidation(code, false); validator.onErrorForwardTo(CodeController.class).index(code, false); repository.update(code); result.forwardTo(this).index(code, true); }
@Get @Path("/reports/{errorEntry.id}/edit") @LoggedIn public void editDetails(ErrorEntry errorEntry) { if (errorEntry == null) { result.redirectTo(getClass()).list(); return; } ErrorEntry errorEntryFromDB = errorEntryDAO.retrieve(new Long(errorEntry.getId())); LOG.debug("Details for: " + errorEntryFromDB); if (errorEntryFromDB == null) { validator.add( new ValidationMessage(ExceptionMessages.PAGE_NOT_FOUND, ExceptionMessages.ERROR)); validator.onErrorUse(Results.logic()).redirectTo(ErrorReportController.class).list(); } else if (!loggedUser.isLogged() || !loggedUser.getUser().getRole().getCanEditErrorReport()) { validator.add( new ValidationMessage(ExceptionMessages.USER_UNAUTHORIZED, ExceptionMessages.ERROR)); validator .onErrorUse(Results.logic()) .redirectTo(ErrorReportController.class) .details(errorEntryFromDB); } else { List<ProcessResult> procRes = cogrooFacade.processText(errorEntryFromDB.getText()); boolean hasError = false; for (ProcessResult processResult : procRes) { if (processResult.getMistakes().size() > 0) { hasError = true; break; } } result .include("errorEntry", errorEntryFromDB) .include("hasError", hasError) .include("processResultList", procRes) .include( "singleGrammarErrorList", cogrooFacade.asSingleGrammarErrorList(errorEntryFromDB.getText(), procRes)) .include("omissionCategoriesList", this.errorEntryLogic.getErrorCategoriesForUser()); } }
/** * Adiciona uma nova tarefa * * @param task tarefa a ser adicionada, recebida via método POST */ @Post @Path("/tasks") public void add(Task task) { task.setDone(false); task.setDeleted(false); validator.onErrorUsePageOf(this).newTask(); dao.save(task); result.redirectTo(this).list(); }
private void CodeValidation(Code code, boolean create) { List<Code> codeList; validator.validate(code); code = WithoutBlankChar(code); if (code.getName().isEmpty()) validator.add(new ValidationMessage("Erro", "O campo Nome nao pode ser deixado em branco")); if (code.getTags().isEmpty()) validator.add(new ValidationMessage("Erro", "O campo Tags não pode ser deixado em branco")); if (code.getLang().isEmpty()) validator.add( new ValidationMessage("Erro", "Escolha uma linguagem para o codigo a ser cadastrado")); if (code.getSnippet().isEmpty()) validator.add( new ValidationMessage( "Erro", "O campo de texto do codigo não pode ser deixado em branco")); if (create) { codeList = repository.findByName(code.getName()); if (!codeList.isEmpty()) validator.add( new ValidationMessage( "Erro", "Nao pode haver dois codigos com o mesmo nome, insira um nome diferente")); } }
@Post("/projects") public void add(final Project project) { validator.checking( new Validations() { { if (project != null) { that(project.getDescription(), is(notEmpty()), "description", "invalid_description"); } } }); validator.onErrorForwardTo(ProjectsController.class).list(); project.setCreation(Calendar.getInstance()); project.setOwner(userInfo.getUser()); projectDao.add(project); result.include("notice", project.getDescription() + " project added"); result.redirectTo(ProjectsController.class).list(); }
public void validate(Validator validator) { validator.checking( new Validations() { { that(isNotBlank(nome), "warning", "fiel.nome.invalido"); if (that(dataDeNascimento != null, "warning", "fiel.dataNascimeto.naoInfomada")) { that( dataDeNascimento.isBeforeNow() || dataDeNascimento.isEqualNow(), "warning", "fiel.dataNascimeto.invalida"); } } }); }
@Test public void deveGravarUmNovoRegistroDeHodometro() { Hodometro hodometro = new Hodometro(); hodometro.setVeiculo(veiculoDAO.busca((long) 4)); hodometro.setUsuario(usuarioDAO.busca((long) 2)); hodometro.setQuilometragem(new BigDecimal("27.34")); hodometro.setDataLeitura(new LocalDateTime(2013, 9, 19, 17, 23, 34)); controller.novoRegistro(hodometro); System.out.println(validator.getErrors()); List<Hodometro> lista = controller.lista(); assertEquals(2, lista.size()); }
/** * Valida se o ddd e o telefone são válidos * * @return true - se o ddd e o telefone forem válidos <br> * false - se o ddd e o telefone forem inválidos */ public void validate(Validator validator) { validator.checking( new Validations() { { if (this.that(isValidDDD(), "validation", "validation.invalid", i18n("phone.ddd"))) ; switch (getType()) { case CELL: if (this.that( isValidCellNumber(), "validation", "validation.invalid", i18n("phone.number"))) ; break; default: if (this.that( isValidNumber(), "validation", "validation.invalid", i18n("phone.number"))) ; } } }); }
@Put @Path("/reports/{reportId}") @LoggedIn public void updateErrorReport( Long reportId, String type, String badintIndex, String badintType, List<String> badintStart, List<String> badintEnd, List<String> badintRule, String omissionCategory, String omissionCustom, String omissionReplaceBy, String omissionStart, String omissionEnd) { LOG.debug( "reportId: " + reportId + "\n" + "type: " + type + "\n" + "badintIndex: " + badintIndex + "\n" + "badintType: " + badintType + "\n" + "badintStart: " + badintStart + "\n" + "badintEnd: " + badintEnd + "\n" + "badintRule: " + badintRule + "\n" + "omissionCategory: " + omissionCategory + "\n" + "omissionCustom: " + omissionCustom + "\n" + "omissionReplaceBy: " + omissionReplaceBy + "\n" + "omissionStart: " + omissionStart + "\n" + "omissionEnd: " + omissionEnd); ErrorEntry errorEntryFromDB = this.errorEntryDAO.retrieve(reportId); ErrorEntry originalErrorEntry = null; try { originalErrorEntry = (ErrorEntry) errorEntryFromDB.clone(); } catch (CloneNotSupportedException e) { LOG.error("Error cloning ErrorEntry object: ", e); } if (type == null) { if (errorEntryFromDB.getBadIntervention() != null) { type = "BADINT"; } else { type = "OMISSION"; } } if (type.equals("BADINT")) { GrammarCheckerBadIntervention newBadIntervention = null; if (errorEntryFromDB.getBadIntervention() == null) { newBadIntervention = new GrammarCheckerBadIntervention(); errorEntryFromDB.setBadIntervention(newBadIntervention); } else { newBadIntervention = errorEntryFromDB.getBadIntervention(); } newBadIntervention.setClassification( Enum.valueOf(BadInterventionClassification.class, badintType)); newBadIntervention.setErrorEntry(errorEntryFromDB); newBadIntervention.setRule(badintRule.get(Integer.valueOf(badintIndex) - 1)); errorEntryFromDB.setSpanStart( Integer.valueOf(badintStart.get(Integer.valueOf(badintIndex) - 1))); errorEntryFromDB.setSpanEnd(Integer.valueOf(badintEnd.get(Integer.valueOf(badintIndex) - 1))); this.errorEntryLogic.updateBadIntervention(errorEntryFromDB, originalErrorEntry); } else { int start = -1; int end = -1; if (omissionStart != null && omissionEnd != null) { start = Integer.parseInt(omissionStart); end = Integer.parseInt(omissionEnd); } GrammarCheckerOmission o = null; if (errorEntryFromDB.getOmission() == null) { o = new GrammarCheckerOmission(); errorEntryFromDB.setOmission(o); } else { o = errorEntryFromDB.getOmission(); } o.setCategory(omissionCategory); if (omissionCategory.equals(ErrorEntryLogic.CUSTOM)) { o.setCustomCategory(sanitizer.sanitize(omissionCustom, false)); } else { o.setCustomCategory(null); } o.setErrorEntry(errorEntryFromDB); o.setReplaceBy(sanitizer.sanitize(omissionReplaceBy, false)); errorEntryFromDB.setSpanStart(start); errorEntryFromDB.setSpanEnd(end); if (!(end > 0 && end > start)) { validator.add( new ValidationMessage( ExceptionMessages.ERROR_REPORT_OMISSION_INVALID_SELECTION, ExceptionMessages.ERROR)); } if (omissionCategory.equals("custom") && (omissionCustom == null || omissionCustom.length() == 0)) { validator.add( new ValidationMessage( ExceptionMessages.ERROR_REPORT_OMISSION_MISSING_CUSTOM_CATEGORY, ExceptionMessages.ERROR)); } if ((omissionReplaceBy == null || omissionReplaceBy.length() == 0)) { validator.add( new ValidationMessage( ExceptionMessages.ERROR_REPORT_OMISSION_MISSING_REPLACE, ExceptionMessages.ERROR)); } if (validator.hasErrors()) { validator .onErrorUse(Results.logic()) .redirectTo(ErrorReportController.class) .editDetails(errorEntryFromDB); return; } this.errorEntryLogic.updateOmission(errorEntryFromDB, originalErrorEntry); } result.include("gaEventErrorChanged", true); result.redirectTo(getClass()).details(errorEntryFromDB); }