Search in sources :

Example 1 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class QuestionController method getComments.

//get the comments for each answer and the question
private void getComments(List<Post> allPosts) {
    Map<String, List<Comment>> allComments = new HashMap<String, List<Comment>>();
    List<String> allCommentIds = new ArrayList<String>();
    List<Post> forUpdate = new ArrayList<Post>(allPosts.size());
    // get the comment ids of the first 5 comments for each post
    for (Post post : allPosts) {
        // not set => read comments if any and embed ids in post object
        if (post.getCommentIds() == null) {
            forUpdate.add(reloadFirstPageOfComments(post));
            allComments.put(post.getId(), post.getComments());
        } else {
            // ids are set => add them to list for bulk read
            allCommentIds.addAll(post.getCommentIds());
        }
    }
    if (!allCommentIds.isEmpty()) {
        // read all comments for all posts on page in bulk
        for (ParaObject comment : pc.readAll(allCommentIds)) {
            List<Comment> postComments = allComments.get(comment.getParentid());
            if (postComments == null) {
                allComments.put(comment.getParentid(), new ArrayList<Comment>());
            }
            allComments.get(comment.getParentid()).add((Comment) comment);
        }
    }
    // embed comments in each post for use within the view
    for (Post post : allPosts) {
        List<Comment> cl = allComments.get(post.getId());
        int clSize = (cl == null) ? 0 : cl.size();
        if (post.getCommentIds().size() != clSize) {
            logger.info("OPAA neshto stava.. {} {}", post.getCommentIds().size(), clSize);
            forUpdate.add(reloadFirstPageOfComments(post));
            clSize = post.getComments().size();
        } else {
            post.setComments(cl);
        }
        // hack to show the "more" button
        post.getItemcount().setCount(clSize + 1);
    }
    if (!forUpdate.isEmpty()) {
        pc.updateAll(allPosts);
    }
}
Also used : Comment(com.erudika.scoold.core.Comment) HashMap(java.util.HashMap) Post(com.erudika.scoold.core.Post) ArrayList(java.util.ArrayList) ParaObject(com.erudika.para.core.ParaObject) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List)

Example 2 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class ScooldUtils method fullQuestionsSearch.

