Example usage for org.springframework.dao DuplicateKeyException DuplicateKeyException

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

Introduction

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

Prototype

public DuplicateKeyException(String msg) 

Source Link

Document

Constructor for DuplicateKeyException.

Usage

From source file:com.trenako.web.controllers.admin.AdminBrandsControllerTests.java

@Test
public void shouldRedirectAfterDuplicatedKeyErrorsDuringBrandCreation() throws IOException {
    when(postedForm().getBrand()).thenReturn(acme());
    when(bindingResults.hasErrors()).thenReturn(false);
    doThrow(new DuplicateKeyException("duplicated key")).when(service).save(eq(acme()));

    String viewName = controller.create(postedForm(), bindingResults, model, redirectAtts);

    assertEquals("brand/new", viewName);
    assertBrandForm(model, "brandForm");
    verify(bindingResults, times(1)).rejectValue("brand.name", "brand.name.already.used");
}

From source file:com.turbospaces.core.SpaceUtility.java

/**
 * raise new {@link DuplicateKeyException} exception for given uniqueIdentifier and persistent class.
 * //from   ww  w  .j  ava 2  s.c  om
 * @param uniqueIdentifier
 *            primary key
 * @param persistentClass
 *            space class
 * @see SpaceErrors#DUPLICATE_KEY_VIOLATION
 */
public static void raiseDuplicateException(final Object uniqueIdentifier, final Class<?> persistentClass) {
    throw new DuplicateKeyException(String.format(SpaceErrors.DUPLICATE_KEY_VIOLATION,
            persistentClass.getSimpleName(), uniqueIdentifier.toString()));
}

From source file:com.trenako.web.controllers.RollingStocksControllerTests.java

@Test
public void shouldShowErrorMessageAfterDuplicatedKeyErrorsDuringCreation() {
    doThrow(new DuplicateKeyException("Duplicate key error")).when(service).createNew(eq(rollingStock()));

    when(mockResult.hasErrors()).thenReturn(false);
    when(mockFile.isEmpty()).thenReturn(true);
    RollingStockForm form = rsForm(mockFile);

    ModelMap model = new ModelMap();

    String viewName = controller.create(form, mockResult, model, mockRedirect);

    assertEquals("rollingstock/new", viewName);
    assertNotNull("Form is null", model.get("rollingStockForm"));
    assertEquals(RollingStocksController.ROLLING_STOCK_DUPLICATED_VALUE_MSG,
            (ControllerMessage) model.get("message"));
}

From source file:it.geosolutions.geofence.core.dao.impl.RuleDAOImpl.java

@Override
public Rule merge(Rule entity) {
    Search search = getDupSearch(entity);

    // check if we are dup'ing some other Rule.
    List<Rule> existent = search(search);
    switch (existent.size()) {
    case 0://from  w w  w . ja  v a2  s  .c o m
        break;

    case 1:
        // We may be updating some other fields in this Rule
        if (!existent.get(0).getId().equals(entity.getId())) {
            throw new DuplicateKeyException("Duplicating Rule " + existent.get(0) + " with " + entity);
        }
        break;

    default:
        throw new IllegalStateException("Too many rules duplicating " + entity);
    }

    return super.merge(entity);
}

From source file:com.trenako.web.controllers.WishListsControllerTests.java

@Test
public void shouldRedirectAfterDuplicatedKeyErrorSavingWishLists() {
    when(bindingResults.hasErrors()).thenReturn(false);
    when(mockUserContext.getCurrentUser()).thenReturn(ownerDetails());
    doThrow(new DuplicateKeyException("duplicated key")).when(wishListsService).saveChanges(eq(wishList()));

    String viewName = controller.saveWishList(postedForm(), bindingResults, model, redirectAtts);

    assertEquals("wishlist/edit", viewName);
    assertTrue("Wish list form is null", model.containsAttribute("editForm"));
    assertEquals(WishListsController.WISH_LIST_DUPLICATED_KEY_MSG, model.get("message"));
}

From source file:org.dcache.chimera.PgSQLFsSqlDriver.java

@Override
void createEntryInParent(FsInode parent, String name, FsInode inode) {
    int n = _jdbc.update(
            "insert into t_dirs (iparent, iname, ichild) " + "(select ? as iparent, ? as iname, ? as ichild "
                    + " where not exists (select 1 from t_dirs where iparent=? and iname=?))",
            ps -> {/*from   w  ww .  j av a2 s .co m*/
                ps.setLong(1, parent.ino());
                ps.setString(2, name);
                ps.setLong(3, inode.ino());
                ps.setLong(4, parent.ino());
                ps.setString(5, name);
            });
    if (n == 0) {
        /*
         * no updates as such entry already exists.
         * To be compatible with others, throw corresponding
         * DataAccessException.
         */
        throw new DuplicateKeyException("Entry already exists");
    }
}

From source file:edu.pitt.dbmi.ccd.anno.group.GroupController.java

