javax.persistence.EntityExistsException Java Examples

The following examples show how to use javax.persistence.EntityExistsException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataManager.java    From syndesis with Apache License 2.0 7 votes vote down vote up
private <T extends WithId<T>> void validateNoDuplicateName(final T entity, final String ignoreSelfId) {
    if (entity instanceof Connection) {
        Connection c = (Connection) entity;
        if (c.getName() == null) {
            LOGGER.error("Connection name is a required field");
            throw new PersistenceException("'Name' is a required field");
        }
        Set<String> ids = fetchIdsByPropertyValue(Connection.class, "name", c.getName());
        if (ids != null) {
            ids.remove(ignoreSelfId);
            if (! ids.isEmpty()) {
                LOGGER.error("Duplicate name, current Connection with id '{}' has name '{}' that already exists on entity with id '{}'",
                    entity.getId().orElse("null"),
                    c.getName(),
                    ids.iterator().next());
                throw new EntityExistsException(
                        "There already exists a Connection with name " + c.getName());
            }
        }
    }
}
 
Example #2
Source File: DocumentMasterDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createDocM(DocumentMaster pDocumentMaster) throws DocumentMasterAlreadyExistsException, CreationException {
    try {
        //the EntityExistsException is thrown only when flush occurs
        em.persist(pDocumentMaster);
        em.flush();
    } catch (EntityExistsException pEEEx) {
        LOGGER.log(Level.FINER,null,pEEEx);
        throw new DocumentMasterAlreadyExistsException(pDocumentMaster);
    } catch (PersistenceException pPEx) {
        //EntityExistsException is case sensitive
        //whereas MySQL is not thus PersistenceException could be
        //thrown instead of EntityExistsException
        LOGGER.log(Level.FINER,null,pPEx);
        throw new CreationException();
    }
}
 
Example #3
Source File: ApplicationCrudServiceImpl.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
public JpaApplication updateApplication(UpdateApplicationRequest updateApplicationRequest, JpaApplication jpaApp, JpaGroup jpaGroup) {

    final Identifier<Application> appId = updateApplicationRequest.getId();

    if (jpaApp != null) {
        jpaApp.setName(updateApplicationRequest.getNewName());
        jpaApp.setWebAppContext(updateApplicationRequest.getNewWebAppContext());
        jpaApp.setGroup(jpaGroup);
        jpaApp.setSecure(updateApplicationRequest.isNewSecure());
        jpaApp.setLoadBalanceAcrossServers(updateApplicationRequest.isNewLoadBalanceAcrossServers());
        jpaApp.setUnpackWar(updateApplicationRequest.isUnpackWar());
        try {
            return update(jpaApp);
        } catch (EntityExistsException eee) {
            LOGGER.error("Error updating application {} in group {}", jpaApp, jpaGroup, eee);
            throw new EntityExistsException("App already exists: " + updateApplicationRequest, eee);
        }
    } else {
        LOGGER.error("Application cannot be found {} attempting to update application", updateApplicationRequest);
        throw new BadRequestException(FaultType.INVALID_APPLICATION_NAME,
                "Application cannot be found: " + appId.getId());
    }
}
 
Example #4
Source File: ApplicationCrudServiceImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test(expected = EntityExistsException.class)
public void testApplicationCrudServiceEEE() {
    CreateApplicationRequest request = new CreateApplicationRequest(expGroupId, textName, textContext, true, true, false);

    JpaApplication created = applicationCrudService.createApplication(request, jpaGroup);

    assertNotNull(created);

    try {
        JpaApplication duplicate = applicationCrudService.createApplication(request, jpaGroup);
        fail(duplicate.toString());
    } catch (BadRequestException e) {
        assertEquals(FaultType.DUPLICATE_APPLICATION, e.getMessageResponseStatus());
        throw e;
    } finally {
        try {
            applicationCrudService.removeApplication(Identifier.<Application>id(created.getId())
            );
        } catch (Exception x) {
            LOGGER.trace("Test tearDown", x);
        }
    }

}
 
