Search in sources :

Example 61 with WebScriptException

use of org.springframework.extensions.webscripts.WebScriptException in project records-management by Alfresco.

the class ExportPost method execute.

/**
 * @see org.alfresco.web.scripts.WebScript#execute(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
 */
@SuppressWarnings("deprecation")
@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    File tempACPFile = null;
    try {
        NodeRef[] nodeRefs = null;
        boolean transferFormat = false;
        String contentType = req.getContentType();
        if (MULTIPART_FORMDATA.equals(contentType)) {
            // get nodeRefs parameter from form
            nodeRefs = getNodeRefs(req.getParameter(PARAM_NODE_REFS));
            // look for the transfer format
            String transferFormatParam = req.getParameter(PARAM_TRANSFER_FORMAT);
            if (transferFormatParam != null && transferFormatParam.length() > 0) {
                transferFormat = Boolean.parseBoolean(transferFormatParam);
            }
        } else {
            // presume the request is a JSON request so get nodeRefs from JSON body
            JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent()));
            nodeRefs = getNodeRefs(json);
            if (json.has(PARAM_TRANSFER_FORMAT)) {
                transferFormat = json.getBoolean(PARAM_TRANSFER_FORMAT);
            }
        }
        // setup the ACP parameters
        ExporterCrawlerParameters params = new ExporterCrawlerParameters();
        params.setCrawlSelf(true);
        params.setCrawlChildNodes(true);
        params.setExportFrom(new Location(nodeRefs));
        // if transfer format has been requested we need to exclude certain aspects
        if (transferFormat) {
            // restrict specific aspects from being returned
            QName[] excludedAspects = new QName[] { RenditionModel.ASPECT_RENDITIONED, ContentModel.ASPECT_THUMBNAILED, RecordsManagementModel.ASPECT_DISPOSITION_LIFECYCLE, RecordsManagementSearchBehaviour.ASPECT_RM_SEARCH, RecordsManagementModel.ASPECT_EXTENDED_SECURITY };
            params.setExcludeAspects(excludedAspects);
        } else {
            // restrict specific aspects from being returned
            QName[] excludedAspects = new QName[] { RecordsManagementModel.ASPECT_EXTENDED_SECURITY };
            params.setExcludeAspects(excludedAspects);
        }
        // create an ACP of the nodes
        tempACPFile = createACP(params, transferFormat ? ZIP_EXTENSION : ACPExportPackageHandler.ACP_EXTENSION, transferFormat);
        // stream the ACP back to the client as an attachment (forcing save as)
        contentStreamer.streamContent(req, res, tempACPFile, null, true, tempACPFile.getName(), null);
    } catch (IOException ioe) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from req.", ioe);
    } catch (JSONException je) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            StringWriter stack = new StringWriter();
            e.printStackTrace(new PrintWriter(stack));
            logger.debug("Caught exception; decorating with appropriate status template : " + stack.toString());
        }
        throw createStatusException(e, req, res);
    } finally {
        // try and delete the temporary file
        if (tempACPFile != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Deleting temporary archive: " + tempACPFile.getAbsolutePath());
            }
            tempACPFile.delete();
        }
    }
}
Also used : QName(org.alfresco.service.namespace.QName) ExporterCrawlerParameters(org.alfresco.service.cmr.view.ExporterCrawlerParameters) JSONException(org.json.JSONException) IOException(java.io.IOException) IOException(java.io.IOException) JSONException(org.json.JSONException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONTokener(org.json.JSONTokener) NodeRef(org.alfresco.service.cmr.repository.NodeRef) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) StringWriter(java.io.StringWriter) File(java.io.File) Location(org.alfresco.service.cmr.view.Location) PrintWriter(java.io.PrintWriter)

Example 62 with WebScriptException

use of org.springframework.extensions.webscripts.WebScriptException in project records-management by Alfresco.

the class RmActionPost method executeImpl.

