Search in sources :

Example 61 with StoreRef

use of org.alfresco.service.cmr.repository.StoreRef in project records-management by Alfresco.

the class RMAfterInvocationProvider method decide.

@SuppressWarnings({ "unchecked", "rawtypes" })
private Collection decide(Authentication authentication, Object object, ConfigAttributeDefinition config, Collection returnedObject) {
    if (returnedObject == null) {
        return null;
    }
    List<ConfigAttributeDefintion> supportedDefinitions = extractSupportedDefinitions(config);
    if (logger.isDebugEnabled()) {
        logger.debug("Entries are " + supportedDefinitions);
    }
    if (supportedDefinitions.size() == 0) {
        return returnedObject;
    }
    // Default to the system-wide values and we'll see if they need to be reduced
    long targetResultCount = returnedObject.size();
    int maxPermissionChecks = Integer.MAX_VALUE;
    long maxPermissionCheckTimeMillis = this.maxPermissionCheckTimeMillis;
    if (returnedObject instanceof PermissionCheckCollection<?>) {
        PermissionCheckCollection permissionCheckCollection = (PermissionCheckCollection) returnedObject;
        // Get values
        targetResultCount = permissionCheckCollection.getTargetResultCount();
        if (permissionCheckCollection.getCutOffAfterCount() > 0) {
            maxPermissionChecks = permissionCheckCollection.getCutOffAfterCount();
        }
        if (permissionCheckCollection.getCutOffAfterTimeMs() > 0) {
            maxPermissionCheckTimeMillis = permissionCheckCollection.getCutOffAfterTimeMs();
        }
    }
    // Start timer and counter for cut-off
    boolean cutoff = false;
    long startTimeMillis = System.currentTimeMillis();
    int count = 0;
    // Keep values explicitly
    List<Object> keepValues = new ArrayList<Object>(returnedObject.size());
    for (Object nextObject : returnedObject) {
        // if the maximum result size or time has been exceeded, then we have to remove only
        long currentTimeMillis = System.currentTimeMillis();
        // NOTE: for reference - the "maxPermissionChecks" has never been honoured by this loop (since previously the count was not being incremented)
        if (count >= targetResultCount) {
            // We have enough results.  We stop without cutoff.
            break;
        } else if (count >= maxPermissionChecks) {
            // We have been cut off by count
            cutoff = true;
            if (logger.isDebugEnabled()) {
                logger.debug("decide (collection) cut-off: " + count + " checks exceeded " + maxPermissionChecks + " checks");
            }
            break;
        } else if ((currentTimeMillis - startTimeMillis) > maxPermissionCheckTimeMillis) {
            // We have been cut off by time
            cutoff = true;
            if (logger.isDebugEnabled()) {
                logger.debug("decide (collection) cut-off: " + (currentTimeMillis - startTimeMillis) + "ms exceeded " + maxPermissionCheckTimeMillis + "ms");
            }
            break;
        }
        boolean allowed = true;
        for (ConfigAttributeDefintion cad : supportedDefinitions) {
            if (cad.mode.equalsIgnoreCase("FilterNode")) {
                NodeRef testNodeRef = null;
                if (cad.parent) {
                    if (StoreRef.class.isAssignableFrom(nextObject.getClass())) {
                        // Will be allowed
                        testNodeRef = null;
                    } else if (NodeRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = nodeService.getPrimaryParent((NodeRef) nextObject).getParentRef();
                    } else if (ChildAssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((ChildAssociationRef) nextObject).getParentRef();
                    } else if (AssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((AssociationRef) nextObject).getSourceRef();
                    } else if (PermissionCheckValue.class.isAssignableFrom(nextObject.getClass())) {
                        NodeRef nodeRef = ((PermissionCheckValue) nextObject).getNodeRef();
                        testNodeRef = nodeService.getPrimaryParent(nodeRef).getParentRef();
                    } else {
                        throw new ACLEntryVoterException("The specified parameter is recognized: " + nextObject.getClass());
                    }
                } else {
                    if (StoreRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = nodeService.getRootNode((StoreRef) nextObject);
                    } else if (NodeRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = (NodeRef) nextObject;
                    } else if (ChildAssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((ChildAssociationRef) nextObject).getChildRef();
                    } else if (AssociationRef.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((AssociationRef) nextObject).getTargetRef();
                    } else if (PermissionCheckValue.class.isAssignableFrom(nextObject.getClass())) {
                        testNodeRef = ((PermissionCheckValue) nextObject).getNodeRef();
                    } else {
                        throw new ACLEntryVoterException("The specified parameter is recognized: " + nextObject.getClass());
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("\t" + cad.typeString + " test on " + testNodeRef + " from " + nextObject.getClass().getName());
                }
                // Null allows
                if (isUnfiltered(testNodeRef)) {
                    // Continue to next ConfigAttributeDefintion
                    continue;
                }
                if (allowed && testNodeRef != null && checkRead(testNodeRef) != AccessDecisionVoter.ACCESS_GRANTED) {
                    allowed = false;
                    // No point evaluating more ConfigAttributeDefintions
                    break;
                }
            }
        }
        // Failure or success, increase the count
        count++;
        if (allowed) {
            keepValues.add(nextObject);
        }
    }
    // Work out how many were left unchecked (for whatever reason)
    int sizeOriginal = returnedObject.size();
    int checksRemaining = sizeOriginal - count;
    // So make sure that the collection needs modification at all
    if (keepValues.size() < sizeOriginal) {
        // There are values that need to be removed.  We have to modify the collection.
        try {
            returnedObject.clear();
            returnedObject.addAll(keepValues);
        } catch (UnsupportedOperationException e) {
            throw new AccessDeniedException("Permission-checked list must be modifiable", e);
        }
    }
    // Attach the extra permission-check data to the collection
    return PermissionCheckedCollectionMixin.create(returnedObject, cutoff, checksRemaining, sizeOriginal);
}
Also used : StoreRef(org.alfresco.service.cmr.repository.StoreRef) AccessDeniedException(net.sf.acegisecurity.AccessDeniedException) ArrayList(java.util.ArrayList) ACLEntryVoterException(org.alfresco.repo.security.permissions.impl.acegi.ACLEntryVoterException) AssociationRef(org.alfresco.service.cmr.repository.AssociationRef) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) NodeRef(org.alfresco.service.cmr.repository.NodeRef) PermissionCheckValue(org.alfresco.repo.security.permissions.PermissionCheckValue) PermissionCheckCollection(org.alfresco.repo.security.permissions.PermissionCheckCollection)

