org.alfresco.util.GUID Java Examples

The following examples show how to use org.alfresco.util.GUID. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseNodeServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 7 votes vote down vote up
/**
 * Tests node creation with a pre-determined {@link ContentModel#PROP_NODE_UUID uuid}.
 */
@Test
public void testCreateNodeWithId() throws Exception
{
    String uuid = GUID.generate();
    // create a node with an explicit UUID
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>(5);
    properties.put(ContentModel.PROP_NODE_UUID, uuid);
    ChildAssociationRef assocRef = nodeService.createNode(
            rootNodeRef,
            ASSOC_TYPE_QNAME_TEST_CHILDREN,
            QName.createQName("pathA"),
            ContentModel.TYPE_CONTAINER,
            properties);
    // check it
    NodeRef expectedNodeRef = new NodeRef(rootNodeRef.getStoreRef(), uuid);
    NodeRef checkNodeRef = assocRef.getChildRef();
    assertEquals("Failed to create node with a chosen ID", expectedNodeRef, checkNodeRef);
}
 
Example #2
Source File: AbstractLuceneIndexerAndSearcherFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 7 votes vote down vote up
@SuppressWarnings("unchecked")
private LuceneIndexer getThreadLocalIndexer(StoreRef storeRef)
{
    Map<StoreRef, LuceneIndexer> indexers = (Map<StoreRef, LuceneIndexer>) AlfrescoTransactionSupport.getResource(indexersKey);
    if (indexers == null)
    {
        indexers = new HashMap<StoreRef, LuceneIndexer>();
        AlfrescoTransactionSupport.bindResource(indexersKey, indexers);
    }
    LuceneIndexer indexer = indexers.get(storeRef);
    if (indexer == null)
    {
        indexer = createIndexer(storeRef, GUID.generate());
        indexers.put(storeRef, indexer);
    }
    return indexer;
}
 
Example #3
Source File: EncodingDAOTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 7 votes vote down vote up
public void testCreateWithRollback() throws Exception
{
    final String encoding = GUID.generate();
    // Create an encoding
    RetryingTransactionCallback<Pair<Long, String>> callback = new RetryingTransactionCallback<Pair<Long, String>>()
    {
        public Pair<Long, String> execute() throws Throwable
        {
            get(encoding, true, true);
            // Now force a rollback
            throw new RuntimeException("Forced");
        }
    };
    try
    {
        txnHelper.doInTransaction(callback);
        fail("Transaction didn't roll back");
    }
    catch (RuntimeException e)
    {
        // Expected
    }
    // Check that it doesn't exist
    get(encoding, false, false);
}
 
Example #4
Source File: SiteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 7 votes vote down vote up
public void testCreateSite() throws Exception
{
    String shortName  = GUID.generate();
    
    // Create a new site
    JSONObject result = createSite("myPreset", shortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 200);        
    assertEquals("myPreset", result.get("sitePreset"));
    assertEquals(shortName, result.get("shortName"));
    assertEquals("myTitle", result.get("title"));
    assertEquals("myDescription", result.get("description"));
    assertNotNull(result.get("node"));
    assertNotNull(result.get("tagScope"));
    assertEquals(SiteVisibility.PUBLIC.toString(), result.get("visibility"));
    assertTrue(result.getBoolean("isPublic"));
    
    // Check for duplicate names
    createSite("myPreset", shortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 400); 
}
 
