Search in sources :

Example 1 with BlogPostInfo

use of org.alfresco.service.cmr.blog.BlogPostInfo in project alfresco-remote-api by Alfresco.

the class AbstractGetBlogWebScript method executeImpl.

@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nonSiteContainer, BlogPostInfo blog, WebScriptRequest req, JSONObject json, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();
    // process additional parameters. <index, count>
    PagingRequest pagingReq = parsePagingParams(req);
    pagingReq.setRequestTotalCountMax(pagingReq.getSkipCount() + pagingReq.getRequestTotalCountMax());
    // begin and end date.
    // Legacy note: these dates are URL query parameters in int form.
    Date fromDate = parseDateParam(req, "fromDate");
    Date toDate = parseDateParam(req, "toDate");
    String tag = req.getParameter("tag");
    if (tag == null || tag.length() == 0) {
        tag = null;
    } else {
        // Tags can be full unicode strings, so decode
        tag = URLDecoder.decode(tag);
    }
    // This is a hacky solution to this special case. FIXME
    if (this.getClass().equals(BlogPostsNewGet.class)) {
        // Default is for 'now' minus seven days.
        final long oneDayInMilliseconds = 24 * 60 * 60 * 1000;
        final long sevenDaysInMilliseconds = 7 * oneDayInMilliseconds;
        fromDate = new Date(System.currentTimeMillis() - sevenDaysInMilliseconds);
        // But if there is a numdays parameter then that changes the fromDate
        String numDays = req.getServiceMatch().getTemplateVars().get("numdays");
        if (numDays != null) {
            Integer numDaysInt = Integer.parseInt(numDays);
            fromDate = new Date(System.currentTimeMillis() - (numDaysInt * oneDayInMilliseconds));
        }
    }
    // Fetch and assign the data
    PagingResults<BlogPostInfo> blogPostList = getBlogPostList(site, nonSiteContainer, fromDate, toDate, tag, pagingReq);
    // We need the container for various bits
    NodeRef container = nonSiteContainer;
    if (container == null) {
        // Container mustn't exist yet
        // Fake it with the site for permissions checking reasons
        container = site.getNodeRef();
    }
    if (log.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Retrieved ").append(blogPostList.getPage().size()).append(" blog posts in page.");
        log.debug(msg.toString());
    }
    createFtlModel(req, model, container, pagingReq, blogPostList);
    return model;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) HashMap(java.util.HashMap) JSONObject(org.json.simple.JSONObject) BlogPostInfo(org.alfresco.service.cmr.blog.BlogPostInfo) PagingRequest(org.alfresco.query.PagingRequest) Date(java.util.Date)

Example 2 with BlogPostInfo

use of org.alfresco.service.cmr.blog.BlogPostInfo in project alfresco-remote-api by Alfresco.

the class BlogPostsPost method createBlogPost.

/**
 * Creates a blog post
 */
private BlogPostInfo createBlogPost(JsonParams jsonParams, SiteInfo site, NodeRef blogNode) {
    String titleParam = jsonParams.getTitle() == null ? "" : jsonParams.getTitle();
    String contentParam = jsonParams.getContent() == null ? "" : jsonParams.getContent();
    boolean isDraftParam = jsonParams.getIsDraft();
    if (log.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Creating blog-post '").append(titleParam).append("'");
        if (isDraftParam) {
            msg.append(" DRAFT");
        }
        log.debug(msg.toString());
    }
    List<String> tagsParam = new ArrayList<String>();
    if (jsonParams.getTags() != null) {
        tagsParam.addAll(jsonParams.getTags());
    }
    BlogPostInfo newPostNode;
    if (site != null) {
        newPostNode = blogService.createBlogPost(site.getShortName(), titleParam, contentParam, isDraftParam);
    } else {
        newPostNode = blogService.createBlogPost(blogNode, titleParam, contentParam, isDraftParam);
    }
    // Ignore empty string tags
    List<String> nonEmptyTags = new ArrayList<String>();
    for (String tag : tagsParam) {
        if (!tag.trim().isEmpty()) {
            nonEmptyTags.add(tag);
        }
    }
    if (!nonEmptyTags.isEmpty()) {
        taggingService.setTags(newPostNode.getNodeRef(), nonEmptyTags);
    }
    return newPostNode;
}
Also used : ArrayList(java.util.ArrayList) BlogPostInfo(org.alfresco.service.cmr.blog.BlogPostInfo)

Example 3 with BlogPostInfo

