Search in sources :

Example 21 with RetryingTransactionHelper

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

the class AddUsersDialog method pickerCallback.

// ------------------------------------------------------------------------------
// Helpers
/**
 * Query callback method executed by the Generic Picker component. This
 * method is part of the contract to the Generic Picker, it is up to the
 * backing bean to execute whatever query is appropriate and return the
 * results.
 *
 * @param filterIndex Index of the filter drop-down selection
 * @param contains Text from the contains textbox
 * @return An array of SelectItem objects containing the results to display
 *         in the picker.
 */
public SelectItem[] pickerCallback(int filterIndex, final String contains) {
    final FacesContext context = FacesContext.getCurrentInstance();
    UserTransaction tx = null;
    try {
        // getUserTransaction(context);
        RetryingTransactionHelper txHelper = Repository.getRetryingTransactionHelper(context);
        return txHelper.doInTransaction(new RetryingTransactionCallback<SelectItem[]>() {

            public SelectItem[] execute() throws Exception {
                SelectItem[] items = new SelectItem[0];
                // Use the Person Service to retrieve user details
                String term = contains.trim();
                if (term.length() != 0) {
                    List<PersonInfo> persons = getPersonService().getPeople(Utils.generatePersonFilter(contains.trim()), true, Utils.generatePersonSort(), new PagingRequest(Utils.getPersonMaxResults(), null)).getPage();
                    ArrayList<SelectItem> itemList = new ArrayList<SelectItem>(persons.size());
                    for (PersonInfo person : persons) {
                        String username = person.getUserName();
                        if (AuthenticationUtil.getGuestUserName().equals(username) == false) {
                            String firstName = person.getFirstName();
                            String lastName = person.getLastName();
                            // build a sensible label for display
                            String name = (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : "");
                            SelectItem item = new SortableSelectItem(username, name + " [" + username + "]", lastName != null ? lastName : username);
                            itemList.add(item);
                        }
                    }
                    items = new SelectItem[itemList.size()];
                    itemList.toArray(items);
                }
                return items;
            }
        });
    } catch (BooleanQuery.TooManyClauses clauses) {
        Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), "too_many_users"));
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
        return new SelectItem[0];
    } catch (Exception err) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
        return new SelectItem[0];
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) FacesContext(javax.faces.context.FacesContext) BooleanQuery(org.apache.lucene.search.BooleanQuery) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) ArrayList(java.util.ArrayList) SortableSelectItem(org.alfresco.web.ui.common.SortableSelectItem) PagingRequest(org.alfresco.query.PagingRequest) SortableSelectItem(org.alfresco.web.ui.common.SortableSelectItem) SelectItem(javax.faces.model.SelectItem) ArrayList(java.util.ArrayList) List(java.util.List)

Example 22 with RetryingTransactionHelper

use of org.alfresco.repo.transaction.RetryingTransactionHelper 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 23 with RetryingTransactionHelper

use of org.alfresco.repo.transaction.RetryingTransactionHelper 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 24 with RetryingTransactionHelper

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

the class PersonServiceTest method addUserUsageContent.

private void addUserUsageContent(final String userName, final int stringDataLength) {
    RetryingTransactionHelper.RetryingTransactionCallback<Void> usageCallback = new RetryingTransactionHelper.RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            try {
                AuthenticationUtil.pushAuthentication();
                AuthenticationUtil.setFullyAuthenticatedUser(userName);
                String textData = "This is default text added. Add more: ";
                for (int i = 0; i < stringDataLength; i++) {
                    textData += "abc";
                }
                NodeRef homeFolder = getHomeSpaceFolderNode(userName);
                NodeRef folder = nodeService.createNode(homeFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "testFolder"), ContentModel.TYPE_FOLDER).getChildRef();
                addTextContent(folder, "text1.txt", textData);
            } finally {
                AuthenticationUtil.popAuthentication();
            }
            return null;
        }
    };
    RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
    txnHelper.doInTransaction(usageCallback);
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper)

Example 25 with RetryingTransactionHelper

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

the class AbstractContextTest method setUp.

@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    Map<String, Object> entityResourceBeans = applicationContext.getBeansWithAnnotation(EntityResource.class);
    Map<String, Object> relationResourceBeans = applicationContext.getBeansWithAnnotation(RelationshipResource.class);
    locator.setDictionary(ResourceDictionaryBuilder.build(entityResourceBeans.values(), relationResourceBeans.values()));
    AbstractResourceWebScript executor = (AbstractResourceWebScript) applicationContext.getBean("executorOfGets");
    AbstractResourceWebScript postExecutor = (AbstractResourceWebScript) applicationContext.getBean("executorOfPost");
    AbstractResourceWebScript putExecutor = (AbstractResourceWebScript) applicationContext.getBean("executorOfPut");
    AbstractResourceWebScript deleteExecutor = (AbstractResourceWebScript) applicationContext.getBean("executorOfDelete");
    // Mock transaction service
    TransactionService transerv = mock(TransactionService.class);
    RetryingTransactionHelper tHelper = mock(RetryingTransactionHelper.class);
    when(transerv.getRetryingTransactionHelper()).thenReturn(tHelper);
    when(tHelper.doInTransaction(any(RetryingTransactionHelper.RetryingTransactionCallback.class), anyBoolean(), anyBoolean())).thenAnswer(new Answer<Object>() {

        @SuppressWarnings("rawtypes")
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            RetryingTransactionHelper.RetryingTransactionCallback cb = (RetryingTransactionHelper.RetryingTransactionCallback) args[0];
            return cb.execute();
        }
    });
    executor.setTransactionService(transerv);
    postExecutor.setTransactionService(transerv);
    putExecutor.setTransactionService(transerv);
    deleteExecutor.setTransactionService(transerv);
}
Also used : TransactionService(org.alfresco.service.transaction.TransactionService) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) AbstractResourceWebScript(org.alfresco.rest.framework.webscripts.AbstractResourceWebScript) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Before(org.junit.Before)

Aggregations

RetryingTransactionHelper (org.alfresco.repo.transaction.RetryingTransactionHelper)25 RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)20 FacesContext (javax.faces.context.FacesContext)8 NodeRef (org.alfresco.service.cmr.repository.NodeRef)8 Serializable (java.io.Serializable)7 HashMap (java.util.HashMap)5 QName (org.alfresco.service.namespace.QName)5 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)4 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)3 NodeService (org.alfresco.service.cmr.repository.NodeService)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 FacesMessage (javax.faces.application.FacesMessage)2 UserTransaction (javax.transaction.UserTransaction)2 ServiceRegistry (org.alfresco.service.ServiceRegistry)2 ContentData (org.alfresco.service.cmr.repository.ContentData)2 ContentWriter (org.alfresco.service.cmr.repository.ContentWriter)2 TransactionService (org.alfresco.service.transaction.TransactionService)2 Node (org.alfresco.web.bean.repository.Node)2