Commit 06472395 authored by Administrator's avatar Administrator

Modifies REST API for a easier client integration

The REST API methods for entity creation and modification have been
simplified with more basic entities.

In addition, the UserResource class has been added so that it is
possible now for clients to use it for user authentication.
parent de68ebfe
...@@ -35,5 +35,6 @@ public class Administrator extends User implements Serializable { ...@@ -35,5 +35,6 @@ public class Administrator extends User implements Serializable {
*/ */
public Administrator(String login, String password) { public Administrator(String login, String password) {
super(login, password); super(login, password);
this.role = "ADMIN";
} }
} }
...@@ -53,6 +53,7 @@ public class Owner extends User implements Serializable { ...@@ -53,6 +53,7 @@ public class Owner extends User implements Serializable {
*/ */
public Owner(String login, String password) { public Owner(String login, String password) {
super(login, password); super(login, password);
this.role = "OWNER";
this.pets = new HashSet<>(); this.pets = new HashSet<>();
} }
......
...@@ -33,6 +33,9 @@ public abstract class User implements Serializable { ...@@ -33,6 +33,9 @@ public abstract class User implements Serializable {
@Column(length = 32, nullable = false) @Column(length = 32, nullable = false)
protected String password; protected String password;
@Column(name="role", insertable = false, updatable = false)
protected String role;
User() {} User() {}
/** /**
...@@ -78,6 +81,16 @@ public abstract class User implements Serializable { ...@@ -78,6 +81,16 @@ public abstract class User implements Serializable {
this.login = login; this.login = login;
} }
/**
* Returns the role of the user. This value is automatically set by JPA, as
* it is the value used as discriminator in the inheritance.
*
* @return the role of the user.
*/
public String getRole() {
return role;
}
/** /**
* Returns the MD5 of the user's password. Capital letters are used * Returns the MD5 of the user's password. Capital letters are used
......
...@@ -18,7 +18,8 @@ import javax.ws.rs.core.Response; ...@@ -18,7 +18,8 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import es.uvigo.esei.xcs.domain.entities.Owner; import es.uvigo.esei.xcs.domain.entities.Owner;
import es.uvigo.esei.xcs.domain.entities.Pet; import es.uvigo.esei.xcs.rest.entity.OwnerEditionData;
import es.uvigo.esei.xcs.rest.entity.OwnerCreationData;
import es.uvigo.esei.xcs.service.OwnerService; import es.uvigo.esei.xcs.service.OwnerService;
/** /**
...@@ -74,19 +75,20 @@ public class OwnerResource { ...@@ -74,19 +75,20 @@ public class OwnerResource {
* Creates a new owner. This owner may include a list of pets, that will be * Creates a new owner. This owner may include a list of pets, that will be
* also created. * also created.
* *
* @param owner a new owner to be stored. * @param ownerData a new owner to be stored.
* @return a {@code CREATED} response with the URI of the new owner in the * @return a {@code CREATED} response with the URI of the new owner in the
* {@code Location} header. * {@code Location} header.
* @throws IllegalArgumentException if owner is {@code null} or if an owner * @throws IllegalArgumentException if owner is {@code null} or if an owner
* with the same login already exists. * with the same login already exists.
*/ */
@POST @POST
public Response create(Owner owner) { public Response create(OwnerCreationData ownerData) {
// Pets are serialized without owner. if (ownerData == null) {
assignOwnerToPets(owner); throw new IllegalArgumentException("ownerData can't be null");
}
try { try {
final Owner newOwner = this.service.create(owner); final Owner newOwner = this.service.create(ownerData.toOwner());
final URI ownerUri = uriInfo.getAbsolutePathBuilder() final URI ownerUri = uriInfo.getAbsolutePathBuilder()
.path(newOwner.getLogin()) .path(newOwner.getLogin())
.build(); .build();
...@@ -101,15 +103,24 @@ public class OwnerResource { ...@@ -101,15 +103,24 @@ public class OwnerResource {
* Updates an owner. This owner may include a list of pets, that will be * Updates an owner. This owner may include a list of pets, that will be
* also created or updated. If the owner does not exists it will be created. * also created or updated. If the owner does not exists it will be created.
* *
* @param owner an owner to be updated. * @param ownerData an owner to be updated.
* @return an empty {@code OK} response. * @return an empty {@code OK} response.
* @throws IllegalArgumentException if owner is {@code null}. * @throws IllegalArgumentException if owner is {@code null}.
*/ */
@Path("{login}")
@PUT @PUT
public Response update(Owner owner) { public Response update(@PathParam("login") String login, OwnerEditionData ownerData) {
// Pets are serialized without owner. if (login == null) {
assignOwnerToPets(owner); throw new IllegalArgumentException("login can't be null");
}
if (ownerData == null) {
throw new IllegalArgumentException("ownerData can't be null");
}
final Owner owner = this.service.get(login);
ownerData.assignData(owner);
this.service.update(owner); this.service.update(owner);
return Response.ok().build(); return Response.ok().build();
...@@ -133,14 +144,4 @@ public class OwnerResource { ...@@ -133,14 +144,4 @@ public class OwnerResource {
return Response.ok().build(); return Response.ok().build();
} }
private static void assignOwnerToPets(Owner owner) {
if (owner == null)
throw new IllegalArgumentException("owner can't be null");
for (Pet pet : owner.getPets()) {
if (pet.getOwner() != owner)
pet.setOwner(owner);
}
}
} }
...@@ -19,6 +19,7 @@ import javax.ws.rs.core.Response; ...@@ -19,6 +19,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import es.uvigo.esei.xcs.domain.entities.Pet; import es.uvigo.esei.xcs.domain.entities.Pet;
import es.uvigo.esei.xcs.rest.entity.PetData;
import es.uvigo.esei.xcs.service.PetService; import es.uvigo.esei.xcs.service.PetService;
/** /**
...@@ -73,7 +74,7 @@ public class PetResource { ...@@ -73,7 +74,7 @@ public class PetResource {
/** /**
* Creates a new pet owned by the current user. * Creates a new pet owned by the current user.
* *
* @param pet a new owner to be stored. * @param petData a new owner to be stored.
* @return a {@code CREATED} response with the URI of the new pet in the * @return a {@code CREATED} response with the URI of the new pet in the
* {@code Location} header. * {@code Location} header.
* @throws IllegalArgumentException if pet is {@code null} or if a pet with * @throws IllegalArgumentException if pet is {@code null} or if a pet with
...@@ -83,14 +84,15 @@ public class PetResource { ...@@ -83,14 +84,15 @@ public class PetResource {
* thrown. * thrown.
*/ */
@POST @POST
public Response create(Pet pet) throws SecurityException { public Response create(PetData petData) throws SecurityException {
if (pet == null) if (petData == null)
throw new IllegalArgumentException("pet can't be null"); throw new IllegalArgumentException("pet can't be null");
try { try {
final Pet newPet = this.service.create(pet); final Pet pet = this.service.create(petData.toPet());
final URI petUri = uriInfo.getAbsolutePathBuilder() final URI petUri = uriInfo.getAbsolutePathBuilder()
.path(Integer.toString(newPet.getId())) .path(Integer.toString(pet.getId()))
.build(); .build();
return Response.created(petUri).build(); return Response.created(petUri).build();
...@@ -105,18 +107,23 @@ public class PetResource { ...@@ -105,18 +107,23 @@ public class PetResource {
* Updates the information of a pet. If the pet is not stored, it will be * Updates the information of a pet. If the pet is not stored, it will be
* created. * created.
* *
* @param pet a pet to be updated. * @param id the identifier of the pet to be modified.
* @param petData a pet to be updated.
* @return an empty {@code OK} response. * @return an empty {@code OK} response.
* @throws IllegalArgumentException if pet is {@code null} of it has no * @throws IllegalArgumentException if pet is {@code null} of it has no
* owner. * owner.
* @throws SecurityException if the pet's owner is not the current user. * @throws SecurityException if the pet's owner is not the current user.
*/ */
@Path("{id}")
@PUT @PUT
public Response update(Pet pet) throws SecurityException { public Response update(@PathParam("id") int id, PetData petData) throws SecurityException {
if (pet == null) if (petData == null)
throw new IllegalArgumentException("pet can't be null"); throw new IllegalArgumentException("pet can't be null");
try { try {
final Pet pet = this.service.get(id);
petData.assignData(pet);
this.service.update(pet); this.service.update(pet);
return Response.ok().build(); return Response.ok().build();
......
package es.uvigo.esei.xcs.rest;
import javax.ejb.EJB;
import javax.ejb.EJBAccessException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import es.uvigo.esei.xcs.domain.entities.User;
import es.uvigo.esei.xcs.rest.entity.UserCredentials;
import es.uvigo.esei.xcs.service.UserService;
@Path("user")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {
@EJB
private UserService service;
@GET
public Response getCredentials() {
try {
final User currentUser = this.service.getCurrentUser();
return Response.ok(new UserCredentials(currentUser)).build();
} catch (EJBAccessException eae) {
throw new SecurityException(eae);
}
}
}
package es.uvigo.esei.xcs.rest.entity;
import java.io.Serializable;
import es.uvigo.esei.xcs.domain.entities.Owner;
public class OwnerCreationData implements Serializable {
private static final long serialVersionUID = 1L;
private String login;
private String password;
OwnerCreationData() {}
public OwnerCreationData(String login, String password) {
this.login = login;
this.password = password;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public Owner toOwner() {
return new Owner(this.login, this.password);
}
}
package es.uvigo.esei.xcs.rest.entity;
import java.io.Serializable;
import es.uvigo.esei.xcs.domain.entities.Owner;
public class OwnerEditionData implements Serializable {
private static final long serialVersionUID = 1L;
private String password;
OwnerEditionData() {}
public OwnerEditionData(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void assignData(Owner owner) {
owner.changePassword(this.password);
}
}
package es.uvigo.esei.xcs.rest.entity;
import java.io.Serializable;
import java.util.Date;
import es.uvigo.esei.xcs.domain.entities.AnimalType;
import es.uvigo.esei.xcs.domain.entities.Pet;
public class PetData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private AnimalType animal;
private Date birth;
PetData() {}
public PetData(String name, AnimalType animal, Date birth) {
this.name = name;
this.animal = animal;
this.birth = birth;
}
public String getName() {
return name;
}
public AnimalType getAnimal() {
return animal;
}
public Date getBirth() {
return birth;
}
public Pet assignData(Pet pet) {
pet.setName(this.name);
pet.setAnimal(this.animal);
pet.setBirth(this.birth);
return pet;
}
public Pet toPet() {
return new Pet(this.name, this.animal, this.birth);
}
}
package es.uvigo.esei.xcs.rest.entity;
import java.io.Serializable;
import es.uvigo.esei.xcs.domain.entities.User;
public class UserCredentials implements Serializable {
private static final long serialVersionUID = 1L;
private String login;
private String role;
public UserCredentials(User user) {
this.login = user.getLogin();
this.role = user.getRole();
}
public String getLogin() {
return login;
}
public String getRole() {
return role;
}
}
...@@ -10,6 +10,18 @@ ...@@ -10,6 +10,18 @@
</servlet-mapping> </servlet-mapping>
<!--Defining security constraint for type of roles available --> <!--Defining security constraint for type of roles available -->
<security-constraint>
<web-resource-collection>
<web-resource-name>user</web-resource-name>
<url-pattern>/api/user/*</url-pattern>
<http-method-omission>OPTIONS</http-method-omission>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
<role-name>OWNER</role-name>
</auth-constraint>
</security-constraint>
<security-constraint> <security-constraint>
<web-resource-collection> <web-resource-collection>
<web-resource-name>admin</web-resource-name> <web-resource-name>admin</web-resource-name>
......
...@@ -7,8 +7,8 @@ import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.NON_EXISTENT_LOGIN ...@@ -7,8 +7,8 @@ import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.NON_EXISTENT_LOGIN
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.OWNER_WITHOUT_PETS_LOGIN; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.OWNER_WITHOUT_PETS_LOGIN;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.OWNER_WITH_PETS_LOGIN; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.OWNER_WITH_PETS_LOGIN;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.existentOwner; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.existentOwner;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerWithFreshPets; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerLogin;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerWithPersistentPets; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerPassword;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerWithoutPets; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerWithoutPets;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newPasswordForExistentOwner; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newPasswordForExistentOwner;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.owners; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.owners;
...@@ -23,7 +23,6 @@ import static org.junit.Assert.assertThat; ...@@ -23,7 +23,6 @@ import static org.junit.Assert.assertThat;
import java.util.List; import java.util.List;
import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
...@@ -48,261 +47,272 @@ import org.junit.runner.RunWith; ...@@ -48,261 +47,272 @@ import org.junit.runner.RunWith;
import es.uvigo.esei.xcs.domain.entities.Owner; import es.uvigo.esei.xcs.domain.entities.Owner;
import es.uvigo.esei.xcs.rest.GenericTypes.ListOwnerType; import es.uvigo.esei.xcs.rest.GenericTypes.ListOwnerType;
import es.uvigo.esei.xcs.rest.entity.OwnerCreationData;
import es.uvigo.esei.xcs.rest.entity.OwnerEditionData;
import es.uvigo.esei.xcs.service.OwnerService; import es.uvigo.esei.xcs.service.OwnerService;
@RunWith(Arquillian.class) @RunWith(Arquillian.class)
public class OwnerResourceRestTest { public class OwnerResourceRestTest {
private final static String BASE_PATH = "api/owner/"; private final static String BASE_PATH = "api/owner/";
private static final String BASIC_AUTHORIZATION = "Basic am9zZTpqb3NlcGFzcw="; private static final String BASIC_AUTHORIZATION = "Basic am9zZTpqb3NlcGFzcw=";
@Deployment @Deployment
public static Archive<?> createDeployment() { public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war") return ShrinkWrap.create(WebArchive.class, "test.war")
.addClass(OwnerResource.class) .addClass(OwnerResource.class)
.addClasses(CORSFilter.class, IllegalArgumentExceptionMapper.class, SecurityExceptionMapper.class) .addClasses(OwnerCreationData.class, OwnerEditionData.class)
.addPackage(OwnerService.class.getPackage()) .addClasses(CORSFilter.class, IllegalArgumentExceptionMapper.class, SecurityExceptionMapper.class)
.addPackage(Owner.class.getPackage()) .addPackage(OwnerService.class.getPackage())
.addAsResource("test-persistence.xml", "META-INF/persistence.xml") .addPackage(Owner.class.getPackage())
.addAsWebInfResource("jboss-web.xml") .addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource("web.xml") .addAsWebInfResource("jboss-web.xml")
.addAsResource("arquillian.extension.persistence.properties") .addAsWebInfResource("web.xml")
.addAsResource("arquillian.extension.persistence.dbunit.properties") .addAsResource("arquillian.extension.persistence.properties")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); .addAsResource("arquillian.extension.persistence.dbunit.properties")
} .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test @InSequence(1)
@UsingDataSet("owners.xml") @Test
@Cleanup(phase = TestExecutionPhase.NONE) @InSequence(1)
public void beforeGet() {} @UsingDataSet("owners.xml")
@Cleanup(phase = TestExecutionPhase.NONE)
@Test @InSequence(2) public void beforeGet() {}
@RunAsClient
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) @Test
public void testGet( @InSequence(2)
@ArquillianResteasyResource(BASE_PATH + EXISTENT_LOGIN) ResteasyWebTarget webTarget @RunAsClient
) throws Exception { @Header(name = "Authorization", value = BASIC_AUTHORIZATION)
final Response response = webTarget.request().get(); public void testGet(
@ArquillianResteasyResource(BASE_PATH + EXISTENT_LOGIN)
assertThat(response, hasOkStatus()); ResteasyWebTarget webTarget
) throws Exception {
final Owner owner = response.readEntity(Owner.class); final Response response = webTarget.request().get();
final Owner expected = existentOwner();
assertThat(response, hasOkStatus());
assertThat(owner, is(equalToOwner(expected)));
} final Owner owner = response.readEntity(Owner.class);
final Owner expected = existentOwner();
@Test @InSequence(3)
@ShouldMatchDataSet("owners.xml") assertThat(owner, is(equalToOwner(expected)));
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" }) }
public void afterGet() {}
@Test
@InSequence(3)
@ShouldMatchDataSet("owners.xml")
@Test @InSequence(4) @CleanupUsingScript({
@UsingDataSet("owners.xml") "cleanup.sql", "cleanup-autoincrement.sql"
@Cleanup(phase = TestExecutionPhase.NONE) })
public void beforeGetNonExistent() {} public void afterGet() {}
@Test @InSequence(5) @Test
@RunAsClient @InSequence(4)
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) @UsingDataSet("owners.xml")
public void testGetNonExistent( @Cleanup(phase = TestExecutionPhase.NONE)
@ArquillianResteasyResource(BASE_PATH + NON_EXISTENT_LOGIN) ResteasyWebTarget webTarget public void beforeGetNonExistent() {}
) throws Exception {
final Response response = webTarget.request().get(); @Test
@InSequence(5)
assertThat(response, hasBadRequestStatus()); @RunAsClient
} @Header(name = "Authorization", value = BASIC_AUTHORIZATION)
public void testGetNonExistent(
@Test @InSequence(6) @ArquillianResteasyResource(BASE_PATH + NON_EXISTENT_LOGIN)
@ShouldMatchDataSet("owners.xml") ResteasyWebTarget webTarget
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" }) ) throws Exception {
public void afterGetNonExistent() {} final Response response = webTarget.request().get();
assertThat(response, hasBadRequestStatus());
}
@Test @InSequence(10)
@UsingDataSet("owners.xml") @Test
@Cleanup(phase = TestExecutionPhase.NONE) @InSequence(6)
public void beforeList() {} @ShouldMatchDataSet("owners.xml")
@CleanupUsingScript({
@Test @InSequence(11) "cleanup.sql", "cleanup-autoincrement.sql"
@RunAsClient })
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) public void afterGetNonExistent() {}
public void testList(
@ArquillianResteasyResource(BASE_PATH) ResteasyWebTarget webTarget @Test
) throws Exception { @InSequence(10)
final Response response = webTarget.request().get(); @UsingDataSet("owners.xml")
@Cleanup(phase = TestExecutionPhase.NONE)
assertThat(response, hasOkStatus()); public void beforeList() {}
final List<Owner> list = ListOwnerType.readEntity(response); @Test
assertThat(list, containsOwnersInAnyOrder(owners())); @InSequence(11)
} @RunAsClient
@Header(name = "Authorization", value = BASIC_AUTHORIZATION)
@Test @InSequence(12) public void testList(
@ShouldMatchDataSet("owners.xml") @ArquillianResteasyResource(BASE_PATH)
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" }) ResteasyWebTarget webTarget
public void afterList() {} ) throws Exception {
final Response response = webTarget.request().get();
assertThat(response, hasOkStatus());
@Test @InSequence(20)
@UsingDataSet("owners.xml") final List<Owner> list = ListOwnerType.readEntity(response);
@Cleanup(phase = TestExecutionPhase.NONE) assertThat(list, containsOwnersInAnyOrder(owners()));
public void beforeCreate() {} }
@Test @InSequence(21) @Test
@RunAsClient @InSequence(12)
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) @ShouldMatchDataSet("owners.xml")
public void testCreate( @CleanupUsingScript({
@ArquillianResteasyResource(BASE_PATH) ResteasyWebTarget webTarget "cleanup.sql", "cleanup-autoincrement.sql"
) throws Exception { })
testCreateOwner(webTarget, newOwnerWithoutPets()); public void afterList() {}
}
@Test
@Test @InSequence(22) @InSequence(20)
@ShouldMatchDataSet({"owners.xml", "owners-create-without-pets.xml"}) @UsingDataSet("owners.xml")
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" }) @Cleanup(phase = TestExecutionPhase.NONE)
public void afterCreate() {} public void beforeCreate() {}
@Test
@InSequence(21)
@Test @InSequence(23) @RunAsClient
@UsingDataSet("owners.xml") @Header(name = "Authorization", value = BASIC_AUTHORIZATION)
@Cleanup(phase = TestExecutionPhase.NONE) public void testCreate(
public void beforeCreateWithPets() {} @ArquillianResteasyResource(BASE_PATH)
ResteasyWebTarget webTarget
@Test @InSequence(24) ) throws Exception {
@RunAsClient final Owner newOwner = newOwnerWithoutPets();
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) final OwnerCreationData ownerData = new OwnerCreationData(newOwnerLogin(), newOwnerPassword());
public void testCreateWithPets(
@ArquillianResteasyResource(BASE_PATH) ResteasyWebTarget webTarget final Response response = webTarget.request().post(json(ownerData));
) throws Exception {
testCreateOwner(webTarget, newOwnerWithFreshPets(), newOwnerWithPersistentPets()); assertThat(response, hasCreatedStatus());
}
final String location = response.getHeaderString("Location");
@Test @InSequence(25)
@ShouldMatchDataSet({"owners.xml", "owners-create-with-pets.xml"}) final Response responseGet = authorizedJsonRequestGet(location);
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" }) final Owner owner = responseGet.readEntity(Owner.class);
public void afterCreateWithPets() {} assertThat(owner, is(equalToOwner(newOwner)));
}
private void testCreateOwner(WebTarget webTarget, Owner newOwner) { @Test
testCreateOwner(webTarget, newOwner, newOwner); @InSequence(22)
} @ShouldMatchDataSet({
"owners.xml", "owners-create-without-pets.xml"
private void testCreateOwner(WebTarget webTarget, Owner newOwner, Owner persistentOwner) { })
final Response response = webTarget.request().post(json(newOwner)); @CleanupUsingScript({
"cleanup.sql", "cleanup-autoincrement.sql"
assertThat(response, hasCreatedStatus()); })
public void afterCreate() {}
final String location = response.getHeaderString("Location");
@Test
final Response responseGet = authorizedJsonRequestGet(location); @InSequence(30)
final Owner owner = responseGet.readEntity(Owner.class); @UsingDataSet("owners.xml")
assertThat(owner, is(equalToOwner(persistentOwner))); @Cleanup(phase = TestExecutionPhase.NONE)
} public void beforeUpdatePassword() {}
@Test
@Test @InSequence(30) @InSequence(31)
@UsingDataSet("owners.xml") @RunAsClient
@Cleanup(phase = TestExecutionPhase.NONE) @Header(name = "Authorization", value = BASIC_AUTHORIZATION)
public void beforeUpdatePassword() {} public void testUpdatePassword(
@ArquillianResteasyResource(BASE_PATH + EXISTENT_LOGIN)
@Test @InSequence(31) ResteasyWebTarget webTarget
@RunAsClient ) throws Exception {
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) final OwnerEditionData ownerData = new OwnerEditionData(newPasswordForExistentOwner());
public void testUpdatePassword(
@ArquillianResteasyResource(BASE_PATH) ResteasyWebTarget webTarget final Response response = webTarget.request().put(json(ownerData));
) throws Exception {
final Owner owner = existentOwner(); assertThat(response, hasOkStatus());
owner.changePassword(newPasswordForExistentOwner()); }
final Response response = webTarget.request().put(json(owner)); @Test
@InSequence(32)
assertThat(response, hasOkStatus()); @ShouldMatchDataSet("owners-update-password.xml")
} @CleanupUsingScript({
"cleanup.sql", "cleanup-autoincrement.sql"
@Test @InSequence(32) })
@ShouldMatchDataSet("owners-update-password.xml") public void afterUpdatePassword() {}
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" })
public void afterUpdatePassword() {} @Test
@InSequence(40)
@UsingDataSet("owners.xml")
@Cleanup(phase = TestExecutionPhase.NONE)
@Test @InSequence(40) public void beforeDeleteWithoutPets() {}
@UsingDataSet("owners.xml")
@Cleanup(phase = TestExecutionPhase.NONE) @Test
public void beforeDeleteWithoutPets() {} @InSequence(41)
@RunAsClient
@Test @InSequence(41) @Header(name = "Authorization", value = BASIC_AUTHORIZATION)
@RunAsClient public void testDeleteWithoutPets(
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) @ArquillianResteasyResource(BASE_PATH + OWNER_WITHOUT_PETS_LOGIN)
public void testDeleteWithoutPets( ResteasyWebTarget webTarget
@ArquillianResteasyResource(BASE_PATH + OWNER_WITHOUT_PETS_LOGIN) ResteasyWebTarget webTarget ) throws Exception {
) throws Exception { final Response response = webTarget.request().delete();
final Response response = webTarget.request().delete();
assertThat(response, hasOkStatus());
assertThat(response, hasOkStatus()); }
}
@Test
@Test @InSequence(42) @InSequence(42)
@ShouldMatchDataSet("owners-remove-without-pets.xml") @ShouldMatchDataSet("owners-remove-without-pets.xml")
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" }) @CleanupUsingScript({
public void afterDeleteWithoutPets() {} "cleanup.sql", "cleanup-autoincrement.sql"
})
public void afterDeleteWithoutPets() {}
@Test @InSequence(43) @Test
@UsingDataSet("owners.xml") @InSequence(43)
@Cleanup(phase = TestExecutionPhase.NONE) @UsingDataSet("owners.xml")
public void beforeDeleteWithPets() {} @Cleanup(phase = TestExecutionPhase.NONE)
public void beforeDeleteWithPets() {}
@Test @InSequence(44)
@RunAsClient @Test
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) @InSequence(44)
public void testDeleteWithPets( @RunAsClient
@ArquillianResteasyResource(BASE_PATH + OWNER_WITH_PETS_LOGIN) ResteasyWebTarget webTarget @Header(name = "Authorization", value = BASIC_AUTHORIZATION)
) throws Exception { public void testDeleteWithPets(
final Response response = webTarget.request().delete(); @ArquillianResteasyResource(BASE_PATH + OWNER_WITH_PETS_LOGIN)
ResteasyWebTarget webTarget
assertThat(response, hasOkStatus()); ) throws Exception {
} final Response response = webTarget.request().delete();
@Test @InSequence(45) assertThat(response, hasOkStatus());
@ShouldMatchDataSet("owners-remove-with-pets.xml") }
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" })
public void afterDeleteWithPets() {} @Test
@InSequence(45)
@ShouldMatchDataSet("owners-remove-with-pets.xml")
@CleanupUsingScript({
@Test @InSequence(46) "cleanup.sql", "cleanup-autoincrement.sql"
@UsingDataSet("owners.xml") })
@Cleanup(phase = TestExecutionPhase.NONE) public void afterDeleteWithPets() {}
public void beforeDeleteNoLogin() {}
@Test
@Test @InSequence(47) @InSequence(46)
@RunAsClient @UsingDataSet("owners.xml")
@Header(name = "Authorization", value = BASIC_AUTHORIZATION) @Cleanup(phase = TestExecutionPhase.NONE)
public void testDeleteNoLogin( public void beforeDeleteNoLogin() {}
@ArquillianResteasyResource(BASE_PATH) ResteasyWebTarget webTarget
) throws Exception { @Test
final Response response = webTarget.request().delete(); @InSequence(47)
@RunAsClient
assertThat(response, hasMethodNotAllowedStatus()); @Header(name = "Authorization", value = BASIC_AUTHORIZATION)
} public void testDeleteNoLogin(
@ArquillianResteasyResource(BASE_PATH)
@Test @InSequence(48) ResteasyWebTarget webTarget
@ShouldMatchDataSet("owners.xml") ) throws Exception {
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" }) final Response response = webTarget.request().delete();
public void afterDeleteNoLogin() {}
assertThat(response, hasMethodNotAllowedStatus());
}
private static Response authorizedJsonRequestGet(String uri) {
return ClientBuilder.newClient().target(uri) @Test
.request(MediaType.APPLICATION_JSON_TYPE) @InSequence(48)
.header("Authorization", BASIC_AUTHORIZATION) @ShouldMatchDataSet("owners.xml")
.get(); @CleanupUsingScript({
} "cleanup.sql", "cleanup-autoincrement.sql"
})
public void afterDeleteNoLogin() {}
private static Response authorizedJsonRequestGet(String uri) {
return ClientBuilder.newClient().target(uri)
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", BASIC_AUTHORIZATION)
.get();
}
} }
...@@ -3,17 +3,19 @@ package es.uvigo.esei.xcs.rest; ...@@ -3,17 +3,19 @@ package es.uvigo.esei.xcs.rest;
import static es.uvigo.esei.xcs.domain.entities.IsEqualToOwner.containsOwnersInAnyOrder; import static es.uvigo.esei.xcs.domain.entities.IsEqualToOwner.containsOwnersInAnyOrder;
import static es.uvigo.esei.xcs.domain.entities.IsEqualToOwner.equalToOwner; import static es.uvigo.esei.xcs.domain.entities.IsEqualToOwner.equalToOwner;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.anyLogin; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.anyLogin;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.anyOwner; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.existentLogin;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.existentOwner; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.existentOwner;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerWithFreshPets; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.existentPassword;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerWithPersistentPets; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerLogin;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newOwnerPassword;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.newPasswordForExistentOwner;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.owners; import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.owners;
import static es.uvigo.esei.xcs.http.util.HasHttpStatus.hasCreatedStatus; import static es.uvigo.esei.xcs.http.util.HasHttpStatus.hasCreatedStatus;
import static es.uvigo.esei.xcs.http.util.HasHttpStatus.hasOkStatus; import static es.uvigo.esei.xcs.http.util.HasHttpStatus.hasOkStatus;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
...@@ -38,177 +40,185 @@ import org.junit.runner.RunWith; ...@@ -38,177 +40,185 @@ import org.junit.runner.RunWith;
import es.uvigo.esei.xcs.domain.entities.Owner; import es.uvigo.esei.xcs.domain.entities.Owner;
import es.uvigo.esei.xcs.domain.entities.OwnersDataset; import es.uvigo.esei.xcs.domain.entities.OwnersDataset;
import es.uvigo.esei.xcs.rest.entity.OwnerCreationData;
import es.uvigo.esei.xcs.rest.entity.OwnerEditionData;
import es.uvigo.esei.xcs.service.OwnerService; import es.uvigo.esei.xcs.service.OwnerService;
@RunWith(EasyMockRunner.class) @RunWith(EasyMockRunner.class)
public class OwnerResourceUnitTest extends EasyMockSupport { public class OwnerResourceUnitTest extends EasyMockSupport {
@TestSubject @TestSubject
private OwnerResource resource = new OwnerResource(); private OwnerResource resource = new OwnerResource();
@Mock @Mock
private OwnerService facade; private OwnerService facade;
@Mock @Mock
private UriInfo uriInfo; private UriInfo uriInfo;
@Mock @Mock
private UriBuilder uriBuilder; private UriBuilder uriBuilder;
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
verifyAll(); verifyAll();
} }
@Test @Test
public void testGet() { public void testGet() {
final Owner owner = OwnersDataset.anyOwner(); final Owner owner = OwnersDataset.anyOwner();
expect(facade.get(owner.getLogin())) expect(facade.get(owner.getLogin()))
.andReturn(owner); .andReturn(owner);
replayAll(); replayAll();
final Response response = resource.get(owner.getLogin()); final Response response = resource.get(owner.getLogin());
assertThat(response, hasOkStatus()); assertThat(response, hasOkStatus());
assertThat(response.getEntity(), is(instanceOf(Owner.class))); assertThat(response.getEntity(), is(instanceOf(Owner.class)));
assertThat((Owner) response.getEntity(), is(equalToOwner(owner))); assertThat((Owner) response.getEntity(), is(equalToOwner(owner)));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testGetNull() { public void testGetNull() {
replayAll(); replayAll();
resource.get(null); resource.get(null);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testGetMissing() { public void testGetMissing() {
final String login = anyLogin(); final String login = anyLogin();
expect(facade.get(login)) expect(facade.get(login))
.andReturn(null); .andReturn(null);
replayAll(); replayAll();
resource.get(login); resource.get(login);
} }
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testList() { public void testList() {
final Owner[] owners = owners(); final Owner[] owners = owners();
expect(facade.list()) expect(facade.list())
.andReturn(asList(owners)); .andReturn(asList(owners));
replayAll(); replayAll();
final Response response = resource.list(); final Response response = resource.list();
assertThat(response, hasOkStatus()); assertThat(response, hasOkStatus());
assertThat(response.getEntity(), is(instanceOf(List.class))); assertThat(response.getEntity(), is(instanceOf(List.class)));
assertThat((List<Owner>) response.getEntity(), containsOwnersInAnyOrder(owners)); assertThat((List<Owner>) response.getEntity(), containsOwnersInAnyOrder(owners));
} }
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testListEmpty() { public void testListEmpty() {
expect(facade.list()) expect(facade.list())
.andReturn(emptyList()); .andReturn(emptyList());
replayAll(); replayAll();
final Response response = resource.list(); final Response response = resource.list();
assertThat(response, hasOkStatus()); assertThat(response, hasOkStatus());
assertThat(response.getEntity(), is(instanceOf(List.class))); assertThat(response.getEntity(), is(instanceOf(List.class)));
assertThat((List<Owner>) response.getEntity(), is(empty())); assertThat((List<Owner>) response.getEntity(), is(empty()));
} }
@Test @Test
public void testCreate() throws Exception { public void testCreate() throws Exception {
final Owner newOwner = newOwnerWithFreshPets(); final OwnerCreationData newOwner = new OwnerCreationData(newOwnerLogin(), newOwnerPassword());
final Owner createdOwner = newOwnerWithPersistentPets(); final Owner createdOwner = OwnersDataset.newOwnerWithoutPets();
final URI mockUri = new URI("http://host/api/owner/" + newOwner.getLogin()); final URI mockUri = new URI("http://host/api/owner/" + newOwner.getLogin());
expect(facade.create(newOwner)) expect(facade.create(anyObject(Owner.class)))
.andReturn(createdOwner); .andReturn(createdOwner);
expect(uriInfo.getAbsolutePathBuilder()) expect(uriInfo.getAbsolutePathBuilder())
.andReturn(uriBuilder); .andReturn(uriBuilder);
expect(uriBuilder.path(newOwner.getLogin())) expect(uriBuilder.path(newOwner.getLogin()))
.andReturn(uriBuilder); .andReturn(uriBuilder);
expect(uriBuilder.build()) expect(uriBuilder.build())
.andReturn(mockUri); .andReturn(mockUri);
replayAll(); replayAll();
final Response response = resource.create(newOwner); final Response response = resource.create(newOwner);
assertThat(response, hasCreatedStatus()); assertThat(response, hasCreatedStatus());
assertThat(response.getHeaderString("Location"), is(equalTo(mockUri.toString()))); assertThat(response.getHeaderString("Location"), is(equalTo(mockUri.toString())));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testCreateNull() { public void testCreateNull() {
replayAll(); replayAll();
resource.create(null); resource.create(null);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testCreateExistentOwner() { public void testCreateExistentOwner() {
final Owner existentOwner = existentOwner(); final OwnerCreationData existentOwner = new OwnerCreationData(existentLogin(), existentPassword());
expect(facade.create(existentOwner)) expect(facade.create(anyObject(Owner.class)))
.andThrow(new EntityExistsException()); .andThrow(new EntityExistsException());
replayAll(); replayAll();
resource.create(existentOwner); resource.create(existentOwner);
} }
@Test @Test
public void testUpdate() { public void testUpdate() {
final Owner owner = anyOwner(); final Owner owner = existentOwner();
final Owner ownerWithChangedPassword = existentOwner();
facade.update(owner); ownerWithChangedPassword.changePassword(newPasswordForExistentOwner());
expectLastCall().andReturn(owner); final OwnerEditionData ownerData = new OwnerEditionData(newPasswordForExistentOwner());
replayAll(); expect(facade.get(owner.getLogin()))
.andReturn(owner);
final Response response = resource.update(owner);
expect(facade.update(anyObject(Owner.class)))
assertThat(response, hasOkStatus()); .andReturn(owner);
}
replayAll();
@Test(expected = IllegalArgumentException.class)
public void testUpdateNull() { final Response response = resource.update(owner.getLogin(), ownerData);
replayAll();
assertThat(response, hasOkStatus());
resource.update(null); }
}
@Test(expected = IllegalArgumentException.class)
@Test public void testUpdateNull() {
public void testDelete() { replayAll();
final String login = anyLogin();
resource.update(null, null);
facade.remove(login); }
replayAll(); @Test
public void testDelete() {
final Response response = resource.delete(login); final String login = anyLogin();
assertThat(response, hasOkStatus()); facade.remove(login);
}
replayAll();
@Test(expected = IllegalArgumentException.class)
public void testDeleteNull() { final Response response = resource.delete(login);
replayAll();
assertThat(response, hasOkStatus());
resource.delete(null); }
}
@Test(expected = IllegalArgumentException.class)
public void testDeleteNull() {
replayAll();
resource.delete(null);
}
} }
package es.uvigo.esei.xcs.service;
import java.security.Principal;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import es.uvigo.esei.xcs.domain.entities.User;
@Stateless
@RolesAllowed({"OWNER", "ADMIN"})
public class UserService {
@PersistenceContext
private EntityManager em;
@Inject
private Principal principal;
/**
* Returns the current user entity.
*
* @return the entity with the information of the current user.
*/
public User getCurrentUser() {
return this.em.find(User.class, this.principal.getName());
}
}
...@@ -63,8 +63,8 @@ public class PetServiceIntegrationTest { ...@@ -63,8 +63,8 @@ public class PetServiceIntegrationTest {
.addPackage(Pet.class.getPackage()) .addPackage(Pet.class.getPackage())
.addAsResource("test-persistence.xml", "META-INF/persistence.xml") .addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource("jboss-web.xml") .addAsWebInfResource("jboss-web.xml")
.addAsResource("arquillian.extension.persistence.properties") .addAsResource("arquillian.extension.persistence.properties")
.addAsResource("arquillian.extension.persistence.dbunit.properties") .addAsResource("arquillian.extension.persistence.dbunit.properties")
.addAsWebInfResource("beans.xml", "beans.xml"); .addAsWebInfResource("beans.xml", "beans.xml");
} }
......
...@@ -9,7 +9,9 @@ import org.junit.runners.Suite.SuiteClasses; ...@@ -9,7 +9,9 @@ import org.junit.runners.Suite.SuiteClasses;
OwnerServiceIntegrationTest.class, OwnerServiceIntegrationTest.class,
OwnerServiceIllegalAccessIntegrationTest.class, OwnerServiceIllegalAccessIntegrationTest.class,
PetServiceIntegrationTest.class, PetServiceIntegrationTest.class,
PetServiceIllegalAccessIntegrationTest.class PetServiceIllegalAccessIntegrationTest.class,
UserServiceIntegrationTest.class,
UserServiceIllegalAccessIntegrationTest.class
}) })
public class ServiceIntegrationTestSuite { public class ServiceIntegrationTestSuite {
} }
package es.uvigo.esei.xcs.service;
import static es.uvigo.esei.xcs.domain.entities.IsEqualToUser.equalToUser;
import static es.uvigo.esei.xcs.domain.entities.OwnersDataset.existentOwner;
import static es.uvigo.esei.xcs.domain.entities.UsersDataset.existentAdmin;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import javax.ejb.EJB;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.persistence.CleanupUsingScript;
import org.jboss.arquillian.persistence.ShouldMatchDataSet;
import org.jboss.arquillian.persistence.UsingDataSet;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import es.uvigo.esei.xcs.domain.entities.Owner;
import es.uvigo.esei.xcs.domain.entities.OwnersDataset;
import es.uvigo.esei.xcs.domain.entities.Pet;
import es.uvigo.esei.xcs.domain.entities.User;
import es.uvigo.esei.xcs.domain.entities.UsersDataset;
import es.uvigo.esei.xcs.service.util.security.RoleCaller;
import es.uvigo.esei.xcs.service.util.security.TestPrincipal;
@RunWith(Arquillian.class)
@UsingDataSet("owners.xml")
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" })
public class UserServiceIllegalAccessIntegrationTest {
@Inject
private UserService facade;
@EJB(beanName = "owner-caller")
private RoleCaller asOwner;
@EJB(beanName = "admin-caller")
private RoleCaller asAdmin;
@Inject
private TestPrincipal principal;
@Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(UserService.class)
.addPackage(RoleCaller.class.getPackage())
.addPackage(Pet.class.getPackage())
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource("jboss-web.xml")
.addAsResource("arquillian.extension.persistence.properties")
.addAsResource("arquillian.extension.persistence.dbunit.properties")
.addAsWebInfResource("beans.xml", "beans.xml");
}
@Test
@ShouldMatchDataSet("owners.xml")
public void testGetOwnerCredentials() {
final Owner existentOwner = existentOwner();
principal.setName(existentOwner.getLogin());
final User actualUser = asOwner.call(() -> facade.getCurrentUser());
assertThat(actualUser, is(equalToUser(existentOwner)));
}
@Test
@ShouldMatchDataSet("owners.xml")
public void testGetAdminCredentials() {
final User existentAdmin = existentAdmin();
principal.setName(existentAdmin.getLogin());
final User actualUser = asAdmin.call(() -> facade.getCurrentUser());
assertThat(actualUser, is(equalToUser(existentAdmin)));
}
}
package es.uvigo.esei.xcs.service;
import javax.ejb.EJBAccessException;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.persistence.CleanupUsingScript;
import org.jboss.arquillian.persistence.ShouldMatchDataSet;
import org.jboss.arquillian.persistence.UsingDataSet;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import es.uvigo.esei.xcs.domain.entities.Pet;
import es.uvigo.esei.xcs.service.util.security.RoleCaller;
@RunWith(Arquillian.class)
@UsingDataSet("owners.xml")
@CleanupUsingScript({ "cleanup.sql", "cleanup-autoincrement.sql" })
public class UserServiceIntegrationTest {
@Inject
private UserService facade;
@Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(UserService.class)
.addPackage(RoleCaller.class.getPackage())
.addPackage(Pet.class.getPackage())
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource("jboss-web.xml")
.addAsResource("arquillian.extension.persistence.properties")
.addAsResource("arquillian.extension.persistence.dbunit.properties")
.addAsWebInfResource("beans.xml", "beans.xml");
}
@Test(expected = EJBAccessException.class)
@ShouldMatchDataSet("owners.xml")
public void testGetCredentialsNoUser() {
facade.getCurrentUser();
}
}
package es.uvigo.esei.xcs.domain.entities;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
public class IsEqualToUser extends IsEqualToEntity<User> {
public IsEqualToUser(User user) {
super(user);
}
@Override
protected boolean matchesSafely(User actual) {
this.clearDescribeTo();
if (actual == null) {
this.addTemplatedDescription("actual", expected.toString());
return false;
} else {
return checkAttribute("login", User::getLogin, actual)
&& checkAttribute("role", User::getRole, actual);
}
}
@Factory
public static IsEqualToUser equalToUser(User user) {
return new IsEqualToUser(user);
}
@Factory
public static Matcher<Iterable<? extends User>> containsUsersInAnyOrder(User ... users) {
return containsEntityInAnyOrder(IsEqualToUser::equalToUser, users);
}
@Factory
public static Matcher<Iterable<? extends User>> containsUsersInAnyOrder(Iterable<User> users) {
return containsEntityInAnyOrder(IsEqualToUser::equalToUser, users);
}
}
...@@ -34,9 +34,9 @@ public class OwnersDataset { ...@@ -34,9 +34,9 @@ public class OwnersDataset {
public static Owner[] owners() { public static Owner[] owners() {
return new Owner[] { return new Owner[] {
new Owner(EXISTENT_LOGIN, "pepepass", new Owner(EXISTENT_LOGIN, EXISTENT_LOGIN + "pass",
new Pet(1, "Pepecat", AnimalType.CAT, new Date(946684861000L))), new Pet(1, "Pepecat", AnimalType.CAT, new Date(946684861000L))),
new Owner(OWNER_WITH_PETS_LOGIN, "juanpass", new Owner(OWNER_WITH_PETS_LOGIN, OWNER_WITH_PETS_LOGIN + "pass",
new Pet(2, "Max", AnimalType.CAT, new Date(946684861000L)), new Pet(2, "Max", AnimalType.CAT, new Date(946684861000L)),
new Pet(3, "Juandog", AnimalType.DOG, new Date(946684861000L)) new Pet(3, "Juandog", AnimalType.DOG, new Date(946684861000L))
), ),
...@@ -45,7 +45,7 @@ public class OwnersDataset { ...@@ -45,7 +45,7 @@ public class OwnersDataset {
new Pet(5, "Max", AnimalType.DOG, new Date(946684861000L)), new Pet(5, "Max", AnimalType.DOG, new Date(946684861000L)),
new Pet(6, "Anabird", AnimalType.BIRD, new Date(946684861000L)) new Pet(6, "Anabird", AnimalType.BIRD, new Date(946684861000L))
), ),
new Owner(OWNER_WITHOUT_PETS_LOGIN, "lorenapass") new Owner(OWNER_WITHOUT_PETS_LOGIN, OWNER_WITHOUT_PETS_LOGIN + "pass")
}; };
} }
...@@ -117,6 +117,22 @@ public class OwnersDataset { ...@@ -117,6 +117,22 @@ public class OwnersDataset {
return new Owner(newOwnerLogin(), newOwnerPassword()); return new Owner(newOwnerLogin(), newOwnerPassword());
} }
public static Owner newOwnerWithFreshPets() {
return new Owner(newOwnerLogin(), newOwnerPassword(),
new Pet("Jacintocat", AnimalType.CAT, new Date(946684861000L)),
new Pet("Jacintodo", AnimalType.DOG, new Date(946684861000L)),
new Pet("Jacintobird", AnimalType.BIRD, new Date(946684861000L))
);
}
public static Owner newOwnerWithPersistentPets() {
return new Owner(newOwnerLogin(), newOwnerPassword(),
new Pet(7, "Jacintocat", AnimalType.CAT, new Date(946684861000L)),
new Pet(8, "Jacintodo", AnimalType.DOG, new Date(946684861000L)),
new Pet(9, "Jacintobird", AnimalType.BIRD, new Date(946684861000L))
);
}
public static String newOwnerLogin() { public static String newOwnerLogin() {
return "jacinto"; return "jacinto";
} }
...@@ -125,22 +141,6 @@ public class OwnersDataset { ...@@ -125,22 +141,6 @@ public class OwnersDataset {
return "jacintopass"; return "jacintopass";
} }
public static Owner newOwnerWithFreshPets() {
return new Owner(newOwnerLogin(), newOwnerPassword(),
new Pet("Jacintocat", AnimalType.CAT, new Date(946684861000L)),
new Pet("Jacintodo", AnimalType.DOG, new Date(946684861000L)),
new Pet("Jacintobird", AnimalType.BIRD, new Date(946684861000L))
);
}
public static Owner newOwnerWithPersistentPets() {
return new Owner(newOwnerLogin(), newOwnerPassword(),
new Pet(7, "Jacintocat", AnimalType.CAT, new Date(946684861000L)),
new Pet(8, "Jacintodo", AnimalType.DOG, new Date(946684861000L)),
new Pet(9, "Jacintobird", AnimalType.BIRD, new Date(946684861000L))
);
}
public static String anyLogin() { public static String anyLogin() {
return existentLogin(); return existentLogin();
} }
...@@ -148,6 +148,10 @@ public class OwnersDataset { ...@@ -148,6 +148,10 @@ public class OwnersDataset {
public static String existentLogin() { public static String existentLogin() {
return EXISTENT_LOGIN; return EXISTENT_LOGIN;
} }
public static String existentPassword() {
return EXISTENT_LOGIN + "pass";
}
public static String nonExistentLogin() { public static String nonExistentLogin() {
return NON_EXISTENT_LOGIN; return NON_EXISTENT_LOGIN;
...@@ -156,6 +160,10 @@ public class OwnersDataset { ...@@ -156,6 +160,10 @@ public class OwnersDataset {
public static Owner anyOwner() { public static Owner anyOwner() {
return ownerWithLogin(anyLogin()); return ownerWithLogin(anyLogin());
} }
public static String anyOwnerPassword() {
return anyOwner().getLogin() + "pass";
}
public static Owner existentOwner() { public static Owner existentOwner() {
return ownerWithLogin(existentLogin()); return ownerWithLogin(existentLogin());
......
package es.uvigo.esei.xcs.domain.entities;
public class UsersDataset {
public static final String EXISTENT_LOGIN = "jose";
public static User[] users() {
final Owner[] owners = OwnersDataset.owners();
final User[] users = new User[owners.length + 1];
users[0] = new Administrator(EXISTENT_LOGIN, EXISTENT_LOGIN + "pass");
System.arraycopy(owners, 0, users, 1, owners.length);
return users;
}
public static User existentAdmin() {
return users()[0];
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment