Java Code Examples for org.javalite.activejdbc.Model

The following examples show how to use org.javalite.activejdbc.Model. These examples are extracted from open source projects. 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 Project: flowchat   Source File: Transformations.java    License: 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 2
Source Project: flowchat   Source File: Transformations.java    License: 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 3
Source Project: javalite   Source File: AttributeLengthValidator.java    License: 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 4
Source Project: flowchat   Source File: Communities.java    License: 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 Project: flowchat   Source File: Comments.java    License: 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 6
Source Project: flowchat   Source File: Comments.java    License: 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 7
Source Project: flowchat   Source File: Comment.java    License: 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 8
Source Project: flowchat   Source File: Transformations.java    License: 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 9
@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 10
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 11
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 12
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 13
Source Project: tutorials   Source File: ActiveJDBCApp.java    License: 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 14
Source Project: javalite   Source File: RegexpValidator.java    License: 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 15
Source Project: javalite   Source File: TimestampValidator.java    License: 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 16
Source Project: javalite   Source File: NumericValidator.java    License: 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 17
Source Project: javalite   Source File: NumericValidator.java    License: 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 18
Source Project: javalite   Source File: UniquenessValidator.java    License: 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 19
Source Project: javalite   Source File: DateValidator.java    License: 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 20
Source Project: javalite   Source File: CustomValidatorTest.java    License: 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 21
Source Project: javalite   Source File: PlantCallback.java    License: 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 22
Source Project: flowchat   Source File: Community.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static Community create(Model c,
                               List<Tables.CommunityTagView> communityTags,
                               List<Tables.CommunityUserView> communityUsers,
                               Integer vote) {
    // convert the tags
    List<Tag> tags = null;
    if (communityTags != null) {
        tags = new ArrayList<>();
        for (Tables.CommunityTagView dtv : communityTags) {
            tags.add(Tag.create(dtv.getLong("tag_id"), dtv.getString("name")));
        }
    }

    // convert the user community roles
    User creator = null;
    List<User> moderators = new ArrayList<>();
    List<User> privateUsers = new ArrayList<>();
    List<User> blockedUsers = new ArrayList<>();

    if (communityUsers != null) {
        for (Tables.CommunityUserView udv : communityUsers) {

            CommunityRole role = CommunityRole.values()[udv.getLong("community_role_id").intValue() - 1];

            User userObj = User.create(udv.getLong("user_id"), udv.getString("name"));

            switch (role) {
                case CREATOR:
                    creator = userObj;
                    break;
                case MODERATOR:
                    moderators.add(userObj);
                    break;
                case BLOCKED:
                    blockedUsers.add(userObj);
                    break;
                case USER:
                    privateUsers.add(userObj);
                    break;
            }
        }
    }

    // Create the modified by user
    User modifiedByUser = User.create(c.getLong("modified_by_user_id"), c.getString("modified_by_user_name"));

    return new Community(c.getLongId(),
            c.getString("name"),
            c.getString("text_"),
            c.getBoolean("private"),
            c.getBoolean("nsfw"),
            c.getInteger("avg_rank"),
            vote,
            c.getInteger("number_of_votes"),
            tags,
            creator,
            modifiedByUser,
            moderators,
            privateUsers,
            blockedUsers,
            c.getBoolean("deleted"),
            c.getTimestamp("created"),
            c.getTimestamp("modified"));
}
 
Example 23
Source Project: flowchat   Source File: Discussions.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static Discussions create(List<? extends Model> discussions,
                                 List<Tables.CommunityNoTextView> communities,
                                 List<Tables.DiscussionTagView> discussionTags,
                                 List<Tables.DiscussionUserView> discussionUsers,
                                 List<Tables.DiscussionRank> discussionRanks,
                                 Long count) {

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

    Map<Long, List<Tables.DiscussionTagView>> tagMap = (discussionTags != null) ?
            Transformations.convertRowsToMap(discussionTags, "discussion_id") : null;

    Map<Long, List<Tables.DiscussionUserView>> userMap = (discussionUsers != null) ?
            Transformations.convertRowsToMap(discussionUsers, "discussion_id") : null;

    // Convert to a list of discussion objects
    Set<Discussion> dos = new LinkedHashSet<>();

    for (Model view : discussions) {
        Long id = view.getLongId();
        Integer vote = (votes != null && votes.get(id) != null) ? votes.get(id) : null;
        List<Tables.DiscussionTagView> tags = (tagMap != null && tagMap.get(id) != null) ? tagMap.get(id) : null;
        List<Tables.DiscussionUserView> users = (userMap != null && userMap.get(id) != null) ? userMap.get(id) : null;
        Tables.CommunityNoTextView community = null;
        if (communities != null) {
            for (Tables.CommunityNoTextView cntv : communities) {
                if (view.getLong("community_id").equals(cntv.getLongId())) {
                    community = cntv;
                    break;
                }
            }
        }

        // TODO should the list of discussions also filter for blocked communities?
        Discussion df = Discussion.create(view, community, tags, users, null, vote);
        dos.add(df);
    }

    return new Discussions(dos, count);
}
 
