Example usage for javax.transaction UserTransaction commit

List of usage examples for javax.transaction UserTransaction commit

Introduction

In this page you can find the example usage for javax.transaction UserTransaction commit.

Prototype

void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException,
        IllegalStateException, SystemException;

Source Link

Document

Complete the transaction associated with the current thread.

Usage

From source file:com.sirma.itt.cmf.integration.workflow.alfresco4.CMFWorkflowDeployer.java

/**
 * Deploy the Workflow Definitions.//from  www .  j  ava2  s.  c  om
 */
public void init() {
    PropertyCheck.mandatory(this, "transactionService", transactionService);
    PropertyCheck.mandatory(this, "authenticationContext", authenticationContext);
    PropertyCheck.mandatory(this, "workflowService", workflowService);

    String currentUser = authenticationContext.getCurrentUserName();
    if (currentUser == null) {
        authenticationContext.setSystemUserAsCurrentUser();
    }
    if (!transactionService.getAllowWrite()) {
        logger.warn("Repository is in read-only mode; not deploying workflows.");
        return;
    }

    UserTransaction userTransaction = transactionService.getUserTransaction();
    try {
        userTransaction.begin();

        // bootstrap the workflow models and static labels (from classpath)
        if (models != null && resourceBundles != null
                && ((models.size() > 0) || (resourceBundles.size() > 0))) {
            DictionaryBootstrap dictionaryBootstrap = new DictionaryBootstrap();
            dictionaryBootstrap.setDictionaryDAO(dictionaryDAO);
            dictionaryBootstrap.setTenantService(tenantService);
            dictionaryBootstrap.setModels(models);
            dictionaryBootstrap.setLabels(resourceBundles);
            dictionaryBootstrap.bootstrap(); // also registers with
            // dictionary
        }

        // bootstrap the workflow definitions (from classpath)
        if (workflowDefinitions != null) {
            for (Properties workflowDefinition : workflowDefinitions) {
                deployFromProperties(workflowDefinition);
            }
        }

        userTransaction.commit();
    } catch (Exception e) {
        // rollback the transaction
        try {
            if (userTransaction != null) {
                userTransaction.rollback();
            }
        } catch (Exception ex) {
            // NOOP
        }
    } finally {
        if (currentUser == null) {
            authenticationContext.clearCurrentSecurityContext();
        }
    }
}

From source file:com.pararede.alfresco.security.AlfrescoContainerSecurityFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession httpSession = httpRequest.getSession();

    String userName = httpRequest.getUserPrincipal().getName();
    User userAuth = AuthenticationHelper.getUser(httpRequest, httpResponse);
    if ((userAuth == null) || !userName.equals(userAuth.getUserName())) {
        try {// w w  w.j  av a2  s .c om
            TransactionService transactionService = this.registry.getTransactionService();
            UserTransaction tx = transactionService.getUserTransaction();
            try {
                tx.begin();

                // remove the session invalidated flag (used to remove last username cookie by
                // AuthenticationFilter)
                httpSession.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED);

                if (logger.isDebugEnabled()) {
                    logger.debug("Authenticating user " + userName);
                }
                AuthenticationService authenticationService = getAuthenticationService();
                authenticationService.authenticate(userName, null);

                PersonService personService = this.registry.getPersonService();
                userAuth = new User(userName, authenticationService.getCurrentTicket(),
                        personService.getPerson(userName));

                NodeService nodeService = this.registry.getNodeService();
                NodeRef homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName),
                        ContentModel.PROP_HOMEFOLDER);
                if (!nodeService.exists(homeSpaceRef)) {
                    throw new InvalidNodeRefException(homeSpaceRef);
                }
                userAuth.setHomeSpaceId(homeSpaceRef.getId());

                httpSession.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, userAuth);
                httpSession.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, true);

                tx.commit();
            } catch (Throwable e) {
                tx.rollback();
                throw new ServletException(e);
            }
        } catch (SystemException e) {
            throw new ServletException(e);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("User " + userName + " already authenticated");
        }

        AuthenticationStatus status = AuthenticationHelper.authenticate(httpSession.getServletContext(),
                httpRequest, httpResponse, false);
        if (status != AuthenticationStatus.Success) {
            throw new ServletException("User not correctly autheticated");
        }
    }

    chain.doFilter(request, response);
}

