Skip to content

Commit

Permalink
Changed to Java 17; Creating a custom validation
Browse files Browse the repository at this point in the history
  • Loading branch information
dearrudam committed Mar 23, 2022
1 parent cafaa85 commit 2c15c26
Show file tree
Hide file tree
Showing 8 changed files with 190 additions and 43 deletions.
10 changes: 9 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<properties>
<compiler-plugin.version>3.8.1</compiler-plugin.version>
<failsafe.useModulePath>false</failsafe.useModulePath>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
Expand Down Expand Up @@ -163,6 +163,14 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
Expand Down
48 changes: 44 additions & 4 deletions src/main/java/io/github/arrudalabs/mizudo/model/Usuario.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,55 @@
package io.github.arrudalabs.mizudo.model;

import io.github.arrudalabs.mizudo.services.GeradorDeHash;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;

import javax.persistence.*;
import java.util.Map;
import java.util.Set;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.*;
import java.util.stream.Stream;

@Entity
@Table(name = "usuarios")
public class Usuario extends PanacheEntityBase {

public static Usuario definirUsuario(Membro membro,
String username,
String senha,
GeradorDeHash geradorDeHash) {

Optional<Usuario> usuarioRef = Usuario.buscarPorUsername(username);

if (usuarioRef.isPresent()) {
throw new IllegalArgumentException("Já existe usuário com o username informado");
}
return Usuario.novoUsuario(membro, username, senha, geradorDeHash);
}

private static Usuario novoUsuario(Membro membro,
String username,
String senha,
GeradorDeHash geradorDeHash) {
Usuario novoUsuario = new Usuario();
novoUsuario.membro = membro;
novoUsuario.username = username;
String salt = UUID.randomUUID().toString();
novoUsuario.salt = salt.getBytes(StandardCharsets.UTF_8);
novoUsuario.hash = geradorDeHash.gerarHash(salt, senha).getBytes(StandardCharsets.UTF_8);
novoUsuario.persist();
novoUsuario.definirPapeis(Set.of(Papeis.ALUNO));
return novoUsuario;
}

public void definirPapeis(Set<Papeis> papeis) {
this.papeis.clear();
this.papeis.addAll(papeis);
}

public static Optional<Usuario> buscarPorUsername(String username) {
return Usuario.findByIdOptional(username);
}

public static Stream<Usuario> buscarUsuariosDoMembro(Membro membro) {
return Usuario.stream("membro.id = :membroId", Map.of("membroId", membro.id));
}
Expand All @@ -21,7 +60,7 @@ public static Stream<Usuario> buscarUsuariosDoMembro(Membro membro) {
*/
@Deprecated
public static void apagarTodosOsUsuarios() {
Usuario.deleteAll();
Usuario.streamAll().forEach(u->u.delete());
}

@Id
Expand All @@ -44,6 +83,7 @@ public static void apagarTodosOsUsuarios() {
joinColumns = @JoinColumn(name = "username"))
@Column(name = "papel")
@Enumerated(EnumType.STRING)
public Set<Papeis> papeis;
public Set<Papeis> papeis = new LinkedHashSet<>();


}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import io.github.arrudalabs.mizudo.model.Membro;
import io.github.arrudalabs.mizudo.model.Usuario;
import io.github.arrudalabs.mizudo.services.GeradorDeHash;
import io.github.arrudalabs.mizudo.validation.DeveSerIdValido;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.ws.rs.PUT;
Expand All @@ -13,7 +16,11 @@
@Path("/membros/{membroId}/user")
public class UsuarioDoMembroResource {

@Inject
GeradorDeHash geradorDeHash;

@PUT
@Transactional
public UsuarioRegistrado definirUsuario(
@DeveSerIdValido(
entityClass = Membro.class,
Expand All @@ -22,36 +29,22 @@ public UsuarioRegistrado definirUsuario(
@PathParam("membroId") final Long membroId,
@Valid final NovoUsuario novoUsuario) {

return UsuarioRegistrado.of(novoUsuario.definirUsuario(membroId));
return new UsuarioRegistrado(Usuario.definirUsuario(Membro.findById(membroId),novoUsuario.username,novoUsuario.senha,geradorDeHash));
}

public static class NovoUsuario {

@NotBlank
public String username;
@NotBlank
public String senha;
@NotBlank
public String confirmacaoSenha;

public Usuario definirUsuario(Long membroId) {
var usuario = new Usuario();
usuario.username = this.username;
//TODO implementar
return usuario;
}
public record NovoUsuario(@NotBlank
String username,
@NotBlank
String senha,
@NotBlank
String confirmacaoSenha) {
}

public static class UsuarioRegistrado {
public record UsuarioRegistrado(String username, String senha) {

public static UsuarioRegistrado of(Usuario usuario) {
var usuarioRegistrado = new UsuarioRegistrado();
usuarioRegistrado.username = usuario.username;
return usuarioRegistrado;
public UsuarioRegistrado(Usuario usuario) {
this(usuario.username, "*****");
}

public String username;
public String senha = "*****";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@
@ApplicationScoped
public class DeveSerIdValidoValidator implements ConstraintValidator<DeveSerIdValido, Serializable> {

private DeveSerIdValido constraintAnnotation;
private DeveSerIdValido constraintAnnotation ;

@Override
public void initialize(DeveSerIdValido constraintAnnotation) {
this.constraintAnnotation = constraintAnnotation;
ConstraintValidator.super.initialize(constraintAnnotation);
this.constraintAnnotation=(constraintAnnotation);
}

@Override
public boolean isValid(Serializable value, ConstraintValidatorContext context) {
return Optional.ofNullable(value)
.map(this::isValid)
.map(v -> this.isValid(v))
.orElse(false);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.github.arrudalabs.mizudo.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.groups.Default;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Predicate;

@Constraint(validatedBy = SuportaValidacaoValidator.class)
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SuportaValidacao {
String message();

Class<? extends Predicate> classeValidadora();

Class<? extends Payload>[] payload() default {};

Class<? extends Default>[] groups() default {};

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.github.arrudalabs.mizudo.validation;

import javax.enterprise.context.ApplicationScoped;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;

@ApplicationScoped
public class SuportaValidacaoValidator implements ConstraintValidator<SuportaValidacao, Object> {

private SuportaValidacao constraintAnnotation;

@Override
public void initialize(SuportaValidacao constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
this.constraintAnnotation = constraintAnnotation;
}

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
try {
return this.constraintAnnotation
.classeValidadora()
.getConstructor(new Class[0])
.newInstance(new Object[0]).test(value);
} catch (IllegalAccessException
| NoSuchMethodException
| InstantiationException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,42 +20,46 @@
import static org.hamcrest.MatcherAssert.*;

@QuarkusTest
public class UsuarioDoMembroTest {
public class UsuarioDoMembroResourceTest {

@Inject
ApiTestSupport apiTestSupport;

@BeforeEach
@AfterEach
void limparMembros(){
void limparMembros() {
apiTestSupport.execute(Usuario::apagarTodosOsUsuarios);
apiTestSupport.execute(Membro::removerTodosMembros);
}

@Test
void deveDefinirUsuarioParaUmMembroValido(){
void deveDefinirUsuarioParaUmMembroValido() {

var membro = apiTestSupport.executeAndGet(()->Membro.novoMembro(UUID.randomUUID().toString()));
var membro = apiTestSupport.executeAndGet(() -> Membro.novoMembro(UUID.randomUUID().toString()));

String senha = UUID.randomUUID().toString();
String username = UUID.randomUUID().toString();
apiTestSupport
.newAuthenticatedRequest()
.log().everything()
.contentType(ContentType.JSON)
.body(Json.createObjectBuilder()
.add("username", username)
.add("senha", senha)
.add("confirmacaoSenha",senha)
.build().toString())
.put("/resources/membros/{id}/user", Map.of("id",membro.id))
.body(
"""
{
"username": "%s",
"senha": "%s",
"confirmacaoSenha": "%s"
}
""".formatted(username, senha, senha))
.put("/resources/membros/{id}/user", Map.of("id", membro.id))
.then()
.log().everything()
.statusCode(Response.Status.OK.getStatusCode())
.body("username", is(username))
.body("senha", is("*****"));

assertThat("Não foi persistido o usuário do membro.", Usuario.buscarUsuariosDoMembro(membro).count(), is(1L));
assertThat("Não foi persistido o usuário do membro com o username informado.", Usuario.buscarPorUsername(username), notNullValue());
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package io.github.arrudalabs.mizudo.validation;

import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;

import javax.inject.Inject;
import javax.validation.Validator;
import javax.validation.constraints.NotBlank;

import java.util.Objects;
import java.util.function.Predicate;

import static org.junit.jupiter.api.Assertions.*;

@QuarkusTest
class SuportaValidacaoValidatorTest {

@Inject
Validator validator;

@Test
void test() {
assertFalse(validator.validate(new Pojo(null,"ewrw")).isEmpty());
}


@SuportaValidacao(
message = "Pojo invalido - atributos diferentes",
classeValidadora = Pojo.PojoValidator.class
)
static record Pojo(@NotBlank String atributo1,
@NotBlank String atributo2) {

public static class PojoValidator implements Predicate<Pojo> {

@Override
public boolean test(Pojo o) {
return Objects.nonNull(o)
&& Objects.equals(o.atributo1, o.atributo2);
}
}

}
}

0 comments on commit 2c15c26

Please sign in to comment.