Java 类javax.persistence.EntityNotFoundException 实例源码

项目:syndesis    文件:DataManager.java   
public <T extends WithId<T>> void update(T entity) {
    Optional<String> id = entity.getId();
    if (!id.isPresent()) {
        throw new EntityNotFoundException("Setting the id on the entity is required for updates");
    }

    String idVal = id.get();

    Kind kind = entity.getKind();
    T previous = this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.update(entity));

    Map<String, T> cache = caches.getCache(kind.getModelName());
    if (!cache.containsKey(idVal) && previous==null) {
        throw new EntityNotFoundException("Can not find " + kind + " with id " + idVal);
    }

    cache.put(idVal, entity);
    broadcast("updated", kind.getModelName(), idVal);

    //TODO 1. properly merge the data ? + add data validation in the REST Resource
}
项目:syndesis    文件:DataManager.java   
public <T extends WithId<T>> boolean delete(Class<T> model, String id) {
    if (id == null || id.equals("")) {
        throw new EntityNotFoundException("Setting the id on the entity is required for updates");
    }

    Kind kind = Kind.from(model);
    Map<String, WithId<T>> cache = caches.getCache(kind.getModelName());

    // Remove it out of the cache
    WithId<T> entity = cache.remove(id);
    boolean deletedInCache = entity != null;

    // And out of the DAO
    boolean deletedFromDAO = Boolean.TRUE.equals(doWithDataAccessObject(model, d -> d.delete(id)));

    // Return true if the entity was found in any of the two.
    if ( deletedInCache || deletedFromDAO ) {
        broadcast("deleted", kind.getModelName(), id);
        return true;
    }

    return false;
}
项目:syndesis    文件:IntegrationHandler.java   
@Override
public Integration get(String id) {
    Integration integration = Getter.super.get(id);

    if (Status.Deleted.equals(integration.getCurrentStatus().get()) ||
        Status.Deleted.equals(integration.getDesiredStatus().get())) {
        //Not sure if we need to do that for both current and desired status,
        //but If we don't do include the desired state, IntegrationITCase is not going to pass anytime soon. Why?
        //Cause that test, is using NoopHandlerProvider, so that means no controllers.
        throw new EntityNotFoundException(String.format("Integration %s has been deleted", integration.getId()));
    }

    //fudging the timesUsed for now
    Optional<Status> currentStatus = integration.getCurrentStatus();
    if (currentStatus.isPresent() && currentStatus.get() == Integration.Status.Activated) {
        return new Integration.Builder()
                .createFrom(integration)
                .timesUsed(BigInteger.valueOf(new Date().getTime()/1000000))
                .build();
    }

    return integration;
}
项目:syndesis    文件:BaseConnectorGeneratorHandler.java   
final <T> T withGeneratorAndTemplate(final String templateId,
    final BiFunction<ConnectorGenerator, ConnectorTemplate, T> callback) {
    final ConnectorTemplate connectorTemplate = getDataManager().fetch(ConnectorTemplate.class, templateId);

    if (connectorTemplate == null) {
        throw new EntityNotFoundException("Connector template: " + templateId);
    }

    final ConnectorGenerator connectorGenerator = context.getBean(templateId, ConnectorGenerator.class);
    if (connectorGenerator == null) {
        throw new EntityNotFoundException(
            "Unable to find connector generator for connector template with id: " + templateId);
    }

    return callback.apply(connectorGenerator, connectorTemplate);
}
项目:oscm    文件:CategorizationServiceBean.java   
/**
 * @param toBeDeleted
 * @throws OperationNotPermittedException
 * @throws ObjectNotFoundException
 */
