Example usage for org.springframework.dao DuplicateKeyException getMessage

List of usage examples for org.springframework.dao DuplicateKeyException getMessage

Introduction

In this page you can find the example usage for org.springframework.dao DuplicateKeyException getMessage.

Prototype

@Override
@Nullable
public String getMessage() 

Source Link

Document

Return the detail message, including the message from the nested exception if there is one.

Usage

From source file:edu.pitt.dbmi.ccd.anno.error.ErrorHandler.java

@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(HttpStatus.CONFLICT)//w ww  . j  a  v  a 2s.c  om
@ResponseBody
public ErrorMessage handleDuplicateKeyException(DuplicateKeyException ex, HttpServletRequest req) {
    LOGGER.info(ex.getMessage());
    return new ErrorMessage(HttpStatus.CONFLICT, ex.getMessage(), req);
}

From source file:be.bittich.quote.controller.impl.DefaultExceptionHandler.java

@RequestMapping(produces = APPLICATION_JSON)
@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(value = HttpStatus.CONFLICT)
public @ResponseBody Map<String, Object> handleDuplicateKeyException(DuplicateKeyException ex)
        throws IOException {
    Map<String, Object> map = newHashMap();
    map.put("error", "Duplicate Key Exception");
    map.put("cause", ex.getLocalizedMessage());
    map.put("supported", ex.getMessage());
    return map;/*from  w w  w .  j  a  v a  2s . c o  m*/
}

From source file:com.epam.ta.reportportal.core.user.impl.CreateUserHandler.java

@Override
public CreateUserRS createUserByAdmin(CreateUserRQFull request, String userName, String basicUrl) {
    String newUsername = EntityUtils.normalizeUsername(request.getLogin());

    expect(userRepository.exists(newUsername), equalTo(false)).verify(USER_ALREADY_EXISTS,
            formattedSupplier("login='{}'", newUsername));

    expect(newUsername, Predicates.SPECIAL_CHARS_ONLY.negate()).verify(ErrorType.INCORRECT_REQUEST,
            formattedSupplier("Username '{}' consists only of special characters", newUsername));

    String projectName = EntityUtils.normalizeProjectName(request.getDefaultProject());
    Project defaultProject = projectRepository.findOne(projectName);
    expect(defaultProject, notNull()).verify(PROJECT_NOT_FOUND, projectName);

    String email = EntityUtils.normalizeEmail(request.getEmail());
    expect(UserUtils.isEmailValid(email), equalTo(true)).verify(BAD_REQUEST_ERROR, email);

    CreateUserRQConfirm req = new CreateUserRQConfirm();
    req.setDefaultProject(projectName);/*  w w  w .j av  a2  s  .c om*/
    req.setEmail(email);
    req.setFullName(request.getFullName());
    req.setLogin(request.getLogin());
    req.setPassword(request.getPassword());

    final Optional<UserRole> userRole = UserRole.findByName(request.getAccountRole());
    expect(userRole.isPresent(), equalTo(true)).verify(BAD_REQUEST_ERROR,
            "Incorrect specified Account Role parameter.");
    User user = userBuilder.get().addCreateUserRQ(req).addUserRole(userRole.get()).build();
    Optional<ProjectRole> projectRole = forName(request.getProjectRole());
    expect(projectRole, Preconditions.IS_PRESENT).verify(ROLE_NOT_FOUND, request.getProjectRole());

    Map<String, UserConfig> projectUsers = defaultProject.getUsers();
    projectUsers.put(user.getId(),
            UserConfig.newOne().withProjectRole(projectRole.get()).withProposedRole(projectRole.get()));
    defaultProject.setUsers(projectUsers);

    CreateUserRS response = new CreateUserRS();

    try {
        userRepository.save(user);
        projectRepository.addUsers(projectName, projectUsers);

        /*
         * Generate personal project for the user
         */
        Project personalProject = PersonalProjectUtils.generatePersonalProject(user);
        if (!defaultProject.getId().equals(personalProject.getId())) {
            projectRepository.save(personalProject);
        }

        safe(() -> emailServiceFactory.getDefaultEmailService(true).sendConfirmationEmail(request, basicUrl),
                e -> response.setWarning(e.getMessage()));
    } catch (DuplicateKeyException e) {
        fail().withError(USER_ALREADY_EXISTS, formattedSupplier("email='{}'", request.getEmail()));
    } catch (Exception exp) {
        throw new ReportPortalException("Error while User creating: " + exp.getMessage(), exp);
    }

    eventPublisher.publishEvent(new UserCreatedEvent(user, userName));

    response.setLogin(user.getLogin());
    return response;
}

From source file:com.traffitruck.service.MongoDAO.java