From source file:com.surevine.alfresco.repo.delete.PerishabilityLogicImpl.java

private synchronized void loadPerishReasons()
        throws JSONException, SecurityException, IllegalStateException, RollbackException,
        HeuristicMixedException, HeuristicRollbackException, SystemException, NotSupportedException {
    UserTransaction transaction = null;
    ResultSet rs = null;/*w w  w .  java 2s. co  m*/

    try {
        StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
        rs = _searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
                "PATH:\"/app:company_home/app:dictionary/cm:perishableReasons.json\"");
        NodeRef nodeRef = null;
        transaction = _transactionService.getUserTransaction(true);

        transaction.begin();

        if (rs.length() == 0) {
            _logger.error(
                    "Unable to load perishable reasons: Didn't find perishableReasons.json in the Data Dictionary.");
            perishReasons = Collections.emptyList();
            perishReasonsByCode = Collections.emptyMap();
            perishReasonsBySite = Collections.emptyMap();
            return;
        }
        nodeRef = rs.getNodeRef(0);

        ContentReader reader = _contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);

        JSONObject obj = new JSONObject(reader.getContentString());

        JSONArray perishableReasons = obj.getJSONArray("perishableReasons");

        perishReasons = new ArrayList<PerishReason>(perishableReasons.length());
        perishReasonsByCode = new HashMap<String, PerishReason>();
        perishReasonsBySite = new HashMap<String, List<PerishReason>>();

        for (int i = 0; i < perishableReasons.length(); ++i) {
            PerishReason reason = PerishReason.fromJSON(perishableReasons.getJSONObject(i));
            perishReasons.add(reason);
            perishReasonsByCode.put(reason.getCode(), reason);
            addPerishReasonBySite(reason);
        }

        transaction.commit();
    } finally {
        if (rs != null) {
            rs.close();
        }

        if ((transaction != null) && (transaction.getStatus() == Status.STATUS_ACTIVE)) {
            transaction.rollback();
        }
    }
}

From source file:it.doqui.index.ecmengine.business.job.move.MoveAggregationJob.java

/**
 * Copies the child associations onto the destiantion node reference.
 * <p>//from  w w w .ja v  a 2 s . co m
 * If copyChildren is true then the nodes at the end of a primary assoc will be copied before they
 * are associated.
 *
 * @param sourceNodeRef         the source node reference
 * @param destinationNodeRef   the destination node reference
 * @param copyChildren         indicates whether to copy the primary children
 * @throws AuthenticationRuntimeException
 * @throws PermissionRuntimeException
 * @throws NodeRuntimeException
 */
