org.javalite.activejdbc.Model Java Examples

The following examples show how to use org.javalite.activejdbc.Model. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AttributeLengthValidator.java    From javalite with Apache License 2.0 6 votes vote down vote up
public void validate(Model m) {
    Object value = m.get(this.attribute);

    if(allowBlank && (null == value || "".equals(value))) {
        return;
    }

    if(null == value) {
        m.addValidator(this, this.attribute);
        return;
    }

    if(!(value instanceof String)) {
        throw new IllegalArgumentException("Attribute must be a String");
    } else {
        if(!this.lengthOption.validate((String)((String)m.get(this.attribute)))) {
            //somewhat confusingly this adds an error for a validator.
            m.addValidator(this, this.attribute);
        }

    }
}
 
Example #2
Source File: Transformations.java    From flowchat with GNU General Public License v3.0 6 votes vote down vote up
public static <T extends Model> Map<Long, Integer> convertRankToMap(List<T> drs, String idColumnName) {

        // Convert those votes to a map from id to rank
        Map<Long, Integer> rankMap = new HashMap<>();
        for (T dr : drs) {
            rankMap.put(dr.getLong(idColumnName), dr.getInteger("rank"));
        }

        try {
            log.debug(Tools.JACKSON.writeValueAsString(rankMap));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return rankMap;
    }
 
Example #3
Source File: Transformations.java    From flowchat with GNU General Public License v3.0 6 votes vote down vote up
public static <T extends Model> Map<Long,List<T>> convertRowsToMap(List<T> tags, String idColumnName) {

        Map<Long,List<T>> map = new HashMap<>();

        for (T dtv : tags) {
            Long id = dtv.getLong(idColumnName);
            List<T> arr = map.get(id);

            if (arr == null) {
                arr = new ArrayList<>();
                map.put(id, arr);
            }

            arr.add(dtv);
        }

        return map;
    }
 
Example #4
Source File: Communities.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public static Communities create(List<? extends Model> communities,
                                 List<Tables.CommunityTagView> communityTags,
                                 List<Tables.CommunityUserView> communityUsers,
                                 List<Tables.CommunityRank> communityRanks,
                                 Long count) {

    // Build maps keyed by community_id of the votes, tags, and users
    Map<Long, Integer> votes = (communityRanks != null) ?
            Transformations.convertRankToMap(communityRanks, "community_id") : null;

    Map<Long, List<Tables.CommunityTagView>> tagMap = (communityTags != null) ?
            Transformations.convertRowsToMap(communityTags, "community_id") : null;

    Map<Long, List<Tables.CommunityUserView>> userMap = (communityUsers != null) ?
            Transformations.convertRowsToMap(communityUsers, "community_id") : null;

    // Convert to a list of community objects
    List<Community> cos = new ArrayList<>();

    for (Model view : communities) {
        Long id = view.getLongId();
        Integer vote = (votes != null && votes.get(id) != null) ? votes.get(id) : null;
        List<Tables.CommunityTagView> tags = (tagMap != null && tagMap.get(id) != null) ? tagMap.get(id) : null;
        List<Tables.CommunityUserView> users = (userMap != null && userMap.get(id) != null) ? userMap.get(id) : null;
        Community c = Community.create(view, tags, users, vote);
        cos.add(c);
    }

    return new Communities(cos, count);
}
 
Example #5
Source File: CustomValidatorTest.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterCustomValidator() {

    class FutureBirthValidator extends ValidatorAdapter {
        FutureBirthValidator(){
            setMessage("invalid.dob.message");
        }
        @Override
        public void validate(Model m) {
            Date dob = m.getDate("dob");
            Date now = new java.sql.Date(System.currentTimeMillis());
            if(dob.after(now)){
                m.addValidator(this, "invalid.dob");//add validator to errors with a key
            }
        }
    }

    FutureBirthValidator validator = new FutureBirthValidator();

    Person.addValidator(validator);

    Person p = new Person();

    GregorianCalendar future = new GregorianCalendar();
    future.set(Calendar.YEAR, 3000);//will people still be using Java then... or computers? :)

    p.set("dob", new Date(future.getTimeInMillis()));
    p.validate();
    a(p.errors().size()).shouldBeEqual(3);

    a(p.errors().get("invalid.dob")).shouldBeEqual("date of birth cannot be in future");

    //this is so that other tests succeed
    Person.removeValidator(validator);
}
 
Example #6
Source File: DateValidator.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Model m) {

    Object val = m.get(attributeName);
    if (!(val instanceof java.util.Date) && !blank(val)) {
        try {
            long time = df.parse(val.toString()).getTime();
            java.sql.Date d = new java.sql.Date(time);
            m.set(attributeName, d);
        } catch (ParseException e) {
            m.addValidator(this, attributeName);
        }
    }
}
 