use of org.alfresco.service.cmr.blog.BlogPostInfo in project alfresco-remote-api by Alfresco.

the class AbstractBlogWebScript method executeImpl.

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    if (templateVars == null) {
        String error = "No parameters supplied";
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
    }
    // Parse the JSON, if supplied
    JSONObject json = null;
    String contentType = req.getContentType();
    if (contentType != null && contentType.indexOf(';') != -1) {
        contentType = contentType.substring(0, contentType.indexOf(';'));
    }
    if (MimetypeMap.MIMETYPE_JSON.equals(contentType)) {
        JSONParser parser = new JSONParser();
        try {
            json = (JSONObject) parser.parse(req.getContent().getContent());
        } catch (IOException io) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Invalid JSON: " + io.getMessage());
        } catch (ParseException pe) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Invalid JSON: " + pe.getMessage());
        }
    }
    // Did they request it by node reference or site?
    NodeRef nodeRef = null;
    SiteInfo site = null;
    BlogPostInfo blog = null;
    if (templateVars.containsKey("site")) {
        // Site, and Optionally Blog Post
        String siteName = templateVars.get("site");
        site = siteService.getSite(siteName);
        if (site == null) {
            String error = "Could not find site: " + siteName;
            throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
        }
        // Did they give a blog post name too?
        if (templateVars.containsKey("path")) {
            String name = templateVars.get("path");
            blog = blogService.getBlogPost(siteName, name);
            if (blog == null) {
                String error = "Could not find blog '" + name + "' for site '" + site.getShortName() + "'";
                throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
            }
            nodeRef = blog.getNodeRef();
        } else {
            // The NodeRef is the container (if it exists)
            if (siteService.hasContainer(siteName, BlogServiceImpl.BLOG_COMPONENT)) {
                nodeRef = siteService.getContainer(siteName, BlogServiceImpl.BLOG_COMPONENT);
            }
        }
    } else if (templateVars.containsKey("store_type") && templateVars.containsKey("store_id") && templateVars.containsKey("id")) {
        // NodeRef, should be a Blog Post
        StoreRef store = new StoreRef(templateVars.get("store_type"), templateVars.get("store_id"));
        nodeRef = new NodeRef(store, templateVars.get("id"));
        if (!nodeService.exists(nodeRef)) {
            String error = "Could not find node: " + nodeRef;
            throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
        }
        // Try to build the appropriate object for it
        blog = blogService.getForNodeRef(nodeRef);
        // See if it's actually attached to a site
        if (blog != null) {
            NodeRef container = blog.getContainerNodeRef();
            if (container != null) {
                NodeRef maybeSite = nodeService.getPrimaryParent(container).getParentRef();
                if (maybeSite != null) {
                    // Try to make it a site, will return Null if it isn't one
                    site = siteService.getSite(maybeSite);
                }
            }
        }
    } else {
        String error = "Unsupported template parameters found";
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
    }
    // Have the real work done
    return executeImpl(site, nodeRef, blog, req, json, status, cache);
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) SiteInfo(org.alfresco.service.cmr.site.SiteInfo) StoreRef(org.alfresco.service.cmr.repository.StoreRef) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException) BlogPostInfo(org.alfresco.service.cmr.blog.BlogPostInfo)

Example 4 with BlogPostInfo

use of org.alfresco.service.cmr.blog.BlogPostInfo in project alfresco-repository by Alfresco.

the class BlogServiceImpl method wrap.

private PagingResults<BlogPostInfo> wrap(final CannedQueryResults<BlogEntity> results, final NodeRef containerNodeRef) {
    // Wrap
    return new PagingResults<BlogPostInfo>() {

        @Override
        public String getQueryExecutionId() {
            return results.getQueryExecutionId();
        }

        @Override
        public Pair<Integer, Integer> getTotalResultCount() {
            return results.getTotalResultCount();
        }

        @Override
        public boolean hasMoreItems() {
            return results.hasMoreItems();
        }

        @Override
        public List<BlogPostInfo> getPage() {
            List<BlogEntity> entities = results.getPage();
            List<BlogPostInfo> posts = new ArrayList<BlogPostInfo>(entities.size());
            for (BlogEntity entity : entities) {
                posts.add(new BlogPostInfoImpl(entity.getNodeRef(), containerNodeRef, entity.getName()));
            }
            return posts;
        }
    };
}
Also used : BlogEntity(org.alfresco.repo.blog.cannedqueries.BlogEntity) EmptyPagingResults(org.alfresco.query.EmptyPagingResults) PagingResults(org.alfresco.query.PagingResults) ArrayList(java.util.ArrayList) BlogPostInfo(org.alfresco.service.cmr.blog.BlogPostInfo)

