예제 #1
0
 /** Construct a join predicate on collection (eg many to many, List) */
 public <T> List<Predicate> byExampleOnManyToMany(
     ManagedType<T> mt,
     Root<T> mtPath,
     final T mtValue,
     SearchParameters sp,
     CriteriaBuilder builder) {
   List<Predicate> predicates = newArrayList();
   for (PluralAttribute<T, ?, ?> pa : mt.getDeclaredPluralAttributes()) {
     if (pa.getCollectionType() == PluralAttribute.CollectionType.LIST) {
       List<?> values = (List<?>) JpaUtil.getValue(mtValue, mt.getAttribute(pa.getName()));
       if (values != null && !values.isEmpty()) {
         if (sp.getUseANDInManyToMany()) {
           if (values.size() > 3) {
             log.warn(
                 "Please note that using AND restriction on an Many to Many relationship requires as many joins as values");
           }
           for (Object value : values) {
             ListJoin<T, ?> join = mtPath.join(mt.getDeclaredList(pa.getName()));
             predicates.add(join.in(value));
           }
         } else {
           ListJoin<T, ?> join = mtPath.join(mt.getDeclaredList(pa.getName()));
           predicates.add(join.in(values));
         }
       }
     }
   }
   return predicates;
 }
예제 #2
0
 /**
  * Invoke byExample method for each not null x-to-one association when their pk is not set. This
  * allows you to search entities based on an associated entity's properties value.
  */
 @SuppressWarnings("unchecked")
 public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(
     ManagedType<T> mt,
     Root<T> mtPath,
     final T mtValue,
     SearchParameters sp,
     CriteriaBuilder builder) {
   List<Predicate> predicates = newArrayList();
   for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
     if (attr.getPersistentAttributeType() == MANY_TO_ONE
         || attr.getPersistentAttributeType() == ONE_TO_ONE) {
       M2O m2oValue = (M2O) JpaUtil.getValue(mtValue, mt.getAttribute(attr.getName()));
       Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
       Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
       ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
       if (m2oValue != null) {
         if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field
           predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId()));
         } else {
           predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
         }
       }
     }
   }
   return predicates;
 }
    private void clearTables(EntityManagerFactory emf) throws SQLException {
      long start = System.currentTimeMillis();
      Set<ManagedType<?>> types = emf.getMetamodel().getManagedTypes();
      EntityManager entityManager = makeEntityManager(emf);
      Set<Class<?>> javaTypes = new HashSet<Class<?>>();
      for (ManagedType<?> type : types) {
        javaTypes.add(type.getJavaType());
      }
      int lastsize = javaTypes.size();
      while (!javaTypes.isEmpty()) {
        Iterator<Class<?>> iterator = javaTypes.iterator();
        Collection<Exception> exceptionsDuringClean = new ArrayList<Exception>();
        while (iterator.hasNext()) {
          Class<?> javaType = iterator.next();
          String name = retrieveEntityName(javaType);
          if (name == null) {
            LOGGER.warn("could not determine name for entity {}", javaType);
            iterator.remove();
            continue;
          }
          try {
            entityManager.getTransaction().begin();
            entityManager.createQuery("DELETE FROM " + name).executeUpdate();
            entityManager.getTransaction().commit();
            iterator.remove();
          } catch (Exception e) {
            if (e instanceof PersistenceException
                || e.getClass()
                    .getName()
                    .equals(
                        "org.eclipse.persistence.exceptions.DatabaseException") // for eclipse-link
                                                                                // < 2.5.0
            ) {
              exceptionsDuringClean.add(e);
              LOGGER.debug("error during delete, could be normal", e);
              entityManager.getTransaction().rollback();
            }
          }
        }
        if (javaTypes.size() == lastsize) {
          entityManager.getTransaction().begin();
          entityManager.createNativeQuery("SHUTDOWN").executeUpdate();

          try {
            entityManager.getTransaction().commit();
          } catch (Exception e) {
            // will always fail because database is shutting down,
            // but we need to clear the transaction-state in the entitymanager
            break;
          }
          LOGGER.error("could not clean database", exceptionsDuringClean.iterator().next());
        }
        lastsize = javaTypes.size();
      }
      entityManager.close();
      LOGGER.info("cleared database in {}ms", System.currentTimeMillis() - start);
    }
  /*
   * ************************************************************************
   * EDM Property Name - RULES
   * ************************************************************************
   * OData Property Names are represented in Camel Case. The first character
   * of JPA Attribute Name is converted to an UpperCase Character and set as
   * OData Property Name. JPA Attribute Name is set as Internal Name for OData
   * Property. The Column name (annotated as @Column(name="x")) is set as
   * column name in the mapping object.
   * ************************************************************************
   * EDM Property Name - RULES
   * ************************************************************************
   */
  public static void build(final JPAEdmPropertyView view, final boolean isComplexMode) {
    Attribute<?, ?> jpaAttribute = view.getJPAAttribute();
    String jpaAttributeName = jpaAttribute.getName();
    String propertyName = null;

    JPAEdmMappingModelAccess mappingModelAccess = view.getJPAEdmMappingModelAccess();
    if (mappingModelAccess != null && mappingModelAccess.isMappingModelExists()) {
      if (isComplexMode) {
        propertyName =
            mappingModelAccess.mapJPAEmbeddableTypeAttribute(
                view.getJPAEdmComplexTypeView()
                    .getJPAEmbeddableType()
                    .getJavaType()
                    .getSimpleName(),
                jpaAttributeName);
      } else {
        propertyName =
            mappingModelAccess.mapJPAAttribute(
                view.getJPAEdmEntityTypeView().getJPAEntityType().getName(), jpaAttributeName);
      }
    }
    if (propertyName == null) {
      propertyName =
          Character.toUpperCase(jpaAttributeName.charAt(0)) + jpaAttributeName.substring(1);
    }

    view.getEdmSimpleProperty().setName(propertyName);

    JPAEdmMapping mapping = new JPAEdmMappingImpl();
    ((Mapping) mapping).setInternalName(jpaAttributeName);

    AnnotatedElement annotatedElement = (AnnotatedElement) jpaAttribute.getJavaMember();
    if (annotatedElement != null) {
      Column column = annotatedElement.getAnnotation(Column.class);
      if (column != null) {
        mapping.setJPAColumnName(column.name());
      }
    } else {
      ManagedType<?> managedType = jpaAttribute.getDeclaringType();
      if (managedType != null) {
        Class<?> clazz = managedType.getJavaType();
        try {
          Field field = clazz.getDeclaredField(jpaAttributeName);
          Column column = field.getAnnotation(Column.class);
          if (column != null) {
            mapping.setJPAColumnName(column.name());
          }
        } catch (SecurityException e) {

        } catch (NoSuchFieldException e) {

        }
      }
    }
    view.getEdmSimpleProperty().setMapping((Mapping) mapping);
  }
