/**
   * Implements a delete method
   *
   * @param leftId The id of the parent model
   * @param rightId The id of the child model
   * @return
   */
  public Promise<Result> delete(final Long leftId, final Long rightId) {
    return Promise.promise(
        new Function0<Result>() {
          public Result apply() {
            L left = createLeftQuery(new ServiceParams()).where().eq("id", leftId).findUnique();
            if (left == null) {
              return CrudResults.notFoundError(leftClass, leftId);
            }

            List<? extends Model> junctions;

            junctions = applyJunctionFiltering(leftId, rightId, null);

            List<? extends Model> rights = getChildObjects(junctions, new ServiceParams());
            List<? extends Model> toDelete = junctions;

            if (rights.size() == 0) {
              return CrudResults.notFoundError(getBaseModelClass(), rightId);
            }
            // Can we not just do, createJunctionQuery().eq(leftId).eq(rightId).findList()?

            for (Model m : toDelete) {
              m.delete();
            }
            return noContent();
          }
        });
  }
  /**
   * Implements a bulk delete method
   *
   * @param leftId The id of the parent object
   * @return
   */
  @play.db.ebean.Transactional
  public Promise<Result> deleteBulk(final Long leftId) {
    return Promise.promise(
        new Function0<Result>() {
          public Result apply() {
            L left = createLeftQuery(new ServiceParams()).where().eq("id", leftId).findUnique();
            if (left == null) {
              return CrudResults.notFoundError(leftClass, leftId);
            }

            List<Long> items = getItemsFromRequest();

            if (items != null) {
              // TODO: Ebean doesn't support deletes based off a where clause.
              // We should switch this to raw sql to reduce it to 1 db call instead of 2. V
              List<J> junks = applyJunctionFiltering(leftId, items, null);
              if (junks.size() == items.size()) {
                // modelMediator.beforeModelDelete(junks);
                Ebean.delete(junks);
                // modelMediator.afterModelDelete(junks);
                return noContent();
              } else {
                return CrudResults.notFoundError(junctionClass, "");
              }
            } else {
              return CrudResults.error("Array of objects with ids required");
            }
          }
        });
  }
  /**
   * Action Read a single model.
   *
   * @param leftId The id of the parent model.
   * @param rightId The id of the child model.
   * @param fields Fields to retrieve off the model. If not provided, retrieves all.
   * @param fetches Get any 1to1 relationships off the model. By default, it returns only the id off
   *     the relationships.
   * @return A promise containing the results
   */
  public Promise<Result> read(
      final Long leftId, final Long rightId, final String fields, final String fetches) {
    return Promise.promise(
        new Function0<Result>() {
          public Result apply() {
            L left = createLeftQuery(new ServiceParams()).where().eq("id", leftId).findUnique();
            if (left == null) {
              return CrudResults.notFoundError(leftClass, leftId);
            }

            ServiceParams rightParams = new ServiceParams(fields, fetches);
            ServiceParams params = new ServiceParams(fields, fetches, rightFieldName + ".");
            Query<J> query = createJunctionQuery(params);

            handleFieldsAndFetches(query, junctionClass, params);
            List<J> junctions = applyJunctionFiltering(leftId, rightId, query);
            List<R> rights = getChildObjects(junctions, rightParams);

            if (rights.size() == 0) {
              return CrudResults.notFoundError(getBaseModelClass(), rightId);
            }

            List<? extends Model> returnList = rights;
            return CrudResults.success(returnList.get(0));
          }
        });
  }
