Search in sources :

Example 96 with WebScriptException

use of org.springframework.extensions.webscripts.WebScriptException 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)

Example 97 with WebScriptException

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

the class RepositoryContainer method transactionedExecute.

/**
 * Execute script within required level of transaction
 *
 * @param script WebScript
 * @param scriptReq WebScriptRequest
 * @param scriptRes WebScriptResponse
 * @throws IOException
 */
protected void transactionedExecute(final WebScript script, final WebScriptRequest scriptReq, final WebScriptResponse scriptRes) throws IOException {
    try {
        final Description description = script.getDescription();
        if (description.getRequiredTransaction() == RequiredTransaction.none) {
            script.execute(scriptReq, scriptRes);
        } else {
            final BufferedRequest bufferedReq;
            final BufferedResponse bufferedRes;
            RequiredTransactionParameters trxParams = description.getRequiredTransactionParameters();
            if (trxParams.getCapability() == TransactionCapability.readwrite) {
                if (trxParams.getBufferSize() > 0) {
                    if (logger.isDebugEnabled())
                        logger.debug("Creating Transactional Response for ReadWrite transaction; buffersize=" + trxParams.getBufferSize());
                    // create buffered request and response that allow transaction retrying
                    bufferedReq = new BufferedRequest(scriptReq, streamFactory);
                    bufferedRes = new BufferedResponse(scriptRes, trxParams.getBufferSize());
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Transactional Response bypassed for ReadWrite - buffersize=0");
                    bufferedReq = null;
                    bufferedRes = null;
                }
            } else {
                bufferedReq = null;
                bufferedRes = null;
            }
            // encapsulate script within transaction
            RetryingTransactionCallback<Object> work = new RetryingTransactionCallback<Object>() {

                public Object execute() throws Exception {
                    try {
                        if (logger.isDebugEnabled())
                            logger.debug("Begin retry transaction block: " + description.getRequiredTransaction() + "," + description.getRequiredTransactionParameters().getCapability());
                        if (bufferedRes == null) {
                            script.execute(scriptReq, scriptRes);
                        } else {
                            // Reset the request and response in case of a transaction retry
                            bufferedReq.reset();
                            bufferedRes.reset();
                            script.execute(bufferedReq, bufferedRes);
                        }
                    } catch (Exception e) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Transaction exception: " + description.getRequiredTransaction() + ": " + e.getMessage());
                            // Note: user transaction shouldn't be null, but just in case inside this exception handler
                            UserTransaction userTrx = RetryingTransactionHelper.getActiveUserTransaction();
                            if (userTrx != null) {
                                logger.debug("Transaction status: " + userTrx.getStatus());
                            }
                        }
                        UserTransaction userTrx = RetryingTransactionHelper.getActiveUserTransaction();
                        if (userTrx != null) {
                            if (userTrx.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
                                if (logger.isDebugEnabled())
                                    logger.debug("Marking web script transaction for rollback");
                                try {
                                    userTrx.setRollbackOnly();
                                } catch (Throwable re) {
                                    if (logger.isDebugEnabled())
                                        logger.debug("Caught and ignoring exception during marking for rollback: " + re.getMessage());
                                }
                            }
                        }
                        // re-throw original exception for retry
                        throw e;
                    } finally {
                        if (logger.isDebugEnabled())
                            logger.debug("End retry transaction block: " + description.getRequiredTransaction() + "," + description.getRequiredTransactionParameters().getCapability());
                    }
                    return null;
                }
            };
            boolean readonly = description.getRequiredTransactionParameters().getCapability() == TransactionCapability.readonly;
            boolean requiresNew = description.getRequiredTransaction() == RequiredTransaction.requiresnew;
            // NOT have any side effects so this scenario as a warning sign something maybe amiss, see ALF-10179.
            if (logger.isDebugEnabled() && !readonly && "GET".equalsIgnoreCase(description.getMethod())) {
                logger.debug("Webscript with URL '" + scriptReq.getURL() + "' is a GET request but it's descriptor has declared a readwrite transaction is required");
            }
            try {
                RetryingTransactionHelper transactionHelper = transactionService.getRetryingTransactionHelper();
                if (script instanceof LoginPost) {
                    // login script requires read-write transaction because of authorization intercepter
                    transactionHelper.setForceWritable(true);
                }
                transactionHelper.doInTransaction(work, readonly, requiresNew);
            } catch (TooBusyException e) {
                // Map TooBusyException to a 503 status code
                throw new WebScriptException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage(), e);
            } finally {
                // Get rid of any temporary files
                if (bufferedReq != null) {
                    bufferedReq.close();
                }
            }
            // Ensure a response is always flushed after successful execution
            if (bufferedRes != null) {
                bufferedRes.writeResponse();
            }
        }
    } catch (IOException ioe) {
        Throwable socketException = ExceptionStackUtil.getCause(ioe, SocketException.class);
        Class<?> clientAbortException = null;
        try {
            clientAbortException = Class.forName("org.apache.catalina.connector.ClientAbortException");
        } catch (ClassNotFoundException e) {
        // do nothing
        }
        // Note: if you need to look for more exceptions in the stack, then create a static array and pass it in
        if ((socketException != null && socketException.getMessage().contains("Broken pipe")) || (clientAbortException != null && ExceptionStackUtil.getCause(ioe, clientAbortException) != null)) {
            if (logger.isDebugEnabled()) {
                logger.warn("Client has cut off communication", ioe);
            } else {
                logger.info("Client has cut off communication");
            }
        } else {
            throw ioe;
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) SocketException(java.net.SocketException) Description(org.springframework.extensions.webscripts.Description) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) IOException(java.io.IOException) 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) RequiredTransactionParameters(org.springframework.extensions.webscripts.Description.RequiredTransactionParameters) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) TooBusyException(org.alfresco.repo.transaction.TooBusyException) LoginPost(org.alfresco.repo.web.scripts.bean.LoginPost)