Example #5
Source File: ScriptNodeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 7 votes vote down vote up
@BeforeClass public static void initStaticData() throws Exception
{
    CONTENT_SERVICE       = APP_CONTEXT_INIT.getApplicationContext().getBean("ContentService", ContentService.class);
    NODE_SERVICE          = APP_CONTEXT_INIT.getApplicationContext().getBean("NodeService", NodeService.class);
    SERVICE_REGISTRY      = APP_CONTEXT_INIT.getApplicationContext().getBean("ServiceRegistry", ServiceRegistry.class);
    TRANSACTION_HELPER    = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);
    PERMISSION_SERVICE    = APP_CONTEXT_INIT.getApplicationContext().getBean("permissionService", PermissionServiceSPI.class);
    SEARCH_SCRIPT         = APP_CONTEXT_INIT.getApplicationContext().getBean("searchScript", Search.class);
    VERSIONABLE_ASPECT    = APP_CONTEXT_INIT.getApplicationContext().getBean("versionableAspect", VersionableAspect.class);
    VERSION_SERVICE       = APP_CONTEXT_INIT.getApplicationContext().getBean("VersionService", VersionService.class);
    DICTIONARY_SERVICE    = APP_CONTEXT_INIT.getApplicationContext().getBean("DictionaryService", DictionaryService.class);       
    NAMESPACE_SERVICE     = APP_CONTEXT_INIT.getApplicationContext().getBean("namespaceService", NamespaceService.class);
    DICTIONARY_DAO        = APP_CONTEXT_INIT.getApplicationContext().getBean("dictionaryDAO", DictionaryDAO.class);
    TENANT_ADMIN_SERVICE  = APP_CONTEXT_INIT.getApplicationContext().getBean("tenantAdminService", TenantAdminService.class);
    MESSAGE_SERVICE       = APP_CONTEXT_INIT.getApplicationContext().getBean("messageService", MessageService.class);
    TRANSACTION_SERVICE   = APP_CONTEXT_INIT.getApplicationContext().getBean("transactionComponent", TransactionService.class);
    POLICY_COMPONENT      = APP_CONTEXT_INIT.getApplicationContext().getBean("policyComponent", PolicyComponent.class);

    USER_ONES_TEST_SITE = STATIC_TEST_SITES.createTestSiteWithUserPerRole(GUID.generate(), "sitePreset", SiteVisibility.PRIVATE, USER_ONE_NAME);
    USER_ONES_TEST_FILE = STATIC_TEST_NODES.createQuickFile(MimetypeMap.MIMETYPE_TEXT_PLAIN, USER_ONES_TEST_SITE.doclib, "test.txt", USER_ONE_NAME);		
}
 
Example #6
Source File: SiteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testDeleteMembership() throws Exception
{
    // Create a site
    String shortName  = GUID.generate();
    createSite("myPreset", shortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 200);
 
    // Build the JSON membership object
    JSONObject membership = new JSONObject();
    membership.put("role", SiteModel.SITE_CONSUMER);
    JSONObject person = new JSONObject();
    person.put("userName", USER_TWO);
    membership.put("person", person);
    
    // Post the membership
    sendRequest(new PostRequest(URL_SITES + "/" + shortName + URL_MEMBERSHIPS, membership.toString(), "application/json"), 200);
    
    // Delete the membership
    sendRequest(new DeleteRequest(URL_SITES + "/" + shortName + URL_MEMBERSHIPS + "/" + USER_TWO), 200);
    
    // Check that the membership has been deleted
    sendRequest(new GetRequest(URL_SITES + "/" + shortName + URL_MEMBERSHIPS + "/" + USER_TWO), 404);
    
}
 
Example #7
Source File: AbstractRenditionIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
NodeRef createContentNodeFromQuickFile(String fileName) throws FileNotFoundException
{
    NodeRef rootNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    NodeRef folderNodeRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(getName() + GUID.generate()),
            ContentModel.TYPE_FOLDER).getChildRef();

    File file = ResourceUtils.getFile("classpath:quick/" + fileName);
    NodeRef contentRef = nodeService.createNode(
            folderNodeRef,
            ContentModel.ASSOC_CONTAINS,
            ContentModel.ASSOC_CONTAINS,
            ContentModel.TYPE_CONTENT,
            Collections.singletonMap(ContentModel.PROP_NAME, fileName))
            .getChildRef();
    ContentWriter contentWriter = contentService.getWriter(contentRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(mimetypeService.guessMimetype(fileName));
    contentWriter.putContent(file);

    return contentRef;
}
 
Example #8
Source File: OnContentUpdateRenditionRoute.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unused")
public OnContentUpdatePolicyEvent createOnContentUpdateEvent(NodeRef sourceNodeRef, boolean newContent)
{
    OnContentUpdatePolicyEvent event = new OnContentUpdatePolicyEvent();

    // Raw event specific
    event.setId(GUID.generate());
    event.setType(EventType.CONTENT_UPDATED.toString());
    event.setAuthenticatedUser(AuthenticationUtil.getFullyAuthenticatedUser());
    event.setExecutingUser(AuthenticationUtil.getRunAsUser());
    event.setTimestamp(System.currentTimeMillis());
    event.setSchema(1);

    // On content update policy event specific
    event.setNodeRef(sourceNodeRef.toString());
    event.setNewContent(newContent);
    return event;
}
 