Esempio n. 4
0
 public static Promise<Proposal> findKeynote() {
   return Promise.promise(
           new Function0<Proposal>() {
             @Override
             public Proposal apply() throws Throwable {
               return find.where().eq("type", SessionType.Keynote).findUnique();
             }
           },
           ctx)
       .recover(
           new Function<Throwable, Proposal>() {
             @Override
             public Proposal apply(Throwable throwable) throws Throwable {
               Logger.error("Failed to fetch keynote information", throwable);
               Proposal proposal = new Proposal();
               proposal.title = "COMING SOON!";
               proposal.content = "";
               Speaker speaker = new Speaker();
               speaker.name = "";
               speaker.pictureUrl = "";
               speaker.twitterId = "";
               proposal.speaker = speaker;
               return proposal;
             }
           },
           ctx);
 }
  /**
   * Action Query a list of models.
   *
   * @param leftId The id of the parent model
   * @param offset An offset from the first item to start filtering from. Used for paging.
   * @param count The total count to query. This is the length of items to query after the offset.
   *     Used for paging.
   * @param orderBy Order the queried models in order by the given properties of the model.
   * @param fields The fields, or properties, of the models to retrieve.
   * @param fetches If the model has 1to1 relationships, use this to retrieve those relationships.
   *     By default, returns the id of each relationship.
   * @param queryString Filter the models with a comma-delimited query string in the format of
   *     "property:value".
   * @return A promise containing the results
   */
  public Promise<Result> list(
      final Long leftId,
      final Integer offset,
      final Integer count,
      final String orderBy,
      final String fields,
      final String fetches,
      final String queryString) {
    return Promise.promise(
        new Function0<Result>() {
          public Result apply() {
            L left = createLeftQuery(new ServiceParams()).where().eq("id", leftId).findUnique();
            if (left == null) {
              return CrudResults.notFoundError(leftClass, leftId);
            }

            ServiceParams rightParams =
                new ServiceParams(offset, count, orderBy, fields, fetches, queryString);
            ServiceParams params =
                new ServiceParams(
                    offset, count, orderBy, fields, fetches, queryString, rightFieldName + ".");

            Query<J> query = createJunctionQuery(params);

            // turn query into like statements, with everything or'd
            // ?q=name:%bri%,location:seattle%
            if (queryString != null) {
              handleSearchQuery(query, getJunctionClass(), params);
            }

            String appendedOrderBy = "";
            // ?orderBy=name asc
            if (orderBy != null && !orderBy.isEmpty()) {
              appendedOrderBy = formatOrderBy(params.orderBy, junctionClass);
              query.orderBy(appendedOrderBy);
            }

            handleFieldsAndFetches(query, junctionClass, params);

            query.where().eq(getTableName(leftClass, leftFieldName) + "_id", leftId);

            query.setFirstRow(offset);
            Integer actualCount =
                count == null
                    ? Play.application().configuration().getInt("crud.defaultCount")
                    : count;
            query.setMaxRows(actualCount == null ? 100 : count);

            if (count == null) {
              Logger.warn("No count specified on request: " + request().uri());
            }

            List<J> junctions = junctions = query.findList();
            return CrudResults.successCount(
                query.findRowCount(), junctions.size(), getChildObjects(junctions, rightParams));
          }
        });
  }
 /**
  * Return the byte stream for the captcha image to be displayed.
  *
  * @param uuid the unique captcha id
  */
 public Promise<Result> getCaptchaImage(final String uuid) {
   return Promise.promise(
       new Function0<Result>() {
         @Override
         public Result apply() throws Throwable {
           String decodedUuid = new String(Base64.decodeBase64(uuid));
           response().setContentType("image/png");
           return ok(CaptchaManager.createCaptcha(decodedUuid));
         }
       });
 }
Esempio n. 7
0
 public Promise<Void> asyncSave() {
   return Promise.promise(
       new Function0<Void>() {
         @Override
         public Void apply() throws Throwable {
           save();
           return null;
         }
       },
       ctx);
 }
Esempio n. 8
0
 public static Promise<Proposal> selectRandomTalk() {
   return Promise.promise(
       new Function0<Proposal>() {
         @Override
         public Proposal apply() throws Throwable {
           // randomly select one if the first
           Long randomId = (long) (1 + Math.random() * (5 - 1));
           return Proposal.find.byId(randomId);
         }
       },
       ctx);
 }
