Example usage for org.springframework.dao DataIntegrityViolationException DataIntegrityViolationException

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

Introduction

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

Prototype

public DataIntegrityViolationException(String msg) 

Source Link

Document

Constructor for DataIntegrityViolationException.

Usage

From source file:org.grails.datastore.mapping.mongo.MongoSession.java

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void flushPendingInserts(final Map<PersistentEntity, Collection<PendingInsert>> inserts) {
    // Optimizes saving multipe entities at once
    for (final PersistentEntity entity : inserts.keySet()) {
        final MongoTemplate template = getMongoTemplate(entity.isRoot() ? entity : entity.getRootEntity());
        final String collectionNameToUse = getCollectionName(entity.isRoot() ? entity : entity.getRootEntity());
        template.execute(new DbCallback<Object>() {
            public Object doInDB(DB db) throws MongoException, DataAccessException {
                WriteConcern writeConcernToUse = writeConcern;

                writeConcernToUse = getDeclaredWriteConcern(writeConcernToUse, entity);
                final DBCollection collection = db.getCollection(collectionNameToUse);

                final Collection<PendingInsert> pendingInserts = inserts.get(entity);
                List<DBObject> dbObjects = new LinkedList<DBObject>();
                List<PendingOperation> postOperations = new LinkedList<PendingOperation>();

                for (PendingInsert pendingInsert : pendingInserts) {

                    final List<PendingOperation> preOperations = pendingInsert.getPreOperations();
                    for (PendingOperation preOperation : preOperations) {
                        preOperation.run();
                    }/*from ww  w  . j  a v a  2  s .c  om*/

                    dbObjects.add((DBObject) pendingInsert.getNativeEntry());
                    postOperations.addAll(pendingInsert.getCascadeOperations());
                    pendingInsert.run();
                }

                WriteResult writeResult = collection.insert(dbObjects.toArray(new DBObject[dbObjects.size()]),
                        writeConcernToUse);
                if (writeResult.getError() != null) {
                    errorOccured = true;
                    throw new DataIntegrityViolationException(writeResult.getError());
                }
                for (PendingOperation pendingOperation : postOperations) {
                    pendingOperation.run();
                }
                return null;
            }
        });
    }
}

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

/**
 * Updates an existing record in the repository and returns its instance.
 *
 * @param entity updated record to be persisted in the repository.
 * @return the updated entity object./*from   w w w  .  java 2  s  .c o  m*/
 */
public <S extends T> S update(S entity) {
    if (this.exists(entity.getId())) {
        this.save(entity);
    } else {
        throw new DataIntegrityViolationException(
                String.format("No record with id exists: %s", entity.getId().toString()));
    }
    return entity;
}

From source file:org.openlmis.fulfillment.web.BaseTransferPropertiesControllerIntegrationTest.java

@Test
public void shouldNotDeletePropertiesWithConflicts() {
    // given//w w w  . j  av  a  2 s .  c  o  m
    T properties = generateProperties();
    given(transferPropertiesRepository.findOne(properties.getId()))
            .willThrow(new DataIntegrityViolationException("This exception is required by IT"));

    // when
    restAssured.given().header(HttpHeaders.AUTHORIZATION, getTokenHeader())
            .contentType(MediaType.APPLICATION_JSON_VALUE).pathParam("id", properties.getId()).when()
            .delete(ID_URL).then().statusCode(409);

    // then
    assertThat(RAML_ASSERT_MESSAGE, restAssured.getLastReport(), RamlMatchers.hasNoViolations());
}

From source file:edu.wisc.my.portlets.dmp.dao.jdbc.JdbcMenuDao.java

/**
 * Loads a complete MenuItem including groups, display states and children.
 * //from w  ww.j  a  v  a 2s .co  m
 * @param itemId The ID of the item to load and return as the root item.
 * @param userGroups The groups to filter the menu items with, if null no group filtering is done.
 * @param parentIds A Set of item IDs that have been loaded and are parents, grandparents, etc.. of this item.
 * @return The item for the specified ID, will be null if no matching group is found and userGroups is not null.
 */
private MenuItem getMenuItemForIdAndGroups(Long itemId, Set userGroups, Set parentIds) {
    //Check for loops in the menu structure
    if (parentIds.contains(itemId)) {
        throw new DataIntegrityViolationException("Loop found in menu structure. itemId='" + itemId
                + "' exists in set of parentIds='" + parentIds + "'");
    }

    //Get MenuItem (no groups, states, children)
    final MenuItem item = this.menuItemQuery.getItem(itemId);
    if (item == null) {
        throw new DataIntegrityViolationException("No MenuItem found for itemId='" + itemId + "'");
    }

    //populate groups[]
    final String[] groups = this.groupsQuery.getGroups(itemId);

    //Check groups to see if this item should be returned based on the specified userGroups
    if (userGroups != null) {
        boolean validItem = false;

        //Check the item groups against the Set
        for (int index = 0; index < groups.length && !validItem; index++) {
            validItem = userGroups.contains(groups[index]);
        }

        //If no matching group was found retun null from this method
        if (!validItem) {
            return null;
        }
    }
    item.setGroups(groups);

    //populate states[]
    final WindowState[] states = this.windowStatesQuery.getWindowStates(itemId);
    item.setDisplayStates(states);

    //get child ID's
    final Long[] childIds = this.relationsQuery.getChildIds(itemId);
    final List childList = new ArrayList(childIds.length);

    //Track the parent item ID when loading children
    parentIds.add(itemId);
    try {
        for (int index = 0; index < childIds.length; index++) {
            final MenuItem childItem = this.getMenuItemForIdAndGroups(childIds[index], userGroups, parentIds);
            if (childItem != null) {
                childList.add(childItem);
            }
        }
    } finally {
        //Ensure the parent id is cleared from the Set.
        parentIds.remove(itemId);
    }

    final MenuItem[] children = (MenuItem[]) childList.toArray(new MenuItem[childList.size()]);
    item.setChildren(children);

    return item;
}