/**
 * Create new group with name and description Creator is added to list of
 * administrators/*from  w  ww  .jav a2 s  . c o  m*/
 *
 * @param principal requester
 * @param form group data
 * @return new group resource
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public GroupResource create(@AuthenticationPrincipal UserAccountDetails principal,
        @RequestBody @Valid GroupForm form) throws DuplicateKeyException {
    final UserAccount requester = principal.getUserAccount();
    final String name = form.getName();
    final String description = form.getDescription();

    // throw exception if non-unique name
    if (groupService.findByName(name) != null) {
        throw new DuplicateKeyException("Group already exists with name: " + name);
    }
    Group group = new Group(name, description);
    group.addMember(requester);
    group.addModerator(requester);
    group = groupService.save(group);
    GroupResource resource = assembler.toResource(group);
    return resource;
}

From source file:org.terasoluna.gfw.web.exception.HandlerExceptionResolverLoggingInterceptorTest.java

@Test
public void testInvoke_SystemExceptionResolver_ignoreExceptions_is_multi() throws Throwable {

    // do setup for test case.
    FileNotFoundException occurException1 = new FileNotFoundException("error.");
    DuplicateKeyException occurException2 = new DuplicateKeyException("error.");

    SystemExceptionResolver resolver = new SystemExceptionResolver();

    when(mockMethodInvocation.proceed()).thenReturn("viewname");
    when(mockMethodInvocation.getThis()).thenReturn(resolver);
    when(mockMethodInvocation.getArguments()).thenReturn(new Object[] { null, null, null, occurException1 },
            new Object[] { null, null, null, occurException2 });

    Set<Class<? extends Exception>> ignoreExceptions = new HashSet<Class<? extends Exception>>();
    ignoreExceptions.add(DataAccessException.class);
    ignoreExceptions.add(IOException.class);
    testTarget.setIgnoreExceptions(ignoreExceptions);

    // do test./*from w  w  w  .  ja v  a 2s.c o  m*/
    testTarget.invoke(mockMethodInvocation);
    testTarget.invoke(mockMethodInvocation);

    // do assert.
    verify(mockExceptionLogger, times(0)).log((Exception) any());
    verify(mockExceptionLogger, times(0)).info((Exception) any());
    verify(mockExceptionLogger, times(0)).warn((Exception) any());
    verify(mockExceptionLogger, times(0)).error((Exception) any());

}

From source file:com.poscoict.license.service.ManagementService.java

public void addProgressContract(String userName, String projectName, String userAddress, String managerName,
        String officePhon, String celPhon, String email, String startDate, String product, String comment,
        HttpSession session) {/*from   w w  w  . j  a  va  2  s.  c  o  m*/
    CustomUserDetails userDetails = (CustomUserDetails) session.getAttribute("userDetails");
    String companyCode = "";

    if (userDetails.getAuthorities().toString().contains(Consts.rolePrefix + Consts.USERLV_ADMIN))
        companyCode = Consts.POSCO_ICT_CODE;
    else
        companyCode = managementDao.getCompanyCode((String) session.getAttribute("USER_NO"));

    String objectId = "pc_" + attachFileDateFormat();
    objectId += UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);

    TransactionStatus status = this.transactionManager.getTransaction(new DefaultTransactionDefinition());

    try {
        //
        managementDao.addProgressContract(objectId, userName, projectName, managerName, officePhon, celPhon,
                email, startDate.isEmpty() ? null : startDate, userAddress, product, companyCode,
                Consts.ProgressStatus.valueOf("P").getProgressStatus(),
                (String) session.getAttribute("USER_NO"));
        // 
        managementDao.insertProgressUserLog(objectId, null,
                Consts.ProgressStatus.valueOf("P").getProgressStatus(),
                (String) session.getAttribute("USER_NO"));
        if (!comment.isEmpty()) {
            managementDao.insertProgressComment(objectId, 1, comment.trim().replaceAll("\n", "<br>"),
                    (String) session.getAttribute("USER_NO"));
        }

        this.transactionManager.commit(status);
    } catch (DuplicateKeyException e) {
        this.transactionManager.rollback(status);
        logger.error("addProgressContract: ", e);
        throw new DuplicateKeyException(
                " ?. ?? ? .");
    } catch (RuntimeException e) {
        this.transactionManager.rollback(status);
        logger.error("addProgressContract: ", e);
    }
}

From source file:com.poscoict.license.service.ManagementService.java

public void modifyProgressInfo(String objectId, String userName, String projectName, String userAddress,
        String managerName, String officePhon, String celPhon, String email, String startDate, String product,
        String userNo) {/*w w w.j  av  a2  s .  c om*/
    TransactionStatus status = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    try {
        managementDao.modifyProgressInfo(objectId, userName, projectName, managerName, officePhon, celPhon,
                email, startDate.isEmpty() ? null : startDate, userAddress, product, userNo);
        managementDao.insertProgressUserLog(objectId, null,
                Consts.ProgressStatus.valueOf("M").getProgressStatus(), userNo);
        this.transactionManager.commit(status);
    } catch (DuplicateKeyException e) {
        this.transactionManager.rollback(status);
        logger.error("addProgressContract: ", e);
        throw new DuplicateKeyException(
                " ?. ?? ? .");
    } catch (RuntimeException e) {
        this.transactionManager.rollback(status);
        logger.error("addProgressContract: ", e);
    }
}