Esempio n. 9
0
 // #async
 public static Promise<SimpleResult> index() {
   Promise<Integer> promiseOfInt =
       Promise.promise(
           new Function0<Integer>() {
             public Integer apply() {
               return intensiveComputation();
             }
           });
   return promiseOfInt.map(
       new Function<Integer, SimpleResult>() {
         public SimpleResult apply(Integer i) {
           return ok("Got result: " + i);
         }
       });
 }
 /**
  * Gets a list of associations for the base model object
  *
  * @return
  */
 @Override
 public Promise<Result> associations(Long leftId) {
   return Promise.promise(
       new Function0<Result>() {
         public Result apply() {
           List<Class<? extends Model>> associations = new ArrayList<Class<? extends Model>>();
           associations.addAll(AssociationFinder.findClassAssociations(junctionClass));
           List<String> simpleAssociations = new ArrayList<String>();
           for (Class<? extends Model> assoc : associations) {
             simpleAssociations.add(assoc.getSimpleName());
           }
           return CrudResults.successCount(
               simpleAssociations.size(), simpleAssociations.size(), simpleAssociations);
         }
       });
 }
  /**
   * Implements a update method
   *
   * @param leftId The id of the parent model
   * @param rightId The id of the child model
   * @return
   */
  @BodyParser.Of(BodyParser.Json.class)
  public Promise<Result> update(final Long leftId, final Long rightId) {
    return Promise.promise(
        new Function0<Result>() {
          public Result apply() {
            J model =
                createJunctionQuery(new ServiceParams())
                    .where()
                    .eq(getTableName(rightClass, rightFieldName) + "_id", rightId)
                    .eq(getTableName(leftClass, leftFieldName) + "_id", leftId)
                    .findUnique();

            // You can only update rights that we have a junction for
            if (model == null) {
              return CrudResults.notFoundError(junctionClass, "");
            }

            return ManyToManyCrudController.super.update(rightId).get(5000);
          }
        });
  }
  /**
   * Create a new entity with the json body of the request. If the body is an array, it will bulk
   * create.
   *
   * @param leftId The id of the parent object
   * @return Result object with the created entities
   */
  @BodyParser.Of(BodyParser.Json.class)
  public Promise<Result> create(final Long leftId) {
    return Promise.promise(
        new Function0<Result>() {
          public Result apply() {
            L left = createLeftQuery(new ServiceParams()).where().eq("id", leftId).findUnique();
            if (left == null) {
              return CrudResults.notFoundError(leftClass, leftId);
            }

            List<R> rightList = new ArrayList<R>();
            List<J> junctionList = new ArrayList<J>();

            // if id is sent get existing model, otherwise create it
            JsonNode reqBody = request().body().asJson();
            JsonNode array;

            // convert the request into an array if it's not. Reduces logic.
            if (!reqBody.isArray()) {
              ArrayNode a = new ArrayNode(JsonNodeFactory.instance);
              a.add(reqBody);
              array = a;
            } else {
              array = reqBody;
            }

            for (final JsonNode node : array) {
              JsonNode rightNode = node;
              R right;
              if (rightNode != null) {
                JsonNode idNode = rightNode.get("id");
                if (idNode != null && !idNode.asText().equals("null")) {
                  Long rightId = idNode.asLong(); // TODO: Slow
                  right = createQuery(new ServiceParams()).where().eq("id", rightId).findUnique();
                  if (right != null) {
                    rightList.add(right);
                  } else {
                    return CrudResults.notFoundError(getBaseModelClass(), rightId);
                  }
                } else {
                  right = Json.fromJson(rightNode, getBaseModelClass());
                  ResultOrValue<R> rov = isModelValid(right);
                  if (rov.result != null) {
                    return rov.result;
                  } else {
                    rightList.add(right);
                  }
                }
              } else {
                return CrudResults.error("No right object found on junction.");
              }
            }

            for (R right : rightList) {
              // save junction - this can be cleaned up
              J junction = null;
              try {
                Constructor<J> ctor = junctionClass.getConstructor();
                junction = ctor.newInstance();
              } catch (NoSuchMethodException e) {
                e.printStackTrace();
              } catch (InstantiationException e) {
                e.printStackTrace();
              } catch (IllegalAccessException e) {
                e.printStackTrace();
              } catch (InvocationTargetException e) {
                e.printStackTrace();
              }

              setSubObject(junction, left, leftFieldName);
              setSubObject(junction, right, rightFieldName);
              junctionList.add(junction);
            }

            Ebean.save(rightList);
            Ebean.save(junctionList);

            // return an array if the request was originally an array
            List<? extends Model> returnList = rightList;
            if (reqBody.isArray()) {
              return CrudResults.successCreate(returnList);
            } else {
              return CrudResults.successCreate(returnList.get(0));
            }
          }
        });
  }