Example usage for javax.transaction UserTransaction begin

List of usage examples for javax.transaction UserTransaction begin

Introduction

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

Prototype

void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

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;/*ww  w . ja va  2s  .c  o 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:org.intalio.tempo.web.AlfrescoFacesPortlet.java

private void setAuthenticatedUser(PortletRequest req, String userName) {

    WebApplicationContext ctx = (WebApplicationContext) getPortletContext()
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    TransactionService transactionService = serviceRegistry.getTransactionService();
    NodeService nodeService = serviceRegistry.getNodeService();

    AuthenticationComponent authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    AuthenticationService authService = (AuthenticationService) ctx.getBean("authenticationService");
    PersonService personService = (PersonService) ctx.getBean("personService");

    // Get a list of the available locales
    ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
    LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages")
            .getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);

    m_languages = configElement.getLanguages();

    // Set up the user information
    UserTransaction tx = transactionService.getUserTransaction();
    NodeRef homeSpaceRef = null;/*from   w w w. java  2s.c o m*/
    User user;
    try {
        tx.begin();
        // Set the authentication
        authComponent.setCurrentUser(userName);
        user = new User(userName, authService.getCurrentTicket(), personService.getPerson(userName));
        homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName),
                ContentModel.PROP_HOMEFOLDER);
        if (homeSpaceRef == null) {
            logger.warn("Home Folder is null for user '" + userName + "', using company_home.");
            homeSpaceRef = (NodeRef) nodeService.getRootNode(Repository.getStoreRef());
        }
        user.setHomeSpaceId(homeSpaceRef.getId());
        tx.commit();
    } catch (Throwable ex) {
        logger.error(ex);

        try {
            tx.rollback();
        } catch (Exception ex2) {
            logger.error("Failed to rollback transaction", ex2);
        }

        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException("Failed to set authenticated user", ex);
        }
    }

    // Store the user
    req.getPortletSession().setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
    req.getPortletSession().setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE);

    logger.debug("...authenticated user is: " + user.getUserName() + user.getTicket());
}

From source file:edu.harvard.i2b2.crc.ejb.QueryExecutorMDB.java

/**
 * Take the XML based message and delegate to the system coordinator to
 * handle the actual processing/* w w w .j  a  v  a  2 s . co m*/
 * 
 * @param msg
 *            th JMS TextMessage object containing XML data
 */
public void onMessage(Message msg) {
    MapMessage message = null;
    QueueConnection conn = null;
    QueueSession session = null;
    QueueSender sender = null;
    QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance();
    Queue replyToQueue = null;
    UserTransaction transaction = sessionContext.getUserTransaction();
    // default timeout three minutes
    int transactionTimeout = 0;

    try {

        transactionTimeout = this.readTimeoutPropertyValue(SMALL_QUEUE);
        if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.MEDIUM_QUEUE)) {
            // four hours
            // transactionTimeout = 14400;
            transactionTimeout = this.readTimeoutPropertyValue(MEDIUM_QUEUE);
        } else if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.LARGE_QUEUE)) {
            // twelve hours
            // transactionTimeout = 43200;
            transactionTimeout = this.readTimeoutPropertyValue(LARGE_QUEUE);
        }

        transaction.setTransactionTimeout(transactionTimeout);

        transaction.begin();
        message = (MapMessage) msg;
        String sessionId = msg.getJMSCorrelationID();
        replyToQueue = (Queue) msg.getJMSReplyTo();
        log.debug("Extracting the message [" + msg.getJMSMessageID() + " ] on " + callingMDBName);
        transaction.commit();
        ExecRunnable er = new ExecRunnable(transaction, transactionTimeout, callingMDBName, message, sessionId);
        er.execute();

    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            if (transaction.getStatus() != 4) {

                transaction.rollback();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("Error extracting message", ex);
    } finally {

        QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil();
        qmBeanUtil.closeAll(sender, null, conn, session);
    }
}

From source file:se.alingsas.alfresco.repo.utils.byggreda.ByggRedaUtil.java

/**
 * Import a document//from   ww w .j  a  v  a2 s. c o  m
 * 
 * @param site
 * @param sourcePath
 * @param document
 * @return
 */