Example #5
Source File: OvsTunnelManagerImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@DB
protected OvsTunnelInterfaceVO createInterfaceRecord(String ip,
        String netmask, String mac, long hostId, String label) {
    OvsTunnelInterfaceVO ti = null;
    try {
        ti = new OvsTunnelInterfaceVO(ip, netmask, mac, hostId, label);
        // TODO: Is locking really necessary here?
        OvsTunnelInterfaceVO lock = _tunnelInterfaceDao
                .acquireInLockTable(Long.valueOf(1));
        if (lock == null) {
            s_logger.warn("Cannot lock table ovs_tunnel_account");
            return null;
        }
        _tunnelInterfaceDao.persist(ti);
        _tunnelInterfaceDao.releaseFromLockTable(lock.getId());
    } catch (EntityExistsException e) {
        s_logger.debug("A record for the interface for network " + label
                + " on host id " + hostId + " already exists");
    }
    return ti;
}
 
Example #6
Source File: ApplicationCrudServiceImpl.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
public JpaApplication createApplication(CreateApplicationRequest createApplicationRequest, JpaGroup jpaGroup) {


    final JpaApplication jpaApp = new JpaApplication();
    jpaApp.setName(createApplicationRequest.getName());
    jpaApp.setGroup(jpaGroup);
    jpaApp.setWebAppContext(createApplicationRequest.getWebAppContext());
    jpaApp.setSecure(createApplicationRequest.isSecure());
    jpaApp.setLoadBalanceAcrossServers(createApplicationRequest.isLoadBalanceAcrossServers());
    jpaApp.setUnpackWar(createApplicationRequest.isUnpackWar());

    try {
        return create(jpaApp);
    } catch (final EntityExistsException eee) {
        LOGGER.error("Error creating app with request {} in group {}", createApplicationRequest, jpaGroup, eee);
        throw new EntityExistsException("App already exists: " + createApplicationRequest, eee);
    }
}
 
Example #7
Source File: OvsTunnelManagerImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@DB
protected OvsTunnelNetworkVO createTunnelRecord(long from, long to, long networkId, int key) {
    OvsTunnelNetworkVO ta = null;
    try {
        ta = new OvsTunnelNetworkVO(from, to, key, networkId);
        OvsTunnelNetworkVO lock = _tunnelNetworkDao.acquireInLockTable(Long.valueOf(1));
        if (lock == null) {
            s_logger.warn("Cannot lock table ovs_tunnel_account");
            return null;
        }
        _tunnelNetworkDao.persist(ta);
        _tunnelNetworkDao.releaseFromLockTable(lock.getId());
    } catch (EntityExistsException e) {
        s_logger.debug("A record for the tunnel from " + from + " to " + to + " already exists");
    }
    return ta;
}
 
Example #8
Source File: CiscoVnmcElement.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public CiscoAsa1000vDevice addCiscoAsa1000vResource(AddCiscoAsa1000vResourceCmd cmd) {
    Long physicalNetworkId = cmd.getPhysicalNetworkId();
    CiscoAsa1000vDevice ciscoAsa1000vResource = null;

    PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
    }

    ciscoAsa1000vResource = new CiscoAsa1000vDeviceVO(physicalNetworkId, cmd.getManagementIp().trim(), cmd.getInPortProfile(), cmd.getClusterId());
    try {
        _ciscoAsa1000vDao.persist((CiscoAsa1000vDeviceVO)ciscoAsa1000vResource);
    } catch (EntityExistsException e) {
        throw new InvalidParameterValueException("An ASA 1000v appliance already exists with same configuration");
    }

    return ciscoAsa1000vResource;
}
 