Example 62 with StoreRef

use of org.alfresco.service.cmr.repository.StoreRef in project records-management by Alfresco.

the class BaseAuditRetrievalWebScript method parseQueryParameters.

/**
 * Parses the given request and builds an instance of
 * RecordsManagementAuditQueryParameters to retrieve the relevant audit entries
 *
 * @param req The request
 * @return RecordsManagementAuditQueryParameters instance
 */
protected RecordsManagementAuditQueryParameters parseQueryParameters(WebScriptRequest req) {
    // create parameters for audit trail retrieval
    RecordsManagementAuditQueryParameters params = new RecordsManagementAuditQueryParameters();
    // the webscripts can have a couple of different forms of url, work out
    // whether a nodeRef has been supplied or whether the whole audit
    // log should be displayed
    NodeRef nodeRef = null;
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    String storeType = templateVars.get("store_type");
    if (storeType != null && storeType.length() > 0) {
        // there is a store_type so all other params are likely to be present
        String storeId = templateVars.get("store_id");
        String nodeId = templateVars.get("id");
        // create the nodeRef
        nodeRef = new NodeRef(new StoreRef(storeType, storeId), nodeId);
    }
    // gather all the common filtering parameters, these could be on the
    // query string, in a multipart/form-data request or in a JSON body
    String size = null;
    String user = null;
    String event = null;
    String from = null;
    String to = null;
    String property = null;
    if (MimetypeMap.MIMETYPE_JSON.equals(req.getContentType())) {
        try {
            JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent()));
            if (json.has(PARAM_SIZE)) {
                size = json.getString(PARAM_SIZE);
            }
            if (json.has(PARAM_USER)) {
                user = json.getString(PARAM_USER);
            }
            if (json.has(PARAM_EVENT)) {
                event = json.getString(PARAM_EVENT);
            }
            if (json.has(PARAM_FROM)) {
                from = json.getString(PARAM_FROM);
            }
            if (json.has(PARAM_TO)) {
                to = json.getString(PARAM_TO);
            }
            if (json.has(PARAM_PROPERTY)) {
                property = json.getString(PARAM_PROPERTY);
            }
        } catch (IOException ioe) {
            // log a warning
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to parse JSON parameters for audit query: " + ioe.getMessage());
            }
        } catch (JSONException je) {
            // log a warning
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to parse JSON parameters for audit query: " + je.getMessage());
            }
        }
    } else {
        size = req.getParameter(PARAM_SIZE);
        user = req.getParameter(PARAM_USER);
        event = req.getParameter(PARAM_EVENT);
        from = req.getParameter(PARAM_FROM);
        to = req.getParameter(PARAM_TO);
        property = req.getParameter(PARAM_PROPERTY);
    }
    // setup the audit query parameters object
    params.setNodeRef(nodeRef);
    params.setUser(user);
    params.setEvent(event);
    if (size != null && size.length() > 0) {
        try {
            params.setMaxEntries(Integer.parseInt(size));
        } catch (NumberFormatException nfe) {
            if (logger.isWarnEnabled()) {
                logger.warn("Ignoring size parameter as '" + size + "' is not a number!");
            }
        }
    }
    if (from != null && from.length() > 0) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN);
            params.setDateFrom(dateFormat.parse(from));
        } catch (ParseException pe) {
            if (logger.isWarnEnabled()) {
                logger.warn("Ignoring from parameter as '" + from + "' does not conform to the date pattern: " + DATE_PATTERN);
            }
        }
    }
    if (to != null && to.length() > 0) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN);
            params.setDateTo(dateFormat.parse(to));
        } catch (ParseException pe) {
            if (logger.isWarnEnabled()) {
                logger.warn("Ignoring to parameter as '" + to + "' does not conform to the date pattern: " + DATE_PATTERN);
            }
        }
    }
    if (property != null && property.length() > 0) {
        try {
            params.setProperty(QName.createQName(property, namespaceService));
        } catch (InvalidQNameException iqe) {
            if (logger.isWarnEnabled()) {
                logger.warn("Ignoring property parameter as '" + property + "' is an invalid QName");
            }
        }
    }
    return params;
}
Also used : StoreRef(org.alfresco.service.cmr.repository.StoreRef) InvalidQNameException(org.alfresco.service.namespace.InvalidQNameException) RecordsManagementAuditQueryParameters(org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditQueryParameters) JSONException(org.json.JSONException) IOException(java.io.IOException) JSONTokener(org.json.JSONTokener) NodeRef(org.alfresco.service.cmr.repository.NodeRef) JSONObject(org.json.JSONObject) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 63 with StoreRef