private ByggRedaDocument importDocument(SiteInfo site, String sourcePath, ByggRedaDocument document) {
    final String currentDestinationPath = destinationPath + "/" + document.getPath();
    UserTransaction trx = getTransactionService().getNonPropagatingUserTransaction();

    try {
        trx.begin();
        // Check if file exists already
        FileInfo repoFileFolder = getRepoFileFolder(site,
                currentDestinationPath + "/" + document.getFileName());
        if (repoFileFolder != null) {
            if (this.updateExisting) {
                try {
                    String fullFilenamePath = checkFileExistsIgnoreExtensionCase(
                            sourcePath + "/" + document.getFileName());
                    if (fullFilenamePath == null) {
                        throw new java.io.FileNotFoundException();
                    }
                    File f = new File(fullFilenamePath);
                    if (!f.exists()) {
                        throw new java.io.FileNotFoundException();
                    }
                    if (!f.exists()) {
                        throw new java.io.FileNotFoundException();
                    }
                    LOG.debug("File " + document.getFileName()
                            + " already exists, attempting to creating a new version at "
                            + currentDestinationPath);
                    final NodeRef workingCopy = checkOutCheckInService.checkout(repoFileFolder.getNodeRef());

                    addProperties(workingCopy, document, true);

                    createFile(workingCopy, site, sourcePath, document);

                    final Map<String, Serializable> properties = new HashMap<String, Serializable>();
                    properties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
                    NodeRef checkin = checkOutCheckInService.checkin(workingCopy, properties);
                    document.setNodeRef(checkin);
                    if (checkin != null && nodeService.exists(checkin)) {
                        document.setReadSuccessfully(true);
                        document.setStatusMsg("Filen " + sourcePath + "/" + document.getFileName()
                                + " uppdaterades till ny version");
                        trx.commit();
                    } else {
                        document.setReadSuccessfully(false);
                        document.setStatusMsg("Uppdatering av fil " + currentDestinationPath + "/"
                                + document.getFileName() + " misslyckades.");
                        LOG.error(document.getStatusMsg());
                        throw new Exception(document.getStatusMsg());
                    }
                } catch (java.io.FileNotFoundException e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg("Inlsning av fil misslyckades, filen " + sourcePath + "/"
                            + document.getFileName() + " kunde inte hittas.");
                    LOG.error(document.getStatusMsg());
                    throw new Exception(document.getStatusMsg(), e);
                } catch (FileExistsException e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg("Inlsning av fil misslyckades, mlfilen " + currentDestinationPath
                            + " finns redan.");
                    LOG.error(document.getStatusMsg());
                    throw new Exception(document.getStatusMsg(), e);
                } catch (Exception e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg(e.getMessage());
                    LOG.error("Error importing document " + document.getRecordNumber(), e);
                    throw new Exception(document.getStatusMsg(), e);
                }
            } else {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Filen existerar redan, hoppar ver.");
                LOG.debug("File already exists");
                trx.commit();
            }
        } else {
            try {
                String fullFilenamePath = checkFileExistsIgnoreExtensionCase(
                        sourcePath + "/" + document.getFileName());
                if (fullFilenamePath == null) {
                    throw new java.io.FileNotFoundException();
                }
                File f = new File(fullFilenamePath);
                if (!f.exists()) {
                    throw new java.io.FileNotFoundException();
                }
                NodeRef folderNodeRef = createFolder(destinationPath, document.getPath(),
                        document.getOriginalPath(), site);
                final FileInfo fileInfo = fileFolderService.create(folderNodeRef, document.getFileName(),
                        AkDmModel.TYPE_AKDM_BYGGREDA_DOC);
                document.setNodeRef(fileInfo.getNodeRef());
                addProperties(document.getNodeRef(), document, false);
                createFile(document.getNodeRef(), site, sourcePath, document);
                createVersionHistory(document.getNodeRef());
                document.setReadSuccessfully(true);
                LOG.debug("Imported document " + document.getRecordDisplay());
                trx.commit();
            } catch (java.io.FileNotFoundException e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Inlsning av fil misslyckades, filen " + sourcePath + "/"
                        + document.getFileName() + " kunde inte hittas.");
                LOG.error(document.getStatusMsg());
                throw new Exception(document.getStatusMsg(), e);
            } catch (FileExistsException e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Inlsning av fil misslyckades, mlfilen " + currentDestinationPath
                        + " finns redan.");
                LOG.error(document.getStatusMsg());
                throw new Exception(document.getStatusMsg(), e);
            } catch (Exception e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Fel vid inlsning av fil, systemmeddelande: " + e.getMessage());
                LOG.error("Error importing document " + document.getRecordNumber(), e);
                throw new Exception(document.getStatusMsg(), e);
            }
        }
    } catch (Exception e) {
        try {
            if (trx.getStatus() == Status.STATUS_ACTIVE) {
                trx.rollback();
            } else {
                LOG.error("The transaction was not active", e);
            }
            return document;
        } catch (Exception e2) {
            LOG.error("Exception: ", e);
            LOG.error("Exception while rolling back transaction", e2);
            throw new RuntimeException(e2);
        }

    }
    return document;

}

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);/*from  www  .j a  v a 2s .c o  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

public void deployTenants(final TenantDeployer deployer, Log logger) {
    if (deployer == null) {
        throw new AlfrescoRuntimeException("Deployer must be provided");
    }// w ww.  j  a v a  2  s .co m
    if (logger == null) {
        throw new AlfrescoRuntimeException("Logger must be provided");
    }

    if (tenantService.isEnabled()) {
        UserTransaction userTransaction = transactionService.getUserTransaction();
        authenticationComponent.setSystemUserAsCurrentUser();

        List<org.alfresco.repo.tenant.Tenant> tenants = null;
        try {
            userTransaction.begin();
            tenants = getAllTenants();
            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 get tenants", e);
        }

        String currentUser = AuthenticationUtil.getCurrentUserName();

        if (tenants != null) {
            try {
                for (org.alfresco.repo.tenant.Tenant tenant : tenants) {
                    if (tenant.isEnabled()) {
                        try {
                            // switch to admin in order to deploy within context of tenant domain
                            // assumes each tenant has default "admin" user
                            AuthenticationUtil.runAs(new RunAsWork<Object>() {
                                public Object doWork() {
                                    // init the service within tenant context
                                    deployer.init();
                                    return null;
                                }
                            }, getTenantAdminUser(tenant.getTenantDomain()));

                        } catch (Throwable e) {
                            logger.error("Deployment failed" + e);

                            StringWriter stringWriter = new StringWriter();
                            e.printStackTrace(new PrintWriter(stringWriter));
                            logger.error(stringWriter.toString());

                            // tenant deploy failure should not necessarily affect other tenants
                        }
                    }
                }
            } finally {
                if (currentUser != null) {
                    AuthenticationUtil.setCurrentUser(currentUser);
                }
            }
        }
    }
}

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

public void undeployTenants(final TenantDeployer deployer, Log logger) {
    if (deployer == null) {
        throw new AlfrescoRuntimeException("Deployer must be provided");
    }// ww w  .  j  a va2s  .c  om
    if (logger == null) {
        throw new AlfrescoRuntimeException("Logger must be provided");
    }

    if (tenantService.isEnabled()) {
        UserTransaction userTransaction = transactionService.getUserTransaction();
        authenticationComponent.setSystemUserAsCurrentUser();

        List<org.alfresco.repo.tenant.Tenant> tenants = null;
        try {
            userTransaction.begin();
            tenants = getAllTenants();
            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 get tenants", e);
        }

        String currentUser = AuthenticationUtil.getCurrentUserName();

        if (tenants != null) {
            try {
                for (org.alfresco.repo.tenant.Tenant tenant : tenants) {
                    if (tenant.isEnabled()) {
                        try {
                            // switch to admin in order to deploy within context of tenant domain
                            // assumes each tenant has default "admin" user
                            AuthenticationUtil.runAs(new RunAsWork<Object>() {
                                public Object doWork() {
                                    // destroy the service within tenant context
                                    deployer.destroy();
                                    return null;
                                }
                            }, getTenantAdminUser(tenant.getTenantDomain()));

                        } catch (Throwable e) {
                            logger.error("Undeployment failed" + e);

                            StringWriter stringWriter = new StringWriter();
                            e.printStackTrace(new PrintWriter(stringWriter));
                            logger.error(stringWriter.toString());

                            // tenant undeploy failure should not necessarily affect other tenants
                        }
                    }
                }
            } finally {
                if (currentUser != null) {
                    AuthenticationUtil.setCurrentUser(currentUser);
                }
            }
        }
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

private int handleRootFolder(File folder, NodeRef parentNodeRef, QName parentAssocTypeQName,
        QName containerTypeQName, QName containerNamePropertyQName, QName containerAssocTypeQName,
        QName contentTypeQName, QName contentNamePropertyQName) throws Exception {
    logger.debug("[ArchiveImporterJob::handleRootFolder] BEGIN");

    // Conto quanti dati sono stati scritti
    int nContent = 0;

    try {//  ww  w  .j a  v  a  2 s  .c o m
        // Prima si inizia col creare i singoli contenuti
        boolean bContent = false;

        {
            // Prendo un oggetto UserTransaction
            UserTransaction transaction = transactionService.getNonPropagatingUserTransaction();

            try {
                // Inizio la transazione
                transaction.begin();

                // Conto i content creati
                int nSubContent = 0;

                // Prima creo i content in una transazione
                File[] folderEntries = folder.listFiles();
                for (File entry : folderEntries) {

                    // Se e' una directory
                    if (!entry.isDirectory()) {
                        logger.debug("[ArchiveImporterJob::handleRootFolder] creating content: "
                                + entry.getName() + ", nodeRef=" + parentNodeRef + ", association="
                                + parentAssocTypeQName);

                        // Creo il contenuti
                        if (createContent(entry, parentNodeRef, contentTypeQName, contentNamePropertyQName,
                                parentAssocTypeQName)) {
                            nSubContent++;
                        }
                    }
                }

                // Se ho inserito 0 content, e non si e' generata una eccezione, vuol dire che i dati inseriti
                // sono tutti dei doppioni, in questo caso, meto bContent a true, e lascio andare avanti l'algoritmo
                bContent = (nSubContent == 0);
                nContent += nSubContent;

                logger.debug("[ArchiveImporterJob::handleRootFolder] Content inseriti: " + nContent);

                // Nel caso che si chiami una commit, senza righe da committare
                // C'e' una eccezione.
                // TODO: gestire le transazioni da 0 contenuti .. ma .. cosa fare in questa situazione?
                transaction.commit();

                // Se non ho ecezione sulla commit, indico come true la creazione content
                bContent = true;

                logger.debug("[ArchiveImporterJob::handleRootFolder] Content bool " + bContent);

            } catch (RollbackException re) {
                try {
                    transaction.rollback();
                } catch (Exception ee) {
                    logger.debug("[ArchiveImporterJob::handleRootFolder] RollbackException");
                }
            } catch (EcmEngineFoundationException e) {
                // Rollback
                try {
                    transaction.rollback();
                } catch (Exception ee) {
                    logger.debug("[ArchiveImporterJob::handleRootFolder] EcmEngineFoundationException");
                }
            } catch (Exception e) {
                logger.debug(e);
                throw e;
            }
        }

        // Se i contenuti vanno a buon fine, inizio a cancellarli da disco
        boolean bDelete = false;
        if (bContent) {
            try {
                // Prima creo i content in una transazione
                File[] folderEntries = folder.listFiles();
                for (File entry : folderEntries) {

                    // Se e' una directory
                    if (!entry.isDirectory()) {
                        // Cancello il contenuto
                        entry.delete();
                    }
                }
                bDelete = true;
            } catch (Exception e) {
                logger.debug(e);
                throw e;
            }
        }

        // Se le delete vanno a buon fine, inizio a creare le directory
        if (bDelete) {
            try {
                boolean bDeleteFolder = true;
                // Per tutti i file della cartella
                File[] folderEntries = folder.listFiles();
                for (File entry : folderEntries) {

                    // Se e' una directory
                    if (entry.isDirectory()) {
                        // Create directory
                        logger.debug("[ArchiveImporterJob::handleRootFolder] creating directory: "
                                + entry.getName() + ", nodeRef=" + parentNodeRef + ", association="
                                + parentAssocTypeQName);

                        // nodo di riferimento
                        NodeRef nr = null;

                        // Stranamente, per una get di dati, viene espressamente richiesta una transazione

                        // Prendo un oggetto UserTransaction
                        UserTransaction transaction = transactionService.getNonPropagatingUserTransaction();
                        try {
                            // Inizio la transazione
                            transaction.begin();

                            // Verifico se la cartella e' presente nel nodo padre
                            nr = nodeService.getChildByName(parentNodeRef, parentAssocTypeQName,
                                    entry.getName());

                            // Anche se non ho fatto
                            transaction.rollback();
                        } catch (Exception e) {
                            logger.debug(e);
                            throw e;
                        } finally {
                            // Anche se non ho fatto
                            try {
                                transaction.rollback();
                            } catch (Exception e) {
                            }
                        }

                        // Prendo un oggetto UserTransaction
                        transaction = transactionService.getNonPropagatingUserTransaction();
                        boolean bTrans = false;
                        try {
                            // Se non e' presente, provo a crearla
                            if (nr == null) {
                                bTrans = true;

                                // Preparo le properties di un folder
                                QName prefixedNameQName = resolvePrefixNameToQName("cm:" + entry.getName());
                                Map<QName, Serializable> props = new HashMap<QName, Serializable>();
                                props.put(containerNamePropertyQName, entry.getName());

                                // Inizio la transazione
                                transaction.begin();

                                // Creo il folder
                                ChildAssociationRef folderNodeRef = nodeService.createNode(parentNodeRef,
                                        parentAssocTypeQName, prefixedNameQName, containerTypeQName, props);

                                // Nel caso che si chiami una commit, senza righe da committare
                                // C'e' una eccezione.
                                // TODO: gestire le transazioni da 0 contenuti
                                transaction.commit();

                                nr = folderNodeRef.getChildRef();
                            }

                            // Creazione del subfolder
                            nContent += handleRootFolder(entry, nr, containerAssocTypeQName, // Non passo il parent, ma passo il containerAssocType nei folder figli
                                    containerTypeQName, containerNamePropertyQName, containerAssocTypeQName,
                                    contentTypeQName, contentNamePropertyQName);

                        } catch (RollbackException re) {
                            if (bTrans) {
                                try {
                                    transaction.rollback();
                                } catch (Exception ee) {
                                    logger.debug(re);
                                }
                            }

                        } catch (EcmEngineFoundationException e) {
                            bDeleteFolder = false;
                            // Rollback
                            try {
                                transaction.rollback();
                            } catch (Exception ee) {
                                logger.debug(e);
                            }

                        } catch (Exception e) {
                            logger.debug(e);
                            throw e;
                        }

                    }
                }

                // Rimuovo la directory, se non ho avuto problemi rimuovendo le subdir
                if (bDeleteFolder) {
                    folder.delete();
                }
            } catch (Exception e) {
                logger.debug(e);
                throw e;
            }
        }

    } catch (Exception e) {
        logger.debug(e);
        throw e;
    } finally {
        logger.debug("[ArchiveImporterJob::handleRootFolder] END");
    }

    return nContent;
}

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

private MoveAggregation getPropertiesFromAspect(NodeRef sourceNodeRef)
        throws DictionaryRuntimeException, NotSupportedException, SystemException, SecurityException,
        IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    logger.debug("[MoveAggregationJob::getPropertiesFromAspect] BEGIN");
    MoveAggregation aggreg = null;//from   ww w  .  j  a v  a  2 s  . c o m

    try {

        UserTransaction userTxSource = transactionService.getNonPropagatingUserTransaction();

        userTxSource.begin();

        QName destinationAspect = resolvePrefixNameToQName("ecm-sys:destination");

        if (nodeService.hasAspect(sourceNodeRef, destinationAspect)) {

            Map<QName, Serializable> nodeProp = nodeService.getProperties(sourceNodeRef);
            QName idNodeDestinationProp = resolvePrefixNameToQName("ecm-sys:idNodeDestination");
            QName repoDestinationProp = resolvePrefixNameToQName("ecm-sys:repoDestination");
            QName idNodeSourceProp = resolvePrefixNameToQName("ecm-sys:idNodeSource");
            QName repoSourceProp = resolvePrefixNameToQName("ecm-sys:repoSource");

            aggreg = new MoveAggregation();

            aggreg.setIdDestinationParent((String) nodeProp.get(idNodeDestinationProp));
            aggreg.setDestinationRepository((String) nodeProp.get(repoDestinationProp));

            aggreg.setIdSourceNode((String) nodeProp.get(idNodeSourceProp));
            aggreg.setSourceRepository((String) nodeProp.get(repoSourceProp));
        }

        userTxSource.commit();

    } finally {
        logger.debug("[MoveAggregationJob::getPropertiesFromAspect] END");
    }
    return aggreg;
}

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

/**
 * @see TenantAdminService.deleteTenant()
 *//*w  w w  .ja  v 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);
        }
    }
}