Example #7
Source File: UniquenessValidator.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Model model) {
    MetaModel metaModel = metaModelOf(model.getClass());
    if (new DB(metaModel.getDbName()).count(metaModel.getTableName(), attribute + " = ?", model.get(attribute)) > 0) {
        model.addValidator(this, attribute);
    }
}
 
Example #8
Source File: NumericValidator.java    From javalite with Apache License 2.0 5 votes vote down vote up
private void validateIntegerOnly(Object value, Model m){
    try{
        Integer.valueOf(value.toString());
    } catch(NumberFormatException e) {
        m.addValidator(this, attribute);
    }
}
 
Example #9
Source File: NumericValidator.java    From javalite with Apache License 2.0 5 votes vote down vote up
private boolean present(Object value, Model m){

        if(allowNull){
            return true;
        }

        if(value == null){
            setMessage("value is missing");
            m.addValidator(this, attribute);
            return false;
        }else{
            return true;
        }
    }
 
Example #10
Source File: TimestampValidator.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Model m) {
    Object val = m.get(attributeName);
    if (!(val instanceof Timestamp) && !blank(val)) {
        try {
            long time = df.parse(val.toString()).getTime();
            Timestamp t = new Timestamp(time);
            m.set(attributeName, t);
        } catch(ParseException e) {
            m.addValidator(this, attributeName);
        }
    }
}
 
Example #11
Source File: RegexpValidator.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Model m) {
    if(m.get(attribute) == null){
        m.addValidator(this, attribute);
        return;
    }
    Object value = m.get(attribute);
    if (!(value instanceof String)) {
        throw new IllegalArgumentException("attribute " + attribute + " is not String");
    }
    Matcher matcher = pattern.matcher((String) value);
    if(!matcher.matches()){
       m.addValidator(this, attribute);
    }
}
 
Example #12
Source File: ActiveJDBCApp.java    From tutorials with MIT License 5 votes vote down vote up
protected void create() {
    Employee employee = new Employee("Hugo","C","M","BN");
    employee.saveIt();
    employee.add(new Role("Java Developer","BN"));
    LazyList<Model> all = Employee.findAll();
    System.out.println(all.size());
}
 
Example #13
Source File: ThreadedChatWebSocket.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
private static LazyList<Model> fetchComments(SessionScope scope) {
  if (scope.getTopParentId() != null) {
    return CommentBreadcrumbsView.where("discussion_id = ? and parent_id = ?", scope.getDiscussionId(),
        scope.getTopParentId());
  } else {
    return CommentThreadedView.where("discussion_id = ?", scope.getDiscussionId());
  }
}
 