use of org.alfresco.service.cmr.repository.StoreRef in project records-management by Alfresco.

the class BaseTransferWebScript method execute.

/**
 * @see org.alfresco.web.scripts.WebScript#execute(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
 */
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    File tempFile = null;
    try {
        // retrieve requested format
        String format = req.getFormat();
        // construct model for template
        Status status = new Status();
        Cache cache = new Cache(getDescription().getRequiredCache());
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("status", status);
        model.put("cache", cache);
        // get the parameters that represent the NodeRef, we know they are present
        // otherwise this webscript would not have matched
        Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
        String storeType = templateVars.get("store_type");
        String storeId = templateVars.get("store_id");
        String nodeId = templateVars.get("id");
        String transferId = templateVars.get("transfer_id");
        // create and return the file plan NodeRef
        NodeRef filePlan = new NodeRef(new StoreRef(storeType, storeId), nodeId);
        if (logger.isDebugEnabled()) {
            logger.debug("Retrieving transfer '" + transferId + "' from file plan: " + filePlan);
        }
        // ensure the file plan exists
        if (!this.nodeService.exists(filePlan)) {
            status.setCode(HttpServletResponse.SC_NOT_FOUND, "Node " + filePlan.toString() + " does not exist");
            Map<String, Object> templateModel = createTemplateParameters(req, res, model);
            sendStatus(req, res, status, cache, format, templateModel);
            return;
        }
        // ensure the node is a filePlan object
        if (!filePlanService.isFilePlan(filePlan)) {
            status.setCode(HttpServletResponse.SC_BAD_REQUEST, "Node " + filePlan.toString() + " is not a file plan");
            Map<String, Object> templateModel = createTemplateParameters(req, res, model);
            sendStatus(req, res, status, cache, format, templateModel);
            return;
        }
        // attempt to find the transfer node
        NodeRef transferNode = findTransferNode(filePlan, transferId);
        // send 404 if the transfer is not found
        if (transferNode == null) {
            status.setCode(HttpServletResponse.SC_NOT_FOUND, "Could not locate transfer with id: " + transferId);
            Map<String, Object> templateModel = createTemplateParameters(req, res, model);
            sendStatus(req, res, status, cache, format, templateModel);
            return;
        }
        // execute the transfer operation
        tempFile = executeTransfer(transferNode, req, res, status, cache);
    } catch (Exception e) {
        throw createStatusException(e, req, res);
    } finally {
        // try and delete the temporary file (if not in debug mode)
        if (tempFile != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Transfer report saved to temporary file: " + tempFile.getAbsolutePath());
            } else {
                tempFile.delete();
            }
        }
    }
}
Also used : Status(org.springframework.extensions.webscripts.Status) NodeRef(org.alfresco.service.cmr.repository.NodeRef) StoreRef(org.alfresco.service.cmr.repository.StoreRef) HashMap(java.util.HashMap) File(java.io.File) IOException(java.io.IOException) Cache(org.springframework.extensions.webscripts.Cache)