@SuppressWarnings("unchecked")
@Override
public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    String reqContentAsString;
    try {
        reqContentAsString = req.getContent().getContent();
    } catch (IOException iox) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    }
    String actionName = null;
    List<NodeRef> targetNodeRefs = new ArrayList<NodeRef>(1);
    Map<String, Serializable> actionParams = new HashMap<String, Serializable>(3);
    try {
        JSONObject jsonObj = new JSONObject(new JSONTokener(reqContentAsString));
        // Get the action name
        if (jsonObj.has(PARAM_NAME)) {
            actionName = jsonObj.getString(PARAM_NAME);
        }
        // Get the target references
        if (jsonObj.has(PARAM_NODE_REF)) {
            NodeRef nodeRef = new NodeRef(jsonObj.getString(PARAM_NODE_REF));
            targetNodeRefs.add(nodeRef);
        }
        if (jsonObj.has(PARAM_NODE_REFS)) {
            JSONArray jsonArray = jsonObj.getJSONArray(PARAM_NODE_REFS);
            if (jsonArray.length() != 0) {
                targetNodeRefs = new ArrayList<NodeRef>(jsonArray.length());
                for (int i = 0; i < jsonArray.length(); i++) {
                    NodeRef nodeRef = new NodeRef(jsonArray.getString(i));
                    targetNodeRefs.add(nodeRef);
                }
            }
        }
        // params are optional.
        if (jsonObj.has(PARAM_PARAMS)) {
            JSONObject paramsObj = jsonObj.getJSONObject(PARAM_PARAMS);
            for (Iterator<String> iter = paramsObj.keys(); iter.hasNext(); ) {
                String nextKeyString = iter.next();
                Object nextValue = paramsObj.get(nextKeyString);
                // Check for date values
                if ((nextValue instanceof JSONObject) && ((JSONObject) nextValue).has("iso8601")) {
                    String dateStringValue = ((JSONObject) nextValue).getString("iso8601");
                    nextValue = ISO8601DateFormat.parse(dateStringValue);
                }
                actionParams.put(nextKeyString, (Serializable) nextValue);
            }
        }
    } catch (JSONException exception) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Unable to parse request JSON.", exception);
    }
    // Some RM actions can be posted without a nodeRef.
    if (actionName == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "A mandatory parameter has not been provided in URL");
    }
    // Check that all the nodes provided exist and build report string
    StringBuilder targetNodeRefsString = new StringBuilder(30);
    boolean firstTime = true;
    for (NodeRef targetNodeRef : targetNodeRefs) {
        if (!nodeService.exists(targetNodeRef)) {
            throw new WebScriptException(Status.STATUS_NOT_FOUND, "The targetNode does not exist (" + targetNodeRef.toString() + ")");
        }
        // Build the string
        if (firstTime) {
            firstTime = false;
        } else {
            targetNodeRefsString.append(", ");
        }
        targetNodeRefsString.append(targetNodeRef.toString());
    }
    // Proceed to execute the specified action on the specified node.
    if (logger.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Executing Record Action ").append(actionName).append(", (").append(targetNodeRefsString.toString()).append("), ").append(actionParams);
        logger.debug(msg.toString());
    }
    Map<String, Object> model = new HashMap<String, Object>();
    if (targetNodeRefs.isEmpty()) {
        RecordsManagementActionResult result = this.rmActionService.executeRecordsManagementAction(actionName, actionParams);
        if (result.getValue() != null) {
            model.put("result", result.getValue().toString());
        }
    } else {
        Map<NodeRef, RecordsManagementActionResult> resultMap = this.rmActionService.executeRecordsManagementAction(targetNodeRefs, actionName, actionParams);
        Map<String, String> results = new HashMap<String, String>(resultMap.size());
        for (Map.Entry<NodeRef, RecordsManagementActionResult> entry : resultMap.entrySet()) {
            Object value = entry.getValue().getValue();
            if (value != null) {
                results.put(entry.getKey().toString(), value.toString());
            }
        }
        model.put("results", results);
    }
    model.put("message", "Successfully queued action [" + actionName + "] on " + targetNodeRefsString.toString());
    return model;
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) NodeRef(org.alfresco.service.cmr.repository.NodeRef) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) RecordsManagementActionResult(org.alfresco.module.org_alfresco_module_rm.action.RecordsManagementActionResult) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 63 with WebScriptException

use of org.springframework.extensions.webscripts.WebScriptException in project records-management by Alfresco.

the class RmEventPut method executeImpl.

/**
 * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest,
 *      org.springframework.extensions.webscripts.Status,
 *      org.springframework.extensions.webscripts.Cache)
 */