private void copyChildAssociations(NodeRef sourceNodeRef, NodeRef destinationNodeRef, boolean copyChildren,
        Map<NodeRef, NodeRef> copiedChildren, String sourceRepo, String destRepo)
        throws NodeRuntimeException, PermissionRuntimeException, AuthenticationRuntimeException {

    try {
        logger.debug("[MoveAggregationJob::copyChildAssociations] BEGIN");

        UserTransaction userTxSource = transactionService.getNonPropagatingUserTransaction();

        UserTransaction userTxDest = transactionService.getNonPropagatingUserTransaction();

        userTxSource.begin();

        RepositoryManager.setCurrentRepository(sourceRepo);

        //authenticate as the system user
        authenticationComponent.setSystemUserAsCurrentUser();

        List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(sourceNodeRef);

        userTxSource.commit();

        if (childAssocs != null) {
            logger.debug(
                    "[MoveAggregationJob::copyChildAssociations] Nodi figli da ricreare in Repo Secondary: "
                            + childAssocs.size());
            for (ChildAssociationRef childAssoc : childAssocs) {
                if (copyChildren == true) {
                    if (childAssoc.isPrimary() == true) {
                        logger.debug("[MoveAggregationJob::copyChildAssociations]"
                                + " Nodo figlio primario da ricreare in Repo Secondary.");
                        // Do not recurse further, if we've already copied this node
                        if (copiedChildren.containsKey(childAssoc.getChildRef()) == false
                                && copiedChildren.containsValue(childAssoc.getChildRef()) == false) {
                            // Copy the child
                            recursiveCopy(childAssoc.getChildRef(), childAssoc.getParentRef(),
                                    destinationNodeRef, childAssoc.getTypeQName(), childAssoc.getQName(),
                                    copyChildren, copiedChildren, sourceRepo, destRepo);
                        }
                    } else {
                        logger.debug(
                                "[MoveAggregationJob::copyChildAssociations] Nodo figlio Non Primario da ricreare.");

                        //Add the child (I figli non primari non vengono ricreati nel deposito)Cosa fare??
                        //TODO: NB i figli secondari non vengono ricreati, ma solo viene creata la relazione
                        //tra padre e figlio( e il figlio si trova nel deposito)
                        NodeRef childRef = childAssoc.getChildRef();

                        userTxDest.begin();

                        RepositoryManager.setCurrentRepository(destRepo);

                        // authenticate as the system user
                        authenticationComponent.setSystemUserAsCurrentUser();

                        nodeService.addChild(destinationNodeRef, childRef, childAssoc.getTypeQName(),
                                childAssoc.getQName());

                        userTxDest.commit();
                    }
                }
            }
        }
    } catch (NotSupportedException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (SystemException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (SecurityException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (IllegalStateException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (RollbackException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        logger.error("[MoveAggregationJob::copyChildAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } finally {
        logger.debug("[MoveAggregationJob::copyChildAssociations] END");
    }
}

From source file:it.doqui.index.ecmengine.business.job.move.MoveAggregationJob.java

/**
 * Copies the target associations onto the destination node reference.
 *
 * @param sourceNodeRef   the destination node reference
 * @param destinationNodeRef   the destination node reference    *
 * @throws NodeRuntimeException/*  w  w w  .j  ava2s .c  o  m*/
 */
private void copyTargetAssociations(NodeRef sourceNodeRef, NodeRef destinationNodeRef, String sourceRepo,
        String destRepo) throws NodeRuntimeException {
    try {
        logger.debug("[MoveAggregationJob::copyTargetAssociations] BEGIN");

        UserTransaction userTxSource = transactionService.getNonPropagatingUserTransaction();

        UserTransaction userTxDest = transactionService.getNonPropagatingUserTransaction();

        userTxSource.begin();

        RepositoryManager.setCurrentRepository(sourceRepo);

        //authenticate as the system user
        authenticationComponent.setSystemUserAsCurrentUser();

        List<AssociationRef> nodeAssocRefs = nodeService.getTargetAssocs(sourceNodeRef,
                RegexQNamePattern.MATCH_ALL);

        userTxSource.commit();

        if (nodeAssocRefs != null) {

            userTxDest.begin();

            RepositoryManager.setCurrentRepository(destRepo);

            //authenticate as the system user
            authenticationComponent.setSystemUserAsCurrentUser();

            for (AssociationRef assocRef : nodeAssocRefs) {
                NodeRef targetRef = assocRef.getTargetRef();

                boolean exists = false;
                for (AssociationRef assocRef2 : nodeService.getTargetAssocs(destinationNodeRef,
                        assocRef.getTypeQName())) {
                    if (targetRef.equals(assocRef2.getTargetRef()) == true) {
                        exists = true;
                        break;
                    }
                }

                if (exists == false) {
                    // Add the association(aggiunge le associazioni di tipo reference verso il nodo che si trova
                    //nel corrente ma questo nodo non viene ricreato nel deposito; Cosa fare? )
                    //TODO:
                    // crea la relazione verso il nodo presente in corrente , ma non crea il nodo in deposito
                    nodeService.createAssociation(destinationNodeRef, targetRef, assocRef.getTypeQName());
                }
            }
            userTxDest.commit();
        }
    } catch (NotSupportedException e) {
        logger.error("[MoveAggregationJob::copyTargetAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (SystemException e) {
        logger.error("[MoveAggregationJob::copyTargetAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (SecurityException e) {
        logger.error("[MoveAggregationJob::copyTargetAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (IllegalStateException e) {
        logger.error("[MoveAggregationJob::copyTargetAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (RollbackException e) {
        logger.error("[MoveAggregationJob::copyTargetAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        logger.error("[MoveAggregationJob::copyTargetAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        logger.error("[MoveAggregationJob::copyTargetAssociations] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } finally {
        logger.debug("[MoveAggregationJob::copyTargetAssociations] END");
    }
}

From source file:it.doqui.index.ecmengine.business.job.move.MoveAggregationJob.java

/**
 * Copies the permissions of the source node reference onto the destination node reference
 *
 * @param sourceNodeRef         the source node reference
 * @param destinationNodeRef   the destination node reference
 * @throws AuthenticationRuntimeException
 * @throws PermissionRuntimeException//  ww w  .j  ava 2s  .  c  om
 */
private void copyPermissions(NodeRef sourceNodeRef, NodeRef destinationNodeRef, String sourceRepo,
        String destRepo) throws PermissionRuntimeException, AuthenticationRuntimeException {
    try {
        logger.debug("[MoveAggregationJob::copyPermissions] BEGIN");

        UserTransaction userTxSource = transactionService.getNonPropagatingUserTransaction();

        UserTransaction userTxDest = transactionService.getNonPropagatingUserTransaction();

        userTxSource.begin();

        RepositoryManager.setCurrentRepository(sourceRepo);

        //authenticate as the system user
        authenticationComponent.setSystemUserAsCurrentUser();

        AccessStatus accessStatus = permissionService.hasPermission(sourceNodeRef,
                PermissionService.READ_PERMISSIONS);

        userTxSource.commit();

        if (accessStatus == AccessStatus.ALLOWED) {
            userTxSource = transactionService.getNonPropagatingUserTransaction();

            userTxSource.begin();

            // Get the permission details of the source node reference
            Set<AccessPermission> permissions = permissionService.getAllSetPermissions(sourceNodeRef);
            boolean includeInherited = permissionService.getInheritParentPermissions(sourceNodeRef);

            userTxSource.commit();

            userTxDest.begin();

            RepositoryManager.setCurrentRepository(destRepo);

            // authenticate as the system user
            authenticationComponent.setSystemUserAsCurrentUser();

            AccessStatus writePermission = permissionService.hasPermission(destinationNodeRef,
                    PermissionService.CHANGE_PERMISSIONS);
            if (writePermission.equals(AccessStatus.ALLOWED)
                    || authenticationService.isCurrentUserTheSystemUser()) {
                // Set the permission values on the destination node
                for (AccessPermission permission : permissions) {
                    permissionService.setPermission(destinationNodeRef, permission.getAuthority(),
                            permission.getPermission(),
                            permission.getAccessStatus().equals(AccessStatus.ALLOWED));
                }
                permissionService.setInheritParentPermissions(destinationNodeRef, includeInherited);
            }

            userTxDest.commit();
        }

    } catch (NotSupportedException e) {
        logger.error("[MoveAggregationJob::copyPermissions] Eccezione: " + e.getMessage());
        e.printStackTrace();
    } catch (SystemException e) {
        logger.error("[MoveAggregationJob::copyPermissions] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (SecurityException e) {
        logger.error("[MoveAggregationJob::copyPermissions] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (IllegalStateException e) {
        logger.error("[MoveAggregationJob::copyPermissions] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (RollbackException e) {
        logger.error("[MoveAggregationJob::copyPermissions] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        logger.error("[MoveAggregationJob::copyPermissions] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        logger.error("[MoveAggregationJob::copyPermissions] Eccezione: " + e.getMessage());

        e.printStackTrace();
    } finally {
        logger.debug("[MoveAggregationJob::copyPermissions] END");
    }
}

From source file:it.doqui.index.ecmengine.business.job.move.MoveAggregationJob.java

private List<NodeRef> searchNodeWithProp()
        throws DictionaryRuntimeException, NotSupportedException, SystemException, SecurityException,
        IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {

    logger.debug("[MoveAggregationJob::searchNodeWithProp] BEGIN");
    //1) ricerca dei nodi spostati
    //a partire dalla company_home(radice) prendere ogni nodo figlio
    // e verificare se possiede un aspect con proprieta` di valore "spostabile"
    // oppure e` possibile fare una ricerca con lucene e prendere i nodi con quel particolare aspect
    // Utilizzare searchService per puntare direttamente ai nodi che hanno un certo aspect

    //RepositoryManager.setCurrentRepository("primary");
    logger.debug("[MoveAggregationJob::searchNodeWithProp] Ricerca nel repository : "
            + RepositoryManager.getCurrentRepository());

    StoreRef spacesStore = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");

    //proprieta ecm-sys:stato (dell'aspect ecm-sys:state)
    SearchParameters searchParams = new SearchParameters();
    searchParams.addStore(spacesStore);/*from   w ww.  j a  v a 2  s . c  o m*/
    searchParams.setLimitBy(LimitBy.UNLIMITED);
    searchParams.setLimit(0);
    searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
    //ricerca per aspect e poi filtrare sulla property relativa
    //searchParams.setQuery("ASPECT:\"{http://www.doqui.it/model/ecmengine/system/1.0}state\"");

    //ricerca direttamente per property
    //@ecm-sys\\:stato:\"spostabile\"
    //searchParams.setQuery("@ecm-sys\\:stato:\"spostabile\"");
    //searchParams.setQuery("@{http://www.doqui.it/model/ecmengine/system/1.0}\\:stato:\"spostabile\"");

    searchParams.setQuery("@ecm-sys\\:stato:\"spostabile\"");

    ResultSet resultSet = null;
    List<NodeRef> listaNodi = null;
    //List<NodeRef> nodiConProp = null;

    UserTransaction userTxSource = transactionService.getNonPropagatingUserTransaction();

    try {
        userTxSource.begin();

        logger.debug("[MoveAggregationJob::searchNodeWithProp] searchService is "
                + (searchService != null ? " <> null" : " null"));
        logger.debug("[MoveAggregationJob::searchNodeWithProp] Query : " + searchParams.getQuery());
        resultSet = searchService.query(searchParams);
        logger.debug("[MoveAggregationJob::searchNodeWithProp] Risultati trovati: " + resultSet.length());

        if (resultSet.length() > 0) {
            listaNodi = resultSet.getNodeRefs();
        }

        userTxSource.commit();

        /*
        QName stateProp = resolvePrefixNameToQName("ecm-sys:stato");
        String valoreStatoNodo = "spostabile";
                
        if (resultSet.length() > 0){
           listaNodi = resultSet.getNodeRefs();
           if(listaNodi!=null){
              Map<QName,Serializable> propMap = null;
              nodiConProp = new ArrayList<NodeRef>();
              for (NodeRef ref : listaNodi) {
          propMap = nodeService.getProperties(ref);
          if(propMap.containsKey(stateProp) && propMap.containsValue(valoreStatoNodo))
          {
             nodiConProp.add(ref);
          }
              }
           }
        }
                
        searchParams.setLanguage(SearchService.LANGUAGE_XPATH);
        searchParams.setQuery("/app:company_home/cm:TestSposta");
        searchParams.setLimitBy(LimitBy.FINAL_SIZE);
        searchParams.setLimit(1);
                
        resultSet = searchService.query(searchParams);
        logger.debug("[MoveAggregationJob::searchNodeWithProp] Query per XPATH : "+searchParams.getQuery());
        if(resultSet.length()>0){
           logger.debug("[MoveAggregationJob::searchNodeWithProp] resultSet per XPATH diverso da Null");
           logger.debug("[MoveAggregationJob::searchNodeWithProp] Numero Risultati trovati : "
          +resultSet.length());
           if (resultSet.getNodeRefs()!=null && resultSet.getNodeRefs().size()>0){
              NodeRef nodo = resultSet.getNodeRef(0);
              Map<QName,Serializable> prop = nodeService.getProperties(nodo);
              String valore =(String) prop.get(stateProp);
              logger.debug("[MoveAggregationJob::searchNodeWithProp] valore property 'ecm-sys:stato' e` : "
             +valore);
           }
        }
        */
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
        logger.debug("[MoveAggregationJob::searchNodeWithProp] END");
    }
    return listaNodi;
}

From source file:it.doqui.index.ecmengine.business.job.move.MoveAggregationJob.java

/**
 * Recursive copy algorithm/*w ww .  jav a2s .  c  om*/
 *
 * @throws NodeRuntimeException
 * @throws AuthenticationRuntimeException
 * @throws PermissionRuntimeException
 */
private NodeRef recursiveCopy(NodeRef sourceNodeRef, NodeRef sourceParentRef, NodeRef destinationParentRef,
        QName destinationAssocTypeQName, QName destinationQName, boolean copyChildren,
        Map<NodeRef, NodeRef> copiedChildren, String sourceRepo, String destRepo)
        throws NodeRuntimeException, PermissionRuntimeException, AuthenticationRuntimeException {

    NodeRef destinationNodeRef = null;

    UserTransaction userTxSource = null;

    UserTransaction userTxDest = null;

    try {

        logger.debug("[MoveAggregationJob::recursiveCopy] BEGIN");

        userTxSource = transactionService.getNonPropagatingUserTransaction();

        userTxSource.begin();

        Map<QName, Serializable> properties = null;
        Set<QName> sourceAspects = null;

        RepositoryManager.setCurrentRepository(sourceRepo);

        //authenticate as the system user
        authenticationComponent.setSystemUserAsCurrentUser();

        QName sourceType = nodeService.getType(sourceNodeRef);
        properties = nodeService.getProperties(sourceNodeRef);
        sourceAspects = nodeService.getAspects(sourceNodeRef);

        userTxSource.commit();

        // Create the new node
        userTxDest = transactionService.getNonPropagatingUserTransaction();

        userTxDest.begin();

        RepositoryManager.setCurrentRepository(destRepo);

        //authenticate as the system user
        authenticationComponent.setSystemUserAsCurrentUser();

        boolean esisteStore = nodeService.exists(destinationParentRef.getStoreRef());

        logger.debug("[MoveAggregationJob::recursiveCopy] Lo Store Destination esiste ? : " + esisteStore);

        final boolean destExists = nodeService.exists(destinationParentRef);

        logger.debug("[MoveAggregationJob::recursiveCopy] " + "Repository di Destinazione : "
                + RepositoryManager.getCurrentRepository());
        logger.debug(
                "[MoveAggregationJob::recursiveCopy] '" + destinationParentRef + "' esiste: " + destExists);

        ChildAssociationRef destinationChildAssocRef = nodeService.createNode(destinationParentRef,
                destinationAssocTypeQName, destinationQName, sourceType, null);

        destinationNodeRef = destinationChildAssocRef.getChildRef();

        logger.debug("[MoveAggregationJob::recursiveCopy] Nodo spostato: " + destinationNodeRef.getId());

        copiedChildren.put(sourceNodeRef, destinationNodeRef);

        for (QName aspect : sourceAspects) {
            nodeService.addAspect(destinationNodeRef, aspect, null);
            logger.debug("[MoveAggregationJob::recursiveCopy] Aspect copiato: " + aspect);
        }

        //setto sul nuovo nodo appena creato tutte le properties, anche quelle degli aspects
        nodeService.setProperties(destinationNodeRef, properties);
        logger.debug("[MoveAggregationJob::recursiveCopy] Property copiate: " + properties.size());

        // Prevent any rules being fired on the new destination node
        //ruleService.disableRules(destinationNodeRef);

        //   Apply the copy aspect to the new node
        //Map<QName, Serializable> copyProperties = new HashMap<QName, Serializable>();
        //copyProperties.put(ContentModel.PROP_COPY_REFERENCE, sourceNodeRef);
        //nodeService.addAspect(destinationNodeRef, ContentModel.ASPECT_COPIEDFROM, copyProperties);

        // Copy the aspects
        //copyAspects(destinationNodeRef, copyDetails);

        userTxDest.commit();

        // Copy the associations
        copyAssociations(sourceNodeRef, destinationNodeRef, copyChildren, copiedChildren, sourceRepo, destRepo);

        // Copy permissions
        copyPermissions(sourceNodeRef, destinationNodeRef, sourceRepo, destRepo);

    } catch (NotSupportedException e) {
        logger.error("[MoveAggregationJob::recursiveCopy] Eccezione: " + e.getMessage());
    } catch (SystemException e) {
        logger.error("[MoveAggregationJob::recursiveCopy] Eccezione: " + e.getMessage());
        e.printStackTrace();
    } catch (SecurityException e) {
        logger.error("[MoveAggregationJob::recursiveCopy] Eccezione: " + e.getMessage());
        e.printStackTrace();
    } catch (IllegalStateException e) {
        logger.error("[MoveAggregationJob::recursiveCopy] Eccezione: " + e.getMessage());
        e.printStackTrace();
    } catch (RollbackException e) {
        logger.error("[MoveAggregationJob::recursiveCopy] Eccezione: " + e.getMessage());
        e.printStackTrace();
    } catch (HeuristicMixedException e) {
        logger.error("[MoveAggregationJob::recursiveCopy] Eccezione: " + e.getMessage());
        e.printStackTrace();
    } catch (HeuristicRollbackException e) {
        logger.error("[MoveAggregationJob::recursiveCopy] Eccezione: " + e.getMessage());
        e.printStackTrace();
    } finally {
        //ruleService.enableRules(destinationNodeRef);
        logger.debug("[MoveAggregationJob::recursiveCopy] END");
    }
    return destinationNodeRef;
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.MultiTAdminServiceImpl.java

@Override
protected void onBootstrap(ApplicationEvent event) {
    logger.debug("[MultiTAdminServiceImpl::onBootstrap] BEGIN");

    ns = (SplittingDbNodeServiceImpl) getApplicationContext().getBean("splittingDbNodeServiceImpl");

    for (Repository repository : repositoryManager.getRepositories()) {
        RepositoryManager.setCurrentRepository(repository.getId());
        logger.info("[MultiTAdminServiceImpl::onBootstrap] Repository '"
                + RepositoryManager.getCurrentRepository() + "' -- Executing multi-tenant admin bootstrap.");

        // initialise the tenant admin service and status of tenants (using attribute service)
        // note: this requires that the repository schema has already been initialised

        // register dictionary - to allow enable/disable tenant callbacks
        register(dictionaryComponent);//w  w  w . ja  v a 2  s  .co  m

        // register file store - to allow enable/disable tenant callbacks
        register(tenantFileContentStore);

        UserTransaction userTransaction = transactionService.getUserTransaction();
        authenticationComponent.setSystemUserAsCurrentUser();

        try {
            userTransaction.begin();

            // bootstrap Tenant Service internal cache
            List<org.alfresco.repo.tenant.Tenant> tenants = getAllTenants();

            int enabledCount = 0;
            int disabledCount = 0;

            if (tenants != null) {
                for (org.alfresco.repo.tenant.Tenant tenant : tenants) {
                    if (tenant.isEnabled()) {
                        // this will also call tenant deployers registered so far ...
                        enableTenant(tenant.getTenantDomain(), true);
                        enabledCount++;
                    } else {
                        // explicitly disable, without calling disableTenant callback
                        disableTenant(tenant.getTenantDomain(), false);
                        disabledCount++;
                    }
                }

                tenantService.register(this); // callback to refresh tenantStatus cache
            }

            userTransaction.commit();

            if (logger.isInfoEnabled()) {
                logger.info(
                        String.format("Alfresco Multi-Tenant startup - %d enabled tenants, %d disabled tenants",
                                enabledCount, disabledCount));
            }
        } catch (Throwable e) {
            // rollback the transaction
            try {
                if (userTransaction != null) {
                    userTransaction.rollback();
                }
            } catch (Exception ex) {
            }
            try {
                authenticationComponent.clearCurrentSecurityContext();
            } catch (Exception ex) {
            }
            throw new AlfrescoRuntimeException("Failed to bootstrap tenants", e);
        }
    }
    logger.debug("[MultiTAdminServiceImpl::onBootstrap] END");
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.MultiTAdminServiceImpl.java

/**
 * @see TenantAdminService.deleteTenant()
 *///  w ww.j av a 2 s. c  om
public void deleteTenant(String tenantDomain) {
    if (!existsTenant(tenantDomain)) {
        throw new RuntimeException("Tenant does not exist: " + tenantDomain);
    } else {
        try {
            final String tenantAdminUser = getTenantAdminUser(tenantDomain);
            //final String tenantAdminUser = tenantService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain);

            AuthenticationUtil.runAs(new RunAsWork<Object>() {
                public Object doWork() {
                    List<WorkflowDefinition> workflowDefs = workflowService.getDefinitions();
                    if (workflowDefs != null) {
                        for (WorkflowDefinition workflowDef : workflowDefs) {
                            workflowService.undeployDefinition(workflowDef.getId());
                        }
                    }

                    List<String> messageResourceBundles = repoAdminService.getMessageBundles();
                    if (messageResourceBundles != null) {
                        for (String messageResourceBundle : messageResourceBundles) {
                            repoAdminService.undeployMessageBundle(messageResourceBundle);
                        }
                    }

                    List<RepoModelDefinition> models = repoAdminService.getModels();
                    if (models != null) {
                        for (RepoModelDefinition model : models) {
                            repoAdminService.undeployModel(model.getRepoName());
                        }
                    }

                    return null;
                }
            }, tenantAdminUser);

            //-------------------------------------
            UserTransaction userTransaction = transactionService.getUserTransaction();
            authenticationComponent.setSystemUserAsCurrentUser();
            try {
                // TODO: occorre usare lo SplittingDbNodeServiceImpl
                // che ha dentro un deleteStore che aggiorna gli indici
                // ora e' usata l'imlementation di ALF che ha il metodo ma non aggiorna gli indici di lucene
                userTransaction.begin();

                ns.deleteStore(tenantService.getName(tenantAdminUser,
                        new StoreRef(PROTOCOL_STORE_WORKSPACE, STORE_BASE_ID_SPACES)));
                ns.deleteStore(tenantService.getName(tenantAdminUser,
                        new StoreRef(PROTOCOL_STORE_ARCHIVE, STORE_BASE_ID_SPACES)));
                ns.deleteStore(tenantService.getName(tenantAdminUser,
                        new StoreRef(PROTOCOL_STORE_WORKSPACE, STORE_BASE_ID_VERSION)));
                ns.deleteStore(tenantService.getName(tenantAdminUser,
                        new StoreRef(PROTOCOL_STORE_SYSTEM, STORE_BASE_ID_SYSTEM)));
                ns.deleteStore(tenantService.getName(tenantAdminUser,
                        new StoreRef(PROTOCOL_STORE_USER, STORE_BASE_ID_USER)));

                userTransaction.commit();

            } catch (Throwable e) {
                // rollback the transaction
                try {
                    if (userTransaction != null) {
                        userTransaction.rollback();
                    }
                } catch (Exception ex) {
                }
                try {
                    authenticationComponent.clearCurrentSecurityContext();
                } catch (Exception ex) {
                }
                throw new AlfrescoRuntimeException("Failed to delete tenant", e);
            }

            // notify listeners that tenant has been deleted & hence disabled
            AuthenticationUtil.runAs(new RunAsWork<Object>() {
                public Object doWork() {
                    List<TenantDeployer> tenantDeployers = getTenantDeployers();
                    for (TenantDeployer tenantDeployer : tenantDeployers) {
                        tenantDeployer.onDisableTenant();
                    }
                    return null;
                }
            }, tenantAdminUser);

            // remove tenant
            attributeService.removeAttribute(TENANTS_ATTRIBUTE_PATH, tenantDomain);
        } catch (Throwable t) {
            throw new AlfrescoRuntimeException("Failed to delete tenant: " + tenantDomain, t);
        }
    }
}