private void deleteCategories(List<VOCategory> toBeDeleted)
        throws OperationNotPermittedException, ObjectNotFoundException {
    final Organization currentOrg = dm.getCurrentUser().getOrganization();
    final Query marketplaceQuery = dm
            .createNamedQuery("Marketplace.findByBusinessKey");
    for (VOCategory voCategory : toBeDeleted) {
        final Category category = dm.getReference(Category.class,
                voCategory.getKey());
        try {
            marketplaceQuery.setParameter("marketplaceId", category
                    .getMarketplace().getMarketplaceId());
        } catch (EntityNotFoundException e) {
            throw new ObjectNotFoundException(ClassEnum.MARKETPLACE,
                    voCategory.getMarketplaceId());
        }
        final Marketplace marketplace = (Marketplace) marketplaceQuery
                .getSingleResult();
        PermissionCheck.owns(marketplace, currentOrg, logger, null);
        List<PlatformUser> usersToBeNotified = collectUsersToBeNotified(category);
        prefetchRequiredObject(category);
        dm.remove(category);
        sendNotification(category, usersToBeNotified);
    }
}
项目:lams    文件:SessionImpl.java   
@Override
public final Object load() {
    final Serializable entityId = resolveNaturalId( this.naturalIdParameters );
    if ( entityId == null ) {
        return null;
    }
    try {
        return this.getIdentifierLoadAccess().load( entityId );
    }
    catch (EntityNotFoundException enf) {
        // OK
    }
    catch (ObjectNotFoundException nf) {
        // OK
    }
    return null;
}
项目:lams    文件:SessionImpl.java   
@Override
public Object load(Object naturalIdValue) {
    final Serializable entityId = resolveNaturalId( getNaturalIdParameters( naturalIdValue ) );
    if ( entityId == null ) {
        return null;
    }
    try {
        return this.getIdentifierLoadAccess().load( entityId );
    }
    catch (EntityNotFoundException enf) {
        // OK
    }
    catch (ObjectNotFoundException nf) {
        // OK
    }
    return null;
}
项目:gitplex-mit    文件:RequestDetailPage.java   
public RequestDetailPage(PageParameters params) {
    super(params);

    if (getProject().getDefaultBranch() == null) 
        throw new RestartResponseException(NoBranchesPage.class, paramsOf(getProject()));

    requestModel = new LoadableDetachableModel<PullRequest>() {

        @Override
        protected PullRequest load() {
            Long requestNumber = params.get(PARAM_REQUEST).toLong();
            PullRequest request = GitPlex.getInstance(PullRequestManager.class).find(getProject(), requestNumber);
            if (request == null)
                throw new EntityNotFoundException("Unable to find request #" + requestNumber + " in project " + getProject());
            return request;
        }

    };

    reviewUpdateId = requestModel.getObject().getLatestUpdate().getId();
}
项目:git-rekt    文件:ResetEmployeePasswordDialogController.java   
/**
 * Handles the actual act of changing the user's password.
 *
 * @param newPassword The password, which should be already validated.
 */
private void changePassword(String newPassword) {
    // Ensure that we have an employee to change the password for
    if(this.employeeId == null) {
        throw new IllegalStateException("Must initialize employeeId");
    }

    EmployeeService employeeService = new EmployeeService();
    Employee employee = employeeService.getEmployeeById(this.employeeId);
    try {
        employee.setPassword(newPassword);
        employeeService.updateEmployee(employee);
    } catch (EntityNotFoundException e) {
        // TODO
    }
}
项目:git-rekt    文件:EmployeeService.java   
/**
 * Performs authentication on the provided employee.
 *
 * @param employeeId The id number of the employee to authenticate.
 *
 * @param plaintextPassword The plaintext password of the employee.
 *
 * @return The appropriate authenticationResult enum type.
 */
