Search in sources :

Example 1 with UnableToAquireLockException

use of org.alfresco.service.cmr.lock.UnableToAquireLockException in project alfresco-remote-api by Alfresco.

the class PutMethodTest method testPutContentToWorkingCopy.

/**
 * Putting a content to a working copy file
 * <p>
 * Create and check out a file by user1
 * <p>
 * Try to put the content to the working copy by user2
 *
 * See MNT-8614.
 */
@SuppressWarnings("deprecation")
@Test
public void testPutContentToWorkingCopy() throws Exception {
    FileInfo folder = fileFolderService.create(companyHomeNodeRef, "folder-" + GUID.generate(), ContentModel.TYPE_FOLDER);
    permissionService.setInheritParentPermissions(folder.getNodeRef(), false);
    permissionService.setPermission(folder.getNodeRef(), USER1_NAME, permissionService.getAllPermission(), true);
    AuthenticationUtil.setFullyAuthenticatedUser(USER1_NAME);
    FileInfo testFileInfo = fileFolderService.create(folder.getNodeRef(), "file-" + GUID.generate(), ContentModel.TYPE_CONTENT);
    NodeRef workingCopyNodeRef = checkOutCheckInService.checkout(testFileInfo.getNodeRef());
    String workingCopyName = fileFolderService.getFileInfo(workingCopyNodeRef).getName();
    String pathToWC = "/" + folder.getName() + "/" + workingCopyName;
    String pathToOriginal = "/" + folder.getName() + "/" + testFileInfo.getName();
    // Negative test, try to edit the WC without permissions.
    AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
    try {
        lockService.lock(workingCopyNodeRef, LockType.WRITE_LOCK);
    } catch (AccessDeniedException ade) {
    // expected
    }
    try {
        executeMethod(WebDAV.METHOD_LOCK, pathToWC, davLockInfoUser2File, null);
        fail("The LOCK execution should fail with a 401 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + HttpServletResponse.SC_UNAUTHORIZED, wse.getHttpStatusCode() == HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }
    // Construct IF HEADER
    String lockToken = workingCopyNodeRef.getId() + WebDAV.LOCK_TOKEN_SEPERATOR + USER2_NAME;
    String lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)";
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_IF, lockHeaderValue);
    try {
        executeMethod(WebDAV.METHOD_PUT, pathToWC, testDataFile, headers);
        fail("The PUT execution should fail with a 423 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + HttpServletResponse.SC_UNAUTHORIZED, wse.getHttpStatusCode() == HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }
    // Positive test
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    permissionService.setPermission(folder.getNodeRef(), USER2_NAME, permissionService.getAllPermission(), true);
    AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
    try {
        executeMethod(WebDAV.METHOD_LOCK, pathToWC, davLockInfoUser2File, null);
        assertEquals("File should be locked", LockStatus.LOCK_OWNER, lockService.getLockStatus(workingCopyNodeRef));
    } catch (Exception e) {
        fail("Failed to lock a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }
    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_IF, lockHeaderValue);
    try {
        executeMethod(WebDAV.METHOD_PUT, pathToWC, testDataFile, headers);
        assertTrue("File does not exist.", nodeService.exists(workingCopyNodeRef));
        assertEquals("Filename is not correct", workingCopyName, nodeService.getProperty(workingCopyNodeRef, ContentModel.PROP_NAME));
        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is " + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());
        assertTrue("File should have NO_CONTENT aspect", nodeService.hasAspect(workingCopyNodeRef, ContentModel.ASPECT_NO_CONTENT));
        InputStream updatedFileIS = fileFolderService.getReader(workingCopyNodeRef).getContentInputStream();
        byte[] updatedFile = IOUtils.toByteArray(updatedFileIS);
        updatedFileIS.close();
        assertTrue("The content has to be equal", ArrayUtils.isEquals(testDataFile, updatedFile));
    } catch (Exception e) {
        fail("Failed to upload a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }
    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_LOCK_TOKEN, "<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">");
    try {
        executeMethod(WebDAV.METHOD_UNLOCK, pathToWC, null, headers);
        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is " + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus());
        assertFalse("File should not have NO_CONTENT aspect", nodeService.hasAspect(workingCopyNodeRef, ContentModel.ASPECT_NO_CONTENT));
        assertEquals("File should be unlocked", LockStatus.NO_LOCK, lockService.getLockStatus(workingCopyNodeRef));
    } catch (Exception e) {
        fail("Failed to unlock a file: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }
    // Negative test try to lock or edit the original file
    AuthenticationUtil.setFullyAuthenticatedUser(USER2_NAME);
    try {
        lockService.lock(testFileInfo.getNodeRef(), LockType.WRITE_LOCK);
    } catch (UnableToAquireLockException uale) {
    // expected
    }
    try {
        executeMethod(WebDAV.METHOD_LOCK, pathToOriginal, davLockInfoUser2File, null);
        fail("The LOCK execution should fail with a 423 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + WebDAV.WEBDAV_SC_LOCKED, wse.getHttpStatusCode() == WebDAV.WEBDAV_SC_LOCKED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }
    // Construct IF HEADER
    lockToken = testFileInfo.getNodeRef().getId() + WebDAV.LOCK_TOKEN_SEPERATOR + USER2_NAME;
    lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)";
    headers = new HashMap<String, String>();
    headers.put(WebDAV.HEADER_IF, lockHeaderValue);
    try {
        executeMethod(WebDAV.METHOD_PUT, pathToOriginal, testDataFile, headers);
        fail("The PUT execution should fail with a 423 error");
    } catch (WebDAVServerException wse) {
        // The execution failed and it is expected
        assertTrue("The status code was " + wse.getHttpStatusCode() + ", but should be " + WebDAV.WEBDAV_SC_LOCKED, wse.getHttpStatusCode() == WebDAV.WEBDAV_SC_LOCKED);
    } catch (Exception e) {
        fail("Unexpected exception occurred: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
    }
    AuthenticationUtil.setFullyAuthenticatedUser(USER1_NAME);
    checkOutCheckInService.checkin(workingCopyNodeRef, null);
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    nodeService.deleteNode(folder.getNodeRef());
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) FileInfo(org.alfresco.service.cmr.model.FileInfo) HashMap(java.util.HashMap) InputStream(java.io.InputStream) UnableToAquireLockException(org.alfresco.service.cmr.lock.UnableToAquireLockException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) UnableToAquireLockException(org.alfresco.service.cmr.lock.UnableToAquireLockException) Test(org.junit.Test)

Example 2 with UnableToAquireLockException

use of org.alfresco.service.cmr.lock.UnableToAquireLockException in project alfresco-repository by Alfresco.

the class LockServiceImplTest method testEphemeralLock.

public void testEphemeralLock() {
    TestWithUserUtils.authenticateUser(GOOD_USER_NAME, PWD, rootNodeRef, this.authenticationService);
    // Check that the node is not currently locked
    assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(noAspectNode));
    assertFalse(lockService.isLocked(noAspectNode));
    // Check that there really is no lockable aspect
    assertEquals(false, nodeService.hasAspect(noAspectNode, ContentModel.ASPECT_LOCKABLE));
    // Lock the node
    lockService.lock(noAspectNode, LockType.WRITE_LOCK, 86400, Lifetime.EPHEMERAL, "some extra data");
    // Check additionalInfo has been stored
    assertEquals("some extra data", lockService.getAdditionalInfo(noAspectNode));
    // Check that we can retrieve LockState
    LockState lockState = lockService.getLockState(noAspectNode);
    assertEquals(noAspectNode, lockState.getNodeRef());
    assertEquals(LockType.WRITE_LOCK, lockState.getLockType());
    assertEquals(GOOD_USER_NAME, lockState.getOwner());
    assertEquals(Lifetime.EPHEMERAL, lockState.getLifetime());
    assertNotNull(lockState.getExpires());
    assertEquals("some extra data", lockState.getAdditionalInfo());
    // The node should be locked
    assertEquals(LockStatus.LOCK_OWNER, lockService.getLockStatus(noAspectNode));
    assertTrue(lockService.isLocked(noAspectNode));
    // The node must still not have the lockable aspect applied
    assertEquals(false, nodeService.hasAspect(noAspectNode, ContentModel.ASPECT_LOCKABLE));
    // ...though the full node service should report that it is present
    NodeService fullNodeService = (NodeService) applicationContext.getBean("nodeService");
    assertEquals(true, fullNodeService.hasAspect(noAspectNode, ContentModel.ASPECT_LOCKABLE));
    TestWithUserUtils.authenticateUser(BAD_USER_NAME, PWD, rootNodeRef, this.authenticationService);
    assertEquals(LockStatus.LOCKED, lockService.getLockStatus(noAspectNode));
    assertTrue(lockService.isLocked(noAspectNode));
    // Test lock when already locked
    try {
        lockService.lock(noAspectNode, LockType.WRITE_LOCK);
        fail("The user should not be able to lock the node since it is already locked by another user.");
    } catch (UnableToAquireLockException exception) {
        System.out.println(exception.getMessage());
    }
    TestWithUserUtils.authenticateUser(GOOD_USER_NAME, PWD, rootNodeRef, this.authenticationService);
    assertEquals(LockStatus.LOCK_OWNER, lockService.getLockStatus(noAspectNode));
    assertTrue(lockService.isLocked(noAspectNode));
    // Test already locked by this user - relock
    try {
        lockService.lock(noAspectNode, LockType.WRITE_LOCK, 0, Lifetime.EPHEMERAL);
    } catch (Exception exception) {
        fail("No error should be thrown when a node is re-locked by the current lock owner.");
    }
    // The node should be locked
    assertEquals(LockStatus.LOCK_OWNER, lockService.getLockStatus(noAspectNode));
    assertTrue(lockService.isLocked(noAspectNode));
    // If we remove the lock info directly from the memory store then the node should no longer
    // be reported as locked (as it is an ephemeral lock)
    LockStore lockStore = (LockStore) applicationContext.getBean("lockStore");
    lockStore.clear();
    // The node must no longer be reported as locked
    assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(noAspectNode));
    assertFalse(lockService.isLocked(noAspectNode));
    // Lock again, ready to test unlocking an ephemeral lock.
    try {
        lockService.lock(noAspectNode, LockType.WRITE_LOCK, 0, Lifetime.EPHEMERAL);
    } catch (Exception exception) {
        fail("No error should be thrown when a node is re-locked by the current lock owner.");
    }
    assertEquals(LockStatus.LOCK_OWNER, lockService.getLockStatus(noAspectNode));
    assertTrue(lockService.isLocked(noAspectNode));
    lockService.unlock(noAspectNode);
    assertEquals(LockStatus.NO_LOCK, lockService.getLockStatus(noAspectNode));
    assertFalse(lockService.isLocked(noAspectNode));
}
Also used : NodeService(org.alfresco.service.cmr.repository.NodeService) LockState(org.alfresco.repo.lock.mem.LockState) UnableToAquireLockException(org.alfresco.service.cmr.lock.UnableToAquireLockException) LockStore(org.alfresco.repo.lock.mem.LockStore) NodeLockedException(org.alfresco.service.cmr.lock.NodeLockedException) UnableToReleaseLockException(org.alfresco.service.cmr.lock.UnableToReleaseLockException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) NotSupportedException(javax.transaction.NotSupportedException) UnableToAquireLockException(org.alfresco.service.cmr.lock.UnableToAquireLockException) SystemException(javax.transaction.SystemException)

Example 3 with UnableToAquireLockException

use of org.alfresco.service.cmr.lock.UnableToAquireLockException in project alfresco-repository by Alfresco.

the class LockServiceImpl method lock.

/**
 * @see org.alfresco.service.cmr.lock.LockService#lock(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.lock.LockType, int, Lifetime, String)
 */
@Override
@Extend(traitAPI = LockServiceTrait.class, extensionAPI = LockServiceExtension.class)
public void lock(NodeRef nodeRef, LockType lockType, int timeToExpire, Lifetime lifetime, String additionalInfo) {
    invokeBeforeLock(nodeRef, lockType);
    if (lifetime.equals(Lifetime.EPHEMERAL) && (timeToExpire > MAX_EPHEMERAL_LOCK_SECONDS)) {
        throw new IllegalArgumentException("Attempt to create ephemeral lock for " + timeToExpire + " seconds - exceeds maximum allowed time.");
    }
    if (lifetime.equals(Lifetime.EPHEMERAL) && (timeToExpire > ephemeralExpiryThreshold)) {
        lifetime = Lifetime.PERSISTENT;
    }
    nodeRef = tenantService.getName(nodeRef);
    // Get the current user name
    String userName = getUserName();
    // Set a default value
    if (lockType == null) {
        lockType = LockType.WRITE_LOCK;
    }
    // Get the current lock info and status for the node ref.
    Pair<LockState, LockStatus> statusAndState = getLockStateAndStatus(nodeRef, userName);
    LockState currentLockInfo = statusAndState.getFirst();
    LockStatus currentLockStatus = statusAndState.getSecond();
    if (LockStatus.LOCKED.equals(currentLockStatus) == true) {
        // Error since we are trying to lock a locked node
        throw new UnableToAquireLockException(nodeRef);
    } else if (LockStatus.NO_LOCK.equals(currentLockStatus) == true || LockStatus.LOCK_EXPIRED.equals(currentLockStatus) == true || LockStatus.LOCK_OWNER.equals(currentLockStatus) == true) {
        final Date expiryDate = makeExpiryDate(timeToExpire);
        // Store the lock in the appropriate place.
        if (lifetime == Lifetime.PERSISTENT) {
            lockableAspectInterceptor.disableForThread();
            try {
                // Add lock aspect if not already present
                ensureLockAspect(nodeRef);
                persistLockProps(nodeRef, lockType, lifetime, userName, expiryDate, additionalInfo);
            } finally {
                lockableAspectInterceptor.enableForThread();
            }
        } else if (lifetime == Lifetime.EPHEMERAL) {
            // Store the lock only in memory.
            LockState lock = LockState.createLock(nodeRef, lockType, userName, expiryDate, lifetime, additionalInfo);
            lockStore.set(nodeRef, lock);
            // Record the NodeRef being locked and its last known lockstate. This allows
            // it to be reverted to this state on rollback.
            TransactionalResourceHelper.getMap(KEY_MODIFIED_NODES).put(nodeRef, currentLockInfo);
            AlfrescoTransactionSupport.bindListener(this);
        } else {
            throw new IllegalStateException(lifetime.getClass().getSimpleName() + " is not a valid value: " + lifetime.toString());
        }
    }
}
Also used : LockStatus(org.alfresco.service.cmr.lock.LockStatus) LockState(org.alfresco.repo.lock.mem.LockState) UnableToAquireLockException(org.alfresco.service.cmr.lock.UnableToAquireLockException) Date(java.util.Date) Extend(org.alfresco.traitextender.Extend)

Example 4 with UnableToAquireLockException

use of org.alfresco.service.cmr.lock.UnableToAquireLockException in project alfresco-repository by Alfresco.

the class LockServiceImplTest method testLock.

/**
 * Test lock
 */
public void testLock() {
    TestWithUserUtils.authenticateUser(GOOD_USER_NAME, PWD, rootNodeRef, this.authenticationService);
    // Check that the node is not currently locked
    assertEquals(LockStatus.NO_LOCK, this.lockService.getLockStatus(this.parentNode));
    assertFalse(lockService.isLocked(parentNode));
    // Test valid lock
    this.lockService.lock(this.parentNode, LockType.WRITE_LOCK);
    assertEquals(LockStatus.LOCK_OWNER, this.lockService.getLockStatus(this.parentNode));
    assertTrue(lockService.isLocked(parentNode));
    // Check that we can retrieve LockState
    LockState lockState = lockService.getLockState(parentNode);
    assertEquals(parentNode, lockState.getNodeRef());
    assertEquals(LockType.WRITE_LOCK, lockState.getLockType());
    assertEquals(GOOD_USER_NAME, lockState.getOwner());
    assertEquals(Lifetime.PERSISTENT, lockState.getLifetime());
    assertEquals(null, lockState.getExpires());
    assertEquals(null, lockState.getAdditionalInfo());
    // Check the correct properties have been set
    Map<QName, Serializable> props = nodeService.getProperties(parentNode);
    assertEquals(GOOD_USER_NAME, props.get(ContentModel.PROP_LOCK_OWNER));
    assertEquals(LockType.WRITE_LOCK.toString(), props.get(ContentModel.PROP_LOCK_TYPE));
    assertEquals(Lifetime.PERSISTENT.toString(), props.get(ContentModel.PROP_LOCK_LIFETIME));
    assertEquals(null, props.get(ContentModel.PROP_EXPIRY_DATE));
    TestWithUserUtils.authenticateUser(BAD_USER_NAME, PWD, rootNodeRef, this.authenticationService);
    assertEquals(LockStatus.LOCKED, this.lockService.getLockStatus(this.parentNode));
    assertTrue(lockService.isLocked(parentNode));
    // Test lock when already locked
    try {
        this.lockService.lock(this.parentNode, LockType.WRITE_LOCK);
        fail("The user should not be able to lock the node since it is already locked by another user.");
    } catch (UnableToAquireLockException exception) {
        System.out.println(exception.getMessage());
    }
    TestWithUserUtils.authenticateUser(GOOD_USER_NAME, PWD, rootNodeRef, this.authenticationService);
    // Test already locked by this user
    try {
        this.lockService.lock(this.parentNode, LockType.WRITE_LOCK);
    } catch (Exception exception) {
        fail("No error should be thrown when a node is re-locked by the current lock owner.");
    }
    // Test with no apect node
    this.lockService.lock(this.noAspectNode, LockType.WRITE_LOCK);
    assertTrue(lockService.isLocked(noAspectNode));
}
Also used : Serializable(java.io.Serializable) QName(org.alfresco.service.namespace.QName) LockState(org.alfresco.repo.lock.mem.LockState) UnableToAquireLockException(org.alfresco.service.cmr.lock.UnableToAquireLockException) NodeLockedException(org.alfresco.service.cmr.lock.NodeLockedException) UnableToReleaseLockException(org.alfresco.service.cmr.lock.UnableToReleaseLockException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) NotSupportedException(javax.transaction.NotSupportedException) UnableToAquireLockException(org.alfresco.service.cmr.lock.UnableToAquireLockException) SystemException(javax.transaction.SystemException)

Aggregations

UnableToAquireLockException (org.alfresco.service.cmr.lock.UnableToAquireLockException)4 LockState (org.alfresco.repo.lock.mem.LockState)3 AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)3 NotSupportedException (javax.transaction.NotSupportedException)2 SystemException (javax.transaction.SystemException)2 NodeLockedException (org.alfresco.service.cmr.lock.NodeLockedException)2 UnableToReleaseLockException (org.alfresco.service.cmr.lock.UnableToReleaseLockException)2 InputStream (java.io.InputStream)1 Serializable (java.io.Serializable)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)1 LockStore (org.alfresco.repo.lock.mem.LockStore)1 LockStatus (org.alfresco.service.cmr.lock.LockStatus)1 FileInfo (org.alfresco.service.cmr.model.FileInfo)1 NodeRef (org.alfresco.service.cmr.repository.NodeRef)1 NodeService (org.alfresco.service.cmr.repository.NodeService)1 QName (org.alfresco.service.namespace.QName)1 Extend (org.alfresco.traitextender.Extend)1 Test (org.junit.Test)1