Example #9
Source File: PutMethodTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testPutContentToAnExistingFile() throws Exception
{
    FileInfo testFileInfo = fileFolderService.create(companyHomeNodeRef, "file-" + GUID.generate(), ContentModel.TYPE_CONTENT);
    try
    {
        executeMethod(WebDAV.METHOD_PUT, testFileInfo.getName(), testDataFile, null);

        assertTrue("File does not exist.", nodeService.exists(testFileInfo.getNodeRef()));
        assertEquals("Filename is not correct.", testFileInfo.getName(), nodeService.getProperty(testFileInfo.getNodeRef(), ContentModel.PROP_NAME));
        assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is " + response.getStatus(),
                HttpServletResponse.SC_NO_CONTENT == response.getStatus());
        InputStream updatedFileIS = fileFolderService.getReader(testFileInfo.getNodeRef()).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()));
    }
    finally
    {
        nodeService.deleteNode(testFileInfo.getNodeRef());
    }
}
 
Example #10
Source File: ContentDataDAOTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testContentUrlCrud() throws Exception
{
    assertNull("Expect null return fetching a URL by ID", contentDataDAO.getContentUrl(0L));
    assertNull("Expect null return fetching a URL", contentDataDAO.getContentUrl("store://someURL"));
    // Update and create
    ContentUrlEntity contentUrlEntity = contentDataDAO.getOrCreateContentUrl("store://" + GUID.generate());
    // Check that it exists, now
    contentUrlEntity = contentDataDAO.getContentUrl(contentUrlEntity.getContentUrl());
    assertNotNull(contentUrlEntity);
    assertNotNull(contentDataDAO.getContentUrl(contentUrlEntity.getId()));

    // test with size
    long size = 100l;
    String url = "store://" + GUID.generate();
    contentUrlEntity = contentDataDAO.getOrCreateContentUrl(url, size);
    contentUrlEntity = contentDataDAO.getContentUrl(contentUrlEntity.getContentUrl());
    assertNotNull(contentUrlEntity);
    assertNotNull(contentDataDAO.getContentUrl(contentUrlEntity.getId()));
    assertEquals("The size does not match.", size, contentUrlEntity.getSize());
    assertEquals("The content URL does not match.", url, contentUrlEntity.getContentUrl());
}
 
Example #11
Source File: UpdateRepoEventIT.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testCreateAndUpdateInTheSameTransaction()
{
    retryingTransactionHelper.doInTransaction(() -> {

        NodeRef node1 = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(TEST_NAMESPACE, GUID.generate()),
            ContentModel.TYPE_CONTENT).getChildRef();

        nodeService.setProperty(node1, ContentModel.PROP_DESCRIPTION, "test description");
        return null;
    });
    //Create and update node are done in the same transaction so one event is expected
    // to be generated
    checkNumOfEvents(1);
}
 
Example #12
Source File: MimetypeDAOTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testUpdate() throws Exception
{
    final String oldMimetype = GUID.generate();
    final String newMimetype = GUID.generate();
    Pair<Long, String> oldMimetypePair = get(oldMimetype, true, true);
    // Update it
    RetryingTransactionCallback<Pair<Long, String>> callback = new RetryingTransactionCallback<Pair<Long, String>>()
    {
        public Pair<Long, String> execute() throws Throwable
        {
            int count = mimetypeDAO.updateMimetype(oldMimetype, newMimetype);
            assertEquals("Incorrect number updated", 1, count);
            return mimetypeDAO.getMimetype(newMimetype);
        }
    };
    Pair<Long, String> newMimetypePair = txnHelper.doInTransaction(callback, false, false);
    // Check
    assertEquals("ID should remain the same if the old mimetype existed",
            oldMimetypePair.getFirst(), newMimetypePair.getFirst());
    get(oldMimetype, false, false);
    get(newMimetype, false, true);
}
 