@Override
public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    ParameterCheck.mandatory("req", req);
    Map<String, Object> model = new HashMap<String, Object>();
    JSONObject json = null;
    try {
        // Convert the request content to JSON
        json = new JSONObject(new JSONTokener(req.getContent().getContent()));
        // Check the event name
        Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
        String eventName = templateVars.get(PARAM_EVENTNAME);
        if (eventName == null || eventName.isEmpty() || !rmEventService.existsEvent(eventName)) {
            throw new WebScriptException(Status.STATUS_NOT_FOUND, "No event name was provided.");
        }
        // Check the event display label
        String eventDisplayLabel = getValue(json, "eventDisplayLabel");
        doCheck(eventDisplayLabel, "No event display label was provided.");
        // Check the event type
        String eventType = getValue(json, "eventType");
        doCheck(eventType, "No event type was provided.");
        // Check if the event can be edited or not
        RecordsManagementEvent event = null;
        if (canEditEvent(eventDisplayLabel, eventName, eventType)) {
            // Create event
            event = rmEventService.addEvent(eventType, eventName, eventDisplayLabel);
        } else {
            // Get event
            event = rmEventService.getEvent(eventName);
        }
        model.put("event", event);
    } catch (IOException iox) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    } catch (JSONException je) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    }
    return model;
}
Also used : JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) HashMap(java.util.HashMap) RecordsManagementEvent(org.alfresco.module.org_alfresco_module_rm.event.RecordsManagementEvent) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) IOException(java.io.IOException)

Example 64 with WebScriptException

use of org.springframework.extensions.webscripts.WebScriptException in project records-management by Alfresco.

the class AuditLogPut method executeImpl.

/*
     * @see org.alfresco.web.scripts.DeclarativeWebScript#executeImpl(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.Status, org.alfresco.web.scripts.Cache)
     */
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    try {
        // determine whether to start or stop auditing
        JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent()));
        // check the enabled property present
        if (!json.has(PARAM_ENABLED)) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Mandatory 'enabled' parameter was not provided in request body");
        }
        boolean enabled = json.getBoolean(PARAM_ENABLED);
        if (enabled) {
            this.rmAuditService.startAuditLog(getDefaultFilePlan());
        } else {
            this.rmAuditService.stopAuditLog(getDefaultFilePlan());
        }
        // create model object with the audit status model
        Map<String, Object> model = new HashMap<String, Object>(1);
        model.put("auditstatus", createAuditStatusModel());
        return model;
    } catch (IOException iox) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    } catch (JSONException je) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    }
}
Also used : JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) HashMap(java.util.HashMap) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) IOException(java.io.IOException)

Example 65 with WebScriptException

use of org.springframework.extensions.webscripts.WebScriptException in project records-management by Alfresco.

the class CustomPropertyDefinitionPost method executeImpl.

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    JSONObject json = null;
    Map<String, Object> ftlModel = null;
    try {
        json = new JSONObject(new JSONTokener(req.getContent().getContent()));
        try {
            ftlModel = createPropertyDefinition(req, json);
        } catch (CustomMetadataException e) {
            status.setCode(Status.STATUS_BAD_REQUEST);
            ftlModel = new HashMap<String, Object>();
            ftlModel.put(MESSAGE, e.getMessage());
        }
    } catch (IOException iox) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from req.", iox);
    } catch (JSONException je) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from req.", je);
    }
    return ftlModel;
}
Also used : JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) HashMap(java.util.HashMap) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) IOException(java.io.IOException) CustomMetadataException(org.alfresco.module.org_alfresco_module_rm.admin.CustomMetadataException)

Aggregations

WebScriptException (org.springframework.extensions.webscripts.WebScriptException)204 HashMap (java.util.HashMap)94 NodeRef (org.alfresco.service.cmr.repository.NodeRef)67 IOException (java.io.IOException)60 JSONException (org.json.JSONException)48 JSONObject (org.json.JSONObject)44 ArrayList (java.util.ArrayList)32 QName (org.alfresco.service.namespace.QName)31 JSONTokener (org.json.JSONTokener)29 JSONObject (org.json.simple.JSONObject)25 JSONArray (org.json.JSONArray)18 Map (java.util.Map)12 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)11 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)11 StoreRef (org.alfresco.service.cmr.repository.StoreRef)10 File (java.io.File)9 Date (java.util.Date)8 JSONParser (org.json.simple.parser.JSONParser)8 Serializable (java.io.Serializable)7 InvalidNodeRefException (org.alfresco.service.cmr.repository.InvalidNodeRefException)7