Search in sources :

Example 61 with UserTransaction

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;
}
Also used : UserTransaction(javax.transaction.UserTransaction) FacesContext(javax.faces.context.FacesContext) User(org.alfresco.web.bean.repository.User) Node(org.alfresco.web.bean.repository.Node) TransientNode(org.alfresco.web.bean.repository.TransientNode) TransientMapNode(org.alfresco.web.bean.repository.TransientMapNode) WorkflowTask(org.alfresco.service.cmr.workflow.WorkflowTask)

Example 62 with UserTransaction

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);
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) ExtCommandProcessor(org.alfresco.web.app.servlet.command.ExtCommandProcessor) MalformedURLException(java.net.MalformedURLException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) StringTokenizer(java.util.StringTokenizer) ExtCommandProcessor(org.alfresco.web.app.servlet.command.ExtCommandProcessor) CommandProcessor(org.alfresco.web.app.servlet.command.CommandProcessor) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ServiceRegistry(org.alfresco.service.ServiceRegistry) PrintWriter(java.io.PrintWriter)

Example 63 with UserTransaction

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);
        }
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) QName(org.alfresco.service.namespace.QName) NodeService(org.alfresco.service.cmr.repository.NodeService) Node(org.alfresco.web.bean.repository.Node) ArrayList(java.util.ArrayList) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) UINodeDescendants(org.alfresco.web.ui.repo.component.UINodeDescendants) IOException(java.io.IOException) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) NodeRef(org.alfresco.service.cmr.repository.NodeRef) DictionaryService(org.alfresco.service.cmr.dictionary.DictionaryService) QuickSort(org.alfresco.web.data.QuickSort) Writer(java.io.Writer)

Example 64 with UserTransaction

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();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) User(org.jpwh.model.associations.onetoone.foreignkey.User) Address(org.jpwh.model.associations.onetoone.foreignkey.Address) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 65 with UserTransaction

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();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) User(org.jpwh.model.associations.onetoone.sharedprimarykey.User) Address(org.jpwh.model.associations.onetoone.sharedprimarykey.Address) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Aggregations

UserTransaction (javax.transaction.UserTransaction)642 EntityManager (javax.persistence.EntityManager)244 Test (org.testng.annotations.Test)187 Test (org.junit.Test)157 JPATest (org.jpwh.env.JPATest)138 InitialContext (javax.naming.InitialContext)62 BigDecimal (java.math.BigDecimal)53 HashMap (java.util.HashMap)52 IOException (java.io.IOException)50 Context (javax.naming.Context)49 List (java.util.List)47 FacesContext (javax.faces.context.FacesContext)43 NamingException (javax.naming.NamingException)43 NodeRef (org.alfresco.service.cmr.repository.NodeRef)43 Node (javax.jcr.Node)42 KieSession (org.kie.api.runtime.KieSession)42 Query (javax.persistence.Query)38 QueryingTest (org.jpwh.test.querying.QueryingTest)36 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)35 Item (org.jpwh.model.querying.Item)35