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:be.bittich.quote.service.impl.UserServiceImpl.java

@Override
public User insert(User user) {
    User exist = this.repository.findOneByUsername(user.getUsername());
    if (exist != null && exist.getUsername().equals(user.getUsername())) {
        throw new DuplicateKeyException(format("User %s already exist.", user.getUsername()));
    }// w w  w  .  jav  a 2s.  com
    String encodedPassword = passwordEncoder.encode(user.getPassword());
    user.setPassword(encodedPassword);
    return this.saveOrUpdate(user);
}

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

@Override
void createEntryInParent(FsInode parent, String name, FsInode inode) {
    int n = _jdbc.update(
            "INSERT INTO t_dirs (iparent, iname, ichild) VALUES(?,?,?) ON CONFLICT ON CONSTRAINT t_dirs_pkey DO NOTHING",
            ps -> {// ww w .j  av a2  s .  c o  m
                ps.setLong(1, parent.ino());
                ps.setString(2, name);
                ps.setLong(3, inode.ino());
            });
    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:com.trenako.web.controllers.AuthControllerTests.java

@Test
public void shouldRedirectAfterDatabaseErrors() {
    doThrow(new DuplicateKeyException("E11000 duplicate key error index")).when(mockService)
            .createAccount(eq(newAccount()));
    when(mockResult.hasErrors()).thenReturn(false);
    ModelMap model = new ExtendedModelMap();

    String viewName = controller.createUser(newAccount(), mockResult, model);

    assertEquals("auth/signup", viewName);
    assertTrue(model.containsAttribute("account"));
    assertTrue(model.containsAttribute("message"));
    assertEquals(AuthController.EMAIL_ADDRESS_OR_DISPLAY_NAME_ALREADY_TAKEN, model.get("message"));
    verify(mockService, times(0)).authenticate(eq(newAccount()));
}

From source file:org.zenoss.zep.impl.MigratedEventQueueListener.java

@Override
@TransactionalRollbackAllExceptions/*w  w  w. j  a v a 2 s  . c o m*/
public void handle(Message message) throws Exception {
    EventSummary summary = (EventSummary) message;
    try {
        // ZEN-5286 - Avoid duplicate UUIDs stored in event_summary/event_archive.
        // This check is prone to race conditions but this is worked around by having a single threaded
        // executor processing all migrated events (in both the summary and archive queues). Multi-instance
        // ZEP (if implemented) should come up with a better protection for this to ensure that duplicate
        // events are never imported into the system.
        if (this.eventStoreDao.findByUuid(summary.getUuid()) != null) {
            throw new DuplicateKeyException("Found existing event");
        }
        this.eventSummaryBaseDao.importEvent(summary);
    } catch (DuplicateKeyException e) {
        // Create event summary entry - if we get a duplicate key exception just skip importing this event as it
        // either has already been imported or there is already an active event with the same fingerprint.
        logger.info("Event with UUID {} already exists in database - skipping", summary.getUuid());
    }
}

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

@Override
public void persist(Rule... entities) {

    // TODO: check if there are any dups in the input list

    for (Rule rule : entities) {
        // check there are no dups for the rules received
        if (rule.getAccess() != GrantType.LIMIT) { // there may be as many LIMIT rules as desired
            Search search = getDupSearch(rule);
            List<Rule> dups = search(search);
            for (Rule dup : dups) {
                if (dup.getAccess() != GrantType.LIMIT) {
                    if (dup.getId().equals(rule.getId())) {
                        // avoid check against self
                        continue;
                    }/*from ww w  .j  a  v a 2  s .  c  o m*/

                    LOGGER.warn(" ORIG: " + dup);
                    LOGGER.warn(" DUP : " + rule);
                    throw new DuplicateKeyException("Duplicate Rule " + rule);
                }
            }
            //                if (count(search) > 0)
            //                {
            //                    throw new DuplicateKeyException("Duplicate Rule " + rule);
            //                }
        }
    }
    super.persist(entities);
}

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

@Test
public void shouldRedirectAfterDuplicatedKeyErrorsDuringWishListsCreation() {
    doThrow(new DuplicateKeyException("Duplicate key error")).when(wishListsService)
            .createNew(eq(form().buildWishList(owner())));

    when(mockUserContext.getCurrentUser()).thenReturn(ownerDetails());
    when(bindingResults.hasErrors()).thenReturn(false);

    String viewName = controller.createWishList(form(), bindingResults, model, redirectAtts);

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

From source file:ch.wisv.areafiftylan.extras.consumption.service.ConsumptionServiceImpl.java

@Override
public Consumption addPossibleConsumption(String consumptionName) {
    if (possibleConsumptionsRepository.findByName(consumptionName).isPresent()) {
        throw new DuplicateKeyException("Consumption " + consumptionName + " is already supported");
    }/*from ww  w  .jav a 2s . c  om*/

    Consumption consumption = new Consumption(consumptionName);
    return possibleConsumptionsRepository.saveAndFlush(consumption);
}

From source file:ru.org.linux.user.UserTagServiceTest.java

@Test
public void addMultiplyTagsTest() {
    UserTagService mockUserTagService = mock(UserTagService.class);
    when(mockUserTagService.addMultiplyTags(any(User.class), anyString(), anyBoolean())).thenCallRealMethod();
    when(mockUserTagService.parseTags(anyString(), any(Errors.class))).thenCallRealMethod();
    try {// w w w.  j av a 2 s . c o  m
        doThrow(new TagNotFoundException()).when(mockUserTagService).favoriteAdd(eq(user), eq("uytutut"));
        doThrow(new DuplicateKeyException("duplicate")).when(mockUserTagService).favoriteAdd(eq(user),
                eq("tag3"));
    } catch (Exception e) {
    }

    List<String> strErrors = mockUserTagService.addMultiplyTags(user, "tag1, tag2, tag3, uytutut, @#$%$#",
            true);
    try {
        verify(mockUserTagService).favoriteAdd(eq(user), eq("tag1"));
        verify(mockUserTagService).favoriteAdd(eq(user), eq("tag2"));
        verify(mockUserTagService).favoriteAdd(eq(user), eq("uytutut"));
        verify(mockUserTagService, never()).favoriteAdd(eq(user), eq("@#$%$#"));
        verify(mockUserTagService, never()).ignoreAdd(any(User.class), anyString());
    } catch (Exception e) {
    }
    Assert.assertEquals(3, strErrors.size());

    reset(mockUserTagService);
    when(mockUserTagService.addMultiplyTags(any(User.class), anyString(), anyBoolean())).thenCallRealMethod();
    when(mockUserTagService.parseTags(anyString(), any(Errors.class))).thenCallRealMethod();
    try {
        doThrow(new TagNotFoundException()).when(mockUserTagService).ignoreAdd(eq(user), eq("uytutut"));
        doThrow(new DuplicateKeyException("duplicate")).when(mockUserTagService).ignoreAdd(eq(user),
                eq("tag3"));
    } catch (Exception e) {
    }

    strErrors = mockUserTagService.addMultiplyTags(user, "tag1, tag2, tag3, uytutut, @#$%$#", false);
    try {
        verify(mockUserTagService).ignoreAdd(eq(user), eq("tag1"));
        verify(mockUserTagService).ignoreAdd(eq(user), eq("tag2"));
        verify(mockUserTagService).ignoreAdd(eq(user), eq("uytutut"));
        verify(mockUserTagService, never()).ignoreAdd(eq(user), eq("@#$%$#"));
        verify(mockUserTagService, never()).favoriteAdd(any(User.class), anyString());
    } catch (Exception e) {
    }
    Assert.assertEquals(3, strErrors.size());
}

From source file:org.oncoblocks.centromere.jpa.CentromereJpaRepository.java

/**
 * Creates a new record in the repository and returns the updated model object.
 *
 * @param entity instance of {@code T} to be persisted.
 * @return updated instance of the entity.
 *///from   w ww  .ja  v  a  2 s  .c  o  m
public <S extends T> S insert(S entity) {
    if (!this.exists(entity.getId())) {
        this.save(entity);
    } else {
        throw new DuplicateKeyException(String.format("Record already exists: %s", entity.toString()));
    }
    return entity;
}

From source file:com.reactivetechnologies.analytics.core.handlers.ModelCombinerComponent.java

private String ensembleModels() throws EngineException {
    List<RegressionModel> models = new ArrayList<>();
    for (Iterator<RegressionModel> iterModel = hzService
            .getSetIterator(ConfigUtil.WEKA_MODEL_SNAPSHOT_SET); iterModel.hasNext();) {
        RegressionModel model = iterModel.next();
        models.add(model);/* ww  w .  j ava  2 s. com*/
    }
    if (!models.isEmpty()) {

        RegressionModel ensemble;
        try {
            Dataset dset = dataGen.generate();
            dset.setOptions(combinerOpts);
            ensemble = classifierBean.findBestFitModel(models, CombinerType.valueOf(combiner), dset);
            log.debug(ensemble.getTrainedClassifier() + "");
            ensemble.generateId();
            boolean saved = hzService.persistItem(ConfigUtil.WEKA_MODEL_PERSIST_MAP, ensemble,
                    ensemble.getStringId());
            if (!saved)
                throw new DuplicateKeyException(ensemble.getStringId());

            log.info("[ensembleModelTask] Saved model generated.. Combiner used- " + combiner);
            return ensemble.getStringId();
        } catch (EngineException e) {
            throw e;
        } catch (DuplicateKeyException e) {
            throw new EngineException("Ignoring model already present in database", e);
        }
    }
    return null;

}