Example 24
Source Project: flowchat   Source File: Discussion.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static Discussion create(Model d,
                                Tables.CommunityNoTextView cntv,
                                List<Tables.DiscussionTagView> discussionTags,
                                List<Tables.DiscussionUserView> discussionUsers,
                                List<Tables.CommunityUserView> communityUsers,
                                Integer vote) {
    // convert the tags
    List<Tag> tags = null;
    if (discussionTags != null) {
        tags = new ArrayList<>();
        for (Tables.DiscussionTagView dtv : discussionTags) {
            tags.add(Tag.create(dtv.getLong("tag_id"), dtv.getString("name")));
        }
    }

    // convert the user discussion roles
    User creator = null;
    List<User> privateUsers = new ArrayList<>();
    List<User> blockedUsers = new ArrayList<>();

    if (discussionUsers != null) {
        for (Tables.DiscussionUserView udv : discussionUsers) {

            DiscussionRole role = DiscussionRole.values()[udv.getLong("discussion_role_id").intValue() - 1];

            User userObj = User.create(udv.getLong("user_id"), udv.getString("name"));

            switch (role) {
                case BLOCKED:
                    blockedUsers.add(userObj);
                    break;
                case USER:
                    privateUsers.add(userObj);
                    break;
                case CREATOR:
                    creator = userObj;
                    break;
            }
        }
    }

    // Create the community
    Community community = (cntv != null) ? Community.create(cntv, null, communityUsers, null) : null;

    // If the community is NSFW, the discussion must be
    Boolean nsfw = (community != null && community.getNsfw()) ? true :  d.getBoolean("nsfw");

    // Create the modified by user
    User modifiedByUser = User.create(d.getLong("modified_by_user_id"), d.getString("modified_by_user_name"));

    return new Discussion(d.getLongId(),
            d.getString("title"),
            d.getString("link"),
            d.getString("text_"),
            d.getBoolean("private"),
            nsfw,
            d.getBoolean("stickied"),
            d.getInteger("avg_rank"),
            vote,
            d.getInteger("number_of_votes"),
            d.getInteger("number_of_comments"),
            tags,
            creator,
            modifiedByUser,
            privateUsers,
            blockedUsers,
            d.getBoolean("deleted"),
            community,
            d.getTimestamp("created"),
            d.getTimestamp("modified"));
}
 
Example 25
Source Project: flowchat   Source File: Transformations.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static Map<Long, Comment> convertCommentThreadedViewToMap(List<? extends Model> cvs,
                                                                 Map<Long, Integer> votes) {

    // Create a top level map of ids to comments
    Map<Long, Comment> commentObjMap = new LinkedHashMap<>();

    for (Model cv : cvs) {

        Long id = cv.getLong("id");

        // Check to make sure it has a vote
        Integer vote = (votes != null && votes.containsKey(id)) ? votes.get(id) : null;

        // Create the comment object
        Comment co = Comment.create(cv, vote);

        commentObjMap.put(id, co);
    }

    return commentObjMap;
}
 
Example 26
Source Project: flowchat   Source File: Transformations.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static List<Comment> convertCommentsToEmbeddedObjects(
        List<? extends Model> cvs,
        Map<Long, Integer> votes,
        Comparator<Comment> comparator) {
    return convertCommentsToEmbeddedObjects(cvs, votes, Long.MAX_VALUE, Long.MAX_VALUE, comparator);
}
 
Example 27
Source Project: flowchat   Source File: Tools.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static Integer findIndexByIdInLazyList(LazyList<? extends Model> ctv, Long searchId) {
    Integer index = IntStream.range(0, ctv.size()).filter(c -> ctv.get(c).getLongId() == searchId).toArray()[0];
    return index;
}
 
Example 28
Source Project: javalite   Source File: AttributePresenceValidator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void validate(Model m) {
    if (blank(m.get(attribute))) {
        m.addValidator(this, attribute);
    }
}
 
Example 29
Source Project: javalite   Source File: NumericValidator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void validate(Model m) {
    Object value = m.get(attribute);

    if(!present(value, m)){
        return;
    }

    // validators should not also do conversion
    if(convertNullIfEmpty && "".equals(value)){
        m.set(attribute, null);
        value = null;
    }

    if(value == null && allowNull){
        return;
    }

    //this is to check just numericality
    if(!(value instanceof Number)) {
        if (value != null) {
            ParsePosition pp = new ParsePosition(0);
            String input = value.toString();
            // toString() is not Locale dependant...
            // ... but NumberFormat is. For Polish locale where decimal separator is "," instead of ".". Might fail some tests...
            NumberFormat nf = NumberFormat.getInstance();
            nf.setParseIntegerOnly(onlyInteger);
            nf.parse(input, pp);
            if (pp.getIndex() != (input.length())) {
                m.addValidator(this, attribute);
            }
        } else {
                m.addValidator(this, attribute);
        }
    }

    if(min != null){
        validateMin(Convert.toDouble(value), m);
    }

    if(max != null){
        validateMax(Convert.toDouble(value), m);
    }

    if(onlyInteger){
        validateIntegerOnly(value, m);
    }
}
 
Example 30
Source Project: javalite   Source File: NumericValidator.java    License: Apache License 2.0 4 votes vote down vote up
private void validateMin(Double value, Model m){

        if(value <= min){
            m.addValidator(this, attribute);
        }
    }