@Bean public CacheManager cacheManager(JHipsterProperties jHipsterProperties) { log.debug("Starting Ehcache"); cacheManager = net.sf.ehcache.CacheManager.create(); cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap()); log.debug("Registering Ehcache Metrics gauges"); Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities(); for (EntityType<?> entity : entities) { String name = entity.getName(); if (name == null || entity.getJavaType() != null) { name = entity.getJavaType().getName(); } Assert.notNull(name, "entity cannot exist without a identifier"); net.sf.ehcache.Cache cache = cacheManager.getCache(name); if (cache != null) { cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds()); net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache); cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache); } } EhCacheCacheManager ehCacheManager = new EhCacheCacheManager(); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }
public static Set<String> getIdFieldNames(Metamodel metamodel, String entityName) { Set<String> ids = entityIdMap.get(entityName); if(ids == null) { ids = new HashSet<>(); for(EntityType<?> et : metamodel.getEntities()) { if(et.getJavaType().getName().equals(entityName)) { if(et.hasSingleIdAttribute()) { ids.add(et.getId(et.getIdType().getJavaType()).getName()); } else { for(SingularAttribute<?, ?> idAttribute : et.getIdClassAttributes()) { ids.add(idAttribute.getName()); } } } } } if(ids.size() == 0) { ids.add("id"); } return ids; }
@Nonnull public static <ID extends Serializable, T extends HasID<ID>> Predicate idInCollection( @Nonnull final CriteriaBuilder cb, @Nonnull final Root<T> root, @Nullable final Collection<ID> ids) { Objects.requireNonNull(cb, "cb must not be null"); Objects.requireNonNull(root, "root must not be null"); if (CollectionUtils.isEmpty(ids)) { return cb.disjunction(); } final EntityType<T> rootModel = root.getModel(); if (!rootModel.hasSingleIdAttribute()) { throw new IllegalArgumentException( "Single-column-identified entity expected but not received: " + rootModel.getJavaType().getName()); } @SuppressWarnings("unchecked") final Class<ID> idClass = (Class<ID>) rootModel.getIdType().getJavaType(); return root.get(root.getModel().getId(idClass)).in(cb.literal(ids)); }
@Override public void startUp(ServletContext servletContext) { try { initializeJPA(); } catch (PersistenceException e) { //fix for MCR-1236 if (MCRConfiguration.instance().getBoolean("MCR.Persistence.Database.Enable", true)) { LogManager.getLogger() .error(() -> "Could not initialize JPA. Database access is disabled in this session.", e); MCRConfiguration.instance().set("MCR.Persistence.Database.Enable", false); } MCREntityManagerProvider.init(e); return; } Metamodel metamodel = MCREntityManagerProvider.getEntityManagerFactory().getMetamodel(); checkHibernateMappingConfig(metamodel); LogManager.getLogger() .info("Mapping these entities: {}", metamodel.getEntities() .stream() .map(EntityType::getJavaType) .map(Class::getName) .collect(Collectors.toList())); MCRShutdownHandler.getInstance().addCloseable(new MCRJPAShutdownProcessor()); }
private void checkHibernateMappingConfig(Metamodel metamodel) { Set<String> mappedEntities = metamodel .getEntities() .stream() .map(EntityType::getJavaType) .map(Class::getName) .collect(Collectors.toSet()); List<String> unMappedEntities = MCRConfiguration .instance() .getStrings("MCR.Hibernate.Mappings", Collections.emptyList()) .stream() .filter(cName -> !mappedEntities.contains(cName)) .collect(Collectors.toList()); if (!unMappedEntities.isEmpty()) { throw new MCRException( "JPA Mapping is inclomplete. Could not find a mapping for these classes: " + unMappedEntities); } }
@Bean public CacheManager cacheManager() { log.debug("Starting Ehcache"); cacheManager = net.sf.ehcache.CacheManager.create(); cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M")); log.debug("Registering Ehcache Metrics gauges"); Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities(); for (EntityType<?> entity : entities) { String name = entity.getName(); if (name == null || entity.getJavaType() != null) { name = entity.getJavaType().getName(); } Assert.notNull(name, "entity cannot exist without a identifier"); net.sf.ehcache.Cache cache = cacheManager.getCache(name); if (cache != null) { cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L)); net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache); cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache); } } EhCacheCacheManager ehCacheManager = new EhCacheCacheManager(); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }
/** * Lookup entities having at least one String attribute matching the passed sp's pattern */ @SuppressWarnings("unused") public <T> Predicate byPattern(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder, final SearchParameters sp, final Class<T> type) { if (!sp.hasSearchPattern()) { return null; } List<Predicate> predicates = newArrayList(); EntityType<T> entity = em.getMetamodel().entity(type); String pattern = sp.getSearchPattern(); for (Attribute<T, ?> attr : entity.getDeclaredSingularAttributes()) { if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { continue; } if (attr.getJavaType() == String.class) { predicates.add(JpaUtil.stringPredicate(root.get(attribute(entity, attr)), pattern, sp, builder)); } } return JpaUtil.orPredicate(builder, predicates); }
@Bean public CacheManager cacheManager(JHipsterProperties jHipsterProperties) { log.debug("Starting Ehcache"); cacheManager = net.sf.ehcache.CacheManager.create(); cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap()); log.debug("Registering Ehcache Metrics gauges"); Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities(); for (EntityType<?> entity : entities) { String name = entity.getName(); if (name == null || entity.getJavaType() != null) { name = entity.getJavaType().getName(); } Assert.notNull(name, "entity cannot exist without an identifier"); reconfigureCache(name, jHipsterProperties); for (PluralAttribute pluralAttribute : entity.getPluralAttributes()) { reconfigureCache(name + "." + pluralAttribute.getName(), jHipsterProperties); } } EhCacheCacheManager ehCacheManager = new EhCacheCacheManager(); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }
/** * Returns the table name for a given entity type in the * {@link EntityManager}. * * @param entityClass * @return */ public <T> String getTableName(Class<T> entityClass) { /* * Check if the specified class is present in the metamodel. Throws * IllegalArgumentException if not. */ Metamodel meta = entityManager.getMetamodel(); EntityType<T> entityType = meta.entity(entityClass); // Check whether @Table annotation is present on the class. Table t = entityClass.getAnnotation(Table.class); String tableName = (t == null) ? entityType.getName().toUpperCase() : t.name(); logger.debug("Table name found: {}", tableName); return tableName; }
public boolean isAccessible(AccessType accessType, Object entity) { EntityType<?> mapping = forModel(metamodel).filterEntity(entity.getClass()); LOG.debug("Evaluating " + accessType + " access for entity of type " + mapping.getName()); Alias alias = new Alias(Introspector.decapitalize(mapping.getName())); AccessDefinition accessDefinition = createAccessDefinition(alias, mapping.getJavaType(), accessType); LOG.debug("Using access definition " + accessDefinition); QueryEvaluationParameters evaluationParameters = new QueryEvaluationParameters(metamodel, persistenceUnitUtil, Collections.singletonMap(alias, entity), accessDefinition.getQueryParameters(), Collections.<Integer, Object>emptyMap()); try { return queryEvaluator.<Boolean>evaluate(accessDefinition.getAccessRules(), evaluationParameters); } catch (NotEvaluatableException e) { throw new SecurityException(e); } }
public boolean isAccessible(AccessType accessType, String entityName, Object... parameters) { EntityType<?> classMapping = ManagedTypeFilter.forModel(metamodel).filter(entityName); Object entity = null; try { entity = ReflectionUtils.newInstance(classMapping.getJavaType(), parameters); } catch (RuntimeException e) { if (LOG.isDebugEnabled()) { LOG.debug("Constructor of " + classMapping.getJavaType() + " threw exception, hence isAccessible returns false.", e); } else { LOG.info("Constructor of " + classMapping.getJavaType() + " threw exception (\"" + e.getMessage() + "\"), hence isAccessible returns false."); } return false; } return isAccessible(accessType, entity); }
@Test public void ruleWithSubselect() throws ParseException { String rule = " GRANT READ ACCESS TO ClientDetails cd " + " WHERE cd.clientRelations.client.id " + " IN (SELECT cs.client.id FROM ClientStaffing cs, ClientStatus cst, Employee e " + " WHERE e.email=CURRENT_PRINCIPAL AND cs.employee=e " + " AND cs.client= cd.clientRelation.client AND cs.endDate IS NULL " + " AND (cst.name <> 'Closed' OR cst.name IS NULL ))"; Metamodel metamodel = mock(Metamodel.class); EntityType clientTradeImportMonitorType = mock(EntityType.class); when(metamodel.getEntities()).thenReturn(Collections.<EntityType<?>>singleton(clientTradeImportMonitorType)); when(clientTradeImportMonitorType.getName()).thenReturn(ClientDetails.class.getSimpleName()); when(clientTradeImportMonitorType.getJavaType()).thenReturn(ClientDetails.class); JpqlParser parser = new JpqlParser(); AccessRulesCompiler compiler = new AccessRulesCompiler(metamodel); JpqlAccessRule accessRule = parser.parseRule(rule); Collection<AccessRule> compiledRules = compiler.compile(accessRule); assertThat(compiledRules.size(), is(1)); AccessRule compiledRule = compiledRules.iterator().next(); assertThat(compiledRule.getSelectedPath(), is(new Path("cd"))); }
@Before public void initialize() throws Exception { metamodel = mock(Metamodel.class); EntityType contactType = mock(EntityType.class); SingularAttribute ownerAttribute = mock(SingularAttribute.class); accessManager = mock(DefaultAccessManager.class); when(accessManager.getContext()).thenReturn(new DefaultSecurityContext()); when(contactType.getName()).thenReturn(Contact.class.getSimpleName()); when(contactType.getJavaType()).thenReturn((Class)Contact.class); when(metamodel.getEntities()) .thenReturn(new HashSet<EntityType<?>>(Arrays.<EntityType<?>>asList(contactType))); when(metamodel.entity(Contact.class)).thenReturn(contactType); when(metamodel.managedType(Contact.class)).thenReturn(contactType); when(contactType.getAttributes()).thenReturn(Collections.singleton(ownerAttribute)); when(contactType.getAttribute("owner")).thenReturn(ownerAttribute); when(ownerAttribute.getName()).thenReturn("owner"); when(ownerAttribute.getJavaMember()).thenReturn(Contact.class.getDeclaredField("owner")); DefaultAccessManager.Instance.register(accessManager); JpqlParser parser = new JpqlParser(); JpqlAccessRule rule = parser.parseRule("GRANT READ ACCESS TO Contact contact WHERE contact.owner = CURRENT_PRINCIPAL"); AccessRulesCompiler compiler = new AccessRulesCompiler(metamodel); accessRules = compiler.compile(rule); }
@Before public void initialize() { metamodel = mock(Metamodel.class); EntityType testBeanType = mock(EntityType.class); when(metamodel.getEntities()).thenReturn(Collections.<EntityType<?>>singleton(testBeanType)); when(testBeanType.getName()).thenReturn(TestBean.class.getSimpleName()); when(testBeanType.getJavaType()).thenReturn(TestBean.class); securityContext = mock(SecurityContext.class); accessManager = mock(DefaultAccessManager.class); DefaultAccessManager.Instance.register(accessManager); parser = new JpqlParser(); compiler = new AccessRulesCompiler(metamodel); entityManagerFactory = Persistence.createEntityManagerFactory("hibernate"); criteriaVisitor = new CriteriaVisitor(metamodel, entityManagerFactory.getCriteriaBuilder()); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); bean1 = new TestBean(); bean2 = new TestBean(); entityManager.persist(bean1); entityManager.persist(bean2); entityManager.getTransaction().commit(); entityManager.close(); }
/** * {@inheritDoc} */ @Override protected synchronized void initializeMetadata(Collection<Class<?>> types) { LOG.info("Initializing JPA Metadata from " + entityManager); masterMetadataMap.clear(); // QUESTION: When is JPA loaded so this service can initialize itself? // Build and store the map for ( IdentifiableType<?> identifiableType : entityManager.getMetamodel().getEntities() ) { //Only extract the metadata if EntityType and not a MappedSuperClass if(identifiableType instanceof EntityType<?>){ EntityType<?> type = (EntityType<?>)identifiableType; try { masterMetadataMap.put(type.getBindableJavaType(), getMetadataForClass(type.getBindableJavaType())); if (LOG.isDebugEnabled()) { LOG.debug("Added Metadata For: " + type.getBindableJavaType()); } } catch (Exception ex) { LOG.error("Error obtaining JPA metadata for type: " + type.getJavaType(), ex); } } } }
/** * Gets a single field's relationship metadata. * * @param rd The singular attribute to process. * @return The single field's relationship metadata. */ protected DataObjectRelationship getRelationshipMetadata(SingularAttribute rd) { try { DataObjectRelationshipImpl relationship = new DataObjectRelationshipImpl(); // OJB stores the related class object name. We need to go into the repository and grab the table name. Class<?> referencedClass = rd.getBindableJavaType(); EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass); relationship.setName(rd.getName()); relationship.setRelatedType(referencedClass); populateImplementationSpecificRelationshipLevelMetadata(relationship, rd); return relationship; } catch (RuntimeException ex) { LOG.error("Unable to process Relationship metadata: " + rd); throw ex; } }
@Test public void testFull() throws Exception { loadContext(getClass().getSimpleName() + "_Full.xml"); Set<EntityType<?>> fullEntities = entityManagerFactory.getMetamodel().getEntities(); assertEquals(5, fullEntities.size()); Set<Class<?>> entityClasses = new HashSet<Class<?>>(); for (EntityType<?> entityType : fullEntities) { entityClasses.add(entityType.getJavaType()); } assertTrue(entityClasses.contains(TestEntity.class)); assertTrue(entityClasses.contains(TestEntity1.class)); assertTrue(entityClasses.contains(TestEntity2.class)); assertTrue(entityClasses.contains(TestEntity3.class)); assertTrue(entityClasses.contains(TestEntity4.class)); assertFalse(isJtaEnabled()); }
/** * Méthode permettant de s'assurer que les attributs des classes marquées @Entity ne seront pas sérialisés en * "bytea" lors de leur écriture en base. * * @param classesAutorisees : concerne uniquement des classes matérialisées. Si une enum fait péter le test, c'est * qu'il manque l'annotation @Enumerated ou que celle-ci prend EnumType.ORDINAL en paramètre */ protected void testMetaModel(List<Attribute<?, ?>> ignoredAttributes, Class<?>... classesAutorisees) throws NoSuchFieldException, SecurityException { List<Class<?>> listeAutorisee = Lists.newArrayList(); listeAutorisee.add(String.class); listeAutorisee.add(Long.class); listeAutorisee.add(Double.class); listeAutorisee.add(Integer.class); listeAutorisee.add(Float.class); listeAutorisee.add(Date.class); listeAutorisee.add(BigDecimal.class); listeAutorisee.add(Boolean.class); listeAutorisee.add(int.class); listeAutorisee.add(long.class); listeAutorisee.add(double.class); listeAutorisee.add(boolean.class); listeAutorisee.add(float.class); for (Class<?> clazz : classesAutorisees) { listeAutorisee.add(clazz); } for (EntityType<?> entityType : getEntityManager().getMetamodel().getEntities()) { for (Attribute<?, ?> attribute : entityType.getDeclaredAttributes()) { testMetaModel(attribute, listeAutorisee, ignoredAttributes); } } }
@Test public void makeSureEntityIDCanbeDetect() { Metamodel model = entityManager.getMetamodel(); final Reflections reflections = new Reflections(EntityIDTest.class.getPackage().getName()); Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class); for (Class<?> entity : entities) { EntityType<?> entityType = model.entity(entity); Class<?> id = entityType.getIdType().getJavaType(); System.out.println(entityType); if (entity.equals(InvalidEntity.class)) { Assert.assertEquals(id, Serializable.class); } else { Assert.assertNotEquals(id, Serializable.class); } } }
@Override public void execute(TilesRequestContext tilesContext, AttributeContext attributeContext) { List<Pair<String, String>> menuMap = new LinkedList<>(); Set<EntityType<?>> entityTypes = entityManager.getMetamodel().getEntities(); for (EntityType entityType : entityTypes) { Class entityClass = entityType.getJavaType(); String entityClassName = entityClass.getSimpleName(); if (JpaEntity.class.isAssignableFrom(entityClass) && repositories.hasRepositoryFor(entityClass)) { menuMap.add(new ImmutablePair<>(entityClassName, "/domain/" + entityClassName)); } int i = 0; } attributeContext.putAttribute("menuMap", new ListAttribute(menuMap), true); }
private void init() { try { final Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities(); for (EntityType<?> entity : entities) { final EntityTableMapping entityTableMapping = new EntityTableMapping(entity.getJavaType()); final Object descriptor = invokeMethod(entity, "getDescriptor"); final String tableName = (String) invokeMethod(descriptor, "getTableName"); entityTableMapping.setTableName(tableName.toLowerCase()); addAttributeMapping(entityTableMapping, descriptor); putEntityTableMapping((String) invokeMethod(descriptor, "getTableName"), entityTableMapping); entityTableMappingByClass.put(entity.getJavaType(), entityTableMapping); } } catch (final Exception e) { e.printStackTrace(); } }
public static Type toType(Bindable bindable) { switch ( bindable.getBindableType() ) { case ENTITY_TYPE: { return (EntityType) bindable; } case SINGULAR_ATTRIBUTE: { return ( (SingularAttribute) bindable ).getType(); } case PLURAL_ATTRIBUTE: { return ( (PluralAttribute) bindable ).getElementType(); } default: { throw new ParsingException( "Unexpected Bindable type : " + bindable ); } } }
public void printPersistenceModel() { Metamodel metaModel = entityManager.getMetamodel(); Set<EntityType<? extends Object>> types = metaModel.getEntities(); for(EntityType<? extends Object> type : types) { logger.log(Level.INFO, "--> Type: {0}", type); Set attributes = type.getAttributes(); for(Object obj : attributes) { logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getName()); logger.log(Level.INFO, "isCollection: {0}", ((Attribute)obj).isCollection()); logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).isAssociation()); logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getPersistentAttributeType()); } } EntityType<Item> item = metaModel.entity(Item.class); }
private String getIdField(final EntityManager manager, final Class<?> type){ final EntityType<?> entity = manager.getMetamodel().entity(type); SingularAttribute<?, ?> attribute = null; final Set<?> attributes = entity.getSingularAttributes(); for (final Object object : attributes) { attribute = (SingularAttribute<?, ?>) object; if (attribute.isId()){ break; } } if(attribute != null){ return attribute.getName(); }else{ throw new RuntimeException("Is not possible find id attribute in " + type); } }