Commit 34814653 authored by Maxym Borodenko's avatar Maxym Borodenko Committed by Matija Obreza

Upgrade hibernate-validator dependency

- added tests
- extended ApiExceptionHandler
parent 601a2a36
......@@ -80,7 +80,7 @@
<querydsl.version>4.1.4</querydsl.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<hibernate.validator.version>4.3.2.Final</hibernate.validator.version>
<hibernate.validator.version>5.2.5.Final</hibernate.validator.version>
<hsqldb.version>2.3.6</hsqldb.version>
<ehcache.version>2.7.4</ehcache.version>
......@@ -619,6 +619,16 @@
<artifactId>jna</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
......
......@@ -16,6 +16,7 @@
package org.genesys.catalog.model.dataset;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
import java.util.Set;
......@@ -71,6 +72,7 @@ public class Dataset extends UuidModel implements Publishable, SelfCleaning, Pub
@ManyToOne(cascade = {}, optional = false)
@JoinColumn(name = "partnerId", updatable = false)
@JsonView({ JsonViews.Public.class })
@NotNull
private Partner owner;
/** The accession identifiers. */
......
......@@ -18,12 +18,15 @@ package org.genesys2.server.api;
import java.io.EOFException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.filerepository.FileRepositoryException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.genesys2.server.exception.InvalidApiUsageException;
import org.genesys2.server.exception.NotFoundElement;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.ConcurrencyFailureException;
......@@ -110,6 +113,31 @@ public class ApiExceptionHandler {
return new ApiError<>(e);
}
/**
* Handle javax validation error.
*
* @param e the e
* @param request the request
* @return the api error
*/
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public ApiError<Exception> handleValidationError(final ConstraintViolationException e, final HttpServletRequest request) {
final StringBuilder message = new StringBuilder("Validation failed: ");
if (e.getConstraintViolations() != null) {
for (ConstraintViolation cv : e.getConstraintViolations()) {
final PathImpl path = (PathImpl) cv.getPropertyPath();
message.append(path.getLeafNode().getName());
message.append(" -> ");
message.append(cv.getMessage());
message.append("; ");
}
}
LOG.warn("{} for {} {}", message.toString(), request.getMethod(), request.getRequestURL(), e);
return new ApiError<>(new Exception(message.toString(), e));
}
/**
* Handle converter error.
*
......
......@@ -61,6 +61,8 @@ import org.springframework.security.test.context.support.WithMockUser;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import javax.validation.ConstraintViolationException;
@WithMockUser(username = "admin", password = "admin", roles = "ADMINISTRATOR")
public class DatasetServiceTest extends AbstractDatasetServiceTest {
......@@ -73,6 +75,16 @@ public class DatasetServiceTest extends AbstractDatasetServiceTest {
assertThat(input.getVersions().getCurrentVersion(), is(input));
}
/**
* Testing javax validation.
* Fail to create dataset when owner = null
*/
@Test(expected = ConstraintViolationException.class)
public void testCreateDatasetWithFailedValidation() {
// Try to create dataset without owner. Should be an error
buildAndSaveDataset(DATASET_TITLE_1, DATASET_DESCRIPTION_1, null, PublishState.DRAFT);
}
@Test
public void testCreateDatasetSelfCleaning() {
Dataset input = buildAndSaveDataset(DATASET_TITLE_1 + " ", " " + DATASET_DESCRIPTION_1, partner, PublishState.DRAFT);
......
......@@ -26,6 +26,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import javax.validation.ConstraintViolationException;
public class SubsetServiceTest extends CatalogServiceTest {
@Autowired
......@@ -94,6 +96,19 @@ public class SubsetServiceTest extends CatalogServiceTest {
assertThat(result.getEmail(), equalTo(newEmail));
}
/**
* Testing javax validation.
* Fail to update subset when title = null
*/
@Test(expected = ConstraintViolationException.class)
public void testUpdateSubsetWithFailedValidation() {
assertThat(subset.getTitle(), notNullValue());
subset.setTitle(null);
// title cannot be null
subsetService.update(subset);
}
@Test
public void testLoadMoreAccessions() {
final Accession accession1 = upsertAccession("instCode1", "acceNumb1", "genus1");
......@@ -196,7 +211,7 @@ public class SubsetServiceTest extends CatalogServiceTest {
assertThat(result.getSubset().getUuid(), is(SUBSET_UUID));
}
private SubsetCreator buildSubsetCreator(UUID uuid) {
private SubsetCreator buildSubsetCreator(final UUID uuid) {
SubsetCreator subsetCreator = new SubsetCreator();
subsetCreator.setFullName(SUBSET_CREATOR_FULL_NAME);
subsetCreator.setEmail(SUBSET_CREATOR_EMAIL);
......@@ -205,7 +220,7 @@ public class SubsetServiceTest extends CatalogServiceTest {
return subsetCreator;
}
private Subset createSubset(UUID uuid) {
private Subset createSubset(final UUID uuid) {
subset = new Subset();
subset.setTitle("Subset");
subset.setWiewsCode("0000");
......
......@@ -210,6 +210,32 @@ public class DatasetControllerTest extends AbstractApiTest {
/*@formatter:on*/
}
/**
* Testing javax validation.
* Fail to create dataset when owner = null
*/
@Test
@WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR")
public void failToCreateDataset() throws Exception {
final Dataset dataset = setUpDataset(PublishState.DRAFT);
dataset.setOwner(null);
final String s = verboseMapper.writeValueAsString(dataset);
/*@formatter:off*/
mockMvc
.perform(RestDocumentationRequestBuilders.post(DatasetController.CONTROLLER_URL + "/create")
.content(s)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$.error", not(nullValue())));
/*@formatter:on*/
}
@Test
@WithMockUser(username = "user", password = "user", roles = "ADMINISTRATOR")
public void createDataset() throws Exception {
......
......@@ -152,17 +152,41 @@ public class SubsetRestControllerTest extends AbstractApiTest {
final String s = verboseMapper.writeValueAsString(setUpSubset());
/*@formatter:off*/
mockMvc.perform(post(SubsetController.API_BASE + "/create")
.contentType(MediaType.APPLICATION_JSON)
.content(s))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$.title", is(TITLE)))
.andExpect(jsonPath("$.description", is(DESCRIPTION)))
.andExpect(jsonPath("$.publisher", is(PUBLISHER)))
.andExpect(jsonPath("$.dateCreated", is(DATE_CREATED)));
mockMvc
.perform(post(SubsetController.API_BASE + "/create")
.contentType(MediaType.APPLICATION_JSON)
.content(s))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$.title", is(TITLE)))
.andExpect(jsonPath("$.description", is(DESCRIPTION)))
.andExpect(jsonPath("$.publisher", is(PUBLISHER)))
.andExpect(jsonPath("$.dateCreated", is(DATE_CREATED)));
/*@formatter:on*/
}
/**
* Testing javax validation.
* Fail to update subset when title = null
*/
@Test
public void failToCreateSubsetTest() throws Exception {
final Subset subset = setUpSubset();
subset.setTitle(null);
final String s = verboseMapper.writeValueAsString(subset);
/*@formatter:off*/
mockMvc
.perform(post(SubsetController.API_BASE + "/create")
.contentType(MediaType.APPLICATION_JSON)
.content(s))
// .andDo(MockMvcResultHandlers.print())
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", not(nullValue())))
.andExpect(jsonPath("$.error", not(nullValue())));
/*@formatter:on*/
}
......
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