Search in sources :

Example 11 with JSONWriter

use of org.springframework.extensions.webscripts.json.JSONWriter in project acs-community-packaging by Alfresco.

the class PickerBean method getCategoryNodes.

/**
 * Return the JSON objects representing a list of categories.
 *
 * IN: "parent" - null for root categories, else the parent noderef of the categories to retrieve.
 *
 * The pseudo root node 'Categories' is not selectable.
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void getCategoryNodes() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();
    UserTransaction tx = null;
    try {
        tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
        tx.begin();
        Collection<ChildAssociationRef> childRefs;
        NodeRef parentRef = null;
        Map params = fc.getExternalContext().getRequestParameterMap();
        String strParentRef = Utils.encode((String) params.get(PARAM_PARENT));
        if (strParentRef == null || strParentRef.length() == 0) {
            childRefs = this.getCategoryService().getRootCategories(Repository.getStoreRef(), ContentModel.ASPECT_GEN_CLASSIFIABLE);
        } else {
            parentRef = new NodeRef(strParentRef);
            childRefs = this.getCategoryService().getChildren(parentRef, CategoryService.Mode.SUB_CATEGORIES, CategoryService.Depth.IMMEDIATE);
        }
        JSONWriter out = new JSONWriter(fc.getResponseWriter());
        out.startObject();
        out.startValue(ID_PARENT);
        out.startObject();
        if (parentRef == null) {
            out.writeNullValue(ID_ID);
            out.writeValue(ID_NAME, Application.getMessage(fc, MSG_CATEGORIES));
            out.writeValue(ID_ISROOT, true);
            out.writeValue(ID_SELECTABLE, false);
        } else {
            out.writeValue(ID_ID, strParentRef);
            out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), parentRef));
        }
        out.endObject();
        out.endValue();
        out.startValue(ID_CHILDREN);
        out.startArray();
        for (ChildAssociationRef ref : childRefs) {
            NodeRef nodeRef = ref.getChildRef();
            out.startObject();
            out.writeValue(ID_ID, nodeRef.toString());
            out.writeValue(ID_NAME, Repository.getNameForNode(this.getInternalNodeService(), nodeRef));
            out.endObject();
        }
        out.endArray();
        out.endValue();
        out.endObject();
        tx.commit();
    } catch (Throwable err) {
        Utils.addErrorMessage("PickerBean exception in getCategoryRootNodes()", err);
        fc.getResponseWriter().write("ERROR: " + err.getMessage());
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) JSONWriter(org.springframework.extensions.webscripts.json.JSONWriter) FacesContext(javax.faces.context.FacesContext) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) Map(java.util.Map) MimetypeMap(org.alfresco.repo.content.MimetypeMap)

Example 12 with JSONWriter

use of org.springframework.extensions.webscripts.json.JSONWriter in project alfresco-remote-api by Alfresco.

the class AbstractLinksWebScript method addActivityEntry.

/**
 * Generates an activity entry for the link
 */
protected void addActivityEntry(String event, LinkInfo link, SiteInfo site, WebScriptRequest req, JSONObject json) {
    // What page is this for?
    String page = req.getParameter("page");
    if (page == null && json != null) {
        if (json.containsKey("page")) {
            page = (String) json.get("page");
        }
    }
    if (page == null) {
        // Default
        page = "links";
    }
    try {
        StringWriter activityJson = new StringWriter();
        JSONWriter activity = new JSONWriter(activityJson);
        activity.startObject();
        activity.writeValue("title", link.getTitle());
        activity.writeValue("page", page + "?linkId=" + link.getSystemName());
        activity.endObject();
        activityService.postActivity("org.alfresco.links.link-" + event, site.getShortName(), LINKS_SERVICE_ACTIVITY_APP_NAME, activityJson.toString());
    } catch (Exception e) {
        // Warn, but carry on
        logger.warn("Error adding link " + event + " to activities feed", e);
    }
}
Also used : JSONWriter(org.springframework.extensions.webscripts.json.JSONWriter) StringWriter(java.io.StringWriter) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) NoSuchPersonException(org.alfresco.service.cmr.security.NoSuchPersonException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException)

Example 13 with JSONWriter

use of org.springframework.extensions.webscripts.json.JSONWriter in project alfresco-remote-api by Alfresco.