public void storeUser(LoadsUser user) {
    StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
    String encryptedPassword = passwordEncryptor.encryptPassword(user.getPassword());
    user.setPassword(encryptedPassword);
    try {/*from w  w  w.  ja  v a2  s.  co  m*/
        mongoTemplate.save(user);
    } catch (DuplicateKeyException e) {
        if (e.getMessage().contains("email"))
            throw new DuplicateEmailException(user.getEmail());
        else
            throw new DuplicateException(user.getUsername());
    }
}

From source file:org.cbioportal.session_service.service.internal.SessionServiceImpl.java

@Override
public Session addSession(String source, String type, String data) throws SessionInvalidException {
    Session session = null;//from  w w  w . j  a va 2  s.c  o  m
    try {
        session = new Session(source, type, data);
        sessionRepository.saveSession(session);
    } catch (DuplicateKeyException e) {
        session = sessionRepository.findOneBySourceAndTypeAndData(source, type, session.getData());
    } catch (ConstraintViolationException e) {
        throw new SessionInvalidException(buildConstraintViolationExceptionMessage(e));
    } catch (JSONParseException e) {
        throw new SessionInvalidException(e.getMessage());
    }
    return session;
}

From source file:om.edu.squ.squportal.portlet.dps.grade.incomplete.db.IncompleteGradeDBImpl.java

@Override
public int setInstructorNotifyForIncompleteGrade(double sequenceNo, GradeIncompleteDTO dto)
        throws NotCorrectDBRecordException {
    String SQL_INCOMPLETE_GRADE_INSERT_NOTIFY_INSTRUCTOR = queryIncompleteGrade
            .getProperty(Constants.CONST_SQL_INCOMPLETE_GRADE_INSERT_NOTIFY_INSTRUCTOR);
    Map<String, String> namedParameterMap = new HashMap<String, String>();
    namedParameterMap.put("paramSeqenceNum", String.valueOf(sequenceNo));
    namedParameterMap.put("paramStdNo", dto.getStudent().getAcademicDetail().getStudentNo());
    namedParameterMap.put("paramStdStatCode", dto.getStudent().getAcademicDetail().getStdStatCode());
    namedParameterMap.put("paramYear", String.valueOf(dto.getCourse().getCourseYear()));
    namedParameterMap.put("paramSem", String.valueOf(dto.getCourse().getSemester()));
    namedParameterMap.put("paramSectCode", dto.getCourse().getSectCode());
    namedParameterMap.put("paramCourseLAbrCode", dto.getCourse().getlAbrCourseNo());
    namedParameterMap.put("paramCourseNo", dto.getCourse().getCourseNo());
    namedParameterMap.put("paramSectNo", dto.getCourse().getSectionNo());
    namedParameterMap.put("paramStatusCode", Constants.CONST_SQL_STATUS_CODE_NAME_PENDING);
    namedParameterMap.put("paramUserName", dto.getUserName());
    namedParameterMap.put("paramComment", dto.getComments());

    try {/*from w  w w . j a  va 2  s . c o  m*/
        return nPJdbcTemplDpsIncompleteGrade.update(SQL_INCOMPLETE_GRADE_INSERT_NOTIFY_INSTRUCTOR,
                namedParameterMap);
    } catch (DuplicateKeyException sqlEx) {
        logger.error("Violation of primary key. Details : {}", sqlEx.getMessage());
        throw new NotCorrectDBRecordException(sqlEx.getMessage());
    }

}

From source file:om.edu.squ.squportal.portlet.dps.grade.gradechange.db.GradeChangeDBImpl.java

/**
 * // www.  j a v a2s.c  o m
 * method name  : setInstructorApplyForGradeChange
 * @param dto
 * @return
 * GradeChangeDBImpl
 * return type  : int
 * 
 * purpose      :
 *
 * Date          :   Nov 21, 2017 12:32:15 PM
 */
public int setInstructorApplyForGradeChange(GradeDTO dto) throws NotCorrectDBRecordException {
    String SQL_GRADE_INSERT_APPLY_INSTRUCTOR = queryGradeChange
            .getProperty(Constants.CONST_SQL_GRADE_INSERT_APPLY_INSTRUCTOR);

    Map<String, String> namedParameterMap = new HashMap<String, String>();
    namedParameterMap.put("paramStdNo", dto.getStudentNo());
    namedParameterMap.put("paramStdStatCode", dto.getStdStatCode());
    namedParameterMap.put("paramYear", dto.getCourseYear());
    namedParameterMap.put("paramSem", dto.getSemester());
    namedParameterMap.put("paramSectCode", dto.getSectCode());
    namedParameterMap.put("paramCourseLAbrCode", dto.getCourse().getlAbrCourseNo());
    namedParameterMap.put("paramCourseNo", dto.getCourse().getCourseNo());
    namedParameterMap.put("paramSectNo", dto.getSectionNo());
    namedParameterMap.put("paramGradeCodeOld", String.valueOf(dto.getGrade().getGradeCodeOld()));
    namedParameterMap.put("paramGradeCodeNew", String.valueOf(dto.getGrade().getGradeCodeNew()));
    namedParameterMap.put("paramComments", dto.getComments());
    namedParameterMap.put("paramStatusCode", Constants.CONST_SQL_STATUS_CODE_NAME_PENDING);
    namedParameterMap.put("paramUserName", dto.getUserName());

    try {
        return nPJdbcTemplDpsGradeChange.update(SQL_GRADE_INSERT_APPLY_INSTRUCTOR, namedParameterMap);
    } catch (DuplicateKeyException sqlEx) {
        logger.error("Violation of primary key. Details : {}", sqlEx.getMessage());
        throw new NotCorrectDBRecordException(sqlEx.getMessage());
    }
}