Example #14
Source File: ThreadedChatWebSocket.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public void messageReply(Session session, JsonNode data) {

    SessionScope ss = SessionScope.findBySession(sessionScopes, session);

    // Get the object
    ReplyData replyData = new ReplyData(data.get("parentId").asLong(), data.get("reply").asText());

    // Collect only works on refetch
    LazyList<Model> comments = fetchComments(ss);

    log.debug(ss.toString());

    // Necessary for comment tree
    Array arr = (Array) comments.collect("breadcrumbs", "id", replyData.getParentId()).get(0);
    List<Long> parentBreadCrumbs = Tools.convertArrayToList(arr);

    com.chat.db.Tables.Comment newComment = Actions.createComment(ss.getUserObj().getId(), ss.getDiscussionId(),
        parentBreadCrumbs, replyData.getReply());

    // Fetch the comment threaded view
    CommentThreadedView ctv = CommentThreadedView.findFirst("id = ?", newComment.getLongId());

    // Convert to a proper commentObj
    Comment co = Comment.create(ctv, null);

    Set<SessionScope> filteredScopes = SessionScope.constructFilteredMessageScopesFromSessionRequest(sessionScopes,
        session, co.getBreadcrumbs());

    broadcastMessage(filteredScopes, messageWrapper(MessageType.Reply, co.json()));

    // TODO find a way to do this without having to query every time?
    com.chat.types.discussion.Discussion do_ = Actions.saveFavoriteDiscussion(ss.getUserObj().getId(),
        ss.getDiscussionId());
    if (do_ != null)
      sendMessage(session, messageWrapper(MessageType.SaveFavoriteDiscussion, do_.json()));
  }
 
Example #15
Source File: ThreadedChatWebSocket.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
@OnWebSocketConnect
public void onConnect(Session session) {

  try {
    Tools.dbInit();

    // Get or create the session scope
    SessionScope ss = setupSessionScope(session);

    sendRecurringPings(session);

    // Send them their user info
    // TODO
    // session.getRemote().sendString(ss.getUserObj().json("user"));

    LazyList<Model> comments = fetchComments(ss);

    // send the comments
    sendMessage(session,
        messageWrapper(MessageType.Comments, Comments
            .create(comments, fetchVotesMap(ss.getUserObj().getId()), topLimit, maxDepth, ss.getCommentComparator())
            .json()));

    // send the updated users to everyone in the right scope(just discussion)
    Set<SessionScope> filteredScopes = SessionScope.constructFilteredUserScopesFromSessionRequest(sessionScopes,
        session);
    broadcastMessage(filteredScopes,
        messageWrapper(MessageType.Users, Users.create(SessionScope.getUserObjects(filteredScopes)).json()));

    log.debug("session scope " + ss + " joined");

  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    Tools.dbClose();
  }

}
 
Example #16
Source File: Comments.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public static Comments create(
        LazyList<? extends Model> comments,
        Map<Long, Integer> votes,
        Long topLimit, Long maxDepth, Comparator<Comment> comparator) {

    List<Comment> commentObjs = Transformations.convertCommentsToEmbeddedObjects(
            comments, votes, topLimit, maxDepth, comparator);

    return new Comments(commentObjs);
}
 
Example #17
Source File: Comments.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public static Comments replies(LazyList<? extends Model> comments) {
    Set<Comment> commentObjs = new LinkedHashSet<>();
    for (Model c : comments) {
        commentObjs.add(Comment.create(c, null));
    }

    // Convert to a list
    List<Comment> list = new ArrayList<>(commentObjs);

    return new Comments(list);

}
 
Example #18
Source File: Comment.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public static Comment create(Model cv, Integer vote) {

        User user = User.create(cv.getLong("user_id"), cv.getString("user_name"));
        User modifiedByUser = User.create(cv.getLong("modified_by_user_id"), cv.getString("modified_by_user_name"));

        return new Comment(cv.getLong("id"), user, modifiedByUser, cv.getLong("discussion_id"),
                cv.getLong("discussion_owner_id"), cv.getString("text_"), cv.getLong("path_length"),
                cv.getLong("parent_id"), cv.getLong("parent_user_id"), cv.getString("breadcrumbs"),
                cv.getLong("num_of_parents"), cv.getLong("num_of_children"), cv.getInteger("avg_rank"), vote,
                cv.getInteger("number_of_votes"), cv.getBoolean("deleted"), cv.getBoolean("read"),
                cv.getBoolean("stickied"), cv.getTimestamp("created"), cv.getTimestamp("modified"));
    }
 