Example #9
Source File: WebServerCrudServiceImpl.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
public WebServer updateWebServer(final WebServer webServer, final String createdBy) {
    try {
        final JpaWebServer jpaWebServer = findById(webServer.getId().getId());

        jpaWebServer.setName(webServer.getName());
        jpaWebServer.setHost(webServer.getHost());
        jpaWebServer.setPort(webServer.getPort());
        jpaWebServer.setHttpsPort(webServer.getHttpsPort());
        jpaWebServer.setStatusPath(webServer.getStatusPath().getPath());
        jpaWebServer.setCreateBy(createdBy);

        return webServerFrom(update(jpaWebServer));
    } catch (final EntityExistsException eee) {
        LOGGER.error("Error updating web server {}", webServer, eee);
        throw new EntityExistsException("Web Server Name already exists", eee);
    }
}
 
Example #10
Source File: WebServerCrudServiceImpl.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
public WebServer createWebServer(final WebServer webServer, final String createdBy) {
    try {
        final JpaWebServer jpaWebServer = new JpaWebServer();

        jpaWebServer.setName(webServer.getName());
        jpaWebServer.setHost(webServer.getHost());
        jpaWebServer.setPort(webServer.getPort());
        jpaWebServer.setHttpsPort(webServer.getHttpsPort());
        jpaWebServer.setStatusPath(webServer.getStatusPath().getPath());
        jpaWebServer.setCreateBy(createdBy);
        jpaWebServer.setState(webServer.getState());
        jpaWebServer.setApacheHttpdMedia(webServer.getApacheHttpdMedia() == null ? null : new ModelMapper()
                .map(webServer.getApacheHttpdMedia(), JpaMedia.class));

        return webServerFrom(create(jpaWebServer));
    } catch (final EntityExistsException eee) {
        LOGGER.error("Error creating web server {}", webServer, eee);
        throw new EntityExistsException("Web server with name already exists: " + webServer,
                eee);
    }

}
 
Example #11
Source File: DeleteServicePackageOfferingCmd.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws ServerApiException, ConcurrentOperationException, EntityExistsException {
    SuccessResponse response = new SuccessResponse();
    try {
        boolean result = _netsclarLbService.deleteServicePackageOffering(this);

        if (response != null && result) {
            response.setDisplayText("Deleted Successfully");
            response.setSuccess(result);
            response.setResponseName(getCommandName());
            this.setResponseObject(response);
        }
    } catch (CloudRuntimeException runtimeExcp) {
        response.setDisplayText(runtimeExcp.getMessage());
        response.setSuccess(false);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
        return;
    } catch (Exception e) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Service Package due to internal error.");
    }
}
 