Example 5 with BlogPostInfo

use of org.alfresco.service.cmr.blog.BlogPostInfo in project alfresco-repository by Alfresco.

the class BlogServiceImplTest method createDraftBlogPostsAndGetPagedResults.

@Test
public void createDraftBlogPostsAndGetPagedResults() throws Exception {
    final int arbitraryNumberGreaterThanPageSize = 42;
    final List<NodeRef> submittedBlogPosts = TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<List<NodeRef>>() {

        @Override
        public List<NodeRef> execute() throws Throwable {
            List<NodeRef> results = new ArrayList<NodeRef>();
            for (int i = 0; i < arbitraryNumberGreaterThanPageSize; i++) {
                BlogPostInfo newBlogPost;
                if (i % 2 == 0) {
                    // By container ref
                    newBlogPost = BLOG_SERVICE.createBlogPost(BLOG_CONTAINER_NODE, "title_" + i, "Hello world", true);
                } else {
                    // By site name
                    newBlogPost = BLOG_SERVICE.createBlogPost(BLOG_SITE.getShortName(), "title_" + i, "Hello world", true);
                }
                results.add(newBlogPost.getNodeRef());
                testNodesToTidy.add(newBlogPost.getNodeRef());
            }
            return results;
        }
    });
    TRANSACTION_HELPER.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            List<BlogPostInfo> recoveredBlogPosts = new ArrayList<BlogPostInfo>(arbitraryNumberGreaterThanPageSize);
            final int pageSize = 10;
            PagingRequest pagingReq = new PagingRequest(0, pageSize, null);
            // must be set if calling getTotalResultCount() later
            pagingReq.setRequestTotalCountMax(arbitraryNumberGreaterThanPageSize);
            PagingResults<BlogPostInfo> pagedResults = BLOG_SERVICE.getDrafts(BLOG_CONTAINER_NODE, ADMIN_USER, pagingReq);
            assertEquals("Wrong total result count.", arbitraryNumberGreaterThanPageSize, (int) pagedResults.getTotalResultCount().getFirst());
            while (pagedResults.hasMoreItems()) {
                recoveredBlogPosts.addAll(pagedResults.getPage());
                pagingReq = new PagingRequest(pagingReq.getSkipCount() + pageSize, pageSize, null);
                pagedResults = BLOG_SERVICE.getDrafts(BLOG_CONTAINER_NODE, ADMIN_USER, pagingReq);
            }
            // and the last page, which only has 2 items in it.
            recoveredBlogPosts.addAll(pagedResults.getPage());
            assertEquals("Wrong number of blog posts.", submittedBlogPosts.size(), recoveredBlogPosts.size());
            // Check the list is sorted by cm:created, descending order.
            assertNodeRefsAreSortedBy(recoveredBlogPosts, ContentModel.PROP_CREATED, false);
            return null;
        }
    });
}
Also used : PagingResults(org.alfresco.query.PagingResults) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) BlogPostInfo(org.alfresco.service.cmr.blog.BlogPostInfo) PagingRequest(org.alfresco.query.PagingRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ArrayList(java.util.ArrayList) List(java.util.List) BaseSpringTest(org.alfresco.util.BaseSpringTest) Test(org.junit.Test)

Aggregations

BlogPostInfo (org.alfresco.service.cmr.blog.BlogPostInfo)16 ArrayList (java.util.ArrayList)10 NodeRef (org.alfresco.service.cmr.repository.NodeRef)10 PagingRequest (org.alfresco.query.PagingRequest)8 PagingResults (org.alfresco.query.PagingResults)8 List (java.util.List)7 RetryingTransactionHelper (org.alfresco.repo.transaction.RetryingTransactionHelper)7 BaseSpringTest (org.alfresco.util.BaseSpringTest)7 Test (org.junit.Test)7 HashMap (java.util.HashMap)5 Date (java.util.Date)4 JSONObject (org.json.simple.JSONObject)4 RangedDateProperty (org.alfresco.service.cmr.blog.BlogService.RangedDateProperty)3 Pair (org.alfresco.util.Pair)3 Category (org.junit.experimental.categories.Category)3 Calendar (java.util.Calendar)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Set (java.util.Set)2 IOException (java.io.IOException)1