Search in sources :

Example 46 with RetryingTransactionCallback

use of org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback in project acs-community-packaging by Alfresco.

the class BaseActionEvaluator method evaluate.

public boolean evaluate(final Object obj) {
    if (obj instanceof Node) {
        RetryingTransactionCallback<Boolean> txnCallback = new RetryingTransactionCallback<Boolean>() {

            @Override
            public Boolean execute() throws Throwable {
                return evaluate((Node) obj);
            }
        };
        TransactionService txnService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getTransactionService();
        return txnService.getRetryingTransactionHelper().doInTransaction(txnCallback, true, true);
    } else {
        return true;
    }
}
Also used : TransactionService(org.alfresco.service.transaction.TransactionService) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) Node(org.alfresco.web.bean.repository.Node)

Example 47 with RetryingTransactionCallback

use of org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback in project acs-community-packaging by Alfresco.

the class Repository method getNamePathEx.

/**
 * Resolve a Path by converting each element into its display NAME attribute.
 * Note: This method resolves path regardless access permissions.
 * Fixes the UI part of the ETWOONE-214 and ETWOONE-238 issues
 *
 * @param path       Path to convert
 * @param separator  Separator to user between path elements
 * @param prefix     To prepend to the path
 *
 * @return Path converted using NAME attribute on each element
 */
public static String getNamePathEx(FacesContext context, final Path path, final NodeRef rootNode, final String separator, final String prefix) {
    String result = null;
    RetryingTransactionHelper transactionHelper = getRetryingTransactionHelper(context);
    transactionHelper.setMaxRetries(1);
    final NodeService runtimeNodeService = (NodeService) FacesContextUtils.getRequiredWebApplicationContext(context).getBean("nodeService");
    result = transactionHelper.doInTransaction(new RetryingTransactionCallback<String>() {

        public String execute() throws Throwable {
            return getNamePath(runtimeNodeService, path, rootNode, separator, prefix);
        }
    });
    return result;
}
Also used : RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) NodeService(org.alfresco.service.cmr.repository.NodeService)

Example 48 with RetryingTransactionCallback

use of org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback in project acs-community-packaging by Alfresco.

the class BaseDialogBean method finish.

public String finish() {
    final FacesContext context = FacesContext.getCurrentInstance();
    final String defaultOutcome = getDefaultFinishOutcome();
    String outcome = null;
    // being pressed multiple times
    if (this.isFinished == false) {
        this.isFinished = true;
        RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context);
        RetryingTransactionCallback<String> callback = new RetryingTransactionCallback<String>() {

            public String execute() throws Throwable {
                // call the actual implementation
                return finishImpl(context, defaultOutcome);
            }
        };
        try {
            // Execute
            outcome = txnHelper.doInTransaction(callback, false, true);
            // allow any subclasses to perform post commit processing
            // i.e. resetting state or setting status messages
            outcome = doPostCommitProcessing(context, outcome);
            // remove container variable
            context.getExternalContext().getSessionMap().remove(AlfrescoNavigationHandler.EXTERNAL_CONTAINER_SESSION);
        } catch (Throwable e) {
            // reset the flag so we can re-attempt the operation
            isFinished = false;
            outcome = getErrorOutcome(e);
            if (e instanceof ReportedException == false) {
                Utils.addErrorMessage(formatErrorMessage(e), e);
            }
            ReportedException.throwIfNecessary(e);
        }
    } else {
        Utils.addErrorMessage(Application.getMessage(context, "error_wizard_completed_already"));
    }
    return outcome;
}
Also used : FacesContext(javax.faces.context.FacesContext) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) ReportedException(org.alfresco.web.ui.common.ReportedException)

Example 49 with RetryingTransactionCallback

use of org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback in project alfresco-remote-api by Alfresco.

the class RepoStore method getDocumentPaths.

/* (non-Javadoc)
     * @see org.alfresco.web.scripts.Store#getDocumentPaths(java.lang.String, boolean, java.lang.String)
     */
