类javax.persistence.EntityExistsException源码实例Demo

下面列出了怎么用javax.persistence.EntityExistsException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: syndesis   文件: DataManager.java
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());
            }
        }
    }
}
 
源代码2 项目: jwala   文件: WebServerCrudServiceImpl.java
@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);
    }

}
 
源代码3 项目: jwala   文件: WebServerCrudServiceImpl.java
@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);
    }
}
 
源代码4 项目: jwala   文件: ApplicationCrudServiceImpl.java
@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);
    }
}
 
源代码5 项目: jwala   文件: ApplicationCrudServiceImpl.java
@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());
    }
}
 
源代码6 项目: jwala   文件: ApplicationCrudServiceImplTest.java
@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);
        }
    }

}
 
源代码7 项目: jwala   文件: GroupServiceRestImpl.java
@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));
    }
}
 
源代码8 项目: jwala   文件: GroupServiceImpl.java
@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);
}
 
源代码9 项目: jwala   文件: GroupServiceImpl.java
@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);
}
 
源代码10 项目: eplmp   文件: FolderDAO.java
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();
    }
}
 
源代码11 项目: eplmp   文件: PathToPathLinkDAO.java
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();
        }
    }
 
源代码12 项目: eplmp   文件: DocumentMasterDAO.java
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();
    }
}
 
源代码13 项目: eplmp   文件: QueryDAO.java
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();
    }
}
 
源代码14 项目: eplmp   文件: TagDAO.java
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();
        }
    }
}
 
源代码15 项目: eplmp   文件: OrganizationDAO.java
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();
    }
}
 
源代码16 项目: cosmic   文件: XcpServerDiscoverer.java
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;
    }
}
 
@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);

}
 
@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);

}
 
源代码19 项目: james-project   文件: JPAMailboxMapper.java
/**
 * 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);
    }
}
 
@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);

}
 
源代码21 项目: syncope   文件: ReportTest.java
@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();
    });
}
 
源代码22 项目: syncope   文件: PlainSchemaTest.java
@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);
    }
}
 
源代码23 项目: syncope   文件: RestServiceExceptionMapper.java
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());
}
 
源代码24 项目: cloudstack   文件: XcpServerDiscoverer.java
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;
    }
}
 
源代码25 项目: cloudstack   文件: OvsTunnelManagerImpl.java
@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;
}
 
源代码26 项目: cloudstack   文件: OvsTunnelManagerImpl.java
@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;
}
 
源代码27 项目: cloudstack   文件: CiscoVnmcElement.java
@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;
}
 
@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.");
    }
}
 
@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());
    }
}
 
/**
 * This inserts a new entity into App Engine datastore. If the entity already
 * exists in the datastore, an exception is thrown.
 * It uses HTTP POST method.
 *
 * @param deviceinfo the entity to be inserted.
 * @return The inserted entity.
 */
@ApiMethod(name = "insertDeviceInfo")
public DeviceInfo insertDeviceInfo(DeviceInfo deviceinfo) {
  EntityManager mgr = getEntityManager();
  try {
    if (containsDeviceInfo(deviceinfo)) {
      throw new EntityExistsException("Object already exists");
    }
    mgr.persist(deviceinfo);
  } finally {
    mgr.close();
  }
  return deviceinfo;
}
 
 类所在包
 同包方法