Example #13
Source File: EnterpriseWorkflowTestApi.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected NodeRef[] createTestDocuments(final RequestContext requestContext) {
    NodeRef[] docNodeRefs = TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef[]>()
    {
        @Override
        public NodeRef[] doWork() throws Exception
        {
            String siteName = "site" + GUID.generate();
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
            TestSite site = currentNetwork.createSite(siteInfo);
            NodeRef nodeRefDoc1 = getTestFixture().getRepoService().createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc1", "Test Doc1 Title", "Test Doc1 Description", "Test Content");
            NodeRef nodeRefDoc2 = getTestFixture().getRepoService().createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc2", "Test Doc2 Title", "Test Doc2 Description", "Test Content");
            
            NodeRef[] result = new NodeRef[2];
            result[0] = nodeRefDoc1;
            result[1] = nodeRefDoc2;
            
            return result;
        }
    }, requestContext.getRunAsUser(), requestContext.getNetworkId());
    
    return docNodeRefs;
}
 
Example #14
Source File: AggregatingContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void before() throws Exception
{
    File tempDir = TempFileProvider.getTempDir();
    // create a primary file store
    String storeDir = tempDir.getAbsolutePath() + File.separatorChar + GUID.generate();
    primaryStore = new FileContentStore(ctx, storeDir);
    // create some secondary file stores
    secondaryStores = new ArrayList<ContentStore>(3);
    for (int i = 0; i < 4; i++)
    {
        storeDir = tempDir.getAbsolutePath() + File.separatorChar + GUID.generate();
        FileContentStore store = new FileContentStore(ctx, storeDir);
        secondaryStores.add(store);
    }
    // Create the aggregating store
    aggregatingStore = new AggregatingContentStore();
    aggregatingStore.setPrimaryStore(primaryStore);
    aggregatingStore.setSecondaryStores(secondaryStores);
}
 
Example #15
Source File: CannedQueryDAOTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@BeforeClass public static void setup() throws Exception
{

    ServiceRegistry serviceRegistry = (ServiceRegistry) APP_CONTEXT_INIT.getApplicationContext().getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
    txnHelper = transactionService.getRetryingTransactionHelper();
    
    cannedQueryDAO = (CannedQueryDAO) APP_CONTEXT_INIT.getApplicationContext().getBean("cannedQueryDAO");
    cannedQueryDAOForTesting = (CannedQueryDAO) APP_CONTEXT_INIT.getApplicationContext().getBean("cannedQueryDAOForTesting");
    mimetypeDAO = (MimetypeDAO) APP_CONTEXT_INIT.getApplicationContext().getBean("mimetypeDAO");

    RetryingTransactionCallback<String> createMimetypeCallback = new RetryingTransactionCallback<String>()
    {
        @Override
        public String execute() throws Throwable
        {
            String mimetypePrefix = GUID.generate();
            mimetypeDAO.getOrCreateMimetype(mimetypePrefix + "-aaa");
            mimetypeDAO.getOrCreateMimetype(mimetypePrefix + "-bbb");
            return mimetypePrefix;
        }
    };
    mimetypePrefix = txnHelper.doInTransaction(createMimetypeCallback);
}
 
Example #16
Source File: DbNodeServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @throws UnsupportedOperationException        Always
 */
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public void deleteStore(StoreRef storeRef) throws InvalidStoreRefException
{
    // Cannot delete the root node but we can delete, without archive, all immediate children
    NodeRef rootNodeRef = nodeDAO.getRootNode(storeRef).getSecond();
    List<ChildAssociationRef> childAssocRefs = getChildAssocs(rootNodeRef);
    for (ChildAssociationRef childAssocRef : childAssocRefs)
    {
        NodeRef childNodeRef = childAssocRef.getChildRef();
        // We do NOT want to archive these, so mark them as temporary
        deleteNode(childNodeRef, false);
    }
    // Rename the store.  This takes all the nodes with it.
    StoreRef deletedStoreRef = new StoreRef(StoreRef.PROTOCOL_DELETED, GUID.generate());
    nodeDAO.moveStore(storeRef, deletedStoreRef);
    
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug("Marked store for deletion: " + storeRef + " --> " + deletedStoreRef);
    }
}
 