Example #12
Source File: DeleteNetscalerControlCenterCmd.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws ServerApiException, ConcurrentOperationException, EntityExistsException {
    SuccessResponse response = new SuccessResponse();
    try {
        boolean result = _netsclarLbService.deleteNetscalerControlCenter(this);
        if (response != null && result) {
            response.setDisplayText("Netscaler Control Center Deleted Successfully");
            response.setSuccess(result);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        }
    } catch (CloudRuntimeException runtimeExcp) {
        response.setDisplayText(runtimeExcp.getMessage());
        response.setSuccess(false);
        response.setResponseName(getCommandName());
        setResponseObject(response);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
 
Example #13
Source File: XcpServerDiscoverer.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
void setClusterGuid(ClusterVO cluster, String guid) {
    cluster.setGuid(guid);
    try {
        _clusterDao.update(cluster.getId(), cluster);
    } catch (EntityExistsException e) {
        QueryBuilder<ClusterVO> sc = QueryBuilder.create(ClusterVO.class);
        sc.and(sc.entity().getGuid(), Op.EQ, guid);
        List<ClusterVO> clusters = sc.list();
        ClusterVO clu = clusters.get(0);
        List<HostVO> clusterHosts = _resourceMgr.listAllHostsInCluster(clu.getId());
        if (clusterHosts == null || clusterHosts.size() == 0) {
            clu.setGuid(null);
            _clusterDao.update(clu.getId(), clu);
            _clusterDao.update(cluster.getId(), cluster);
            return;
        }
        throw e;
    }
}
 
Example #14
Source File: RestServiceExceptionMapper.java    From syncope with Apache License 2.0 6 votes vote down vote up
private String getPersistenceErrorMessage(final Throwable ex) {
    Throwable throwable = ExceptionUtils.getRootCause(ex);

    String message = null;
    if (throwable instanceof SQLException) {
        String messageKey = EXCEPTION_CODE_MAP.get(((SQLException) throwable).getSQLState());
        if (messageKey != null) {
            message = env.getProperty("errMessage." + messageKey);
        }
    } else if (throwable instanceof EntityExistsException || throwable instanceof DuplicateException) {
        message = env.getProperty("errMessage." + UNIQUE_MSG_KEY);
    }

    return Optional.ofNullable(message)
        .orElseGet(() -> (ex.getCause() == null) ? ex.getMessage() : ex.getCause().getMessage());
}
 
Example #15
Source File: PlainSchemaTest.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void checkIdUniqueness() {
    assertNotNull(derSchemaDAO.find("cn"));

    PlainSchema schema = entityFactory.newEntity(PlainSchema.class);
    schema.setKey("cn");
    schema.setType(AttrSchemaType.String);
    plainSchemaDAO.save(schema);

    try {
        entityManager().flush();
        fail("This should not happen");
    } catch (Exception e) {
        assertTrue(e instanceof EntityExistsException || e.getCause() instanceof EntityExistsException);
    }
}
 
Example #16
Source File: ReportTest.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void saveWithExistingName() {
    assertThrows(EntityExistsException.class, () -> {
        Report report = reportDAO.find("0062ea9c-924d-4ecf-9961-4492a8cc6d1b");
        assertNotNull(report);

        String name = report.getName();

        report = entityFactory.newEntity(Report.class);
        report.setName(name);
        report.setActive(true);
        report.setTemplate(reportTemplateDAO.find("sample"));

        reportDAO.save(report);
        entityManager().flush();
    });
}
 
Example #17
Source File: JPAMailboxMapper.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Commit the transaction. If the commit fails due a conflict in a unique key constraint a {@link MailboxExistsException}
 * will get thrown
 */
@Override
protected void commit() throws MailboxException {
    try {
        getEntityManager().getTransaction().commit();
    } catch (PersistenceException e) {
        if (e instanceof EntityExistsException) {
            throw new MailboxExistsException(lastMailboxName);
        }
        if (e instanceof RollbackException) {
            Throwable t = e.getCause();
            if (t instanceof EntityExistsException) {
                throw new MailboxExistsException(lastMailboxName);
            }
        }
        throw new MailboxException("Commit of transaction failed", e);
    }
}
 
Example #18
Source File: GreetingServiceTest.java    From spring-boot-fundamentals with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithId() {

    Exception exception = null;

    Greeting entity = new Greeting();
    entity.setId(Long.MAX_VALUE);
    entity.setText("test");

    try {
        service.create(entity);
    } catch (EntityExistsException e) {
        exception = e;
    }

    Assert.assertNotNull("failure - expected exception", exception);
    Assert.assertTrue("failure - expected EntityExistsException",
            exception instanceof EntityExistsException);

}
 
Example #19
Source File: GroupServiceRestImpl.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
public Response updateGroup(final JsonUpdateGroup anUpdatedGroup,
                            final AuthenticatedUser aUser) {
    LOGGER.info("Update Group requested: {} by user {}", anUpdatedGroup, aUser.getUser().getId());
    try {
        // TODO: Refactor adhoc conversion to process group name instead of Id.
        final Group group = groupService.getGroup(anUpdatedGroup.getId());
        final JsonUpdateGroup updatedGroup = new JsonUpdateGroup(group.getId().getId().toString(),
                anUpdatedGroup.getName());

        return ResponseBuilder.ok(groupService.updateGroup(updatedGroup.toUpdateGroupCommand(),
                aUser.getUser()));
    } catch (EntityExistsException eee) {
        LOGGER.error("Group Name already exists: {}", anUpdatedGroup.getName(), eee);
        return ResponseBuilder.notOk(Response.Status.INTERNAL_SERVER_ERROR, new FaultCodeException(
                FaultType.DUPLICATE_GROUP_NAME, eee.getMessage(), eee));
    }
}
 
Example #20
Source File: GreetingServiceTest.java    From spring-data-fundamentals with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithId() {

    Exception exception = null;

    Greeting entity = new Greeting();
    entity.setId(Long.MAX_VALUE);
    entity.setText("test");

    try {
        service.create(entity);
    } catch (EntityExistsException e) {
        exception = e;
    }

    Assert.assertNotNull("failure - expected exception", exception);
    Assert.assertTrue("failure - expected EntityExistsException",
            exception instanceof EntityExistsException);

}
 
Example #21
Source File: GroupServiceImpl.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public Group createGroup(final CreateGroupRequest createGroupRequest,
                         final User aCreatingUser) {
    createGroupRequest.validate();
    try {
        groupPersistenceService.getGroup(createGroupRequest.getGroupName());
        String message = MessageFormat.format("Group Name already exists: {0} ", createGroupRequest.getGroupName());
        LOGGER.error(message);
        throw new EntityExistsException(message);
    } catch (NotFoundException e) {
        LOGGER.debug("No group name conflict, ignoring not found exception for creating group ", e);
    }

    return groupPersistenceService.createGroup(createGroupRequest);
}
 
Example #22
Source File: GroupServiceImpl.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public Group updateGroup(final UpdateGroupRequest anUpdateGroupRequest,
                         final User anUpdatingUser) {
    anUpdateGroupRequest.validate();
    Group orginalGroup = getGroup(anUpdateGroupRequest.getId());
    try {
        if (!orginalGroup.getName().equalsIgnoreCase(anUpdateGroupRequest.getNewName()) && null != groupPersistenceService.getGroup(anUpdateGroupRequest.getNewName())) {
            String message = MessageFormat.format("Group Name already exists: {0}", anUpdateGroupRequest.getNewName());
            LOGGER.error(message);
            throw new EntityExistsException(message);
        }
    } catch (NotFoundException e) {
        LOGGER.debug("No group name conflict, ignoring not found exception for creating group ", e);
    }
    return groupPersistenceService.updateGroup(anUpdateGroupRequest);
}
 
Example #23
Source File: XcpServerDiscoverer.java    From cosmic with Apache License 2.0 6 votes vote down vote up
void setClusterGuid(final ClusterVO cluster, final String guid) {
    cluster.setGuid(guid);
    try {
        this._clusterDao.update(cluster.getId(), cluster);
    } catch (final EntityExistsException e) {
        final QueryBuilder<ClusterVO> sc = QueryBuilder.create(ClusterVO.class);
        sc.and(sc.entity().getGuid(), Op.EQ, guid);
        final List<ClusterVO> clusters = sc.list();
        final ClusterVO clu = clusters.get(0);
        final List<HostVO> clusterHosts = this._resourceMgr.listAllHostsInCluster(clu.getId());
        if (clusterHosts == null || clusterHosts.size() == 0) {
            clu.setGuid(null);
            this._clusterDao.update(clu.getId(), clu);
            this._clusterDao.update(cluster.getId(), cluster);
            return;
        }
        throw e;
    }
}
 
Example #24
Source File: FolderDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createFolder(Folder pFolder) throws FolderAlreadyExistsException, CreationException{
    try{
        //the EntityExistsException is thrown only when flush occurs          
        em.persist(pFolder);
        em.flush();
    }catch(EntityExistsException pEEEx){
        LOGGER.log(Level.FINEST,null,pEEEx);
        throw new FolderAlreadyExistsException(pFolder);
    }catch(PersistenceException pPEx){
        //EntityExistsException is case sensitive
        //whereas MySQL is not thus PersistenceException could be
        //thrown instead of EntityExistsException
        LOGGER.log(Level.FINEST,null,pPEx);
        throw new CreationException();
    }
}
 
Example #25
Source File: OrganizationDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createOrganization(Organization pOrganization) throws OrganizationAlreadyExistsException, CreationException {
    try {
        //the EntityExistsException is thrown only when flush occurs
        if (pOrganization.getName().trim().equals(""))
            throw new CreationException();
        em.persist(pOrganization);
        em.flush();
    } catch (EntityExistsException pEEEx) {
        throw new OrganizationAlreadyExistsException(pOrganization);
    } catch (PersistenceException pPEx) {
        //EntityExistsException is case sensitive
        //whereas MySQL is not thus PersistenceException could be
        //thrown instead of EntityExistsException
        throw new CreationException();
    }
}
 
Example #26
Source File: PathToPathLinkDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createPathToPathLink(PathToPathLink pPathToPathLink) throws CreationException, PathToPathLinkAlreadyExistsException {

        try {
            //the EntityExistsException is thrown only when flush occurs
            em.persist(pPathToPathLink);
            em.flush();
        } catch (EntityExistsException pEEEx) {
            LOGGER.log(Level.FINEST,null,pEEEx);
            throw new PathToPathLinkAlreadyExistsException(pPathToPathLink);
        } catch (PersistenceException pPEx) {
            LOGGER.log(Level.FINEST,null,pPEx);
            //EntityExistsException is case sensitive
            //whereas MySQL is not thus PersistenceException could be
            //thrown instead of EntityExistsException
            throw new CreationException();
        }
    }
 
Example #27
Source File: TagDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createTag(Tag pTag, boolean silent) throws CreationException, TagAlreadyExistsException {
    try {
        //the EntityExistsException is thrown only when flush occurs
        em.persist(pTag);
        em.flush();
    } catch (EntityExistsException pEEEx) {
        if(!silent) {
            throw new TagAlreadyExistsException(pTag);
        }
    } catch (PersistenceException pPEx) {
        //EntityExistsException is case sensitive
        //whereas MySQL is not thus PersistenceException could be
        //thrown instead of EntityExistsException
        if(!silent) {
            throw new CreationException();
        }
    }
}
 
Example #28
Source File: QueryDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createQuery(Query query) throws CreationException, QueryAlreadyExistsException {
    try {

        QueryRule queryRule = query.getQueryRule();

        if (queryRule != null) {
            persistQueryRules(queryRule);
        }

        QueryRule pathDataQueryRule = query.getPathDataQueryRule();

        if (pathDataQueryRule != null) {
            persistQueryRules(pathDataQueryRule);
        }

        em.persist(query);
        em.flush();
        persistContexts(query, query.getContexts());
    } catch (EntityExistsException pEEEx) {
        LOGGER.log(Level.FINEST, null, pEEEx);
        throw new QueryAlreadyExistsException(query);
    } catch (PersistenceException pPEx) {
        LOGGER.log(Level.FINEST, null, pPEx);
        throw new CreationException();
    }
}
 
Example #29
Source File: GreetingServiceTest.java    From spring-security-fundamentals with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithId() {

    Exception exception = null;

    Greeting entity = new Greeting();
    entity.setId(Long.MAX_VALUE);
    entity.setText("test");

    try {
        service.create(entity);
    } catch (EntityExistsException e) {
        exception = e;
    }

    Assert.assertNotNull("failure - expected exception", exception);
    Assert.assertTrue("failure - expected EntityExistsException",
            exception instanceof EntityExistsException);

}
 
Example #30
Source File: PersonInsertRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenEntityExistsExceptionIsThrown() {
    assertThatExceptionOfType(EntityExistsException.class).isThrownBy(() -> {
        insertPersonWithEntityManager();
        insertPersonWithEntityManager();
    });
}