public List<Post> fullQuestionsSearch(String query, Pager... pager) {
    String typeFilter = Config._TYPE + ":(" + String.join(" OR ", Utils.type(Question.class), Utils.type(Reply.class), Utils.type(Comment.class)) + ")";
    String qs = StringUtils.isBlank(query) || query.startsWith("*") ? typeFilter : query + " AND " + typeFilter;
    List<ParaObject> mixedResults = pc.findQuery("", qs, pager);
    Predicate<ParaObject> isQuestion = obj -> obj.getType().equals(Utils.type(Question.class));
    Map<String, ParaObject> idsToQuestions = new HashMap<>(mixedResults.stream().filter(isQuestion).collect(Collectors.toMap(q -> q.getId(), q -> q)));
    Set<String> toRead = new LinkedHashSet<>();
    mixedResults.stream().filter(isQuestion.negate()).forEach(obj -> {
        if (!idsToQuestions.containsKey(obj.getParentid())) {
            toRead.add(obj.getParentid());
        }
    });
    // find all parent posts but this excludes parents of parents - i.e. won't work for comments in answers
    List<Post> parentPostsLevel1 = pc.readAll(new ArrayList<>(toRead));
    parentPostsLevel1.stream().filter(isQuestion).forEach(q -> idsToQuestions.put(q.getId(), q));
    toRead.clear();
    // read parents of parents if any
    parentPostsLevel1.stream().filter(isQuestion.negate()).forEach(obj -> {
        if (!idsToQuestions.containsKey(obj.getParentid())) {
            toRead.add(obj.getParentid());
        }
    });
    List<Post> parentPostsLevel2 = pc.readAll(new ArrayList<>(toRead));
    parentPostsLevel2.stream().forEach(q -> idsToQuestions.put(q.getId(), q));
    ArrayList<Post> results = new ArrayList<Post>(idsToQuestions.size());
    for (ParaObject result : idsToQuestions.values()) {
        if (result instanceof Post) {
            results.add((Post) result);
        }
    }
    return results;
}
Also used : Question(com.erudika.scoold.core.Question) Arrays(java.util.Arrays) Webhook(com.erudika.para.core.Webhook) ServletException(javax.servlet.ServletException) Date(java.util.Date) HttpUtils.getCookieValue(com.erudika.scoold.utils.HttpUtils.getCookieValue) JOSEException(com.nimbusds.jose.JOSEException) LoggerFactory(org.slf4j.LoggerFactory) Vote(com.erudika.para.core.Vote) Scanner(java.util.Scanner) ParaClient(com.erudika.para.client.ParaClient) Revision(com.erudika.scoold.core.Revision) StringUtils(org.apache.commons.lang3.StringUtils) Base64(org.apache.commons.codec.binary.Base64) MACVerifier(com.nimbusds.jose.crypto.MACVerifier) Matcher(java.util.regex.Matcher) Locale(java.util.Locale) Map(java.util.Map) ParseException(java.text.ParseException) Config(com.erudika.para.core.utils.Config) ConstraintViolation(javax.validation.ConstraintViolation) ValidationUtils(com.erudika.para.core.validation.ValidationUtils) ParaObject(com.erudika.para.core.ParaObject) Predicate(java.util.function.Predicate) HttpHeaders(org.springframework.http.HttpHeaders) AvatarFormat(com.erudika.scoold.utils.avatars.AvatarFormat) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConfigObject(com.typesafe.config.ConfigObject) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Emailer(com.erudika.para.core.email.Emailer) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) Collectors(java.util.stream.Collectors) Comment(com.erudika.scoold.core.Comment) List(java.util.List) JWSSigner(com.nimbusds.jose.JWSSigner) Tag(com.erudika.para.core.Tag) GravatarAvatarGenerator(com.erudika.scoold.utils.avatars.GravatarAvatarGenerator) Optional(java.util.Optional) DEFAULT_SPACE(com.erudika.scoold.core.Post.DEFAULT_SPACE) Para(com.erudika.para.core.utils.Para) Pattern(java.util.regex.Pattern) Feedback(com.erudika.scoold.core.Feedback) Sysprop(com.erudika.para.core.Sysprop) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) ALL_MY_SPACES(com.erudika.scoold.core.Post.ALL_MY_SPACES) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) AvatarRepositoryProxy(com.erudika.scoold.utils.avatars.AvatarRepositoryProxy) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) Pager(com.erudika.para.core.utils.Pager) ENTHUSIAST(com.erudika.scoold.core.Profile.Badge.ENTHUSIAST) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) Named(javax.inject.Named) LinkedList(java.util.LinkedList) TEACHER(com.erudika.scoold.core.Profile.Badge.TEACHER) UnapprovedReply(com.erudika.scoold.core.UnapprovedReply) LinkedHashSet(java.util.LinkedHashSet) MACSigner(com.nimbusds.jose.crypto.MACSigner) JWSVerifier(com.nimbusds.jose.JWSVerifier) RegExUtils(org.apache.commons.lang3.RegExUtils) Logger(org.slf4j.Logger) AvatarRepository(com.erudika.scoold.utils.avatars.AvatarRepository) Address(com.erudika.para.core.Address) Post(com.erudika.scoold.core.Post) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) User(com.erudika.para.core.User) Utils(com.erudika.para.core.utils.Utils) Report(com.erudika.scoold.core.Report) Component(org.springframework.stereotype.Component) TreeMap(java.util.TreeMap) ScooldServer(com.erudika.scoold.ScooldServer) NumberUtils(org.apache.commons.lang3.math.NumberUtils) Reply(com.erudika.scoold.core.Reply) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) InputStream(java.io.InputStream) LinkedHashSet(java.util.LinkedHashSet) Comment(com.erudika.scoold.core.Comment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Post(com.erudika.scoold.core.Post) ArrayList(java.util.ArrayList) ParaObject(com.erudika.para.core.ParaObject) UnapprovedReply(com.erudika.scoold.core.UnapprovedReply) Reply(com.erudika.scoold.core.Reply) Question(com.erudika.scoold.core.Question) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion)

Example 3 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class AdminController method importPostsFromSO.