public String[] getDocumentPaths(String path, boolean includeSubPaths, String documentPattern) {
    if ((documentPattern == null) || (documentPattern.length() == 0)) {
        documentPattern = "*";
    }
    String matcher = documentPattern.replace(".", "\\.").replace("*", ".*");
    final Pattern pattern = Pattern.compile(matcher);
    String encPath = encodePathISO9075(path);
    // final StringBuilder query = new StringBuilder(128);
    // query.append("+PATH:\"").append(repoPath)
    // .append(encPath.length() != 0 ? ('/' + encPath) : "")
    // .append((includeSubPaths ? '/' : ""))
    // .append("/*\" +QNAME:")
    // .append(lucenifyNamePattern(documentPattern));
    final StringBuilder xpath = new StringBuilder(128);
    xpath.append(repoPath);
    xpath.append(encPath.length() != 0 ? ('/' + encPath) : "");
    xpath.append((includeSubPaths ? '/' : ""));
    xpath.append("/*[like(@cm:name, '" + SearchLanguageConversion.convert(SearchLanguageConversion.DEF_LUCENE, SearchLanguageConversion.DEF_XPATH_LIKE, documentPattern + "*") + "', false)]");
    return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String[]>() {

        public String[] doWork() throws Exception {
            return retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<String[]>() {

                public String[] execute() throws Exception {
                    int baseDirLength = getBaseDir().length() + 1;
                    List<String> documentPaths;
                    NodeRef repoStoreRootNodeRef = nodeService.getRootNode(repoStore);
                    List<NodeRef> nodeRefs = searchService.selectNodes(repoStoreRootNodeRef, xpath.toString(), new QueryParameterDefinition[] {}, namespaceService, false, SearchService.LANGUAGE_XPATH);
                    documentPaths = new ArrayList<String>(nodeRefs.size());
                    for (NodeRef nodeRef : nodeRefs) {
                        if (isContentPresent(nodeRef)) {
                            String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
                            if (pattern.matcher(name).matches()) {
                                String nodeDir = getPath(nodeRef);
                                String documentPath = nodeDir.substring(baseDirLength);
                                documentPaths.add(documentPath);
                            }
                        }
                    }
                    // }
                    return documentPaths.toArray(new String[documentPaths.size()]);
                }
            }, true, false);
        }
    }, AuthenticationUtil.getSystemUserName());
}
Also used : Pattern(java.util.regex.Pattern) NodeRef(org.alfresco.service.cmr.repository.NodeRef) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) FileNotFoundException(org.alfresco.service.cmr.model.FileNotFoundException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 50 with RetryingTransactionCallback

use of org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback in project alfresco-remote-api by Alfresco.

the class RepositoryContainer method executeScriptInternal.

protected void executeScriptInternal(WebScriptRequest scriptReq, WebScriptResponse scriptRes, final Authenticator auth) throws IOException {
    final WebScript script = scriptReq.getServiceMatch().getWebScript();
    final Description desc = script.getDescription();
    final boolean debug = logger.isDebugEnabled();
    // Escalate the webscript declared level of authentication to the container required authentication
    // eg. must be guest if MT is enabled unless credentials are empty
    RequiredAuthentication containerRequiredAuthentication = getRequiredAuthentication();
    final RequiredAuthentication required = (desc.getRequiredAuthentication().compareTo(containerRequiredAuthentication) < 0 && !auth.emptyCredentials() ? containerRequiredAuthentication : desc.getRequiredAuthentication());
    final boolean isGuest = scriptReq.isGuest();
    if (required == RequiredAuthentication.none) {
        // TODO revisit - cleared here, in-lieu of WebClient clear
        // AuthenticationUtil.clearCurrentSecurityContext();
        transactionedExecuteAs(script, scriptReq, scriptRes);
    } else if ((required == RequiredAuthentication.user || required == RequiredAuthentication.admin) && isGuest) {
        throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script " + desc.getId() + " requires user authentication; however, a guest has attempted access.");
    } else {
        try {
            AuthenticationUtil.pushAuthentication();
            // 
            if (debug) {
                String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
                logger.debug("Current authentication: " + (currentUser == null ? "unauthenticated" : "authenticated as " + currentUser));
                logger.debug("Authentication required: " + required);
                logger.debug("Guest login requested: " + isGuest);
            }
            // 
            // Apply appropriate authentication to Web Script invocation
            // 
            RetryingTransactionCallback<Boolean> authWork = new RetryingTransactionCallback<Boolean>() {

                public Boolean execute() throws Exception {
                    if (auth == null || auth.authenticate(required, isGuest)) {
                        // Check to see if they supplied HTTP Auth or Ticket as guest, on a script that needs more
                        if (required == RequiredAuthentication.user || required == RequiredAuthentication.admin) {
                            String authenticatedUser = AuthenticationUtil.getFullyAuthenticatedUser();
                            String runAsUser = AuthenticationUtil.getRunAsUser();
                            if ((authenticatedUser == null) || (authenticatedUser.equals(runAsUser) && authorityService.hasGuestAuthority()) || (!authenticatedUser.equals(runAsUser) && authorityService.isGuestAuthority(authenticatedUser))) {
                                throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script " + desc.getId() + " requires user authentication; however, a guest has attempted access.");
                            }
                        }
                        // Check to see if they're admin or system on an Admin only script
                        if (required == RequiredAuthentication.admin && !(authorityService.hasAdminAuthority() || AuthenticationUtil.getFullyAuthenticatedUser().equals(AuthenticationUtil.getSystemUserName()))) {
                            throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script " + desc.getId() + " requires admin authentication; however, a non-admin has attempted access.");
                        }
                        if (debug) {
                            String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
                            logger.debug("Authentication: " + (currentUser == null ? "unauthenticated" : "authenticated as " + currentUser));
                        }
                        return true;
                    }
                    return false;
                }
            };
            boolean readOnly = transactionService.isReadOnly();
            boolean requiresNew = !readOnly && AlfrescoTransactionSupport.getTransactionReadState() == TxnReadState.TXN_READ_ONLY;
            if (transactionService.getRetryingTransactionHelper().doInTransaction(authWork, readOnly, requiresNew)) {
                // Execute Web Script if authentication passed
                // The Web Script has its own txn management with potential runAs() user
                transactionedExecuteAs(script, scriptReq, scriptRes);
            } else {
                throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed for Web Script " + desc.getId());
            }
        } finally {
            // 
            // Reset authentication for current thread
            // 
            AuthenticationUtil.popAuthentication();
            if (debug) {
                String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
                logger.debug("Authentication reset: " + (currentUser == null ? "unauthenticated" : "authenticated as " + currentUser));
            }
        }
    }
}
Also used : Description(org.springframework.extensions.webscripts.Description) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) WebScript(org.springframework.extensions.webscripts.WebScript) SocketException(java.net.SocketException) TooBusyException(org.alfresco.repo.transaction.TooBusyException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) RequiredAuthentication(org.springframework.extensions.webscripts.Description.RequiredAuthentication)

Aggregations

RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)78 NodeRef (org.alfresco.service.cmr.repository.NodeRef)44 RetryingTransactionHelper (org.alfresco.repo.transaction.RetryingTransactionHelper)20 FileInfo (org.alfresco.service.cmr.model.FileInfo)20 WebApiDescription (org.alfresco.rest.framework.WebApiDescription)16 HashMap (java.util.HashMap)15 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)15 FacesContext (javax.faces.context.FacesContext)12 QName (org.alfresco.service.namespace.QName)11 Serializable (java.io.Serializable)10 List (java.util.List)9 ArrayList (java.util.ArrayList)8 ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)8 IOException (java.io.IOException)7 FileNotFoundException (org.alfresco.service.cmr.model.FileNotFoundException)7 Test (org.junit.Test)7 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)7 AuthenticationUtil (org.alfresco.repo.security.authentication.AuthenticationUtil)6 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)6 AbstractList (java.util.AbstractList)5