the class BulkMetadataGet method execute.

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    JSONObject jsonIn;
    JSONArray nodeRefsArray;
    try {
        Content c = req.getContent();
        if (c == null) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body.");
        }
        jsonIn = new JSONObject(c.getContent());
        nodeRefsArray = jsonIn.getJSONArray("nodeRefs");
        if (nodeRefsArray == null || nodeRefsArray.length() == 0) {
            throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Must provide node refs");
        }
        JSONWriter jsonOut = new JSONWriter(res.getWriter());
        res.setContentType("application/json");
        // TODO: Should be settable on JSONWriter
        res.setContentEncoding(Charset.defaultCharset().displayName());
        jsonOut.startObject();
        {
            jsonOut.startValue("nodes");
            {
                jsonOut.startArray();
                {
                    for (int i = 0; i < nodeRefsArray.length(); i++) {
                        NodeRef nodeRef = new NodeRef(nodeRefsArray.getString(i));
                        if (nodeService.exists(nodeRef)) {
                            NodeRef parentNodeRef = null;
                            ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(nodeRef);
                            if (childAssocRef != null) {
                                parentNodeRef = childAssocRef.getParentRef();
                            }
                            QName type = nodeService.getType(nodeRef);
                            String shortType = type.toPrefixString(services.getNamespaceService());
                            Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
                            jsonOut.startObject();
                            {
                                jsonOut.writeValue("nodeRef", nodeRef.toString());
                                jsonOut.writeValue("parentNodeRef", parentNodeRef.toString());
                                jsonOut.writeValue("type", type.toString());
                                jsonOut.writeValue("shortType", shortType);
                                TypeDefinition typeDef = dictionaryService.getType(type);
                                jsonOut.writeValue("typeTitle", typeDef.getTitle(dictionaryService));
                                jsonOut.writeValue("name", (String) properties.get(ContentModel.PROP_NAME));
                                jsonOut.writeValue("title", (String) properties.get(ContentModel.PROP_TITLE));
                                jsonOut.writeValue("mimeType", getMimeType((ContentData) properties.get(ContentModel.PROP_CONTENT)));
                                jsonOut.writeValue("hasWritePermission", permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.ALLOWED);
                                jsonOut.writeValue("hasDeletePermission", permissionService.hasPermission(nodeRef, PermissionService.DELETE) == AccessStatus.ALLOWED);
                            }
                            jsonOut.endObject();
                        } else {
                            jsonOut.startObject();
                            {
                                jsonOut.writeValue("nodeRef", nodeRef.toString());
                                jsonOut.writeValue("error", "true");
                                jsonOut.writeValue("errorCode", "invalidNodeRef");
                                jsonOut.writeValue("errorText", I18NUtil.getMessage("msg.invalidNodeRef", nodeRef.toString()));
                            }
                            jsonOut.endObject();
                        }
                    }
                }
                jsonOut.endArray();
            }
            jsonOut.endValue();
        }
        jsonOut.endObject();
    } catch (JSONException jErr) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Unable to parse JSON POST body: " + jErr.getMessage());
    }
    res.getWriter().close();
    res.setStatus(Status.STATUS_OK);
}
Also used : JSONWriter(org.springframework.extensions.webscripts.json.JSONWriter) QName(org.alfresco.service.namespace.QName) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentData(org.alfresco.service.cmr.repository.ContentData) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) Content(org.springframework.extensions.surf.util.Content) Map(java.util.Map)

Example 14 with JSONWriter

use of org.springframework.extensions.webscripts.json.JSONWriter in project alfresco-remote-api by Alfresco.

the class PrepareTransferCommandProcessor method process.

/*
     * (non-Javadoc)
     * 
     * @see org.alfresco.repo.web.scripts.transfer.CommandProcessor#process(org.alfresco .web.scripts.WebScriptRequest,
     * org.alfresco.web.scripts.WebScriptResponse)
     */
public int process(WebScriptRequest req, WebScriptResponse resp) {
    String transferRecordId = null;
    // Read the transfer id from the request
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
    String transferId = servletRequest.getParameter("transferId");
    if (transferId == null) {
        logger.debug("transferId is missing");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    try {
        logger.debug("prepare transferId: " + transferId);
        receiver.prepare(transferId);
        // return the unique transfer id (the lock id)
        StringWriter stringWriter = new StringWriter(300);
        JSONWriter jsonWriter = new JSONWriter(stringWriter);
        jsonWriter.startObject();
        jsonWriter.writeValue("transferId", transferRecordId);
        jsonWriter.endObject();
        String response = stringWriter.toString();
        resp.setContentType("application/json");
        resp.setContentEncoding("UTF-8");
        int length = response.getBytes("UTF-8").length;
        resp.addHeader("Content-Length", "" + length);
        resp.setStatus(Status.STATUS_OK);
        resp.getWriter().write(response);
        logger.debug("prepared transferId: " + transferId);
        return Status.STATUS_OK;
    } catch (Exception ex) {
        logger.debug("in exception handler", ex);
        receiver.end(transferRecordId);
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONWriter(org.springframework.extensions.webscripts.json.JSONWriter) TransferException(org.alfresco.service.cmr.transfer.TransferException) StringWriter(java.io.StringWriter) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) TransferException(org.alfresco.service.cmr.transfer.TransferException)

Aggregations

JSONWriter (org.springframework.extensions.webscripts.json.JSONWriter)14 StringWriter (java.io.StringWriter)9 Map (java.util.Map)5 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)5 NodeRef (org.alfresco.service.cmr.repository.NodeRef)5 TransferException (org.alfresco.service.cmr.transfer.TransferException)5 FacesContext (javax.faces.context.FacesContext)4 UserTransaction (javax.transaction.UserTransaction)4 MimetypeMap (org.alfresco.repo.content.MimetypeMap)4 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 WebScriptRequest (org.springframework.extensions.webscripts.WebScriptRequest)3 WrappingWebScriptRequest (org.springframework.extensions.webscripts.WrappingWebScriptRequest)3 WebScriptServletRequest (org.springframework.extensions.webscripts.servlet.WebScriptServletRequest)3 IOException (java.io.IOException)2 FileInfo (org.alfresco.service.cmr.model.FileInfo)2 JSONException (org.json.JSONException)2 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 StringTokenizer (java.util.StringTokenizer)1