예제 #5
0
  /** Add a predicate for each simple property whose value is not null. */
  public <T> List<Predicate> byExample(
      ManagedType<T> mt,
      Path<T> mtPath,
      final T mtValue,
      SearchParameters sp,
      CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
      if (attr.getPersistentAttributeType() == MANY_TO_ONE //
          || attr.getPersistentAttributeType() == ONE_TO_ONE //
          || attr.getPersistentAttributeType() == EMBEDDED) {
        continue;
      }

      Object attrValue = JpaUtil.getValue(mtValue, attr);
      if (attrValue != null) {
        if (attr.getJavaType() == String.class) {
          if (isNotEmpty((String) attrValue)) {
            predicates.add(
                JpaUtil.stringPredicate(
                    mtPath.get(JpaUtil.stringAttribute(mt, attr)), attrValue, sp, builder));
          }
        } else {
          predicates.add(builder.equal(mtPath.get(JpaUtil.attribute(mt, attr)), attrValue));
        }
      }
    }
    return predicates;
  }
예제 #6
0
  @Path("/typepermissions/{username}/{action}")
  @GET
  @RunAsAdmin
  public NameValueList hasTypePermission(
      @PathParam("username") String username, @PathParam("action") String actionName) {
    List<FxRole> roles = new ArrayList<>(1);
    FxRole user = FxRole.loadByName(username, em);
    roles.add(user);

    NameValueList mList = new NameValueList();
    Action action = ACLHelper.getActionByName(actionName);
    for (ManagedType<?> t : JpaMetamodelHelper.getMetamodel().getManagedTypes()) {
      if (permissionChecker.hasPermission(action, roles, t.getJavaType().getSimpleName(), null)) {
        mList.addPair(t.getJavaType().getSimpleName(), "true");
      } else {
        mList.addPair(t.getJavaType().getSimpleName(), "false");
      }
    }
    return mList;
  }