List of usage examples for javax.persistence EntityManager find
public <T> T find(Class<T> entityClass, Object primaryKey);
From source file:seava.j4e.presenter.converter.ReflookupResolver.java
/** * Do the actual work, update the reference field in the entity based on the * ref-lookup rule./*from www . jav a2 s . com*/ * * @param m * @param e * @param refLookup * @param isInsert * @throws Exception */ private void doRefLookup1(M ds, E e, RefLookup refLookup, boolean isInsert, EntityManager em) throws Exception { String refIdDsFieldName = refLookup.refId(); Object refIdDsFieldValue = this._getDsFieldValue(refIdDsFieldName, ds); String refEntityFieldName = null; Field refIdDsField = this._getDsField(refIdDsFieldName); if (!refIdDsField.isAnnotationPresent(DsField.class)) { throw new Exception("Field " + refIdDsFieldName + " cannot be used as value for refId in @RefLookup annotation as it is not marked as @DsField "); } else { DsField dsFieldAnnotation = refIdDsField.getAnnotation(DsField.class); /* Obey the noInsert and noUpdate rules. */ if ((isInsert && dsFieldAnnotation.noInsert()) || (!isInsert && dsFieldAnnotation.noUpdate())) { return; } String path = dsFieldAnnotation.path(); if (path.indexOf('.') > 0) { // TODO: handle the deep references also ( a.b.c.id ) refEntityFieldName = path.substring(0, path.indexOf('.')); } else { throw new Exception("Field " + refIdDsFieldName + " cannot be used as value for refId in @RefLookup annotation as its path(`" + path + "`) in @DsField is not a reference path."); } } Class<?> refClass = this._getEntityField(refEntityFieldName).getType(); Object ref = this._getEntityFieldValue(refEntityFieldName, e); Method setter = this._getEntitySetter(refEntityFieldName); if (refIdDsFieldValue != null && !"".equals(refIdDsFieldValue)) { /* * if there is an ID now in DS which points to a different reference * as the one in the original entity then update it to the new one */ if (ref == null || !((IModelWithId<?>) ref).getId().equals(refIdDsFieldValue)) { setter.invoke(e, em.find(refClass, refIdDsFieldValue)); } } else { /* * If there is no ID given in DS for the reference, try to lookup an * entity based on the given named query which must be a query based * on an unique-key. The given fields as parameters for the * named-query must uniquely identify an entity. */ boolean shouldTryToFindReference = true; String namedQueryName = refLookup.namedQuery(); Map<String, Object> values = new HashMap<String, Object>(); Map<String, Object> namedQueryParams = new HashMap<String, Object>(); if (namedQueryName == null || namedQueryName.equals("")) { shouldTryToFindReference = false; } else { for (Param p : refLookup.params()) { String paramName = p.name(); String fieldName = p.field(); String staticValue = p.value(); Object fieldValue = null; if (staticValue != null && !"".equals(staticValue)) { fieldValue = staticValue; } else { fieldValue = this._getDsFieldValue(fieldName, ds); } if (fieldValue == null || (fieldValue instanceof String && ((String) fieldValue).equals(""))) { shouldTryToFindReference = false; break; } else { values.put(fieldName, fieldValue); namedQueryParams.put(paramName, fieldValue); } } } if (shouldTryToFindReference) { Object theReference = null; try { theReference = (findEntityService(refClass)).findByUk(namedQueryName, namedQueryParams); } catch (javax.persistence.NoResultException exception) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, Object> entry : values.entrySet()) { sb.append(" `" + entry.getKey() + "` = `" + entry.getValue() + "`"); } throw new BusinessException(ErrorCode.G_RUNTIME_ERROR, "Cannot find `" + refClass.getSimpleName() + "` reference using " + sb.toString() + " for data-source `" + ds.getClass().getSimpleName() + "`"); } setter.invoke(e, theReference); Method refIdFieldInDsSetter = this._getDsSetter(refIdDsFieldName); refIdFieldInDsSetter.invoke(ds, ((IModelWithId<?>) theReference).getId()); } else { setter.invoke(e, (Object) null); } } }
From source file:org.apache.juddi.validation.ValidatePublish.java
public void validateSaveTModelMax(EntityManager em) throws DispositionReportFaultMessage { //Obtain the maxSettings for this publisher or get the defaults Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); Integer maxTModels = publisher.getMaxTmodels(); try {// w w w. j av a2 s. c om if (maxTModels == null) { if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER)) { maxTModels = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); } else { maxTModels = -1; } } } catch (ConfigurationException e) { log.error(e.getMessage(), e); maxTModels = -1; //incase the config isn't available } //if we have the TModels set for a publisher then we need to make sure we did not exceed it. if (maxTModels > 0) { //get the tmodels owned by this publisher List<?> tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, null); if (tmodelKeysFound != null && tmodelKeysFound.size() > maxTModels) { throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxTModelsExceeded")); } } }
From source file:org.apache.juddi.validation.ValidatePublish.java
public void validateSaveBusinessMax(EntityManager em) throws DispositionReportFaultMessage { //Obtain the maxSettings for this publisher or get the defaults Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); Integer maxBusinesses = publisher.getMaxBusinesses(); try {//from w w w. j a v a2 s. co m if (maxBusinesses == null) { if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER)) { maxBusinesses = AppConfig.getConfiguration() .getInteger(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } else { maxBusinesses = -1; } } } catch (ConfigurationException e) { log.error(e.getMessage(), e); maxBusinesses = -1; //in case the configuration is not available } //if we have the maxBusinesses set for this publisher then we need to make sure we did not exceed it. if (maxBusinesses > 0) { //get the businesses owned by this publisher List<?> businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, null); if (businessKeysFound != null && businessKeysFound.size() > maxBusinesses) { throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxBusinessesExceeded")); } } }
From source file:org.apache.juddi.validation.ValidatePublish.java
public void validateSaveBindingMax(EntityManager em, String serviceKey) throws DispositionReportFaultMessage { //Obtain the maxSettings for this publisher or get the defaults Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); Integer maxBindings = publisher.getMaxBindingsPerService(); try {/*from ww w . j av a 2 s . c o m*/ if (maxBindings == null) { if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_BINDINGS_PER_SERVICE)) { maxBindings = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); } else { maxBindings = -1; } } } catch (ConfigurationException e) { log.error(e.getMessage(), e); maxBindings = -1; //incase the config isn't available } //if we have the maxBindings set for a service then we need to make sure we did not exceed it. if (maxBindings > 0) { //get the bindings owned by this service org.apache.juddi.model.BusinessService modelBusinessService = em .find(org.apache.juddi.model.BusinessService.class, serviceKey); if (modelBusinessService.getBindingTemplates() != null && modelBusinessService.getBindingTemplates().size() > maxBindings) { throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxBindingsExceeded")); } } }
From source file:org.apache.juddi.validation.ValidatePublish.java
public void validateSaveServiceMax(EntityManager em, String businessKey) throws DispositionReportFaultMessage { //Obtain the maxSettings for this publisher or get the defaults Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); Integer maxServices = publisher.getMaxBusinesses(); try {/*from www . j a v a2 s.c o m*/ if (maxServices == null) { if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_SERVICES_PER_BUSINESS)) { maxServices = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); } else { maxServices = -1; } } } catch (ConfigurationException e) { log.error(e.getMessage(), e); maxServices = -1; //incase the configuration isn't available } //if we have the maxServices set for a business then we need to make sure we did not exceed it. if (maxServices > 0) { //get the businesses owned by this publisher org.apache.juddi.model.BusinessEntity modelBusinessEntity = em .find(org.apache.juddi.model.BusinessEntity.class, businessKey); if (modelBusinessEntity.getBusinessServices() != null && modelBusinessEntity.getBusinessServices().size() > maxServices) { throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxServicesExceeded")); } } }
From source file:org.apache.juddi.validation.ValidatePublish.java
/** * throws if it doesn't exist, returns it if it does * * @param tmodelKey// w w w. ja va2 s .co m * @return null, or a TModel object * @throws ValueNotAllowedException * @since 3.3 */ private TModel verifyTModelKeyExists(String tmodelKey) throws ValueNotAllowedException, DispositionReportFaultMessage { TModel api = null; EntityManager em = PersistenceManager.getEntityManager(); boolean found = false; if (em == null) { log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); } else { Tmodel modelTModel = null; { EntityTransaction tx = em.getTransaction(); try { tx.begin(); modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); if (modelTModel != null) { found = true; api = new TModel(); MappingModelToApi.mapTModel(modelTModel, api); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } } if (!found) { throw new ValueNotAllowedException( new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); } return api; }
From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * {@inheritDoc}//from w w w .ja v a 2s. co m * * @see org.opencastproject.serviceregistry.api.ServiceRegistry#getJob(long) */ @Override public Job getJob(long id) throws NotFoundException, ServiceRegistryException { EntityManager em = null; try { em = emf.createEntityManager(); JobJpaImpl job = em.find(JobJpaImpl.class, id); if (job == null) { throw new NotFoundException("Job " + id + " not found"); } // JPA's caches can be out of date if external changes (e.g. another node in the cluster) have been made to // this row in the database em.refresh(job); job.getArguments(); setJobUri(job); return job; } catch (Exception e) { if (e instanceof NotFoundException) { throw (NotFoundException) e; } else { throw new ServiceRegistryException(e); } } finally { if (em != null) em.close(); } }
From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * Internal method to update a job, throwing unwrapped JPA exceptions. * /*from www . ja v a 2 s. c om*/ * @param em * the current entity manager * @param job * the job to update * @return the updated job * @throws PersistenceException * if there is an exception thrown while persisting the job via JPA * @throws IllegalArgumentException */ protected Job updateInternal(EntityManager em, Job job) throws PersistenceException { EntityTransaction tx = em.getTransaction(); try { tx.begin(); JobJpaImpl fromDb; fromDb = em.find(JobJpaImpl.class, job.getId()); if (fromDb == null) { throw new NoResultException(); } update(fromDb, (JaxbJob) job); em.merge(fromDb); tx.commit(); ((JaxbJob) job).setVersion(fromDb.getVersion()); setJobUri(job); return job; } catch (PersistenceException e) { if (tx.isActive()) { tx.rollback(); } throw e; } }
From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * Internal method to update the service registration state, throwing unwrapped JPA exceptions. * /*from w ww . j a v a 2s .co m*/ * @param em * the current entity manager * @param registration * the service registration to update * @return the updated service registration * @throws PersistenceException * if there is an exception thrown while persisting the job via JPA * @throws IllegalArgumentException */ private ServiceRegistration updateServiceState(EntityManager em, ServiceRegistrationJpaImpl registration) throws PersistenceException { EntityTransaction tx = em.getTransaction(); try { tx.begin(); ServiceRegistrationJpaImpl fromDb; fromDb = em.find(ServiceRegistrationJpaImpl.class, registration.getId()); if (fromDb == null) { throw new NoResultException(); } fromDb.setServiceState(registration.getServiceState()); fromDb.setStateChanged(registration.getStateChanged()); fromDb.setWarningStateTrigger(registration.getWarningStateTrigger()); fromDb.setErrorStateTrigger(registration.getErrorStateTrigger()); tx.commit(); servicesStatistics.updateService(registration); return registration; } catch (PersistenceException e) { if (tx.isActive()) { tx.rollback(); } throw e; } }
From source file:org.apache.juddi.validation.ValidatePublish.java
/** * Validates that a tmodel key is registered Alex O'Ree * * @param tmodelKey//from w w w. java 2 s .c o m * @param em * @throws ValueNotAllowedException * @see org.apache.juddi.config.Install * @since 3.1.5 */ private boolean verifyTModelKeyExistsAndChecked(String tmodelKey, Configuration config) throws ValueNotAllowedException { boolean checked = true; if (tmodelKey == null || tmodelKey.length() == 0) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:types")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:nodes")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_inquiry")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_publication")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_security")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_ownership_transfer")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscription")) { return false; } if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscriptionlistener")) { return false; } if (config == null) { log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullConfig")); return false; } boolean checkRef = false; try { checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); } catch (Exception ex) { log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); } if (checkRef) { if (log.isDebugEnabled()) { log.debug("verifyTModelKeyExists " + tmodelKey); } EntityManager em = PersistenceManager.getEntityManager(); if (em == null) { //this is normally the Install class firing up log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); } else { //Collections.sort(buildInTmodels); //if ((buildInTmodels, tmodelKey) == -1) Tmodel modelTModel = null; { EntityTransaction tx = em.getTransaction(); try { tx.begin(); modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); if (modelTModel == null) { checked = false; } else { for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag() .getKeyedReferences()) { if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getKeyName())) { checked = false; break; } } } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } if (modelTModel == null) { throw new ValueNotAllowedException( new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); } } } } return checked; }