Example #17
Source File: CompositePasswordEncoderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testUserChain() throws Exception
{
    String rawPassword = "[email protected]";
    String salt = GUID.generate();

    ShaPasswordEncoderImpl sha = new ShaPasswordEncoderImpl(256);
    String shaEncoded = sha.encodePassword(rawPassword, salt);
    assertTrue(encoder.matches("sha256", rawPassword, shaEncoded, salt));

    List<String> nowHashed = new ArrayList<String>();
    nowHashed.add("sha256");
    nowHashed.add("bcrypt10");
    String nowEncoded = encoder.encode("bcrypt10", shaEncoded, salt);
    String nowEncoded2 = encoder.encode("bcrypt10", shaEncoded, salt);
    String nowEncoded3 = encoder.encode("bcrypt10", shaEncoded, salt);
    assertTrue(encoder.matchesPassword(rawPassword, nowEncoded, salt, nowHashed));
    assertTrue(encoder.matchesPassword(rawPassword, nowEncoded2, salt, nowHashed));
    assertTrue(encoder.matchesPassword(rawPassword, nowEncoded3, salt, nowHashed));
}
 
Example #18
Source File: ChainingUserRegistrySynchronizerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Iterator<NodeDescription> iterator()
{
    return new Iterator<NodeDescription>()
    {

        private int pos;

        public boolean hasNext()
        {
            return this.pos < RandomPersonCollection.this.size;
        }

        public NodeDescription next()
        {
            this.pos++;
            return newPerson("U" + GUID.generate());
        }

        public void remove()
        {
            throw new UnsupportedOperationException();
        }
    };

}
 
Example #19
Source File: TaggingServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
@Category({RedundantTests.class,LuceneTests.class})
public void testPagedTags() throws UnsupportedEncodingException
{
    authenticationComponent.setSystemUserAsCurrentUser();
    Pair<List<String>, Integer> tags = taggingService.getPagedTags(storeRef, 1, 10);
    assertNotNull(tags);
    PagingResults<Pair<NodeRef, String>> res = taggingService.getTags(storeRef, new PagingRequest(10));
    assertNotNull(res);


    String guid = GUID.generate();
    // Create a node
    Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1);
    String docName = "testDocument" + guid + ".txt";
    docProps.put(ContentModel.PROP_NAME, docName);
    NodeRef myDoc = nodeService.createNode(
            folder,
            ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, docName),
            ContentModel.TYPE_CONTENT,
            docProps).getChildRef();
    taggingService.addTag(myDoc,"dog");

    res = taggingService.getTags(myDoc, new PagingRequest(10));
    assertNotNull(res);
    assertTrue(res.getTotalResultCount().getFirst() == 1);
}
 
Example #20
Source File: SiteServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testGetSite() throws Exception
{
    // Get a site that doesn't exist
    sendRequest(new GetRequest(URL_SITES + "/" + "somerandomshortname"), 404);
    
    // Create a site and get it
    String shortName  = GUID.generate();
    createSite("myPreset", shortName, "myTitle", "myDescription", SiteVisibility.PUBLIC, 200);
    sendRequest(new GetRequest(URL_SITES + "/" + shortName), 200);
   
}
 
Example #21
Source File: FacetRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** The REST API should accept both 'cm:name' and '{http://www.alfresco.org/model/content/1.0}name' forms of filter IDs. */
public void testCreateFacetWithLongFormQnameFilterId() throws Exception
{
    final JSONObject filter = new JSONObject();
    final String filterName = "filter" + GUID.generate();
    filters.add(filterName);
    filter.put("filterID", filterName);
    // This is the long-form qname that needs to be acceptable.
    filter.put("facetQName", "{http://www.alfresco.org/model/content/1.0}testLongQname");
    filter.put("displayName", "facet-menu.facet.testLongQname");
    filter.put("displayControl", "alfresco/search/FacetFilters/testLongQname");
    filter.put("maxFilters", 5);
    filter.put("hitThreshold", 1);
    filter.put("minFilterValueLength", 4);
    filter.put("sortBy", "ALPHABETICALLY");
    
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            // Post the filter
            sendRequest(new PostRequest(POST_FACETS_URL, filter.toString(), "application/json"), 200);
            return null;
        }
    }, SEARCH_ADMIN_USER);
}
 
