use of javax.transaction.UserTransaction in project acs-community-packaging by Alfresco.
the class WorkflowBean method getTasksToDo.
/**
* Returns a list of nodes representing the to do tasks the
* current user has.
*
* @return List of to do tasks
*/
public List<Node> getTasksToDo() {
if (this.tasks == null) {
// get the current username
FacesContext context = FacesContext.getCurrentInstance();
User user = Application.getCurrentUser(context);
String userName = user.getUserName();
UserTransaction tx = null;
try {
tx = Repository.getUserTransaction(context, true);
tx.begin();
// get the current in progress tasks for the current user
List<WorkflowTask> tasks = this.getWorkflowService().getAssignedTasks(userName, WorkflowTaskState.IN_PROGRESS, true);
// create a list of transient nodes to represent
this.tasks = new ArrayList<Node>(tasks.size());
for (WorkflowTask task : tasks) {
Node node = createTask(task);
this.tasks.add(node);
if (logger.isDebugEnabled())
logger.debug("Added to do task: " + node);
}
// commit the changes
tx.commit();
} catch (Throwable e) {
// rollback the transaction
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception ex) {
}
Utils.addErrorMessage("Failed to get to do tasks: " + e.toString(), e);
}
}
return this.tasks;
}
use of javax.transaction.UserTransaction in project acs-community-packaging by Alfresco.
the class CommandServlet method service.
/**
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String uri = req.getRequestURI();
if (logger.isDebugEnabled())
logger.debug("Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));
AuthenticationStatus status = servletAuthenticate(req, res);
if (status == AuthenticationStatus.Failure) {
return;
}
setNoCacheHeaders(res);
uri = uri.substring(req.getContextPath().length());
StringTokenizer t = new StringTokenizer(uri, "/");
int tokenCount = t.countTokens();
if (tokenCount < 3) {
throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
}
// skip servlet name
t.nextToken();
// get the command processor to execute the command e.g. "workflow"
String procName = t.nextToken();
// get the command to perform
String command = t.nextToken();
// get any remaining uri elements to pass to the processor
String[] urlElements = new String[tokenCount - 3];
for (int i = 0; i < tokenCount - 3; i++) {
urlElements[i] = t.nextToken();
}
// retrieve the URL arguments to pass to the processor
Map<String, String> args = new HashMap<String, String>(8, 1.0f);
Enumeration names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
args.put(name, req.getParameter(name));
}
try {
// get configured command processor by name from Config Service
CommandProcessor processor = createCommandProcessor(procName);
// validate that the processor has everything it needs to run the command
if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
redirectToLoginPage(req, res, getServletContext());
return;
}
ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
UserTransaction txn = null;
try {
txn = serviceRegistry.getTransactionService().getUserTransaction();
txn.begin();
// inform the processor to execute the specified command
if (processor instanceof ExtCommandProcessor) {
((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
} else {
processor.process(serviceRegistry, req, command);
}
// commit the transaction
txn.commit();
} catch (Throwable txnErr) {
try {
if (txn != null) {
txn.rollback();
}
} catch (Exception tex) {
}
throw txnErr;
}
String returnPage = req.getParameter(ARG_RETURNPAGE);
if (returnPage != null && returnPage.length() != 0) {
validateReturnPage(returnPage, req);
if (logger.isDebugEnabled())
logger.debug("Redirecting to specified return page: " + returnPage);
res.sendRedirect(returnPage);
} else {
if (logger.isDebugEnabled())
logger.debug("No return page specified, displaying status output.");
if (res.getContentType() == null && !res.isCommitted()) {
res.setContentType("text/html");
// request that the processor output a useful status message
PrintWriter out = res.getWriter();
processor.outputStatus(out);
out.close();
}
}
} catch (Throwable err) {
throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
}
}
use of javax.transaction.UserTransaction in project acs-community-packaging by Alfresco.
the class NodeDescendantsLinkRenderer method encodeEnd.
/**
* @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
*/
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
// always check for this flag - as per the spec
if (component.isRendered() == true) {
Writer out = context.getResponseWriter();
UINodeDescendants control = (UINodeDescendants) component;
// make sure we have a NodeRef from the 'value' property ValueBinding
Object val = control.getValue();
if (val instanceof NodeRef == false) {
throw new IllegalArgumentException("UINodeDescendants component 'value' property must resolve to a NodeRef!");
}
NodeRef parentRef = (NodeRef) val;
// use Spring JSF integration to get the node service bean
NodeService service = getNodeService(context);
DictionaryService dd = getDictionaryService(context);
UserTransaction tx = null;
try {
tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
tx.begin();
// TODO: need a comparator to sort node refs (based on childref qname)
// as currently the list is returned in a random order per request!
String separator = (String) component.getAttributes().get("separator");
if (separator == null) {
separator = DEFAULT_SEPARATOR;
}
// calculate the number of displayed child refs
if (service.exists(parentRef) == true) {
List<ChildAssociationRef> childRefs = service.getChildAssocs(parentRef, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
List<Node> nodes = new ArrayList<Node>(childRefs.size());
for (int index = 0; index < childRefs.size(); index++) {
ChildAssociationRef ref = childRefs.get(index);
QName type = service.getType(ref.getChildRef());
TypeDefinition typeDef = dd.getType(type);
if (typeDef != null && dd.isSubClass(type, ContentModel.TYPE_FOLDER) && dd.isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
nodes.add(new Node(ref.getChildRef()));
}
}
QuickSort sorter = new QuickSort(nodes, "name", true, IDataContainer.SORT_CASEINSENSITIVE);
sorter.sort();
// walk each child ref and output a descendant link control for each item
int total = 0;
int maximum = nodes.size() > control.getMaxChildren() ? control.getMaxChildren() : nodes.size();
for (int index = 0; index < maximum; index++) {
Node node = nodes.get(index);
QName type = service.getType(node.getNodeRef());
TypeDefinition typeDef = dd.getType(type);
if (typeDef != null && dd.isSubClass(type, ContentModel.TYPE_FOLDER) && dd.isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
// output separator if appropriate
if (total > 0) {
out.write(separator);
}
out.write(renderDescendant(context, control, node.getNodeRef(), false));
total++;
}
}
// do we need to render ellipses to indicate more items than the maximum
if (control.getShowEllipses() == true && nodes.size() > maximum) {
out.write(separator);
// TODO: is this the correct way to get the information we need?
// e.g. primary parent may not be the correct path? how do we make sure we find
// the correct parent and more importantly the correct Display Name value!
out.write(renderDescendant(context, control, service.getPrimaryParent(parentRef).getChildRef(), true));
}
}
tx.commit();
} catch (Throwable err) {
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
throw new RuntimeException(err);
}
}
}
use of javax.transaction.UserTransaction in project microservices by pwillhan.
the class OneToOneForeignKey method storeNonUniqueRelationship.
@Test(expectedExceptions = org.hibernate.exception.ConstraintViolationException.class)
public void storeNonUniqueRelationship() throws Throwable {
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
Address someAddress = new Address("Some Street 123", "12345", "Some City");
User userOne = new User("johndoe");
userOne.setShippingAddress(someAddress);
// OK
em.persist(userOne);
User userTwo = new User("janeroe");
userTwo.setShippingAddress(someAddress);
// Fails, true unique @OneToOne!
em.persist(userTwo);
try {
// Hibernate tries the INSERT but fails
em.flush();
} catch (Exception ex) {
throw unwrapCauseOfType(ex, org.hibernate.exception.ConstraintViolationException.class);
}
} finally {
TM.rollback();
}
}
use of javax.transaction.UserTransaction in project microservices by pwillhan.
the class OneToOneSharedPrimaryKey method storeAndLoadUserAddress.
@Test
public void storeAndLoadUserAddress() throws Exception {
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
Address someAddress = new Address("Some Street 123", "12345", "Some City");
// Generate identifier value
em.persist(someAddress);
User someUser = new User(// Assign same identifier value
someAddress.getId(), "johndoe");
em.persist(someUser);
// Optional...
someUser.setShippingAddress(someAddress);
tx.commit();
em.close();
Long USER_ID = someUser.getId();
Long ADDRESS_ID = someAddress.getId();
tx.begin();
em = JPA.createEntityManager();
User user = em.find(User.class, USER_ID);
assertEquals(user.getShippingAddress().getZipcode(), "12345");
Address address = em.find(Address.class, ADDRESS_ID);
assertEquals(address.getZipcode(), "12345");
assertEquals(user.getId(), address.getId());
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
Aggregations