Search in sources :

Example 1 with EntityExistsException

use of ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException in project irida by phac-nml.

the class UsersController method handleCreateUpdateException.

/**
 * Handle exceptions for the create and update pages
 *
 * @param ex
 *            an exception to handle
 * @param locale
 *            The locale to work with
 *
 * @return A Map<String,String> of errors to render
 */
private Map<String, String> handleCreateUpdateException(Exception ex, Locale locale) {
    Map<String, String> errors = new HashMap<>();
    if (ex instanceof ConstraintViolationException) {
        ConstraintViolationException cvx = (ConstraintViolationException) ex;
        logger.debug("User provided data threw ConstrainViolation");
        Set<ConstraintViolation<?>> constraintViolations = cvx.getConstraintViolations();
        for (ConstraintViolation<?> violation : constraintViolations) {
            logger.debug(violation.getMessage());
            String errorKey = violation.getPropertyPath().toString();
            errors.put(errorKey, violation.getMessage());
        }
    } else if (ex instanceof DataIntegrityViolationException) {
        DataIntegrityViolationException divx = (DataIntegrityViolationException) ex;
        logger.debug(divx.getMessage());
        if (divx.getMessage().contains(User.USER_EMAIL_CONSTRAINT_NAME)) {
            errors.put("email", messageSource.getMessage("user.edit.emailConflict", null, locale));
        }
    } else if (ex instanceof EntityExistsException) {
        EntityExistsException eex = (EntityExistsException) ex;
        errors.put(eex.getFieldName(), eex.getMessage());
    } else if (ex instanceof PasswordReusedException) {
        errors.put("password", messageSource.getMessage("user.edit.passwordReused", null, locale));
    }
    return errors;
}
Also used : HashMap(java.util.HashMap) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) PasswordReusedException(ca.corefacility.bioinformatics.irida.exceptions.PasswordReusedException) EntityExistsException(ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 2 with EntityExistsException

use of ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException in project irida by phac-nml.

the class UsersController method submitCreateUser.

/**
 * Create a new user object
 *
 * @param user
 *            User to create as a motel attribute
 * @param systemRole
 *            The system role to give to the user
 * @param confirmPassword
 *            Password confirmation
 * @param requireActivation
 *            Checkbox whether the user account needs to be activated
 * @param model
 *            Model for the view
 * @param principal
 *            The user creating the object
 *
 * @return A redirect to the user details view
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')")
public String submitCreateUser(@ModelAttribute User user, @RequestParam String systemRole, @RequestParam String confirmPassword, @RequestParam(required = false) String requireActivation, Model model, Principal principal) {
    Map<String, String> errors = new HashMap<>();
    String returnView = null;
    Locale locale = LocaleContextHolder.getLocale();
    User creator = userService.getUserByUsername(principal.getName());
    // check if we need to generate a password
    boolean generateActivation = !Strings.isNullOrEmpty(requireActivation);
    if (generateActivation) {
        user.setPassword(generatePassword());
        confirmPassword = user.getPassword();
        user.setCredentialsNonExpired(false);
    }
    // check validity of password
    if (!user.getPassword().equals(confirmPassword)) {
        errors.put("password", messageSource.getMessage("user.edit.password.match", null, locale));
    }
    // Check if there are any errors for the user creation
    if (errors.isEmpty()) {
        if (isAdmin(principal)) {
            user.setSystemRole(Role.valueOf(systemRole));
        } else {
            user.setSystemRole(Role.ROLE_USER);
        }
        try {
            user = userService.create(user);
            Long userId = user.getId();
            returnView = "redirect:/users/" + userId;
            // if the password isn't set, we'll generate a password reset
            PasswordReset passwordReset = null;
            if (generateActivation) {
                passwordReset = passwordResetService.create(new PasswordReset(user));
                logger.trace("Created password reset for activation");
            }
            emailController.sendWelcomeEmail(user, creator, passwordReset);
        } catch (ConstraintViolationException | DataIntegrityViolationException | EntityExistsException ex) {
            errors = handleCreateUpdateException(ex, locale);
        } catch (final MailSendException e) {
            logger.error("Failed to send user activation e-mail.", e);
            model.addAttribute("mailFailure", true);
        }
    }
    if (!errors.isEmpty()) {
        model.addAttribute("errors", errors);
        model.addAttribute("given_username", user.getUsername());
        model.addAttribute("given_firstName", user.getFirstName());
        model.addAttribute("given_lastName", user.getLastName());
        model.addAttribute("given_email", user.getEmail());
        model.addAttribute("given_phoneNumber", user.getPhoneNumber());
        model.addAttribute("given_requireActivation", generateActivation);
        returnView = createUserPage(model);
    }
    return returnView;
}
Also used : Locale(java.util.Locale) DTUser(ca.corefacility.bioinformatics.irida.ria.web.models.datatables.DTUser) User(ca.corefacility.bioinformatics.irida.model.user.User) MailSendException(org.springframework.mail.MailSendException) HashMap(java.util.HashMap) EntityExistsException(ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) PasswordReset(ca.corefacility.bioinformatics.irida.model.user.PasswordReset) ConstraintViolationException(javax.validation.ConstraintViolationException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with EntityExistsException

use of ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException in project irida by phac-nml.

the class ControllerExceptionHandlerTest method testHandleExistsException.

@Test
public void testHandleExistsException() {
    ResponseEntity<ErrorResponse> response = controller.handleExistsException(new EntityExistsException("exists"));
    assertEquals(HttpStatus.CONFLICT, response.getStatusCode());
}
Also used : EntityExistsException(ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException) ErrorResponse(ca.corefacility.bioinformatics.irida.web.controller.api.exception.ErrorResponse) Test(org.junit.Test)

Example 4 with EntityExistsException

use of ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException in project irida by phac-nml.

the class RESTProjectSamplesControllerTest method testAlreadyCopiedSampleToProject.

@Test(expected = EntityExistsException.class)
public void testAlreadyCopiedSampleToProject() {
    final Project p = TestDataFactory.constructProject();
    final Sample s = TestDataFactory.constructSample();
    when(projectService.read(p.getId())).thenReturn(p);
    when(sampleService.read(s.getId())).thenReturn(s);
    when(projectService.addSampleToProject(p, s, false)).thenThrow(new EntityExistsException("sample already exists!"));
    controller.copySampleToProject(p.getId(), Lists.newArrayList(s.getId()), new MockHttpServletResponse());
}
Also used : Project(ca.corefacility.bioinformatics.irida.model.project.Project) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) EntityExistsException(ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 5 with EntityExistsException

use of ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException in project irida by phac-nml.

the class AnnouncementServiceImplIT method testUserMarkAnnouncementAsReadSuccess.

@Test
@WithMockUser(username = "user3", roles = "USER")
public void testUserMarkAnnouncementAsReadSuccess() {
    final Announcement a = announcementService.read(2L);
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    final User user = userService.getUserByUsername(auth.getName());
    try {
        announcementService.markAnnouncementAsReadByUser(a, user);
    } catch (AccessDeniedException e) {
        fail("User should be able able to mark announcement as read.");
    } catch (EntityExistsException e) {
        fail("Failed for unknown reason, stack trace follows:");
        e.printStackTrace();
    }
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) WithMockUser(org.springframework.security.test.context.support.WithMockUser) User(ca.corefacility.bioinformatics.irida.model.user.User) Announcement(ca.corefacility.bioinformatics.irida.model.announcements.Announcement) Authentication(org.springframework.security.core.Authentication) EntityExistsException(ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException) WithMockUser(org.springframework.security.test.context.support.WithMockUser) Test(org.junit.Test)

Aggregations

EntityExistsException (ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException)12 Test (org.junit.Test)6 Project (ca.corefacility.bioinformatics.irida.model.project.Project)4 Sample (ca.corefacility.bioinformatics.irida.model.sample.Sample)4 ConstraintViolationException (javax.validation.ConstraintViolationException)4 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)4 ConstraintViolation (javax.validation.ConstraintViolation)3 ProjectSampleJoin (ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin)2 User (ca.corefacility.bioinformatics.irida.model.user.User)2 HashMap (java.util.HashMap)2 AccessDeniedException (org.springframework.security.access.AccessDeniedException)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 WithMockUser (org.springframework.security.test.context.support.WithMockUser)2 LaunchesProjectEvent (ca.corefacility.bioinformatics.irida.events.annotations.LaunchesProjectEvent)1 PasswordReusedException (ca.corefacility.bioinformatics.irida.exceptions.PasswordReusedException)1 Announcement (ca.corefacility.bioinformatics.irida.model.announcements.Announcement)1 ProjectEvent (ca.corefacility.bioinformatics.irida.model.event.ProjectEvent)1 SampleAddedProjectEvent (ca.corefacility.bioinformatics.irida.model.event.SampleAddedProjectEvent)1 UserRemovedProjectEvent (ca.corefacility.bioinformatics.irida.model.event.UserRemovedProjectEvent)1 UserRoleSetProjectEvent (ca.corefacility.bioinformatics.irida.model.event.UserRoleSetProjectEvent)1