Example #22
Source File: RepoTransferReceiverImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @return
 */
private TransferManifestNormalNode createContentNode(/*String transferId*/) throws Exception
{
    TransferManifestNormalNode node = new TransferManifestNormalNode();
    String uuid = GUID.generate();
    NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, uuid);
    node.setNodeRef(nodeRef);
    node.setUuid(uuid);
    byte[] dummyContent = "This is some dummy content.".getBytes("UTF-8");

    node.setType(ContentModel.TYPE_CONTENT);
    
    /**
     * Get guest home
     */
    NodeRef parentFolder = guestHome;

    String nodeName = uuid + ".testnode" + getNameSuffix();

    List<ChildAssociationRef> parents = new ArrayList<ChildAssociationRef>();
    ChildAssociationRef primaryAssoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, parentFolder, QName
            .createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName), node.getNodeRef(), true, -1);
    parents.add(primaryAssoc);
    node.setParentAssocs(parents);
    node.setParentPath(nodeService.getPath(parentFolder));
    node.setPrimaryParentAssoc(primaryAssoc);

    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NODE_UUID, uuid);
    props.put(ContentModel.PROP_NAME, nodeName);
    ContentData contentData = new ContentData("/" + uuid, "text/plain", dummyContent.length, "UTF-8");
    props.put(ContentModel.PROP_CONTENT, contentData);
    node.setProperties(props);

    return node;
}
 
Example #23
Source File: StandardQuotaStrategyTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private File createFileOfSize(long sizeInKB) throws IOException
{
    File file = new File(TempFileProvider.getSystemTempDir(), GUID.generate() + ".generated");
    file.deleteOnExit();
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
    for (long i = 0; i < sizeInKB; i++)
    {
        os.write(aKB);
    }
    os.close();
    
    return file;
}
 
Example #24
Source File: DiscussionRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for <a href=https://issues.alfresco.com/jira/browse/MNT-11964>MNT-11964</a>
 * @throws Exception 
 */
public void testCreateForumPermission() throws Exception
{
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    
    String siteName = SITE_SHORT_NAME_DISCUSSION + GUID.generate();
    this.siteService.createSite("ForumSitePreset", siteName, "SiteTitle", "SiteDescription", SiteVisibility.PUBLIC);
    
    String userName = USER_ONE + GUID.generate();
    createUser(userName, SiteModel.SITE_COLLABORATOR, siteName);

    // Check permissions for admin
    checkForumPermissions(siteName);
    
    // Check permissions for user
    this.authenticationComponent.setCurrentUser(userName);
    checkForumPermissions(siteName);

    // Cleanup
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    this.siteService.deleteSite(siteName);
    
    // Create a new site as user
    this.authenticationComponent.setCurrentUser(userName);
    siteName = SITE_SHORT_NAME_DISCUSSION + GUID.generate();
    this.siteService.createSite("BlogSitePreset", siteName, "SiteTitle", "SiteDescription", SiteVisibility.PUBLIC);
    
    // Check permissions for user
    checkForumPermissions(siteName);
    
    // Check permissions for admin
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    checkForumPermissions(siteName);
    
    // Cleanup
    this.siteService.deleteSite(siteName);
    this.personService.deletePerson(userName);
}
 
Example #25
Source File: GroupsTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Group generateGroup()
{
    Group group = new Group();
    group.setId("TST" + GUID.generate());

    return group;
}
 
Example #26
Source File: AbstractContextAwareRepoEvent.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected NodeRef createNode(QName contentType, PropertyMap propertyMap)
{
    return retryingTransactionHelper.doInTransaction(() -> nodeService.createNode(
        rootNodeRef,
        ContentModel.ASSOC_CHILDREN,
        QName.createQName(TEST_NAMESPACE, GUID.generate()),
        contentType,
        propertyMap).getChildRef());
}
 