private void importPostsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport) throws ParseException {
    logger.info("Importing {} posts...", objs.size());
    for (Map<String, Object> obj : objs) {
        Post p;
        if ("question".equalsIgnoreCase((String) obj.get("postType"))) {
            p = new Question();
            p.setTitle((String) obj.get("title"));
            String t = StringUtils.stripStart(StringUtils.stripEnd((String) obj.getOrDefault("tags", ""), "|"), "|");
            p.setTags(Arrays.asList(t.split("\\|")));
            p.setAnswercount(((Integer) obj.getOrDefault("answerCount", 0)).longValue());
            Integer answerId = (Integer) obj.getOrDefault("acceptedAnswerId", null);
            p.setAnswerid(answerId != null ? "post_" + answerId : null);
        } else {
            p = new Reply();
            Integer parentId = (Integer) obj.getOrDefault("parentId", null);
            p.setParentid(parentId != null ? "post_" + parentId : null);
        }
        p.setId("post_" + (Integer) obj.getOrDefault("id", Utils.getNewId()));
        p.setBody((String) obj.get("bodyMarkdown"));
        p.setVotes((Integer) obj.getOrDefault("score", 0));
        p.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
        Integer creatorId = (Integer) obj.getOrDefault("ownerUserId", null);
        if (creatorId == null || creatorId == -1) {
            p.setCreatorid(utils.getSystemUser().getId());
        } else {
            // add prefix to avoid conflicts
            p.setCreatorid(Profile.id("user_" + creatorId));
        }
        toImport.add(p);
    }
    pc.createAll(toImport);
}
Also used : Post(com.erudika.scoold.core.Post) Reply(com.erudika.scoold.core.Reply) ParaObject(com.erudika.para.core.ParaObject) Question(com.erudika.scoold.core.Question)

Example 4 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class AdminController method importUsersFromSO.

private void importUsersFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport) throws ParseException {
    logger.info("Importing {} users...", objs.size());
    for (Map<String, Object> obj : objs) {
        User u = new User();
        u.setId("user_" + (Integer) obj.get("id"));
        u.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
        u.setActive(true);
        u.setCreatorid(((Integer) obj.get("accountId")).toString());
        u.setGroups("admin".equalsIgnoreCase((String) obj.get("userTypeId")) ? User.Groups.ADMINS.toString() : User.Groups.USERS.toString());
        u.setEmail(u.getId() + "@scoold.com");
        u.setIdentifier(u.getEmail());
        u.setName((String) obj.get("realName"));
        String lastLogin = (String) obj.get("lastLoginDate");
        u.setUpdated(StringUtils.isBlank(lastLogin) ? null : DateUtils.parseDate(lastLogin, soDateFormat1, soDateFormat2).getTime());
        u.setPicture((String) obj.get("profileImageUrl"));
        u.setPassword(Utils.generateSecurityToken(10));
        Profile p = Profile.fromUser(u);
        p.setVotes((Integer) obj.get("reputation"));
        p.setAboutme((String) obj.getOrDefault("title", ""));
        p.setLastseen(u.getUpdated());
        toImport.add(u);
        toImport.add(p);
    }
    pc.createAll(toImport);
}
Also used : User(com.erudika.para.core.User) ParaObject(com.erudika.para.core.ParaObject) Profile(com.erudika.scoold.core.Profile)

Example 5 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class AdminController method importTagsFromSO.

private void importTagsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport) {
    logger.info("Importing {} tags...", objs.size());
    for (Map<String, Object> obj : objs) {
        Tag t = new Tag((String) obj.get("name"));
        t.setCount((Integer) obj.getOrDefault("count", 0));
        toImport.add(t);
    }
    pc.createAll(toImport);
}
Also used : ParaObject(com.erudika.para.core.ParaObject) Tag(com.erudika.para.core.Tag)

Aggregations

ParaObject (com.erudika.para.core.ParaObject)17 Profile (com.erudika.scoold.core.Profile)10 Comment (com.erudika.scoold.core.Comment)7 Post (com.erudika.scoold.core.Post)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 LinkedHashMap (java.util.LinkedHashMap)5 LinkedList (java.util.LinkedList)5 Pager (com.erudika.para.core.utils.Pager)4 IOException (java.io.IOException)4 List (java.util.List)4 Tag (com.erudika.para.core.Tag)3 User (com.erudika.para.core.User)3 Question (com.erudika.scoold.core.Question)3 Reply (com.erudika.scoold.core.Reply)3 Map (java.util.Map)3 PostMapping (org.springframework.web.bind.annotation.PostMapping)3 ParaClient (com.erudika.para.client.ParaClient)2 Sysprop (com.erudika.para.core.Sysprop)2 Webhook (com.erudika.para.core.Webhook)2