From source file:com.acuityph.commons.jpa.ActiveJpaDao.java

/**
 * Similar to {@link #findByNamedQueryAndNamedParams(String, Map)}, but
 * expects only a single row to be returned. Returns null if more than one
 * row is returned./*from w  ww  .j a  va  2 s .co  m*/
 *
 * @param queryName
 *        the named query name
 * @param params
 *        the query parameters
 * @return object of type T, or null
 */
public final E findSingleResultByNamedQueryAndNamedParams(final String queryName, final Map<String, ?> params) {
    final List<E> list = findByNamedQueryAndNamedParams(queryName, params);
    final int n = list.size();
    if (n == 1) {
        return list.get(0);
    }
    if (n != 0) {
        throw new DataIntegrityViolationException(
                format("Named query \"%s\" returned %d results, expecting 0 or 1!", queryName, n));
    }
    return null;
}

From source file:edu.wisc.my.portlets.dmp.dao.jdbc.JdbcMenuDao.java

/**
 * Recursivly deletes a menu structure starting with the specified itemId
 * //from   w  w w  . jav a2 s.c  om
 * @param itemId The root id to start deleting from, all children, groups, states will be removed.
 * @param parentIds A Set of item IDs that have been stored and are parents, grandparents, etc.. of this item.
 */
private void deleteMenuItem(Long itemId, Set parentIds) {
    //Check for loops in the menu structure
    if (parentIds.contains(itemId)) {
        throw new DataIntegrityViolationException("Loop found in menu structure. itemId='" + itemId
                + "' exists in set of parentIds='" + parentIds + "'");
    }

    //Get the child IDs before removing the relations
    final Long[] childIds = this.relationsQuery.getChildIds(itemId);

    //Delete relations
    this.relationsDelete.delete(itemId);

    //Recurse on children
    //Track the parent item ID when deleting children
    parentIds.add(itemId);
    try {
        for (int index = 0; index < childIds.length; index++) {
            //recurse on each child
            this.deleteMenuItem(childIds[index], parentIds);
        }
    } finally {
        //Ensure the parent id is cleared from the Set.
        parentIds.remove(itemId);
    }

    //Delete states
    this.windowStatesDelete.delete(itemId);

    //Delete groups
    this.groupsDelete.delete(itemId);

    //Delete item
    this.menuItemDelete.delete(itemId);
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimUserEndpointsTests.java

@Test
public void testHandleExceptionWithConstraintViolation() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    endpoints.setMessageConverters(new HttpMessageConverter<?>[] { new ExceptionReportHttpMessageConverter() });
    View view = endpoints.handleException(new DataIntegrityViolationException("foo"), request);
    ConvertingExceptionView converted = (ConvertingExceptionView) view;
    converted.render(Collections.<String, Object>emptyMap(), request, response);
    String body = response.getContentAsString();
    assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
    // System.err.println(body);
    assertTrue("Wrong body: " + body, body.contains("message\":\"foo"));
}

From source file:ch.systemsx.cisd.openbis.generic.server.CommonServerTest.java

@Test
public void testDeleteFileFormatWithDataSets() throws Exception {
    final String code = "used-type";
    final List<String> codes = Arrays.asList(code);
    prepareGetSession();/* w  ww . ja  v  a2  s . c o m*/
    context.checking(new Expectations() {
        {
            one(fileFormatDAO).tryToFindFileFormatTypeByCode(code);
            FileFormatTypePE type = createFileFormatType(code);
            will(returnValue(type));

            one(fileFormatDAO).delete(type);
            will(throwException(new DataIntegrityViolationException("")));
        }
    });
    boolean exceptionThrown = false;
    try {
        createServer().deleteFileFormatTypes(SESSION_TOKEN, codes);
    } catch (UserFailureException ex) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);
    context.assertIsSatisfied();
}

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

/**
 * @return              Returns the read-only cached property map
 *//* w w  w  .  j a va 2 s .  c om*/
private Map<QName, Serializable> getNodePropertiesCached(Long nodeId) {
    NodeVersionKey nodeVersionKey = getNodeNotNull(nodeId, false).getNodeVersionKey();
    Pair<NodeVersionKey, Map<QName, Serializable>> cacheEntry = propertiesCache.getByKey(nodeVersionKey);
    if (cacheEntry == null) {
        invalidateNodeCaches(nodeId);
        throw new DataIntegrityViolationException("Invalid node ID: " + nodeId);
    }
    // We have the properties from the cache
    Map<QName, Serializable> cachedProperties = cacheEntry.getSecond();
    return cachedProperties;
}

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

/**
 * @return              Returns a writable copy of the cached aspects set
 *///from  ww w  .j a  v a2s  . com
private Set<QName> getNodeAspectsCached(Long nodeId) {
    NodeVersionKey nodeVersionKey = getNodeNotNull(nodeId, false).getNodeVersionKey();
    Pair<NodeVersionKey, Set<QName>> cacheEntry = aspectsCache.getByKey(nodeVersionKey);
    if (cacheEntry == null) {
        invalidateNodeCaches(nodeId);
        throw new DataIntegrityViolationException("Invalid node ID: " + nodeId);
    }
    return new HashSet<QName>(cacheEntry.getSecond());
}