Example #27
Source File: EncryptionKeysRegistryImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void registerKey(String keyAlias, Key key)
{
    if(isKeyRegistered(keyAlias))
    {
        throw new IllegalArgumentException("Key " + keyAlias + " is already registered");
    }

    // register the key by creating an attribute that stores a guid and its encrypted value
    String guid = GUID.generate();

    KeyMap keys = new KeyMap();
    keys.setKey(keyAlias, key);
    Encryptor encryptor = getEncryptor(keys);
    Serializable encrypted = encryptor.sealObject(keyAlias, null, guid);
    Pair<String, Serializable> keyCheck = new Pair<String, Serializable>(guid, encrypted);
    RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
    final RetryingTransactionCallback<Void> createAttributeCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
        	attributeService.createAttribute(keyCheck, TOP_LEVEL_KEY, keyAlias);
            return null;
        }
    };
    retryingTransactionHelper.doInTransaction(createAttributeCallback, false);

    logger.info("Registered key " + keyAlias);
}
 
Example #28
Source File: LinksRestApiTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for <a href=https://issues.alfresco.com/jira/browse/MNT-11964>MNT-11964</a>
 * @throws Exception 
 */
public void testCreateLinkPermission() throws Exception
{
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    
    String siteName = SITE_SHORT_NAME_LINKS + GUID.generate();
    this.siteService.createSite("LinkSitePreset", siteName, "SiteTitle", "SiteDescription", SiteVisibility.PUBLIC);
    
    String userName = USER_ONE + GUID.generate();
    createUser(userName, SiteModel.SITE_COLLABORATOR, siteName);

    // Check permissions for admin
    checkLinkPermissions(siteName);
    
    // Check permissions for user
    this.authenticationComponent.setCurrentUser(userName);
    checkLinkPermissions(siteName);

    // Cleanup
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    this.siteService.deleteSite(siteName);
    
    // Create a new site as user
    this.authenticationComponent.setCurrentUser(userName);
    siteName = SITE_SHORT_NAME_LINKS + GUID.generate();
    this.siteService.createSite("LinkSitePreset", siteName, "SiteTitle", "SiteDescription", SiteVisibility.PUBLIC);
    
    // Check permissions for user
    checkLinkPermissions(siteName);
    
    // Check permissions for admin
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    checkLinkPermissions(siteName);
    
    // Cleanup
    this.siteService.deleteSite(siteName);
    this.personService.deletePerson(userName);
}
 
Example #29
Source File: SerializeTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testSerializeCustom() throws IOException
{
    assertNotNull(helper);
    String uuid = GUID.generate();
    String out = writeResponse(uuid);
    NodeRef n = jsonHelper.construct(new StringReader(out),NodeRef.class);
    assertNotNull(n);
    assertEquals(uuid, n.getId());
}
 
Example #30
Source File: SiteServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 *  From MNT-14452, insure that GROUP_EVERYONE have read access to public sites' containers.
 */
@Test
public void testChangeSiteVisibility()
{
    String siteName = GUID.generate();
    
    //Check Private->public
    SiteInfo siteInfo = createSite(siteName, "doclib", SiteVisibility.PRIVATE);

    NodeRef container = this.siteService.getContainer(siteInfo.getShortName(), "doclib");

    siteInfo.setVisibility(SiteVisibility.PUBLIC);
    siteService.updateSite(siteInfo);

    assertTrue(getAllowedPermissionsMap(container).get(PermissionService.ALL_AUTHORITIES).contains("ReadPermissions"));

    //Check public->moderated
    siteInfo.setVisibility(SiteVisibility.MODERATED);
    siteService.updateSite(siteInfo);

    assertNull("GROUP_EVERYONE shouldn't have any permissions on a moderated site's containers", getAllowedPermissionsMap(container).get(PermissionService.ALL_AUTHORITIES));

    //Check moderated->public
    siteInfo.setVisibility(SiteVisibility.PUBLIC);
    siteService.updateSite(siteInfo);

    assertTrue(getAllowedPermissionsMap(container).get(PermissionService.ALL_AUTHORITIES).contains("ReadPermissions"));
    
    //Check public->private
    siteInfo.setVisibility(SiteVisibility.PRIVATE);
    siteService.updateSite(siteInfo);

    assertNull("GROUP_EVERYONE shouldn't have any permissions on a moderated site's containers", getAllowedPermissionsMap(container).get(PermissionService.ALL_AUTHORITIES));        

}