Example #1
0
  public Object select(
      final BeanContext beanContext,
      final String methodSignature,
      final String returnType,
      final Object... args)
      throws FinderException {
    final String signature = beanContext.getAbstractSchemaName() + "." + methodSignature;

    try {
      // execute the select query
      final Collection<Object> results = cmpEngine.queryBeans(beanContext, signature, args);

      //
      // process the results
      //

      // If we need to return a set...
      final Collection<Object> proxies;
      if (returnType.equals("java.util.Set")) {
        // we collect values into a LinkedHashSet to preserve ordering
        proxies = new LinkedHashSet<Object>();
      } else {
        // otherwise use a simple array list
        proxies = new ArrayList<Object>();
      }

      final boolean isSingleValued =
          !returnType.equals("java.util.Collection") && !returnType.equals("java.util.Set");
      ProxyFactory proxyFactory = null;
      for (Object value : results) {
        // if this is a single valued query and we already have results, throw FinderException
        if (isSingleValued && !proxies.isEmpty()) {
          throw new FinderException(
              "The single valued query " + methodSignature + "returned more than one item");
        }

        // if we have an EntityBean, we need to proxy it
        if (value instanceof EntityBean) {
          final EntityBean entityBean = (EntityBean) value;
          if (proxyFactory == null) {
            final BeanContext result = getBeanContextByClass(entityBean.getClass());
            if (result != null) {
              proxyFactory = new ProxyFactory(result);
            }
          }

          if (proxyFactory != null) {
            if (beanContext.isRemoteQueryResults(methodSignature)) {
              value = proxyFactory.createRemoteProxy(entityBean, this);
            } else {
              value = proxyFactory.createLocalProxy(entityBean, this);
            }
          }
        }
        proxies.add(value);
      }

      // if not single valued, return the set
      if (!isSingleValued) {
        return proxies;
      }

      // single valued query that returned no rows, is an exception
      if (proxies.isEmpty()) {
        throw new ObjectNotFoundException();
      }

      // return the single item.... multiple return values was handled in for loop above
      return proxies.iterator().next();
    } catch (final RuntimeException e) {
      throw new EJBException(e);
    }
  }