List of usage examples for javax.transaction UserTransaction commit
void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException;
From source file:org.alfresco.repo.cache.CacheTest.java
public void testTransactionalCacheStatsForClears() throws Throwable { // add item to global cache TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null); TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null); TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null); TransactionService transactionService = serviceRegistry.getTransactionService(); UserTransaction txn = transactionService.getUserTransaction(); final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT); final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS); final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT); final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE); final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR); try {/*from w w w. j av a 2 s. c om*/ // begin a transaction txn.begin(); // Perform some puts transactionalCache.put("stats-test4", "v"); transactionalCache.put("stats-test5", "v"); transactionalCache.put("stats-test6", "v"); transactionalCache.put("stats-test7", "v"); transactionalCache.put("stats-test8", "v"); // Perform some gets... // hits transactionalCache.get("stats-test3"); transactionalCache.get("stats-test2"); transactionalCache.get("stats-test1"); // repeated hits won't touch the shared cache transactionalCache.get("stats-test2"); transactionalCache.get("stats-test1"); // misses - not yet committed transactionalCache.get("stats-miss1"); transactionalCache.get("stats-miss2"); transactionalCache.get("stats-miss3"); transactionalCache.get("stats-miss4"); // repeated misses won't touch the shared cache transactionalCache.get("stats-miss2"); transactionalCache.get("stats-miss3"); // Perform some removals transactionalCache.remove("stats-test1"); transactionalCache.remove("stats-test2"); transactionalCache.remove("stats-test3"); transactionalCache.remove("stats-test9"); transactionalCache.remove("stats-test10"); transactionalCache.remove("stats-test11"); transactionalCache.remove("stats-test12"); transactionalCache.remove("stats-test13"); // Perform some clears transactionalCache.clear(); transactionalCache.clear(); // Check nothing has changed yet - changes not written through until commit or rollback assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT)); assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS)); assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT)); assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE)); assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR)); // commit the transaction txn.commit(); assertEquals(clearsAtStart + 2, cacheStats.count("transactionalCache", OpType.CLEAR)); // There are no removes or puts propagated to the shared cache, as a result of the clears. assertEquals(removesAtStart + 0, cacheStats.count("transactionalCache", OpType.REMOVE)); assertEquals(putsAtStart + 0, cacheStats.count("transactionalCache", OpType.PUT)); assertEquals(hitsAtStart + 3, cacheStats.count("transactionalCache", OpType.GET_HIT)); assertEquals(missesAtStart + 4, cacheStats.count("transactionalCache", OpType.GET_MISS)); } catch (Throwable e) { if (txn.getStatus() == Status.STATUS_ACTIVE) { txn.rollback(); } throw e; } }
From source file:org.alfresco.repo.domain.audit.AuditDAOTest.java
private void scriptCanDeleteOrphanedPropsWork(final boolean performance) throws Exception { final int iterationStep, maxIterations; if (performance) { iterationStep = 1000;/*from ww w . j a v a 2 s . c o m*/ maxIterations = 1000; } else { iterationStep = 1; maxIterations = 1; } UserTransaction txn; for (int i = iterationStep; i <= maxIterations * iterationStep; i += iterationStep) { List<String> stringValues = new LinkedList<String>(); List<Double> doubleValues = new LinkedList<Double>(); List<Date> dateValues = new LinkedList<Date>(); txn = transactionService.getUserTransaction(); long startCreate = System.currentTimeMillis(); txn.begin(); for (int j = 0; j < i; j++) { PropValGenerator valueGen = new PropValGenerator(propertyValueDAO); String stringValue = valueGen.createUniqueString(); stringValues.add(stringValue); Double doubleValue = valueGen.createUniqueDouble(); doubleValues.add(doubleValue); Date dateValue = valueGen.createUniqueDate(); dateValues.add(dateValue); AuditQueryCallbackImpl preDeleteCallback = new AuditQueryCallbackImpl(); AuditQueryCallbackImpl resultsCallback = new AuditQueryCallbackImpl(); AuditApplicationInfo info1 = createAuditApp(); String app1 = info1.getName(); String username = "alexi"; Map<String, Serializable> values = new HashMap<String, Serializable>(); values.put("/a/b/string-" + j, stringValue); values.put("/a/b/double-" + j, doubleValue); values.put("/a/b/date-" + j, dateValue); // TODO: how to deal with Serializable values which cannot be retrieved later in test by value alone? long now = System.currentTimeMillis(); auditDAO.createAuditEntry(info1.getId(), now, username, values); auditDAO.findAuditEntries(preDeleteCallback, new AuditQueryParameters(), Integer.MAX_VALUE); assertEquals(1, preDeleteCallback.numEntries(app1)); // Delete audit entries between times - for all applications. auditDAO.deleteAuditEntries(info1.getId(), null, null); if (!performance) { auditDAO.findAuditEntries(resultsCallback, new AuditQueryParameters(), Integer.MAX_VALUE); assertEquals("All entries should have been deleted from app1", 0, resultsCallback.numEntries(app1)); } } txn.commit(); System.out.println("Created values for " + i + " entries in " + (System.currentTimeMillis() - startCreate) + " ms."); if (!performance) { // Check there are some persisted values to delete. // Unlike PropertyValueDAOTest we're using the getPropertyValue() method here, // instead of the datatype-specific methods (e.g. getPropertyStringValue()). // This is because AuditDAO persists an entire map of values resulting in different behaviour // (i.e. dates are persisted as Serializable) for (String stringValue : stringValues) { assertEquals(stringValue, propertyValueDAO.getPropertyValue(stringValue).getSecond()); } for (Double doubleValue : doubleValues) { assertEquals(doubleValue, propertyValueDAO.getPropertyValue(doubleValue).getSecond()); } for (Date dateValue : dateValues) { assertEquals(dateValue, propertyValueDAO.getPropertyValue(dateValue).getSecond()); } } long startDelete = System.currentTimeMillis(); RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>() { public Void execute() throws Throwable { propertyValueDAO.cleanupUnusedValues(); return null; } }; // use a new transaction so it will retry in that transaction txnHelper.doInTransaction(callback, false, true); System.out.println("Cleaned values for " + i + " entries in " + (System.currentTimeMillis() - startDelete) + " ms."); if (!performance) { // Check all the properties have been deleted. txn = transactionService.getUserTransaction(); txn.begin(); for (String stringValue : stringValues) { assertPropDeleted(propertyValueDAO.getPropertyValue(stringValue)); } for (Double doubleValue : doubleValues) { assertPropDeleted(propertyValueDAO.getPropertyValue(doubleValue)); } for (Date dateValue : dateValues) { assertPropDeleted(propertyValueDAO.getPropertyValue(dateValue)); } txn.commit(); } } }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
@Override public void setUp() throws Exception { logger.debug("In SetUp"); serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry"); transactionService = serviceRegistry.getTransactionService(); nodeService = serviceRegistry.getNodeService(); importerService = serviceRegistry.getImporterService(); personService = serviceRegistry.getPersonService(); authenticationService = serviceRegistry.getAuthenticationService(); searchService = serviceRegistry.getSearchService(); namespaceService = serviceRegistry.getNamespaceService(); fileFolderService = serviceRegistry.getFileFolderService(); // start the transaction UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/* ww w .j av a 2 s. c o m*/ authenticationService.authenticate(ADMIN_USER_NAME, ADMIN_USER_PASSWORD.toCharArray()); // downgrade integrity IntegrityChecker.setWarnInTransaction(); anotherUserName = "user" + System.currentTimeMillis(); PropertyMap testUser = new PropertyMap(); testUser.put(ContentModel.PROP_USERNAME, anotherUserName); testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName); testUser.put(ContentModel.PROP_LASTNAME, anotherUserName); testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com"); testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle"); personService.createPerson(testUser); // create the ACEGI Authentication instance for the new user authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray()); StoreRef storeRef = new StoreRef(storePath); storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false); NodeRef companyHomeNodeRef = nodeRefs.get(0); nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null, namespaceService, false); if (nodeRefs != null && nodeRefs.size() > 0) { fileFolderService.delete(nodeRefs.get(0)); } ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap"); ApplicationContext imapCtx = imap.getApplicationContext(); ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService"); imapServer = (AlfrescoImapServer) imapCtx.getBean("imapServer"); if (!imapServer.isImapServerEnabled()) { imapServer.setImapServerEnabled(true); imapServer.setHost(HOST); imapServer.setPort(PORT); imapServer.startup(); } // Creating IMAP test folder for IMAP root LinkedList<String> folders = new LinkedList<String>(); folders.add(IMAP_FOLDER_NAME); FileFolderUtil.makeFolders(fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER); // Setting IMAP root RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean(); imapHome.setStore(storePath); imapHome.setRootPath(companyHomePathInStore); imapHome.setFolderPath(NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME); imapServiceImpl.setImapHome(imapHome); // Starting IMAP imapServiceImpl.startupInTxn(true); nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null, namespaceService, false); testImapFolderNodeRef = nodeRefs.get(0); /* * Importing test folders: Test folder contains: "___-___folder_a" "___-___folder_a" contains: "___-___folder_a_a", "___-___file_a", "Message_485.eml" (this is IMAP * Message) "___-___folder_a_a" contains: "____-____file_a_a" */ importInternal("imap/imapservice_test_folder_a.acp", testImapFolderNodeRef); txn.commit(); // Init mail client session Properties props = new Properties(); props.setProperty("mail.imap.partialfetch", "false"); this.session = Session.getDefaultInstance(props, null); // Get the store this.store = session.getStore(PROTOCOL); //this.store.connect(HOST, PORT, anotherUserName, anotherUserName); this.store.connect(imapServer.getHost(), imapServer.getPort(), anotherUserName, anotherUserName); // Get folder folder = (IMAPFolder) store.getFolder(TEST_FOLDER); folder.open(Folder.READ_ONLY); logger.debug("End SetUp"); }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testMessageModifiedBetweenReads() throws Exception { // Get test message UID final Long uid = getMessageUid(folder, 1); // Get unmodified message BODY body = getMessageBody(folder, uid); // Parse the multipart MIME message MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new BufferedInputStream(body.getByteArrayInputStream())); // Reading first part - should be successful MimeMultipart content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); // Reading second part - should be successful assertNotNull(content.getBodyPart(1).getContent()); // Modify message. The size of letter describing the node may change // These changes should be committed because it should be visible from client NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE); UserTransaction txn = transactionService.getUserTransaction(); txn.begin();//from w w w .ja va 2s . c om ContentWriter writer = fileFolderService.getWriter(contentNode); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 2000; i++) { sb.append("test string"); } writer.putContent(sb.toString()); txn.commit(); // Read updated message part BODY bodyNew = getMessageBody(folder, uid); // The body should be updated assertFalse(Arrays.equals(bodyNew.getByteArray().getBytes(), body.getByteArray().getBytes())); // Parse the multipart MIME message message = new MimeMessage(Session.getDefaultInstance(new Properties()), new BufferedInputStream(bodyNew.getByteArrayInputStream())); // Reading first part - should be successful content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); // Reading second part - should be successful assertNotNull(content.getBodyPart(1).getContent()); }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testMessageRenamedBetweenReads() throws Exception { // Get test message UID final Long uid = getMessageUid(folder, 1); // Get Message size final int count = getMessageSize(folder, uid); // Get first part // Split the message into 2 part using a non multiple of 4 - 103 is a prime number // as the BASE64Decoder may not throw the IOException // see MNT-12995 BODY body = getMessageBodyPart(folder, uid, 0, count - 103); // Rename message. The size of letter describing the node will change // These changes should be committed because it should be visible from client NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE); UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/* www . j a va 2 s.c o m*/ fileFolderService.rename(contentNode, "testtesttesttesttesttesttesttesttesttest"); txn.commit(); // Read second message part BODY bodyRest = getMessageBodyPart(folder, uid, count - 103, 103); // Creating and parsing message from 2 parts MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()), new BufferedInputStream(bodyRest.getByteArrayInputStream()))); // Reading first part - should be successful MimeMultipart content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); try { // Reading second part cause error content.getBodyPart(1).getContent(); fail("Should raise an IOException"); } catch (IOException e) { } }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void dontTestMessageCache() throws Exception { // Create messages NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE); UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/*from ww w. ja v a2 s. c om*/ // Create messages more than cache capacity for (int i = 0; i < 51; i++) { FileInfo fi = fileFolderService.create(nodeService.getParentAssocs(contentNode).get(0).getParentRef(), "test" + i, ContentModel.TYPE_CONTENT); ContentWriter writer = fileFolderService.getWriter(fi.getNodeRef()); writer.putContent("test"); } txn.commit(); // Reload folder folder.close(false); folder = (IMAPFolder) store.getFolder(TEST_FOLDER); folder.open(Folder.READ_ONLY); // Read all messages for (int i = 1; i < 51; i++) { // Get test message UID final Long uid = getMessageUid(folder, i); // Get Message size final int count = getMessageSize(folder, uid); // Get first part BODY body = getMessageBodyPart(folder, uid, 0, count - 100); // Read second message part BODY bodyRest = getMessageBodyPart(folder, uid, count - 100, 100); // Creating and parsing message from 2 parts MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()), new BufferedInputStream(bodyRest.getByteArrayInputStream()))); // Reading first part - should be successful MimeMultipart content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); assertNotNull(content.getBodyPart(1).getContent()); } }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
@Override public void tearDown() throws Exception { // Deleting created test environment logger.debug("tearDown "); UserTransaction txn = transactionService.getUserTransaction(); txn.begin();//from www. ja va 2 s .co m List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null, namespaceService, false); if (nodeRefs != null && nodeRefs.size() > 0) { fileFolderService.delete(nodeRefs.get(0)); } authenticationService.deleteAuthentication(anotherUserName); personService.deletePerson(anotherUserName); txn.commit(); // Closing client connection folder.close(false); store.close(); logger.debug("tearDown end"); }
From source file:org.alfresco.repo.imap.LoadTester.java
@Override public void setUp() throws Exception { ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry"); authenticationService = serviceRegistry.getAuthenticationService(); imapService = serviceRegistry.getImapService(); importerService = serviceRegistry.getImporterService(); NodeService nodeService = serviceRegistry.getNodeService(); SearchService searchService = serviceRegistry.getSearchService(); NamespaceService namespaceService = serviceRegistry.getNamespaceService(); PersonService personService = serviceRegistry.getPersonService(); FileFolderService fileFolderService = serviceRegistry.getFileFolderService(); TransactionService transactionService = serviceRegistry.getTransactionService(); PermissionService permissionService = serviceRegistry.getPermissionService(); // start the transaction UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/*from w ww .j ava2 s. c o m*/ authenticationService.authenticate(USER_NAME, USER_PASSWORD.toCharArray()); anotherUserName = "test_imap_user"; NodeRef person = personService.getPerson(anotherUserName); if (person != null) { personService.deletePerson(anotherUserName); PropertyMap testUser = new PropertyMap(); testUser.put(ContentModel.PROP_USERNAME, anotherUserName); testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName); testUser.put(ContentModel.PROP_LASTNAME, anotherUserName); testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com"); testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle"); personService.createPerson(testUser); } if (authenticationService.authenticationExists(anotherUserName)) { authenticationService.deleteAuthentication(anotherUserName); } authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray()); user = new AlfrescoImapUser(anotherUserName + "@alfresco.com", anotherUserName, anotherUserName); String storePath = "workspace://SpacesStore"; String companyHomePathInStore = "/app:company_home"; StoreRef storeRef = new StoreRef(storePath); NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false); NodeRef companyHomeNodeRef = nodeRefs.get(0); ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap"); ApplicationContext imapCtx = imap.getApplicationContext(); ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService"); // Delete test folder nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + TEST_IMAP_ROOT_FOLDER_NAME, null, namespaceService, false); if (nodeRefs.size() == 1) { NodeRef ch = nodeRefs.get(0); nodeService.deleteNode(ch); } // Creating IMAP test folder for IMAP root LinkedList<String> folders = new LinkedList<String>(); folders.add(TEST_IMAP_ROOT_FOLDER_NAME); FileFolderServiceImpl.makeFolders(fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER); // Setting IMAP root RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean(); imapHome.setStore(storePath); imapHome.setRootPath(companyHomePathInStore); imapHome.setFolderPath(TEST_IMAP_ROOT_FOLDER_NAME); imapServiceImpl.setImapHome(imapHome); // Starting IMAP imapServiceImpl.startupInTxn(true); nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + TEST_IMAP_ROOT_FOLDER_NAME, null, namespaceService, false); // Used to create User's folder NodeRef userFolderRef = imapService.getUserImapHomeRef(anotherUserName); permissionService.setPermission(userFolderRef, anotherUserName, PermissionService.ALL_PERMISSIONS, true); importTestData("imap/load_test_data.acp", userFolderRef); reauthenticate(anotherUserName, anotherUserName); AlfrescoImapFolder testDataFolder = imapService.getOrCreateMailbox(user, TEST_DATA_FOLDER_NAME, true, false); SimpleStoredMessage m = testDataFolder.getMessages().get(0); m = testDataFolder.getMessage(m.getUid()); AlfrescoImapFolder folder = imapService.getOrCreateMailbox(user, TEST_FOLDER_NAME, false, true); logger.info("Creating folders..."); long t = System.currentTimeMillis(); try { for (int i = 0; i < MESSAGE_QUANTITY; i++) { System.out.println("i = " + i); folder.appendMessage(m.getMimeMessage(), new Flags(), new Date()); } } catch (Exception e) { logger.error(e, e); } t = System.currentTimeMillis() - t; logger.info("Create time: " + t + " ms (" + t / 1000 + " s (" + t / 60000 + " min))"); txn.commit(); }
From source file:org.alfresco.repo.importer.ExportSourceImporter.java
@SuppressWarnings("unchecked") public void doImport() { UserTransaction userTransaction = null; try {/*w w w . j a va 2 s.c o m*/ AuthenticationUtil.pushAuthentication(); userTransaction = transactionService.getUserTransaction(); userTransaction.begin(); AuthenticationUtil.setRunAsUserSystem(); if (clearAllChildren) { logger.debug("clear all children"); List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null, namespacePrefixResolver, false); for (NodeRef ref : refs) { if (logger.isDebugEnabled()) { logger.debug("clear node ref" + ref); } for (ChildAssociationRef car : nodeService.getChildAssocs(ref)) { if (logger.isDebugEnabled()) { logger.debug("delete child" + car.getChildRef()); } nodeService.deleteNode(car.getChildRef()); } } } if (caches != null) { logger.debug("clearing caches"); for (SimpleCache cache : caches) { cache.clear(); } } File tempFile = TempFileProvider.createTempFile("ExportSourceImporter-", ".xml"); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8")); XMLWriter xmlWriter = createXMLExporter(writer); exportSource.generateExport(xmlWriter); xmlWriter.close(); Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempFile), "UTF-8")); Location location = new Location(storeRef); location.setPath(path); importerService.importView(reader, location, REPLACE_BINDING, null); reader.close(); if (caches != null) { for (SimpleCache cache : caches) { cache.clear(); } } logger.debug("about to commit"); userTransaction.commit(); } catch (Throwable t) { try { if (userTransaction != null) { logger.debug("rolling back due to exception", t); userTransaction.rollback(); } } catch (Exception ex) { logger.debug("exception during rollback", ex); } throw new ExportSourceImporterException("Failed to import", t); } finally { AuthenticationUtil.popAuthentication(); } }
From source file:org.alfresco.repo.importer.FileSourceImporter.java
@SuppressWarnings("unchecked") public void doImport() { UserTransaction userTransaction = null; try {/* w w w . j a v a 2 s . c o m*/ long start = System.nanoTime(); userTransaction = transactionService.getUserTransaction(); userTransaction.begin(); authenticationContext.setSystemUserAsCurrentUser(); if (clearAllChildren) { List<NodeRef> refs = searchService.selectNodes(nodeService.getRootNode(storeRef), path, null, namespacePrefixResolver, false); for (NodeRef ref : refs) { for (ChildAssociationRef car : nodeService.getChildAssocs(ref)) { nodeService.deleteNode(car.getChildRef()); } } } if (caches != null) { for (SimpleCache cache : caches) { cache.clear(); } } Reader reader = new BufferedReader(new FileReader(fileLocation)); Location location = new Location(storeRef); location.setPath(path); importerService.importView(reader, location, REPLACE_BINDING, null); reader.close(); if (caches != null) { for (SimpleCache cache : caches) { cache.clear(); } } userTransaction.commit(); long end = System.nanoTime(); s_logger.info("Imported " + fileLocation + " in " + ((end - start) / 1e9f) + " seconds"); } catch (Throwable t) { try { if (userTransaction != null) { userTransaction.rollback(); } } catch (Exception ex) { } try { authenticationContext.clearCurrentSecurityContext(); } catch (Exception ex) { } throw new ExportSourceImporterException("Failed to import", t); } finally { authenticationContext.clearCurrentSecurityContext(); } }