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];
}
}
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;
}
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;
}
}
}
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);
}
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);
}
Aggregations