Example 64 with StoreRef

use of org.alfresco.service.cmr.repository.StoreRef in project records-management by Alfresco.

the class RFC822MetadataExtracter method getNodeRef.

/**
 * Given a set of properties, try and retrieve the node reference
 * @param properties    node properties
 * @return NodeRef      null if none, otherwise valid node reference
 */
private NodeRef getNodeRef(Map<QName, Serializable> properties) {
    NodeRef result = null;
    // Get the elements of the node reference
    String storeProto = (String) properties.get(ContentModel.PROP_STORE_PROTOCOL);
    String storeId = (String) properties.get(ContentModel.PROP_STORE_IDENTIFIER);
    String nodeId = (String) properties.get(ContentModel.PROP_NODE_UUID);
    if (storeProto != null && storeProto.length() != 0 && storeId != null && storeId.length() != 0 && nodeId != null && nodeId.length() != 0) {
        // Create the node reference
        result = new NodeRef(new StoreRef(storeProto, storeId), nodeId);
    }
    return result;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) StoreRef(org.alfresco.service.cmr.repository.StoreRef)

Example 65 with StoreRef

use of org.alfresco.service.cmr.repository.StoreRef in project records-management by Alfresco.

the class RoleDeclarativeWebScript method getFilePlan.

/**
 * Utility method to get the file plan from the passed parameters.
 *
 * @param req
 * @return
 */
protected NodeRef getFilePlan(WebScriptRequest req) {
    NodeRef filePlan = null;
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    String siteId = templateVars.get("siteid");
    if (siteId != null) {
        filePlan = filePlanService.getFilePlanBySiteId(siteId);
    }
    if (filePlan == null) {
        String storeType = templateVars.get("store_type");
        String storeId = templateVars.get("store_id");
        String id = templateVars.get("id");
        if (!StringUtils.isEmpty(storeType) && !StringUtils.isEmpty(storeId) && !StringUtils.isEmpty(id)) {
            StoreRef storeRef = new StoreRef(storeType, storeId);
            NodeRef nodeRef = new NodeRef(storeRef, id);
            if (filePlanService.isFilePlan(nodeRef)) {
                filePlan = nodeRef;
            }
        }
    }
    if (filePlan == null) {
        // Assume we are in a legacy repository and we will grab the default file plan
        filePlan = filePlanService.getFilePlanBySiteId(FilePlanService.DEFAULT_RM_SITE_ID);
    }
    return filePlan;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) StoreRef(org.alfresco.service.cmr.repository.StoreRef)

Aggregations

StoreRef (org.alfresco.service.cmr.repository.StoreRef)67 NodeRef (org.alfresco.service.cmr.repository.NodeRef)50 HashMap (java.util.HashMap)18 QName (org.alfresco.service.namespace.QName)17 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)13 StringPropertyValue (org.alfresco.solr.client.StringPropertyValue)13 PropertyValue (org.alfresco.solr.client.PropertyValue)11 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)10 ArrayList (java.util.ArrayList)9 ContentPropertyValue (org.alfresco.solr.client.ContentPropertyValue)9 MLTextPropertyValue (org.alfresco.solr.client.MLTextPropertyValue)9 IOException (java.io.IOException)7 Date (java.util.Date)6 MultiPropertyValue (org.alfresco.solr.client.MultiPropertyValue)6 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)5 PermissionService (org.alfresco.service.cmr.security.PermissionService)5 SolrCore (org.apache.solr.core.SolrCore)5 StringTokenizer (java.util.StringTokenizer)4 RetryingTransactionHelper (org.alfresco.repo.transaction.RetryingTransactionHelper)4 ServiceRegistry (org.alfresco.service.ServiceRegistry)4