public AuthenticationResult authenticate(Long employeeId, String plaintextPassword) {
    Employee employee = getEmployeeById(employeeId);
    String hashed; // The encrypted (hashed) password of the employee.
    try {
        hashed = employee.getHashedPassword();
    } catch (EntityNotFoundException e) {
        return AuthenticationResult.FAILURE;
    }

    boolean passwordCorrect = BCrypt.checkpw(plaintextPassword, hashed);
    if(passwordCorrect) {
        return AuthenticationResult.SUCCESS;
    } else {
        return AuthenticationResult.FAILURE;
    }
}
项目:bootstrap    文件:ApiTokenResource.java   
/**
 * Update a named token with a new generated one.
 * 
 * @param name
 *            Token to update.
 * @return the new generated token.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{name:[\\w\\-\\.]+}")
public String update(@PathParam("name") final String name) throws GeneralSecurityException {
    final SystemApiToken entity = repository.findByUserAndName(securityHelper.getLogin(), name);
    if (entity == null) {
        // No token with given name
        throw new EntityNotFoundException();
    }

    // Token has been found, update it
    final String token = newToken(entity);
    repository.saveAndFlush(entity);
    return token;
}
项目:dev_backend    文件:RvepEventItemService.java   
@Override
public List<RvepEventItem> getAllEventItems(String eventProfileId, String email) {
    // get user id
    RvepUser user = this.rvepUserProfileDAO.findByEmail(email).getRvepUser();

    // get event
    RvepEvent event = rvepEventProfileDAO
            .findById(Integer.valueOf(eventProfileId).intValue())
            .getRvepEvent();

    // get user event roles
    List<RvepUserEventRole> rvepUserEventRoles = this.rvepUserEventRoleDAO
            .findByRvepUserIdAndRvepEventId(user.getId(), event.getId());

    // check if user has roles for the event
    if (rvepUserEventRoles.size() > 0) {
        return this.rvepEventItemDAO.findByRvepEventId(event.getId());
    }

    // no access found, throw exception
    throw new EntityNotFoundException();
}
项目:oma-riista-web    文件:Person.java   
@Nonnull
public LocalisedString getHomeMunicipalityName() {
    if (this.homeMunicipality != null) {
        if (!Hibernate.isInitialized(this.homeMunicipality)) {
            try {
                // Referenced row might not exist
                return this.homeMunicipality.getNameLocalisation();
            } catch (UnresolvableObjectException | EntityNotFoundException o) {
                this.homeMunicipality = null;
            }
        } else {
            return this.homeMunicipality.getNameLocalisation();
        }
    }
    return LocalisedString.EMPTY;
}
项目:comics-blog    文件:ComicBookController.java   
@RequestMapping(value = {"/{id}"},
        consumes = {"application/json"},
        produces = {"application/json; charset=UTF-8"},
        method = RequestMethod.PUT)
@ResponseBody
public Object putComicBook(@PathVariable("id") Long id, @RequestBody ComicBookWebDTO dto, HttpServletResponse httpResponse) throws ExecutionException, InterruptedException {
    ComicBookEntity entity = service.findById(id);
    if (entity != null) {
        converter.updateEntity(entity, dto);
        try {
            ComicBookEntity result = service.update(entity);
            httpResponse.setDateHeader(HttpHeaders.LAST_MODIFIED, result.getUpdated().getTime());
            return converter.convertEntity(result);
        } catch (EntityNotFoundException e) {
            LOGGER.warn("Can't modify the resource: " + entity, e);
            httpResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    } else {
        httpResponse.setStatus(HttpStatus.NOT_FOUND.value());
        return null;
    }
}
项目:comics-blog    文件:ComicBookController.java   
@RequestMapping(value = {"/{id}"}, method = RequestMethod.DELETE)
@ResponseBody
public Object deleteComicBook(@PathVariable(value = "id") Long id, HttpServletResponse httpResponse) {
    ComicBookEntity entity = service.findById(id);
    if (entity != null) {
        try {
            service.delete(id);
        } catch (EntityNotFoundException e) {
            LOGGER.warn("Can't delete the resource: " + entity, e);
            httpResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        httpResponse.setStatus(HttpStatus.NO_CONTENT.value());
    } else {
        httpResponse.setStatus(HttpStatus.NOT_FOUND.value());
    }
    return null;
}
项目:syndesis-rest    文件:DataManager.java   
public <T extends WithId<T>> void update(T entity) {
    Optional<String> id = entity.getId();
    if (!id.isPresent()) {
        throw new EntityNotFoundException("Setting the id on the entity is required for updates");
    }

    String idVal = id.get();

    Kind kind = entity.getKind();
    T previous = this.<T, T>doWithDataAccessObject(kind.getModelClass(), d -> d.update(entity));

    Map<String, T> cache = caches.getCache(kind.getModelName());
    if (!cache.containsKey(idVal) && previous==null) {
        throw new EntityNotFoundException("Can not find " + kind + " with id " + idVal);
    }

    cache.put(idVal, entity);
    broadcast("updated", kind.getModelName(), idVal);

    //TODO 1. properly merge the data ? + add data validation in the REST Resource
}
项目:syndesis-rest    文件:DataManager.java   
public <T extends WithId<T>> boolean delete(Class<T> model, String id) {
    if (id == null || id.equals("")) {
        throw new EntityNotFoundException("Setting the id on the entity is required for updates");
    }

    Kind kind = Kind.from(model);
    Map<String, WithId<T>> cache = caches.getCache(kind.getModelName());

    // Remove it out of the cache
    WithId<T> entity = cache.remove(id);
    boolean deletedInCache = entity != null;

    // And out of the DAO
    boolean deletedFromDAO = Boolean.TRUE.equals(doWithDataAccessObject(model, d -> d.delete(id)));

    // Return true if the entity was found in any of the two.
    if ( deletedInCache || deletedFromDAO ) {
        broadcast("deleted", kind.getModelName(), id);
        return true;
    }

    return false;
}
项目:syndesis-rest    文件:IntegrationHandler.java   
@Override
public Integration get(String id) {
    Integration integration = Getter.super.get(id);

    if (Status.Deleted.equals(integration.getCurrentStatus().get()) ||
        Status.Deleted.equals(integration.getDesiredStatus().get())) {
        //Not sure if we need to do that for both current and desired status,
        //but If we don't do include the desired state, IntegrationITCase is not going to pass anytime soon. Why?
        //Cause that test, is using NoopHandlerProvider, so that means no controllers.
        throw new EntityNotFoundException(String.format("Integration %s has been deleted", integration.getId()));
    }

    //fudging the timesUsed for now
    Optional<Status> currentStatus = integration.getCurrentStatus();
    if (currentStatus.isPresent() && currentStatus.get() == Integration.Status.Activated) {
        return new Integration.Builder()
                .createFrom(integration)
                .timesUsed(BigInteger.valueOf(new Date().getTime()/1000000))
                .build();
    }

    return integration;
}
项目:syndesis-rest    文件:ConnectorHandler.java   
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes("application/json")
@Path("/{connector-template-id}")
public Connector create(@NotNull @PathParam("connector-template-id") final String connectorTemplateId, final Connector template) {
    final ConnectorTemplate connectorTemplate = getDataManager().fetch(ConnectorTemplate.class, connectorTemplateId);

    if (connectorTemplate == null) {
        throw new EntityNotFoundException("Connector template: " + connectorTemplateId);
    }

    final ConnectorGenerator connectorGenerator = applicationContext.getBean(connectorTemplateId, ConnectorGenerator.class);

    final Connector connector = connectorGenerator.generate(connectorTemplate, template);

    return getDataManager().create(connector);
}
项目:java-persistence    文件:Index.java   
/**
 * Obtain a specific item, but instead of returning null, throw EntityNotFoundException
 *
 * NOTE: This only works on "main" indexes.
 *
 * @param hk is the hash key.
 *
 * @param rk is the range key.
 *
 * @return the item with this primary key, never returns null.
 *
 * @throws EntityNotFoundException if no such item exists.
 */
