Пример #1
0
/**
 * @author blair christensen.
 * @version $Id: TestCompositeModel.java,v 1.2 2009-03-20 19:56:40 mchyzer Exp $
 */
public class TestCompositeModel extends GrouperTest {

  public static void main(String[] args) {
    TestRunner.run(TestCompositeModel.class);
  }

  // Private Static Class Constants
  private static final Log LOG = GrouperUtil.getLog(TestCompositeModel.class);

  public TestCompositeModel(String name) {
    super(name);
  }

  public void testFailInvalidSession() {
    LOG.info("testFailInvalidSession");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          new Composite(null, null, null, null, null);
          Assert.fail("created composite with invalid session");
        }
        catch (IllegalStateException eIS) {
          Assert.assertTrue("OK: did not create composite with null session", true);
        }
        catch (Exception e) {
          T.e(e);
        }
    */
  } // public void testFailInvalidSession()

  public void testFailNullOwner() {
    LOG.info("testFailNullOwner");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(0, 0, 0);
          new Composite(r.rs, null, null, null, null);
          r.rs.stop();
          Assert.fail("created composite with null owner");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with null owner", true);
          T.string("error message", E.COMP_O, eM.getMessage());
        }
        catch (Exception e) {
          T.e(e);
        }
    */
  } // public void testFailNullOwner()

  public void testIntersectionComposite() {
    LOG.info("testIntersectionComposite");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R         r     = R.populateRegistry(1, 2, 0);
          Owner     owner = r.ns;
          Owner     left  = r.getGroup("a", "a");
          Owner     right = r.getGroup("a", "b");
          Composite c     = new Composite(
            r.rs, owner, left, right, CompositeType.INTERSECTION
          );
          Assert.assertTrue("created intersection composite", true);
          Assert.assertTrue("instanceof Composite", c instanceof Composite);
          Assert.assertEquals( "owner", owner.getUuid(),            c.getOwner() );
          Assert.assertEquals( "left",  left.getUuid(),             c.getLeft()  );
          Assert.assertEquals( "right", right.getUuid(),            c.getRight() );
          Assert.assertEquals( "type",  CompositeType.INTERSECTION, c.getType()  );
          r.rs.stop();
        }
        catch (ModelException eM) {
          Assert.fail("could not create intersection composite: " + eM.getMessage());
        }
        catch (Exception e) {
          T.e(e);
        }
    */
  } // public void testIntersectionComposite()

  public void testComplementComposite() {
    LOG.info("testComplementComposite");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R         r     = R.populateRegistry(1, 2, 0);
          Owner     owner = r.ns;
          Owner     left  = r.getGroup("a", "a");
          Owner     right = r.getGroup("a", "b");
          Composite c     = new Composite(
            r.rs, owner, left, right, CompositeType.COMPLEMENT
          );
          Assert.assertTrue("created complement composite", true);
          Assert.assertTrue("instanceof Composite", c instanceof Composite);
          Assert.assertEquals("owner",  owner.getUuid(),          c.getOwner() );
          Assert.assertEquals("left",   left.getUuid(),           c.getLeft()  );
          Assert.assertEquals("right",  right.getUuid(),          c.getRight() );
          Assert.assertEquals("type",   CompositeType.COMPLEMENT, c.getType()  );
          r.rs.stop();
        }
        catch (ModelException eM) {
          Assert.fail("could not create complement composite: " + eM.getMessage());
        }
        catch (Exception e) {
          T.e(e);
        }
    */
  } // public void testComplementComposite()

  public void testFailInvalidType() {
    LOG.info("testFailInvalidType");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(
            r.rs, r.ns, r.getGroup("a", "a"), r.getGroup("a", "b"),
            CompositeType.getInstance("invalid type")
          );
          r.rs.stop();
          Assert.fail("created composite with null type");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with invalid type", true);
          T.string("error message", E.COMP_T, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailInvalidType()

  public void testFailLeftEqualsRight() {
    LOG.info("testFailLeftEqualsRight");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(
            r.rs, r.getGroup("a", "a"), r.getGroup("a", "b"), r.getGroup("a", "b"), CompositeType.UNION
          );
          r.rs.stop();
          Assert.fail("created composite with left == right");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with left == right", true);
          T.string("error message", E.COMP_LR, eM.getMessage());
        }
        catch (Exception e) {
          T.e(e);
        }
    */
  } // public void testFailLeftEqualsRight()

  public void testFailLeftNotGroup() {
    LOG.info("testFailLeftNotGroup");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(
            r.rs, r.ns, r.getStem("a"), r.getGroup("a", "b"),
            CompositeType.getInstance("union")
          );
          r.rs.stop();
          Assert.fail("created composite with !group left");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with !group left", true);
          T.string("error message", E.COMP_LC, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailLeftNotGroup()

  public void testFailNullLeft() {
    LOG.info("testFailNullLeft");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(0, 0, 0);
          new Composite(r.rs, r.ns, null, null, null);
          r.rs.stop();
          Assert.fail("created composite with null left");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with null left", true);
          T.string("error message", E.COMP_L, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailNullLeft()

  public void testFailNullRight() {
    LOG.info("testFailNullRight");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(r.rs, r.ns, r.getGroup("a", "a"), null, null);
          r.rs.stop();
          Assert.fail("created composite with null right");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with null right", true);
          T.string("error message", E.COMP_R, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailNullRight()

  public void testFailNullType() {
    LOG.info("testFailNullType");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(
            r.rs, r.ns, r.getGroup("a", "a"), r.getGroup("a", "b"), null
          );
          r.rs.stop();
          Assert.fail("created composite with null type");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with null type", true);
          T.string("error message", E.COMP_T, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailNullType()

  public void testFailOwnerEqualsLeftFactor() {
    LOG.info("testFailOwnerEqualsLeftFactor");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(
            r.rs, r.getGroup("a", "a"), r.getGroup("a", "a"), r.getGroup("a", "b"), CompositeType.UNION
          );
          r.rs.stop();
          Assert.fail("created composite where left == owner");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: cannot create composites where left == owner", true);
          T.string("error message", E.COMP_CL, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailOwnerEqualsLeftFactor()

  public void testFailOwnerEqualsRightFactor() {
    LOG.info("testFailOwnerEqualsRightFactor");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(
            r.rs, r.getGroup("a", "b"), r.getGroup("a", "a"), r.getGroup("a", "b"), CompositeType.UNION
          );
          r.rs.stop();
          Assert.fail("created composite where right == owner");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: cannot create composites where right == owner", true);
          T.string("error message", E.COMP_CR, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailOwnerEqualsRightFactor()

  public void testFailOwnerNotGroupOrStem() {
    LOG.info("testFailOwnerNotGroupOrStem");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          Composite c0 = new Composite(
            r.rs, r.ns, r.getGroup("a", "a"), r.getGroup("a", "b"), CompositeType.UNION
          );
          try {
            new Composite(
            r.rs, c0, r.getGroup("a", "a"), r.getGroup("a", "b"), CompositeType.UNION
            );
            Assert.fail("created composite with composite as owner");
          }
          catch (ModelException eM) {
            Assert.assertTrue("OK: cannot create composites with !(group|stem) as owner", true);
            T.string("error message", E.COMP_OC, eM.getMessage());
          }
          finally {
            r.rs.stop();
          }
        }
        catch (Exception e) {
          T.e(e);
        }
    */
  } // public void testFailOwnerNotGroupOrStem()

  public void testFailRightNotGroup() {
    LOG.info("testFailRightNotGroup");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R r = R.populateRegistry(1, 2, 0);
          new Composite(
            r.rs, r.ns, r.getGroup("a", "b"), r.getStem("a"),
            CompositeType.getInstance("union")
          );
          r.rs.stop();
          Assert.fail("created composite with !group rifht");
        }
        catch (ModelException eM) {
          Assert.assertTrue("OK: did not create composite with !group right", true);
          T.string("error message", E.COMP_RC, eM.getMessage());
        }
        catch (Exception e) {
          Assert.fail("unexpected exception: " + e.getMessage());
        }
    */
  } // public void testFailRightNotGroup()

  public void testUnionComposite() {
    LOG.info("testUnionComposite");
    assertTrue("TODO 20070131 this test no longer works", true);
    /*
        try {
          R         r     = R.populateRegistry(1, 2, 0);
          Owner     owner = r.ns;
          Owner     left  = r.getGroup("a", "a");
          Owner     right = r.getGroup("a", "b");
          Composite c     = new Composite(
            r.rs, owner, left, right, CompositeType.UNION
          );
          Assert.assertTrue("created union composite", true);
          Assert.assertTrue("instanceof Composite", c instanceof Composite);
          Assert.assertEquals( "owner", owner.getUuid(),      c.getOwner() );
          Assert.assertEquals( "left",  left.getUuid(),       c.getLeft()  ) ;
          Assert.assertEquals( "right", right.getUuid(),      c.getRight() );
          Assert.assertEquals( "type",  CompositeType.UNION,  c.getType()  );
          r.rs.stop();
        }
        catch (ModelException eM) {
          Assert.fail("could not create union composite: " + eM.getMessage());
        }
        catch (Exception e) {
          T.e(e);
        }
    */
  } // public void testUnionComposite()
}
Пример #2
0
/**
 * Hooks to handle the field associated to the dynamic group type.
 *
 * @author GIP RECIA - A. Deman 18 May 2009
 */
public class ESCOAttributeHooks extends AttributeHooks implements Serializable {

  /** Serial version UID. */
  private static final long serialVersionUID = 9122480003264627999L;

  /** The logger to use. */
  private static final Log LOGGER = GrouperUtil.getLog(ESCOAttributeHooks.class);

  /** Builds an instance of ESCOAttributeHooks. */
  public ESCOAttributeHooks() {

    if (LOGGER.isInfoEnabled()) {
      LOGGER.info("Creation of an hooks of class: " + getClass().getSimpleName());
    }
  }

  /**
   * Tests and veto if needed a modification of an attribute that contains the logic definition of a
   * group.
   *
   * @param hooksContext The hook context.
   * @param preUpdateBean The available Grouper information.
   * @see edu.internet2.middleware.grouper.hooks.AttributeHooks#attributePreUpdate(HooksContext,
   *     HooksAttributeBean)
   */
  @Override
  public void attributePreUpdate(
      final HooksContext hooksContext, final HooksAttributeBean preUpdateBean) {

    Attribute attribute = preUpdateBean.getAttribute();

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(
          "preUpdate attribute: " + attribute.getAttrName() + ": '" + attribute.getValue() + "'");
    }
  }

  /**
   * Handles the fact that a dynamic groups becomes a static group.
   *
   * @param hooksContext The hook context.
   * @param postDeleteBean The available Grouper information.
   */
  @Override
  public void attributePostDelete(
      final HooksContext hooksContext, final HooksAttributeBean postDeleteBean) {

    Attribute attribute = postDeleteBean.getAttribute();

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(
          "postDelete attribute: " + attribute.getGroupUuid() + ", " + attribute.getAttrName());
    }
  }

  /**
   * @param hooksContext
   * @param preInsertBean
   * @see edu.internet2.middleware.grouper.hooks.AttributeHooks#attributePreInsert(HooksContext,
   *     HooksAttributeBean)
   */
  @Override
  public void attributePreInsert(
      final HooksContext hooksContext, final HooksAttributeBean preInsertBean) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(
          "preInsert attribute: "
              + preInsertBean.getAttribute().getAttrName()
              + " = '"
              + preInsertBean.getAttribute().getValue()
              + "'");
    }
  }
}
Пример #3
0
/**
 * for simple criteria queries, use this instead of inverse of control. this will do proper error
 * handling and descriptive exception handling. This will by default use the transaction modes
 * GrouperTransactionType.READONLY_OR_USE_EXISTING, and
 * GrouperTransactionType.READ_WRITE_OR_USE_EXISTING depending on if a transaction is needed.
 *
 * @author mchyzer
 */
public class ByCriteriaStatic {

  /** logger */
  private static final Log LOG = GrouperUtil.getLog(ByCriteriaStatic.class);

  /**
   * assign a transaction type, default use the transaction modes
   * GrouperTransactionType.READONLY_OR_USE_EXISTING, and
   * GrouperTransactionType.READ_WRITE_OR_USE_EXISTING depending on if a transaction is needed
   */
  private GrouperTransactionType grouperTransactionType = null;

  /** assign if this query is cacheable or not. */
  private Boolean cacheable = null;

  /**
   * assign a different grouperTransactionType (e.g. for autonomous transactions)
   *
   * @param theGrouperTransactionType
   * @return the same object for chaining
   */
  public ByCriteriaStatic setGrouperTransactionType(
      GrouperTransactionType theGrouperTransactionType) {
    this.grouperTransactionType = theGrouperTransactionType;
    return this;
  }

  /**
   * assign if this query is cacheable or not.
   *
   * @param cacheable the cacheable to set
   * @return this object for chaining
   */
  public ByCriteriaStatic setCacheable(Boolean cacheable) {
    this.cacheable = cacheable;
    return this;
  }

  /**
   *
   *
   * <pre>
   * call hql list result, and put the results in an ordered set
   *
   * e.g.
   *
   * Set<GroupTypeTupleDTO> groupTypeTupleDTOs =
   *  HibernateSession.byHqlStatic()
   *    .createQuery("from Hib3GroupTypeTupleDAO as gtt where gtt.groupUuid = :group")
   *    .setCacheable(false).setString("group", uuid).listSet(Hib3GroupTypeTupleDAO.class);
   * </pre>
   *
   * @param returnType type of the result (can typecast)
   * @param <S> is the template
   * @param theCriterions
   * @return the ordered set or the empty set if not found (never null)
   * @throws GrouperDAOException
   */
  public <S> Set<S> listSet(Class<S> returnType, Criterion theCriterions)
      throws GrouperDAOException {
    Set<S> result = new LinkedHashSet<S>(this.list(returnType, theCriterions));
    return result;
  }

  /**
   *
   *
   * <pre>
   * call criteria list result, and put the results in map with the key as one of the fields
   *
   * </pre>
   *
   * @param valueClass type of the result (can typecast)
   * @param theCriterions are the criteria for the query
   * @param keyClass is the type of the key of the map
   * @param <K> is the template of the key of the map
   * @param <V> is the template of the value of the map
   * @param keyPropertyName name of the javabeans property for the key in the map
   * @return the ordered set or the empty set if not found (never null)
   * @throws GrouperDAOException
   */
  public <K, V> Map<K, V> listMap(
      final Class<K> keyClass,
      final Class<V> valueClass,
      Criterion theCriterions,
      String keyPropertyName)
      throws GrouperDAOException {
    List<V> list = this.list(valueClass, theCriterions);
    Map<K, V> map = GrouperUtil.listToMap(list, keyClass, valueClass, keyPropertyName);
    return map;
  }

  /**
   * string value for error handling
   *
   * @return the string value
   */
  @Override
  public String toString() {
    StringBuilder result = new StringBuilder("ByCriteriaStatic, persistentClass: '");
    result
        .append(this.persistentClass)
        .append("', criterions: ")
        .append(this.criterions)
        .append("', cacheable: ")
        .append(this.cacheable);
    result.append(", cacheRegion: ").append(this.cacheRegion);
    result.append(", entityName: ").append(this.entityName);
    result.append(", tx type: ").append(this.grouperTransactionType);
    if (this.queryOptions != null) {
      result.append(", options: ").append(this.queryOptions.toString());
    }
    return result.toString();
  }

  /** cache region for cache */
  private String cacheRegion = null;

  /** alias for class */
  private String alias = null;

  /** criterions to query */
  private Criterion criterions = null;

  /** class to execute criteria on */
  private Class<?> persistentClass = null;

  /** if we are sorting, paging, resultSize, etc */
  private QueryOptions queryOptions = null;

  /** assign the entity name to refer to this mapping (multiple mappings per object) */
  private String entityName = null;

  /**
   * add a paging/sorting/resultSetSize, etc to the query
   *
   * @param queryOptions1
   * @return this for chaining
   */
  public ByCriteriaStatic options(QueryOptions queryOptions1) {
    this.queryOptions = queryOptions1;
    return this;
  }

  /**
   * cache region for cache
   *
   * @param cacheRegion the cacheRegion to set
   * @return this object for chaining
   */
  public ByCriteriaStatic setCacheRegion(String cacheRegion) {
    this.cacheRegion = cacheRegion;
    return this;
  }

  /**
   * alias for queried class
   *
   * @param theAlias the cacheRegion to set
   * @return this object for chaining
   */
  public ByCriteriaStatic setAlias(String theAlias) {
    this.alias = theAlias;
    return this;
  }

  /**
   *
   *
   * <pre>
   * call hql unique result (returns one or null)
   *
   * e.g.
   *
   * Hib3GroupDAO hib3GroupDAO = HibernateSession.byHqlStatic()
   * .createQuery("from Hib3GroupDAO as g where g.uuid = :uuid")
   *  .setCacheable(false)
   *  .setCacheRegion(KLASS + ".Exists")
   *  .setString("uuid", uuid).uniqueResult(Hib3GroupDAO.class);
   *
   * </pre>
   *
   * @param returnType type of the result (in future can use this for typecasting)
   * @param theCriterions are the criterions to use (pack multiple with HibUtils.listCrit())
   * @param <T> is the template
   * @return the object or null if none found
   * @throws GrouperDAOException
   */
  public <T> T uniqueResult(Class<T> returnType, Criterion theCriterions)
      throws GrouperDAOException {
    this.persistentClass = returnType;
    this.criterions = theCriterions;
    try {
      GrouperTransactionType grouperTransactionTypeToUse =
          (GrouperTransactionType)
              ObjectUtils.defaultIfNull(
                  this.grouperTransactionType, GrouperTransactionType.READONLY_OR_USE_EXISTING);

      T result =
          (T)
              HibernateSession.callbackHibernateSession(
                  grouperTransactionTypeToUse,
                  AuditControl.WILL_NOT_AUDIT,
                  new HibernateHandler() {

                    public Object callback(HibernateHandlerBean hibernateHandlerBean)
                        throws GrouperDAOException {
                      HibernateSession hibernateSession =
                          hibernateHandlerBean.getHibernateSession();

                      Session session = hibernateSession.getSession();
                      Criteria criteria = ByCriteriaStatic.this.attachCriteriaInfo(session);
                      GrouperContext.incrementQueryCount();
                      Object object = criteria.uniqueResult();
                      HibUtils.evict(hibernateSession, object, true);
                      return object;
                    }
                  });

      return result;
    } catch (GrouperStaleObjectStateException e) {
      throw e;
    } catch (RuntimeException e) {

      String errorString = "Exception in uniqueResult: (" + returnType + "), " + this;

      if (!GrouperUtil.injectInException(e, errorString)) {
        LOG.error(errorString, e);
      }

      throw e;
    }
  }

  /** query count exec queries, used for testing */
  public static int queryCountQueries = 0;

  /**
   *
   *
   * <pre>
   * call hql unique result (returns one or null)
   *
   * e.g.
   *
   * List<Hib3GroupTypeTupleDAO> hib3GroupTypeTupleDAOs =
   *  HibernateSession.byHqlStatic()
   *    .createQuery("from Hib3GroupTypeTupleDAO as gtt where gtt.groupUuid = :group")
   *    .setCacheable(false).setString("group", uuid).list(Hib3GroupTypeTupleDAO.class);
   * </pre>
   *
   * @param returnType type of the result (can typecast)
   * @param theCriterions are the criterions to use (pack multiple with HibUtils.listCrit())
   * @param <T> is the template
   * @return the list or the empty list if not found (never null)
   * @throws GrouperDAOException
   */
  public <T> List<T> list(Class<T> returnType, Criterion theCriterions) throws GrouperDAOException {
    this.persistentClass = returnType;
    this.criterions = theCriterions;
    try {
      GrouperTransactionType grouperTransactionTypeToUse =
          (GrouperTransactionType)
              ObjectUtils.defaultIfNull(
                  this.grouperTransactionType, GrouperTransactionType.READONLY_OR_USE_EXISTING);

      List<T> result =
          (List<T>)
              HibernateSession.callbackHibernateSession(
                  grouperTransactionTypeToUse,
                  AuditControl.WILL_NOT_AUDIT,
                  new HibernateHandler() {

                    public Object callback(HibernateHandlerBean hibernateHandlerBean)
                        throws GrouperDAOException {
                      HibernateSession hibernateSession =
                          hibernateHandlerBean.getHibernateSession();

                      Session session = hibernateSession.getSession();
                      List<T> list = null;

                      // see if we are even retrieving the results
                      if (ByCriteriaStatic.this.queryOptions == null
                          || ByCriteriaStatic.this.queryOptions.isRetrieveResults()) {
                        Criteria criteria = ByCriteriaStatic.this.attachCriteriaInfo(session);
                        GrouperContext.incrementQueryCount();
                        // not sure this can ever be null, but make sure not to make iterating
                        // results easier
                        list = GrouperUtil.nonNull(criteria.list());
                        HibUtils.evict(hibernateSession, list, true);
                      }
                      // no nulls
                      list = GrouperUtil.nonNull(list);
                      QueryPaging queryPaging =
                          ByCriteriaStatic.this.queryOptions == null
                              ? null
                              : ByCriteriaStatic.this.queryOptions.getQueryPaging();

                      // now see if we should get the query count
                      boolean retrieveQueryCountNotForPaging =
                          ByCriteriaStatic.this.queryOptions != null
                              && ByCriteriaStatic.this.queryOptions.isRetrieveCount();
                      boolean findQueryCount =
                          (queryPaging != null && queryPaging.isDoTotalCount())
                              || (retrieveQueryCountNotForPaging);
                      if (findQueryCount) {

                        long resultSize = -1;
                        if (queryPaging != null) {
                          // see if we already know the total size (if less than page size and first
                          // page)
                          resultSize = GrouperUtil.length(list);
                          if (resultSize >= queryPaging.getPageSize()) {
                            resultSize = -1;
                          } else {
                            // we are on the last page, see how many records came before us, add
                            // those in
                            resultSize +=
                                (queryPaging.getPageSize() * (queryPaging.getPageNumber() - 1));
                          }
                        }

                        // do this if we dont have a total, or if we are not caching the total
                        if ((queryPaging != null
                                && (queryPaging.getTotalRecordCount() < 0
                                    || !queryPaging.isCacheTotalCount()))
                            || resultSize > -1
                            || retrieveQueryCountNotForPaging) {

                          // if we dont already know the size
                          if (resultSize == -1) {
                            queryCountQueries++;

                            Criteria countQuery =
                                StringUtils.isBlank(ByCriteriaStatic.this.alias)
                                    ? session.createCriteria(ByCriteriaStatic.this.persistentClass)
                                    : session.createCriteria(ByCriteriaStatic.this.alias);

                            // turn it into a row count
                            countQuery.setProjection(
                                Projections.projectionList().add(Projections.rowCount()));

                            // add criterions
                            if (ByCriteriaStatic.this.criterions != null) {
                              countQuery.add(ByCriteriaStatic.this.criterions);
                            }
                            resultSize = (Long) countQuery.list().get(0);
                          }

                          if (queryPaging != null) {
                            queryPaging.setTotalRecordCount((int) resultSize);

                            // calculate the page stuff like how many pages etc
                            queryPaging.calculateIndexes();
                          }
                          if (retrieveQueryCountNotForPaging) {
                            ByCriteriaStatic.this.queryOptions.setCount(resultSize);
                          }
                        }
                      }

                      return list;
                    }
                  });

      return result;
    } catch (GrouperStaleObjectStateException e) {
      throw e;
    } catch (GrouperDAOException e) {
      GrouperUtil.injectInException(e, "Exception in list: (" + returnType + "), " + this);
      throw e;
    } catch (RuntimeException e) {
      GrouperUtil.injectInException(e, "Exception in list: (" + returnType + "), " + this);
      throw e;
    }
  }

  /**
   * prepare query based on criteria
   *
   * @param session hib session
   * @return the query
   */
  private Criteria attachCriteriaInfo(Session session) {
    Criteria query = null;

    if (StringUtils.isBlank(this.entityName)) {
      if (StringUtils.isBlank(this.alias)) {
        query = session.createCriteria(this.persistentClass);
      } else {
        query = session.createCriteria(this.persistentClass, alias);
      }
    } else {
      query = session.createCriteria(this.entityName);
    }

    // add criterions
    if (this.criterions != null) {
      query.add(this.criterions);
    }
    boolean secondLevelCaching =
        HibUtils.secondLevelCaching(
            ByCriteriaStatic.this.cacheable, ByCriteriaStatic.this.queryOptions);
    query.setCacheable(secondLevelCaching);

    if (secondLevelCaching) {
      String secondLevelCacheRegion =
          HibUtils.secondLevelCacheRegion(
              ByCriteriaStatic.this.cacheRegion, ByCriteriaStatic.this.queryOptions);
      if (!StringUtils.isBlank(secondLevelCacheRegion)) {
        query.setCacheRegion(secondLevelCacheRegion);
      }
    }

    QuerySort querySort = this.queryOptions == null ? null : this.queryOptions.getQuerySort();
    if (querySort != null) {
      List<QuerySortField> sorts = querySort.getQuerySortFields();

      for (QuerySortField theSort : GrouperUtil.nonNull(sorts)) {

        Order order =
            theSort.isAscending()
                ? Order.asc(theSort.getColumn())
                : Order.desc(theSort.getColumn());

        query.addOrder(order);
      }
    }
    QueryPaging queryPaging = this.queryOptions == null ? null : this.queryOptions.getQueryPaging();
    if (queryPaging != null) {

      // GRP-1024: sql server problems with paging page number when not initted
      if (queryPaging.getFirstIndexOnPage() < 0) {
        query.setFirstResult(0);
      } else {
        query.setFirstResult(queryPaging.getFirstIndexOnPage());
      }

      query.setMaxResults(queryPaging.getPageSize());
    }

    return query;
  }

  /**
   * entity name if the object is mapped to more than one table
   *
   * @param theEntityName the entity name of the object
   * @return this object for chaining
   */
  public ByCriteriaStatic setEntityName(String theEntityName) {
    this.entityName = theEntityName;
    return this;
  }

  /** constructor */
  ByCriteriaStatic() {}
}
Пример #4
0
/**
 * Class to start a simple HTTP/HTTPS server to listen for incoming event notifications to process
 * as changes in the Grouper registry. Server is started as a quartz job
 *
 * <p>SSL and basic auth supported for security. All configuration in grouper-loader.properties
 */
public class EsbHttpServer implements Job {

  private static final Log LOG = GrouperUtil.getLog(EsbHttpServer.class);

  /**
   * Method to start the Jetty server
   *
   * @param jobDataMap
   */
  private void startServer(JobDataMap jobDataMap) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Initialising HTTP server");
    }
    int port = Integer.parseInt(jobDataMap.getString("port"));
    String bindAddress = jobDataMap.getString("bindAddress");
    String authConfigFile = jobDataMap.getString("authConfigFile");
    String keystore = jobDataMap.getString("keystore");
    Server server = new Server();
    if (keystore == null || keystore.equals("")) {
      LOG.info("Starting with HTTP (non-encrypted) protocol");
      SelectChannelConnector connector = new SelectChannelConnector();
      connector.setHost(bindAddress);
      connector.setPort(port);
      server.addConnector(connector);
    } else {
      LOG.info("Starting with HTTPS (encrypted) protocol");
      SslSocketConnector sslConnector = new SslSocketConnector();
      sslConnector.setHost(bindAddress);
      sslConnector.setPort(port);
      sslConnector.setKeystore(jobDataMap.getString("keystore"));
      sslConnector.setKeyPassword(jobDataMap.getString("keyPassword"));
      sslConnector.setTruststore(jobDataMap.getString("trustStore"));
      sslConnector.setTrustPassword(jobDataMap.getString("trustPassword"));
      sslConnector.setPassword(jobDataMap.getString("password"));
      server.addConnector(sslConnector);
    }

    if (authConfigFile != null && !(authConfigFile.equals(""))) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Requiring basic auth");
      }
      Constraint constraint = new Constraint();
      constraint.setName(Constraint.__BASIC_AUTH);
      ;
      constraint.setRoles(new String[] {"user", "grouper"});
      constraint.setAuthenticate(true);

      ConstraintMapping cm = new ConstraintMapping();
      cm.setConstraint(constraint);
      cm.setPathSpec("/*");

      SecurityHandler sh = new SecurityHandler();
      try {
        sh.setUserRealm(new HashUserRealm("Grouper", authConfigFile));
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      sh.setConstraintMappings(new ConstraintMapping[] {cm});

      Handler[] handlers = new Handler[] {sh, new EsbHttpHandler()};
      server.setHandlers(handlers);

    } else {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Not requiring basic auth");
      }
      server.setHandler(new EsbHttpHandler());
    }
    try {
      server.start();
      LOG.info("HTTP server started on address " + bindAddress + " port " + port);
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /** Method called by quartz to start the server */
  public void execute(JobExecutionContext context) throws JobExecutionException {
    // TODO Auto-generated method stub
    JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
    this.startServer(jobDataMap);
  }
}
Пример #5
0
/** Publishes Grouper events to HTTP(S) server as JSON strings */
public class EsbHttpPublisher extends EsbListenerBase {

  private static final Log LOG = GrouperUtil.getLog(EsbHttpPublisher.class);

  @Override
  public boolean dispatchEvent(String eventJsonString, String consumerName) {
    // TODO Auto-generated method stub

    String urlString =
        GrouperLoaderConfig.retrieveConfig()
            .propertyValueString("changeLog.consumer." + consumerName + ".publisher.url");
    String username =
        GrouperLoaderConfig.retrieveConfig()
            .propertyValueString("changeLog.consumer." + consumerName + ".publisher.username", "");
    String password =
        GrouperLoaderConfig.retrieveConfig()
            .propertyValueString("changeLog.consumer." + consumerName + ".publisher.password", "");
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Consumer name: "
              + consumerName
              + " sending "
              + GrouperUtil.indent(eventJsonString, false)
              + " to "
              + urlString);
    }
    int retries =
        GrouperLoaderConfig.retrieveConfig()
            .propertyValueInt("changeLog.consumer." + consumerName + ".publisher.retries", 0);
    int timeout =
        GrouperLoaderConfig.retrieveConfig()
            .propertyValueInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000);
    PostMethod post = new PostMethod(urlString);
    post.getParams()
        .setParameter(
            HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, false));
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout));
    // post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    // activemq might require: application/x-www-form-urlencoded
    post.setRequestHeader(
        "Content-Type",
        GrouperLoaderConfig.retrieveConfig()
            .propertyValueString(
                "changeLog.consumer." + consumerName + ".publisher.contentTypeHeader",
                "application/json; charset=utf-8"));
    RequestEntity requestEntity;
    try {
      // requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8");

      String stringRequestEntityPrefix = "";

      if (GrouperLoaderConfig.retrieveConfig()
          .containsKey(
              "changeLog.consumer." + consumerName + ".publisher.stringRequestEntityPrefix")) {
        stringRequestEntityPrefix =
            GrouperLoaderConfig.retrieveConfig()
                .propertyValueString(
                    "changeLog.consumer." + consumerName + ".publisher.stringRequestEntityPrefix");
      }

      // activemq might require: application/x-www-form-urlencoded
      requestEntity =
          new StringRequestEntity(
              StringUtils.defaultString(stringRequestEntityPrefix) + eventJsonString,
              GrouperLoaderConfig.retrieveConfig()
                  .propertyValueString(
                      "changeLog.consumer."
                          + consumerName
                          + ".publisher.stringRequestEntityContentType",
                      "application/json"),
              "utf-8");

      post.setRequestEntity(requestEntity);
      HttpClient httpClient = new HttpClient();
      if (!(username.equals(""))) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Authenticating using basic auth");
        }
        URL url = new URL(urlString);
        httpClient
            .getState()
            .setCredentials(
                new AuthScope(null, url.getPort(), null),
                new UsernamePasswordCredentials(username, password));
        httpClient.getParams().setAuthenticationPreemptive(true);
        post.setDoAuthentication(true);
      }
      int statusCode = httpClient.executeMethod(post);
      if (statusCode == 200) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Status code 200 recieved, event sent OK");
        }
        return true;
      } else {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Status code " + statusCode + " recieved, event send failed");
        }
        return false;
      }
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (HttpException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return false;
  }

  @Override
  public void disconnect() {
    // Unused, client does not maintain a persistent connection in this version

  }
}