Example #19
Source File: PlantCallback.java    From javalite with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeValidation(Model m) {
    beforeValidationCalled = true;
    if(Util.blank(m.get("category"))){
        m.set("category", "none");
    }
}
 
Example #20
Source File: ThreadedChatWebSocket.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public void messageNextPage(Session session, JsonNode data) {
  SessionScope ss = SessionScope.findBySession(sessionScopes, session);

  // Get the object
  NextPageData nextPageData = new NextPageData(data.get("topLimit").asLong(), data.get("maxDepth").asLong());

  // Refetch the comments based on the new limit
  LazyList<Model> comments = fetchComments(ss);

  // send the comments from up to the new limit to them
  sendMessage(session,
      messageWrapper(MessageType.Comments, Comments.create(comments, fetchVotesMap(ss.getUserObj().getId()),
          nextPageData.getTopLimit(), nextPageData.getMaxDepth(), ss.getCommentComparator()).json()));

}
 
Example #21
Source File: Transformations.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public static List<Comment> convertCommentsToEmbeddedObjects(
        List<? extends Model> cvs,
        Map<Long, Integer> votes,
        Long topLimit, Long maxDepth, Comparator<Comment> comparator) {

    Map<Long, Comment> commentObjMap = convertCommentThreadedViewToMap(cvs, votes);

    List<Comment> cos = convertCommentsMapToEmbeddedObjects(commentObjMap, topLimit, maxDepth, comparator);

    return cos;
}
 
Example #22
Source File: FruitCallbackChecker.java    From javalite with Apache License 2.0 4 votes vote down vote up
protected void checkBeforeDelete(Model m){
    beforeDeleteCalled = true;
    if(m.isFrozen())
        throw new TestException("new model must not be frozen before delete()");

}
 
Example #23
Source File: BelongsToAssociation.java    From javalite with Apache License 2.0 4 votes vote down vote up
public BelongsToAssociation(Class<? extends Model> source, Class<? extends Model> target, String fkName) {
    super(source, target);
    this.fkName = fkName;
}
 
Example #24
Source File: BelongsToPolymorphicAssociation.java    From javalite with Apache License 2.0 4 votes vote down vote up
public BelongsToPolymorphicAssociation(Class<? extends Model> sourceModelClass, Class<? extends Model> targetModelClass, String typeLabel, String parentClassName) {
    super(sourceModelClass, targetModelClass);
    this.typeLabel = typeLabel;
    this.parentClassName = parentClassName;
}
 
Example #25
Source File: VegetableCallbackChecker.java    From javalite with Apache License 2.0 4 votes vote down vote up
protected void checkAfterValidation(Model m){
    afterValidationCalled = true;
    if(m.errors().size() == 0)
            throw new TestException("model after validation must have errors");
}
 
Example #26
Source File: FruitCallbackChecker.java    From javalite with Apache License 2.0 4 votes vote down vote up
protected void checkBeforeSave(Model m){
    beforeSaveCalled = true;
    if(m.getId() != null)
        throw new TestException("new model must not have an ID before save()");
}
 
Example #27
Source File: FruitCallbackChecker.java    From javalite with Apache License 2.0 4 votes vote down vote up
protected void checkBeforeCreate(Model m){
    beforeCreateCalled = true;
    if(m.getId() != null)
        throw new TestException("new model must not have an ID before insert()");
}
 
Example #28
Source File: FruitCallbackChecker.java    From javalite with Apache License 2.0 4 votes vote down vote up
protected void checkAfterCreate(Model m){
       afterCreateCalled = true;
       if(m.getId() == null)
           throw new TestException("new model must have an ID after insert()");
}
 
Example #29
Source File: FruitCallbackChecker.java    From javalite with Apache License 2.0 4 votes vote down vote up
protected void checkAfterSave(Model m){
    afterSaveCalled = true;
    if(m.getId() == null)
        throw new TestException("new model must have an ID after save()");
}
 
Example #30
Source File: PlantCallback.java    From javalite with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeDelete(Model m) {
    beforeDeleteCalled = true;
}