Example 98 with WebScriptException

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

the class RepositoryTemplateProcessor method hasTemplate.

/* (non-Javadoc)
     * @see org.alfresco.web.scripts.TemplateProcessor#hasTemplate(java.lang.String)
     */
public boolean hasTemplate(String templatePath) {
    boolean hasTemplate = false;
    try {
        Template template = templateConfig.getTemplate(templatePath);
        hasTemplate = (template != null);
    } catch (FileNotFoundException e) {
    // NOTE: return false as template is not found
    } catch (IOException e) {
        throw new WebScriptException("Failed to retrieve template " + templatePath, e);
    }
    return hasTemplate;
}
Also used : WebScriptException(org.springframework.extensions.webscripts.WebScriptException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Template(freemarker.template.Template)

Example 99 with WebScriptException

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

the class RunningReplicationActionsPost method identifyAction.

@Override
protected Action identifyAction(WebScriptRequest req, Status status, Cache cache) {
    // Which action did they ask for?
    String name = req.getParameter("name");
    if (name == null) {
        try {
            JSONObject json = new JSONObject(new JSONTokener(req.getContent().getContent()));
            if (!json.has("name")) {
                throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not find required 'name' parameter");
            }
            name = json.getString("name");
        } catch (IOException iox) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not read content from request.", iox);
        } catch (JSONException je) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not parse JSON from request.", je);
        }
    }
    // Load the specified replication definition
    ReplicationDefinition replicationDefinition = replicationService.loadReplicationDefinition(name);
    return replicationDefinition;
}
Also used : JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) ReplicationDefinition(org.alfresco.service.cmr.replication.ReplicationDefinition) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 100 with WebScriptException

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

the class ArchivedNodePut method executeImpl.

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();
    // Current user
    String userID = AuthenticationUtil.getFullyAuthenticatedUser();
    if (userID == null) {
        throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script [" + req.getServiceMatch().getWebScript().getDescription() + "] requires user authentication.");
    }
    NodeRef nodeRefToBeRestored = parseRequestForNodeRef(req);
    if (nodeRefToBeRestored == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "nodeRef not recognised. Could not restore.");
    }
    // check if the current user has the permission to restore the node
    validatePermission(nodeRefToBeRestored, userID);
    RestoreNodeReport report = nodeArchiveService.restoreArchivedNode(nodeRefToBeRestored);
    // Handling of some error scenarios
    if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_INVALID_ARCHIVE_NODE)) {
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find archive node: " + nodeRefToBeRestored);
    } else if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_PERMISSION)) {
        throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Unable to restore archive node: " + nodeRefToBeRestored);
    } else if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_DUPLICATE_CHILD_NODE_NAME)) {
        throw new WebScriptException(HttpServletResponse.SC_CONFLICT, "Unable to restore archive node: " + nodeRefToBeRestored + ". Duplicate child node name");
    } else if (report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_INVALID_PARENT) || report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_INTEGRITY) || report.getStatus().equals(RestoreNodeReport.RestoreStatus.FAILURE_OTHER)) {
        throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to restore archive node: " + nodeRefToBeRestored);
    }
    model.put("restoreNodeReport", report);
    return model;
}
Also used : RestoreNodeReport(org.alfresco.repo.node.archive.RestoreNodeReport) NodeRef(org.alfresco.service.cmr.repository.NodeRef) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) HashMap(java.util.HashMap)

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