From source file:org.jutge.joc.porra.service.AccountService.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void handleDuplicatekeyException(final DuplicateKeyException exception) throws SignupException {
    final Throwable cause = exception.getCause();
    if (cause instanceof MongoException) {
        final Locale locale = LocaleContextHolder.getLocale();
        final MongoException mongoException = (MongoException) cause;
        final String exceptionMessage = mongoException.getMessage();
        List errorMessages = new ArrayList();
        if (exceptionMessage.indexOf("account.$_id_") != -1) {
            final String message = this.messageSource.getMessage("exception.accountNameTaken", null, locale);
            final MessageBox messageBox = new MessageBox("accountNameTaken", message, new ArrayList<String>());
            errorMessages.add(messageBox);
        } else if (exceptionMessage.indexOf("account.$email") != -1) {
            final String message = this.messageSource.getMessage("exception.accountEmailTaken", null, locale);
            final MessageBox messageBox = new MessageBox("accountEmailTaken", message, new ArrayList<String>());
            errorMessages.add(messageBox);
        }/*w ww.ja  v  a  2 s. com*/
        throw new SignupException(errorMessages);
    } else {
        this.logger.error(exception.getMessage());
    }
}

From source file:org.opentestsystem.authoring.testauth.service.impl.FormPartitionServiceImpl.java

private FormPartition saveNewFormPartition(final FormPartition formPartition) {
    FormPartition savedFormPartition = null;
    try {//from  w w w .  j a v  a  2  s  . c o  m
        savedFormPartition = this.formPartitionRepository.save(formPartition);
    } catch (final DuplicateKeyException dke) {
        if (StringUtils.contains(dke.getMessage(), FormPartition.SEGMENT_INDEX_NAME)) {
            throw new LocalizedException("formPartition.already.exists.segment",
                    new String[] { formPartition.getFormId(), formPartition.getSegmentId() }, dke);
        } else {
            throw new LocalizedException("formPartition.already.exists.name",
                    new String[] { formPartition.getFormId(), formPartition.getName() }, dke);
        }
    }
    return savedFormPartition;
}

From source file:org.opentestsystem.authoring.testauth.service.impl.FormPartitionServiceImpl.java

private FormPartition updateExistingFormPartition(final FormPartition formPartition) {
    final List<FormPartition> formPartitionsToSave = Lists.newArrayList(formPartition);
    final FormPartition currentValuePartition = getFormPartition(formPartition.getId());
    if (!currentValuePartition.getSegmentId().equals(formPartition.getSegmentId())) {
        FormPartition rivalFormPartition = null;
        final SearchResponse<FormPartition> searchResponse = searchFormPartitions(
                ImmutableMap.of("formId", new String[] { formPartition.getFormId() }, "segmentId",
                        new String[] { formPartition.getSegmentId() }));
        if (searchResponse.getReturnCount() > 0) {
            rivalFormPartition = searchResponse.getSearchResults().get(0);
            rivalFormPartition.setSegmentId(currentValuePartition.getSegmentId());
            formPartitionsToSave.add(rivalFormPartition);
            removeFormPartition(rivalFormPartition.getId());
        }/*from   w w w  .  ja  va  2  s  .c  o m*/
    }
    List<FormPartition> savedFormPartition = null;
    try {
        savedFormPartition = this.formPartitionRepository.save(formPartitionsToSave);
    } catch (final DuplicateKeyException dke) {
        if (StringUtils.contains(dke.getMessage(), FormPartition.SEGMENT_INDEX_NAME)) {
            throw new LocalizedException("formPartition.already.exists.segment",
                    new String[] { formPartition.getFormId(), formPartition.getSegmentId() }, dke);
        } else {
            throw new LocalizedException("formPartition.already.exists.name",
                    new String[] { formPartition.getFormId(), formPartition.getName() }, dke);
        }
    }
    return savedFormPartition.get(0);
}