@Override @Transactional public void save(T entity) { Assert.notNull(entity, "Entity can not be null. [" + entity.getClass() + "]"); if (useCache()) { if (entity instanceof Persistable && (null != ((Persistable) entity).getId())) { evictCache(getBasic((ID) ((Persistable) entity).getId())); } else { evictCache(entity); } } repository.save(entity); if (useCache()) { evictCache(entity); } }
@Override @Transactional public void saveIgnoreNull(T entity) { Assert.notNull(entity, "Entity can not be null. [" + entity.getClass() + "]"); if (useCache()) { if (entity instanceof Persistable && (null != ((Persistable) entity).getId())) { evictCache(getBasic((ID) ((Persistable) entity).getId())); } else { evictCache(entity); } } repository.saveIgnoreNull(entity); if (useCache()) { evictCache(entity); } }
@Override @Transactional public void insert(T entity) { Assert.notNull(entity, "Entity can not be null. [" + entity.getClass() + "]"); if (useCache()) { if (entity instanceof Persistable && (null != ((Persistable) entity).getId())) { evictCache(getBasic((ID) ((Persistable) entity).getId())); } else { evictCache(entity); } } repository.insert(entity); if (useCache()) { evictCache(entity); } }
@Override @Transactional public void update(T entity) { Assert.notNull(entity, "Entity can not be null. [" + entity.getClass() + "]"); if (useCache()) { if (entity instanceof Persistable && (null != ((Persistable) entity).getId())) { evictCache(getBasic((ID) ((Persistable) entity).getId())); } else { evictCache(entity); } } repository.update(entity); if (useCache()) { evictCache(entity); } }
@Override @Transactional public void updateIgnore(T entity) { Assert.notNull(entity, "Entity can not be null. [" + entity.getClass() + "]"); if (useCache()) { if (entity instanceof Persistable && (null != ((Persistable) entity).getId())) { evictCache(getBasic((ID) ((Persistable) entity).getId())); } else { evictCache(entity); } } repository.updateIgnoreNull(entity); if (useCache()) { evictCache(entity); } }
public static <T extends Persistable<? extends Serializable>, U extends Persistable<ID>, ID extends Serializable> void assertRelationIdNotChanged( @Nonnull final T entity, @Nonnull final Function<? super T, U> relationFunction, @Nonnull final ID relationId) { Objects.requireNonNull(entity, "entity is null"); Objects.requireNonNull(relationFunction, "relationAttribute is null"); Objects.requireNonNull(relationId, "relationId is null"); if (!entity.isNew()) { final U relatedObject = relationFunction.apply(entity); if (!Objects.equals(relationId, relatedObject.getId())) { throw new CannotChangeAssociatedEntityException(String.format( "%s: cannot change ID of related %s: %d -> %d", entity.getClass().getSimpleName(), relatedObject.getClass().getSimpleName(), relatedObject.getId(), relationId)); } } }
/** * Execute workflow transition for domains. * * @param executionContext ExecutionContext. */ @SuppressWarnings("unchecked") @Override public void execute(ExecutionContext executionContext) { Assert.notNull(transitionIdExpression, "transitionIdExpression not set"); Assert.notNull(domainExpression, "domainExpression not set"); Object domain = executionContext.getExpressionExecutor() .evaluate(executionContext, domainExpression); String transitionId = executionContext.getExpressionExecutor() .evaluate(executionContext, transitionIdExpression); if (domain != null) { if (domain instanceof Collection) { Collection<Persistable<Long>> domains = (Collection<Persistable<Long>>) domain; for (Persistable<Long> object : domains) { transition(object, transitionId, executionContext); } } else { transition((Persistable<Long>) domain, transitionId, executionContext); } } }
private void transition(Persistable<Long> domain, String transitionId, ExecutionContext executionContext) { Assert.notNull(transitionId, "transitionIdExpression has not evaluated to a valid transitionId"); ProcessToken token = tokenRepository.findByDomain(domain); Assert.isTrue(domain == token.getDomainObject(), "Loaded token should have same instance of domain as returned in expression 'domainExpression'."); //Create a new parameters map to prevent contamination and initialise from executionContext parameters. HashMap<String, Object> parameters = new HashMap<String, Object>(executionContext.getParameters()); workflowEnvironment.getService().executeTransition(token, transitionId, parameters); tokenRepository.save(token); }
/** * JAVADOC Method Level Comments * * @param type JAVADOC. * @param id JAVADOC. * * @return JAVADOC. */ @SuppressWarnings("unchecked") @Override public Persistable<?extends Serializable> load(String type, Serializable id) { Class<?> clazz = instanceFactory.getClassType(type); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<?> cq = cb.createQuery(clazz); Root<?> token = cq.from(clazz); cq.where(cb.equal(token.get("id"), id)); try { return (Persistable<?extends Serializable>) entityManager.createQuery(cq).getSingleResult(); } catch (Exception e) { LOG.info("Oops", e); return null; } }
private void create(ProcessToken token) { Assert.notNull(token, "token cannot be null"); Assert.isNull(token.getId(), "This must be a new token"); Assert.notNull(token.getDomainObject(), "token must have a domainObject"); if (token.getDomainObject().getId() == null) { Persistable<?extends Serializable> domain = token.getDomainObject(); entityManager.persist(domain); Assert.notNull(domain.getId(), "id must now be set on domainObject"); token.setDomainObject(domain); } else { entityManager.merge(token.getDomainObject()); } // Now set id and type of domainObject on Token token.setDomainObjectId(token.getDomainObject().getId()); BeanWrapper beanWrapper = new BeanWrapperImpl(token.getDomainObject()); token.setDomainObjectType((String) beanWrapper.getPropertyValue("applicationType")); entityManager.persist(token); }
private Object process(AbstractElementDescriptor descriptor, ExecutionContext context) { String application = (String) descriptor.get("application"); BeanWrapper beanWrapper = new BeanWrapperImpl(context.getToken().getDomainObject()); descriptor.put("domainType", beanWrapper.getPropertyValue("applicationType")); Persistable<?> po = context.getToken().getDomainObject(); descriptor.put("domainId", (po instanceof EntityDescriptor) ? ((EntityDescriptor) po).getRemoteId() : po.getId()); if (StringUtils.isEmpty(application)) { throw new IllegalArgumentException("application is not specified"); // return testLocal(ced, executionContext); } return sendAndReceive(conversionService.convert(descriptor, ProcessElementDto.class), context); }
public <T extends Persistable<NodeRef>> T queryForObject(final String query, final NodePropertiesMapper<T> mapper, final String language) throws IncorrectResultSizeException { Assert.notNull(mapper); Assert.hasText(query); List<T> list = queryForList(query.toString(), mapper, 2, 0, 1, StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, language).getContent(); int size = list.size(); switch (size) { case 0: if (LOGGER.isDebugEnabled()) { LOGGER.debug("No result found. Returning null."); } return null; case 1: return list.get(0); default: LOGGER.error(IncorrectResultSizeException.DEFAULT_MESSAGE_ID, size); throw new IncorrectResultSizeException(size); } }
@SuppressWarnings({"rawtypes", "unchecked"}) protected static EntityInformation createEntityInformation(Class<?> entityType) { if (Persistable.class.isAssignableFrom(entityType)) { return new PersistableEntityInformation(entityType); } return new ReflectionEntityInformation(entityType); }
@Override public void serialize(final Persistable<?> bean, final JsonGenerator generator, final SerializerProvider provider) throws IOException { if (bean.getId() instanceof Number) { // Numeric, but no decimal accepted generator.writeNumber(((Number) bean.getId()).longValue()); } else { // Consider ID as a String (not failsafe) generator.writeString((String) bean.getId()); } }
public static <T, ID extends Serializable> MybatisEntityInformation<T, ID> getEntityInformation(MybatisMappingContext mappingContext, AuditorAware<?> auditorAware, AuditDateAware<?> auditDateAware, Class<T> domainClass) { Assert.notNull(domainClass); PersistentEntity<T, ?> persistentEntity = (PersistentEntity<T, ?>) mappingContext.getPersistentEntity(domainClass); if (Persistable.class.isAssignableFrom(domainClass)) { return new MybatisPersistableEntityInformation(persistentEntity, auditorAware, auditDateAware, domainClass); } return new MybatisMetamodelEntityInformation<T, ID>(persistentEntity, auditorAware, auditDateAware, domainClass); }
@Override public boolean equals(Object that) { if (this == that) { return true; } if (!(that instanceof Persistable)) { return false; } final Persistable<?> thatPersistable = (Persistable<?>) that; return null != this.getId() && this.getId().equals(thatPersistable.getId()); }
@Override public boolean equals(Object that) { if (this == that) return true; if (!(that instanceof Persistable)) return false; final Persistable<?> thatPersistable = (Persistable<?>) that; return null != this.getId() && this.getId().equals(thatPersistable.getId()); }
@Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null || !isCompatibleClass(that)) { return false; } final Persistable<?> thatPersistable = (Persistable<?>) that; return null != this.getId() && this.getId().equals(thatPersistable.getId()); }
private void saveAndFlush(final Collection<? extends Persistable<?>> entities) { Objects.requireNonNull(entities); final int numberOfEntities = entities.size(); if (numberOfEntities > 0) { entities.forEach(this::save); entityManager.flush(); LOG.debug("Inserted {} entities into database.", numberOfEntities); } }
private void save(final Persistable<?> entity) { try { Objects.requireNonNull(entity); entityManager.persist(entity); } catch (final ConstraintViolationException cve) { throw new ConstraintViolationException( cve.getConstraintViolations().stream() .map(Functions.CONSTRAINT_VIOLATION_TO_STRING) .collect(joining("\n", "Violated JSR-303 constraints:\n", "")), cve.getConstraintViolations()); } }
@Nonnull public static <T, ID extends Serializable, U extends HasID<ID> & Persistable<ID>, R extends BaseRepository<U, ID>> Function<T, U> singleQueryFunction( @Nonnull final Iterable<? extends T> objects, @Nonnull final Function<? super T, U> function, @Nonnull final R repository, final boolean letFunctionThrowExceptionOnNullResult) { return singleQueryFunction( objects, function, repository, Optional.empty(), letFunctionThrowExceptionOnNullResult); }
@Nonnull public static <T, ID extends Serializable, U extends HasID<ID> & Persistable<ID>, R extends BaseRepository<U, ID>> Function<T, U> singleQueryFunction( @Nonnull final Iterable<? extends T> objects, @Nonnull final Function<? super T, U> function, @Nonnull final R repository, @Nonnull final Specification<U> relationConstraint, final boolean letFunctionThrowExceptionOnNullResult) { return singleQueryFunction( objects, function, repository, Optional.of(relationConstraint), letFunctionThrowExceptionOnNullResult); }
@Nonnull public static <ID extends Serializable, T extends Persistable<ID> & HasID<ID>, U> Function<T, Long> createAssociationCountFunction( @Nonnull final Iterable<? extends T> collection, @Nonnull final Class<U> associatedClass, @Nonnull final SingularAttribute<? super U, T> associationAttribute, @Nonnull final EntityManager entityManager) { Objects.requireNonNull(collection, "collection is null"); Objects.requireNonNull(associatedClass, "associatedClass is null"); Objects.requireNonNull(associationAttribute, "associationAttribute is null"); Objects.requireNonNull(entityManager, "entityManager is null"); if (Iterables.isEmpty(collection)) { return t -> 0L; } final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<Object> query = cb.createQuery(); final Root<U> root = query.from(associatedClass); final EntityType<T> targetEntityType = entityManager.getMetamodel().entity(associationAttribute.getJavaType()); final Path<ID> targetEntityIdPath = root.get(associationAttribute).get(getSingularIdAttribute(targetEntityType)); query.select(cb.construct(Tuple2.class, targetEntityIdPath, cb.count(root))) .where(targetEntityIdPath.in(cb.literal(F.getUniqueIds(collection)))) .groupBy(targetEntityIdPath); @SuppressWarnings({ "rawtypes", "unchecked" }) final List<Tuple2<ID, Long>> pairs = (List) entityManager.createQuery(query).getResultList(); if (pairs.isEmpty()) { return t -> 0L; } final HashMap<ID, Long> idToCount = HashMap.ofEntries(pairs); return t -> idToCount.get(F.getId(t)).getOrElse(0L); }
private static <ID extends Serializable, T extends Persistable<ID>> SingularAttribute<? super T, ID> getSingularIdAttribute( final EntityType<T> entityType) { if (!entityType.hasSingleIdAttribute()) { throw new UnsupportedOperationException("Multi-attribute-ID not supported."); } @SuppressWarnings("unchecked") final Class<ID> idClass = (Class<ID>) entityType.getIdType().getJavaType(); return entityType.getId(idClass); }
public EntitySupplier(@Nonnull final NumberGenerator numberGenerator, @Nonnull final List<Persistable<?>> transientEntityList, @Nonnull final Supplier<Riistakeskus> riistakeskusSupplier) { this.numberGenerator = Objects.requireNonNull(numberGenerator, "numberGenerator is null"); this.transientEntityList = Objects.requireNonNull(transientEntityList, "transientEntityList is null"); this.riistakeskusSupplier = Objects.requireNonNull(riistakeskusSupplier, "riistakeskusSupplier is null"); }
protected static String toMessage(Class<? extends Persistable> entityClass, Map<String, Object> fields) { StringBuilder sb = new StringBuilder() .append("Duplicate ") .append(entityClass.getSimpleName()) .append(" with "); for (Map.Entry<String, Object> field : fields.entrySet()) { sb.append(field.getKey()).append("=").append(String.valueOf(field.getValue())).append(" "); } return sb.append("found!").toString(); }
/** * Calls save on domainRepository and nullifies domainObject on Token * * @param executionContext ExecutionContext. */ @Override public void execute(ExecutionContext executionContext) { Persistable<?> entity = executionContext.getToken().getDomainObject(); domainRepository.save(entity); executionContext.getToken().setDomainObject(entity); }
/** * JAVADOC Method Level Comments * * @param domain JAVADOC. */ @Override public void save(Persistable<?extends Serializable> domain) { if (domain.isNew()) { entityManager.persist(domain); } else { entityManager.merge(domain); } }
/** * JAVADOC Method Level Comments * * @param domain * JAVADOC. * * @return JAVADOC. */ @Override @Transactional public ProcessToken findByDomain(Persistable<?> domain) { Assert.notNull(domain, "Domain is null"); BeanWrapper bw = new BeanWrapperImpl(domain); Assert.isTrue(bw.isReadableProperty("id"), "No 'id' property on object of type '" + domain.getClass() + "'"); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<ProcessToken> cq = cb.createQuery(ProcessToken.class); Root<ProcessToken> token = cq.from(ProcessToken.class); cq.where(cb.and(cb.equal(token.get("domainObjectType"), domain.getClass().getSimpleName()), cb.equal(token.get("domainObjectId"), bw.getPropertyValue("id")))); try { ProcessToken wt = entityManager.createQuery(cq).getSingleResult(); wt.setDomainObject(domain); return wt; } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring this", e); } return null; } }
@SuppressWarnings("rawtypes") public boolean isNew(T entity) { if (entity instanceof Persistable) { return ((Persistable) entity).isNew(); } else { return getRev(entity) == null; } }
public <T extends Persistable<NodeRef>> T queryForObject(final NodeRef nodeRef, final NodePropertiesMapper<T> mapper) { Assert.notNull(mapper); Assert.notNull(nodeRef); Map<QName, Serializable> properties = serviceRegistry.getNodeService().getProperties(nodeRef); return mapper.mapNodeProperties(nodeRef, properties); }
public <T extends Persistable<NodeRef>> Page<T> queryForList(final String query, final NodePropertiesMapper<T> mapper, final Pageable pageable, final StoreRef store, final String searchLanguage, final QueryConsistency queryConsistency) { Assert.notNull(query); Assert.notNull(mapper); Assert.notNull(store); Assert.notNull(pageable); Assert.notNull(queryConsistency); Assert.hasText(searchLanguage); SearchParameters sp = new SearchParameters(); sp.addStore(store); sp.setLanguage(searchLanguage); Sort sort = pageable.getSort(); if(sort != null) { for (Order order : sort) { sp.addSort(order.getProperty(), order.isAscending()); } } // sp.setMaxItems(maxItems); sp.setLimit(pageable.getPageSize()); sp.setLimitBy(LimitBy.FINAL_SIZE); sp.setQuery(query.toString()); // if (skipCount > 0) { // sp.setSkipCount(skipCount); // } return queryForList(sp, mapper, pageable); }
public <T extends Persistable<NodeRef>> Page<T> queryForList(final SearchParameters sp, final NodePropertiesMapper<T> mapper, final Pageable pageable) { Assert.notNull(sp); Assert.notNull(mapper); final int ps = pageable.getPageSize() > 0 ? pageable.getPageSize() : defaultPagesize; final int p = pageable.getPageNumber() > 1 ? pageable.getPageNumber() - 1 : 0; List<T> list = new ArrayList<T>(); ResultSet results = null; try { results = serviceRegistry.getSearchService().query(sp); if (results != null && results.length() != 0) { final int startIndex = (p * ps) - 1; int count = 0; for (ResultSetRow resultSetRow : results) { if (count > startIndex && list.size() < ps) { NodeRef nodeRef = resultSetRow.getNodeRef(); if (serviceRegistry.getNodeService().exists(nodeRef)) { Map<QName, Serializable> properties = new HashMap<>(); for (Map.Entry<String, Serializable> entry : resultSetRow.getValues().entrySet()) { properties.put(QName.createQName(entry.getKey()), entry.getValue()); } list.add(mapper.mapNodeProperties(nodeRef, properties)); } } count++; } } } finally { if (results != null) { results.close(); } } return new PageImpl<T>(list, pageable, results.getNumberFound()); }
protected ToIdSerializer() { super(Persistable.class, false); }
private static <T extends Persistable<? extends Serializable>> String toXmlId(final T entity) { return toXmlId(entity.getClass().getSimpleName(), entity.getId()); }
@Transactional(propagation = Propagation.REQUIRES_NEW) public void saveInNewTransaction(@Nonnull final Persistable<?> entity) { saveAndFlush(entity); }
@Transactional(propagation = Propagation.REQUIRES_NEW) public void saveInNewTransaction(@Nonnull final Collection<? extends Persistable<?>> entities) { saveAndFlush(entities); }
@Transactional(propagation = Propagation.MANDATORY, noRollbackFor = RuntimeException.class) public <T extends Persistable<?>> T saveInCurrentlyOpenTransaction(@Nonnull final T entity) { return saveAndFlush(entity); }
@Transactional(propagation = Propagation.MANDATORY, noRollbackFor = RuntimeException.class) public void saveInCurrentlyOpenTransaction(@Nonnull final Collection<? extends Persistable<?>> entities) { saveAndFlush(entities); }
private <T extends Persistable<?>> T saveAndFlush(final T entity) { save(entity); entityManager.flush(); LOG.debug("Inserted {}(id={}) entity into database.", entity.getClass().getSimpleName(), entity.getId()); return entity; }