public default T getItemOrThrow(Object hk, Object rk) throws EntityNotFoundException {
    T result = getItem(hk, rk);
    if ( null == result ) {
        StringBuilder sb = new StringBuilder()
            .append("Item in '")
            .append(getTableName())
            .append("' not found with ")
            .append(getHashKeyName())
            .append("='")
            .append(hk.toString())
            .append("'");
        if ( null != getRangeKeyName() ) {
            sb.append(" and ")
                .append(getRangeKeyName())
                .append("='")
                .append(rk.toString())
                .append("'");
        }
        throw new EntityNotFoundException(sb.toString());
    }
    return result;
}
项目:discoursedb-core    文件:LightSideDataExport.java   
@Override
@Transactional 
public void run(String... args) throws Exception {
    String discourseName = args[0];
    Assert.hasText(discourseName, "Discourse name cannot be empty.");

    String outputFilePath = args[1];
    Assert.hasText(outputFilePath, "Path to the output file cannot be empty.");     

    File outputFile = new File(outputFilePath);
    Assert.isTrue(!outputFile.isDirectory(), outputFilePath+" points to a Directory but should point to a file.");

    DiscoursePartTypes dptype = DiscoursePartTypes.THREAD;
    if(args.length==3){
        dptype = DiscoursePartTypes.valueOf(args[2]);
    }

    Discourse discourse = discourseService.findOne(discourseName).orElseThrow(() -> new EntityNotFoundException("Discourse with name " + discourseName + " does not exist."));

    for(DiscoursePart dp: discoursePartService.findAllByDiscourseAndType(discourse, dptype)){
        lsService.exportDataForAnnotation(outputFilePath, dp);
    }           
}
项目:discoursedb-core    文件:BratExport.java   
@Override
@Transactional 
public void run(String... args) throws Exception {
    String discourseName = args[0];
    String outputFolder = args[1];

    String dpType = "THREAD";
    if(args.length==3){
        dpType=args[2].toUpperCase();
    }

    Discourse discourse = discourseService.findOne(discourseName).orElseThrow(() -> new EntityNotFoundException("Discourse with name " + discourseName + " does not exist."));

    for(DiscoursePart dp: discoursePartService.findAllByDiscourseAndType(discourse, DiscoursePartTypes.valueOf(dpType))){
        bratService.exportDiscoursePart(dp, outputFolder);
    }   
}
项目:java-tutorials    文件:CustomerJpaController.java   
public void destroy(long id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Customer customer;
        try {
            customer = em.getReference(Customer.class, id);
            customer.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The customer with id " + id + " no longer exists.", enfe);
        }
        em.remove(customer);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:java-tutorials    文件:UsersJpaController.java   
public void destroy(String id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Users users;
        try {
            users = em.getReference(Users.class, id);
            users.getUsername();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The users with id " + id + " no longer exists.", enfe);
        }
        em.remove(users);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:europa    文件:RegistryBlobDb.java   
public void addPart(String blobId, int partIndex, RegistryBlobPart partId, byte[] oldMDState, byte[] newMDState)
    throws EntityNotFoundException, ConcurrentModificationException
{
    try {
        _main.updateItem(blobId, null)
            .listSet(ATTR_PART_IDS, partIndex, AttrType.MAP, partId)
            .set(ATTR_MD_ENCODED_STATE, AttrType.BIN, newMDState)
            .when((expr) -> expr.and(
                      expr.exists(ATTR_BLOB_ID),
                      ( null == oldMDState )
                      ? expr.not(expr.exists(ATTR_MD_ENCODED_STATE))
                      : expr.eq(ATTR_MD_ENCODED_STATE, oldMDState)));
    } catch ( RollbackException ex ) {
        // Doesn't exist, then throw EntityNotFoundException?
        RegistryBlob blob = _main.getItemOrThrow(blobId, null);
        throw new ConcurrentModificationException(
            "Expected mdState="+(null==oldMDState?"null":printHexBinary(oldMDState))+", but got="+
            (null == blob.getMdEncodedState()?"null":printHexBinary(blob.getMdEncodedState())));
    }
}
项目:development    文件:CategorizationServiceBean.java   
/**
 * @param toBeDeleted
 * @throws OperationNotPermittedException
 * @throws ObjectNotFoundException
 */
private void deleteCategories(List<VOCategory> toBeDeleted)
        throws OperationNotPermittedException, ObjectNotFoundException {
    final Organization currentOrg = dm.getCurrentUser().getOrganization();
    final Query marketplaceQuery = dm
            .createNamedQuery("Marketplace.findByBusinessKey");
    for (VOCategory voCategory : toBeDeleted) {
        final Category category = dm.getReference(Category.class,
                voCategory.getKey());
        try {
            marketplaceQuery.setParameter("marketplaceId", category
                    .getMarketplace().getMarketplaceId());
        } catch (EntityNotFoundException e) {
            throw new ObjectNotFoundException(ClassEnum.MARKETPLACE,
                    voCategory.getMarketplaceId());
        }
        final Marketplace marketplace = (Marketplace) marketplaceQuery
                .getSingleResult();
        PermissionCheck.owns(marketplace, currentOrg, logger, null);
        List<PlatformUser> usersToBeNotified = collectUsersToBeNotified(category);
        prefetchRequiredObject(category);
        dm.remove(category);
        sendNotification(category, usersToBeNotified);
    }
}
项目:kc-rice    文件:ObjectUtils.java   
/**
 * This method is a OJB Proxy-safe way to test for null on a proxied object that may or may not be materialized yet.
 * It is safe
 * to use on a proxy (materialized or non-materialized) or on a non-proxy (ie, regular object). Note that this will
 * force a
 * materialization of the proxy if the object is a proxy and unmaterialized.
 *
 * @param object - any object, proxied or not, materialized or not
 * @return true if the object (or underlying materialized object) is null, false otherwise
 */
public static boolean isNull(Object object) {

    // regardless, if its null, then its null
    if (object == null) {
        return true;
    }

    // only try to materialize the object to see if its null if this is a
    // proxy object
    if (ProxyHelper.isProxy(object) || ProxyHelper.isCollectionProxy(object)) {
        if (ProxyHelper.getRealObject(object) == null) {
            return true;
        }
    }

    // JPA does not provide a way to determine if an object is a proxy, instead we invoke
    // the equals method and catch an EntityNotFoundException
    try {
        object.equals(null);
    } catch (EntityNotFoundException e) {
        return true;
    }

    return false;
}
项目:nsy107    文件:TrucJpaController.java   
public void destroy(String id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Truc truc;
        try {
            truc = em.getReference(Truc.class, id);
            truc.getIdTRUC();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The truc with id " + id + " no longer exists.", enfe);
        }
        em.remove(truc);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:nsy107    文件:PayementHistoryJpaController.java   
public void destroy(Integer id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        PayementHistory payementHistory;
        try {
            payementHistory = em.getReference(PayementHistory.class, id);
            payementHistory.getCommit();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The payementHistory with id " + id + " no longer exists.", enfe);
        }
        Payementlog payId = payementHistory.getPayId();
        if (payId != null) {
            payId.getPayementHistoryList().remove(payementHistory);
            payId = em.merge(payId);
        }
        em.remove(payementHistory);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:NetworkTopologyDatastore    文件:TopologyManagerFactoryDBImpl.java   
@Override
public TopologyManager createTopologyManager(String id) throws TopologyException {
  if (id==null)
    throw new TopologyException("ID cannot be null");
  EntityManager em = EntityManagerFactoryHelper.getEntityManager();
  try {
    TopologyManager manager = em.find((TopologyManagerDBImpl.class), id);
    if (manager!=null)
      throw new TopologyException("ID is not unique, a topology manager instance with ID: "+ id + " exists");
  } catch (EntityNotFoundException | NoResultException e) {
    //Do nothing
  }
  //Entity does not exist, create one
  em.getTransaction().begin();
  TopologyManagerDBImpl managerDB = new TopologyManagerDBImpl(id);
  em.persist(managerDB);
  em.getTransaction().commit();
  return managerDB;
}
项目:yummy-xml-UI    文件:TerminalmgrJpaController.java   
public void destroy(String id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Terminalmgr terminalmgr;
        try {
            terminalmgr = em.getReference(Terminalmgr.class, id);
            terminalmgr.getName();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The terminalmgr with id " + id + " no longer exists.", enfe);
        }
        em.remove(terminalmgr);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:yummy-xml-UI    文件:TerminaldeviceJpaController.java   
public void destroy(String id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Terminaldevice terminaldevice;
        try {
            terminaldevice = em.getReference(Terminaldevice.class, id);
            terminaldevice.getTerminalno();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The terminaldevice with id " + id + " no longer exists.", enfe);
        }
        Terminalinfo terminalinfo = terminaldevice.getTerminalinfo();
        if (terminalinfo != null) {
            terminalinfo.setTerminaldevice(null);
            terminalinfo = em.merge(terminalinfo);
        }
        em.remove(terminaldevice);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:laboratorio-is    文件:ArchivoJpaController.java   
public void destroy(Integer id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Archivo archivo;
        try {
            archivo = em.getReference(Archivo.class, id);
            archivo.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The archivo with id " + id + " no longer exists.", enfe);
        }
        MimeType mimeTypeId = archivo.getMimeTypeId();
        if (mimeTypeId != null) {
            mimeTypeId.getArchivoList().remove(archivo);
            mimeTypeId = em.merge(mimeTypeId);
        }
        em.remove(archivo);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:JEE7-Demo    文件:GradeServiceImpl.java   
@Override
public Map<Discipline, Double> getAvgGradesForStudent(String studentId) {

    if (getNbGradesForStudent(studentId) == 0) {
        throw new EntityNotFoundException(studentId);
    }

    TypedQuery<Object[]> q = entityManager.createQuery(
            "select g.discipline, avg(g.grade) from Grade g where g.studentId=:studentId group by g.discipline",
            Object[].class);
    q.setParameter("studentId", studentId);
    List<Object[]> l = q.getResultList();
    Map<Discipline, Double> map = new HashMap<Discipline, Double>();
    for (Object[] r : l) {
        map.put((Discipline) r[0], (Double) r[1]);
    }
    return map;
}
项目:low-latency-high-throughput    文件:AlternativeJPAController.java   
public void destroy(Long id) throws IllegalOrphanException, NonExistingEntityException, RollbackFailureException, Exception {
        Alternative alternative;
        try {
            alternative = em.getReference(Alternative.class, id);
            alternative.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonExistingEntityException("The alternative with id " + id + " no longer exists.", enfe);
        }
//        List<String> illegalOrphanMessages = null;
//        List<Vote> votesOrphanCheck = alternative.getVotes();
//        for (Vote votesOrphanCheckVote : votesOrphanCheck) {
//            if (illegalOrphanMessages == null) {
//                illegalOrphanMessages = new ArrayList<String>();
//            }
//            illegalOrphanMessages.add("This Alternative (" + alternative + ") cannot be destroyed since the Vote " + votesOrphanCheckVote + " in its votes field has a non-nullable alternative field.");
//        }
//        if (illegalOrphanMessages != null) {
//            throw new IllegalOrphanException(illegalOrphanMessages);
//        }
        Poll poll = alternative.getPoll();
        if (poll != null) {
            poll.getAlternatives().remove(alternative);
            poll = em.merge(poll);
        }
        em.remove(alternative);
    }
项目:javaee-samples    文件:GenericDAO.java   
/**
 * Loads (detached) entity object into persistence context (unless already been loaded).
 *
 * @param entityObject (detached) entity object to load
 * @return never returns null
 * @throws EntityNotFoundException  entity reference does not exist in database
 * @throws IllegalArgumentException if {@code entityObject} does not have id, or
 *                                  the object is found not to be an entity
 * @throws IllegalStateException    if the entity manager has been closed, or
 *                                  the entity manager factory has been closed
 */
@Override
@NotNull
@SuppressWarnings("checkstyle:innerassignment")
public
E reload(@NotNull E entityObject) {
    final PK id;
    if (!hasId(entityObject) || (id = getIdentifier(entityObject)) == null) {
        throw new IllegalArgumentException("does not have id");
    }
    final E e = load(id);
    if (e == null) {
        throw new EntityNotFoundException(getEntityType().getSimpleName()
                + " record with "
                + id
                + " does not exist in database");
    }
    return e;
}
项目:plugin-id-ldap    文件:LdapPluginResourceTest.java   
@Test(expected = EntityNotFoundException.class)
public void linkNotVisibleProject() throws Exception {

    // Invoke link for an already created entity, since for now
    initSpringSecurityContext("any");
    resource.link(this.subscription);
}
项目:Sem-Update    文件:PropietarioJpaController.java   
public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
    EntityManager em = null;
    try {
        utx.begin();
        em = getEntityManager();
        Propietario propietario;
        try {
            propietario = em.getReference(Propietario.class, id);
            propietario.getCedula();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The propietario with id " + id + " no longer exists.", enfe);
        }
        List<String> illegalOrphanMessages = null;
        Collection<Telefono> telefonoCollectionOrphanCheck = propietario.getTelefonoCollection();
        for (Telefono telefonoCollectionOrphanCheckTelefono : telefonoCollectionOrphanCheck) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This Propietario (" + propietario + ") cannot be destroyed since the Telefono " + telefonoCollectionOrphanCheckTelefono + " in its telefonoCollection field has a non-nullable propietarioId field.");
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        em.remove(propietario);
        utx.commit();
    } catch (Exception ex) {
        try {
            utx.rollback();
        } catch (Exception re) {
            throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:Sem-Update    文件:TelefonoJpaController.java   
public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
    EntityManager em = null;
    try {
        utx.begin();
        em = getEntityManager();
        Telefono telefono;
        try {
            telefono = em.getReference(Telefono.class, id);
            telefono.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The telefono with id " + id + " no longer exists.", enfe);
        }
        Propietario propietarioId = telefono.getPropietarioId();
        if (propietarioId != null) {
            propietarioId.getTelefonoCollection().remove(telefono);
            propietarioId = em.merge(propietarioId);
        }
        em.remove(telefono);
        utx.commit();
    } catch (Exception ex) {
        try {
            utx.rollback();
        } catch (Exception re) {
            throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}
项目:appserv    文件:BankDAO.java   
/**
 * Searches for the account with the specified account number.
 *
 * @param acctNo The number of the searched account.
 * @return The account with the specified number, if such an account was found.
 * @throws EntityNotFoundException If no account with the specified number was found.
 */
public Account findAccountByAcctNo(int acctNo) {
    Account account = em.find(Account.class, acctNo);
    if (account == null) {
        throw new EntityNotFoundException("No account with number " + acctNo);
    }
    return account;
}