org.apache.chemistry.opencmis.client.api.Session Java Examples

The following examples show how to use org.apache.chemistry.opencmis.client.api.Session. 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: TestRemovePermissions.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected Session getATOMPUB_11_Session()
{
    try
    {
        Map<String, String> parameters = new HashMap<String, String>();
        int port = getTestFixture().getJettyComponent().getPort();

        parameters.put(SessionParameter.USER, ADMIN_USER);
        parameters.put(SessionParameter.PASSWORD, ADMIN_PASSWORD);
        parameters.put(SessionParameter.ATOMPUB_URL, MessageFormat.format(ATOMPUB_URL_11, DEFAULT_HOSTNAME, String.valueOf(port)));
        parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());

        SessionFactory sessionFactory = SessionFactoryImpl.newInstance();

        parameters.put(SessionParameter.REPOSITORY_ID, sessionFactory.getRepositories(parameters).get(0).getId());
        return sessionFactory.createSession(parameters);
    }
    catch (Exception ex)
    {
        logger.error(ex);

    }
    return null;
}
 
Example #2
Source File: CmisIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private void deleteAllContent() {
    Session session = createSession();
    Folder rootFolder = session.getRootFolder();
    ItemIterable<CmisObject> children = rootFolder.getChildren();
    for (CmisObject cmisObject : children) {
        if ("cmis:folder".equals(cmisObject.getPropertyValue(PropertyIds.OBJECT_TYPE_ID))) {
            List<String> notDeltedIdList = ((Folder)cmisObject)
                    .deleteTree(true, UnfileObject.DELETE, true);
            if (notDeltedIdList != null && notDeltedIdList.size() > 0) {
                throw new RuntimeException("Cannot empty repo");
            }
        } else {
            cmisObject.delete(true);
        }
    }
    session.getBinding().close();
}
 
Example #3
Source File: TestRemovePermissions.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected Session getATOMPUB_10_Session()
{
    try
    {
        Map<String, String> parameters = new HashMap<String, String>();
        int port = getTestFixture().getJettyComponent().getPort();

        parameters.put(SessionParameter.USER, ADMIN_USER);
        parameters.put(SessionParameter.PASSWORD, ADMIN_PASSWORD);
        parameters.put(SessionParameter.ATOMPUB_URL, MessageFormat.format(ATOMPUB_URL_OC, DEFAULT_HOSTNAME, String.valueOf(port)));
        parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());

        SessionFactory sessionFactory = SessionFactoryImpl.newInstance();

        parameters.put(SessionParameter.REPOSITORY_ID, sessionFactory.getRepositories(parameters).get(0).getId());
        return sessionFactory.createSession(parameters);
    }
    catch (Exception ex)
    {
        logger.error(ex);
    }
    return null;
}
 
Example #4
Source File: TestRemovePermissions.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected Session getBROWSER_11_Session()
{
    try
    {
        Map<String, String> parameter = new HashMap<String, String>();
        int port = getTestFixture().getJettyComponent().getPort();

        parameter.put(SessionParameter.BINDING_TYPE, BindingType.BROWSER.value());
        parameter.put(SessionParameter.BROWSER_URL, MessageFormat.format(BROWSE_URL_11, DEFAULT_HOSTNAME, String.valueOf(port)));
        parameter.put(SessionParameter.COOKIES, "true");

        parameter.put(SessionParameter.USER, ADMIN_USER);
        parameter.put(SessionParameter.PASSWORD, ADMIN_PASSWORD);

        SessionFactory sessionFactory = SessionFactoryImpl.newInstance();

        parameter.put(SessionParameter.REPOSITORY_ID, sessionFactory.getRepositories(parameter).get(0).getId());
        return sessionFactory.createSession(parameter);
    }
    catch (Exception ex)
    {
        logger.error(ex);

    }
    return null;
}
 
Example #5
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Document createDocument(Folder target, String newDocName, Session session)
{
    Map<String, String> props = new HashMap<String, String>();
    props.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
    props.put(PropertyIds.NAME, newDocName);
    String content = "aegif Mind Share Leader Generating New Paradigms by aegif corporation.";
    byte[] buf = null;
    try
    {
        buf = content.getBytes("ISO-8859-1"); // set the encoding here for the content stream
    }
    catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }

    ByteArrayInputStream input = new ByteArrayInputStream(buf);

    ContentStream contentStream = session.getObjectFactory().createContentStream(newDocName, buf.length,
            "text/plain; charset=UTF-8", input); // additionally set the charset here
    // NOTE that we intentionally specified the wrong charset here (as UTF-8)
    // because Alfresco does automatic charset detection, so we will ignore this explicit request
    return target.createDocument(props, contentStream, VersioningState.MAJOR);
}
 
Example #6
Source File: CMISDataCreatorTest.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Session getSession(String user, String pwd)
{
    String url = "http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom";
    
    SessionFactory factory = SessionFactoryImpl.newInstance();
    Map<String, String> parameter = new HashMap<String, String>();
    parameter.put(SessionParameter.USER, user);
    parameter.put(SessionParameter.PASSWORD, pwd);
    parameter.put(SessionParameter.ATOMPUB_URL, url);
    parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
    
    List<Repository> repositories = factory.getRepositories(parameter);
    Session session = repositories.get(0).createSession();
    
    return session;
}
 
Example #7
Source File: TestRemovePermissions.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param session Session
 * @return List<Ace>
 */
private List<Ace> create2TestACLs(Session session)
{
    List<Ace> newACE = new ArrayList<Ace>();
    LinkedList<String> permissions1 = new LinkedList<String>();
    permissions1.add("{http://www.alfresco.org/model/system/1.0}base.ReadPermissions");

    LinkedList<String> permissions2 = new LinkedList<String>();
    permissions2.add("{http://www.alfresco.org/model/system/1.0}base.Unlock");

    Ace ace1 = session.getObjectFactory().createAce("testUser1", permissions1);
    Ace ace2 = session.getObjectFactory().createAce("testUser2", permissions2);
    newACE.add(ace1);
    newACE.add(ace2);
    return newACE;

}
 
Example #8
Source File: PublicApiClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Create a CMIS session using Enterprise AtomPub binding.
 *
 * @param repositoryId String
 * @param username String
 * @param password String
 * @return CmisSession
 */
public CmisSession createCMISSession(String repositoryId, String username, String password)
{
    // default factory implementation
    SessionFactory factory = SessionFactoryImpl.newInstance();
    Map<String, String> parameters = new HashMap<String, String>();

    // user credentials
    parameters.put(SessionParameter.USER, username);
    parameters.put(SessionParameter.PASSWORD, password);

    // connection settings
    parameters.put(SessionParameter.ATOMPUB_URL, client.getCmisUrl(repositoryId, null));
    parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
    if(repositoryId != null)
    {
        parameters.put(SessionParameter.REPOSITORY_ID, repositoryId);
    }
    parameters.put(SessionParameter.OBJECT_FACTORY_CLASS, AlfrescoObjectFactoryImpl.class.getName());

    // create session
    Session session = factory.createSession(parameters);

    CmisSession cmisSession = new CmisSession(session);
    return cmisSession;
}
 
Example #9
Source File: PublicApiClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public FolderNode getDescendants(String folderId, int depth)
{
    Session session = getCMISSession();

    CmisObject o = session.getObject(folderId);
    if(o instanceof Folder)
    {
        Folder f = (Folder)o;

        OperationContextImpl ctx = new OperationContextImpl();
        List<Tree<FileableCmisObject>> res = f.getDescendants(depth, ctx);
        FolderNode ret = (FolderNode)CMISNode.createNode(f);
        for(Tree<FileableCmisObject> t : res)
        {
            addChildren(ret, t);
        }

        return ret;
    }
    else
    {
        throw new IllegalArgumentException("Folder does not exist or is not a folder");
    }
}
 
Example #10
Source File: CmisServiceImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
@HasPermission(type = DefaultPermission.class, action = "clone_content_cmis")
public void cloneContent(@ProtectedResourceId(SITE_ID_RESOURCE_ID) String siteId, String cmisRepoId, String cmisPath,
                         @ProtectedResourceId(PATH_RESOURCE_ID) String studioPath)
        throws StudioPathNotFoundException, CmisRepositoryNotFoundException, CmisUnavailableException, CmisTimeoutException, CmisPathNotFoundException, ServiceLayerException {
    if (!contentService.contentExists(siteId, studioPath))
        throw new StudioPathNotFoundException("Studio repository path does not exist for site " + siteId +
                " (path: " + studioPath + ")");
    List<CmisContentItemTO> toRet = new ArrayList<CmisContentItemTO>();
    DataSourceRepository repositoryConfig = getConfiguration(siteId, cmisRepoId);
    if (repositoryConfig != null) {
        logger.debug("Create new CMIS session");
        Session session = createCMISSession(repositoryConfig);
        if (session != null) {
            String contentPath = Paths.get(repositoryConfig.getBasePath(), cmisPath).toString();
            logger.debug("Find object for CMIS path: " + contentPath);
            CmisObject cmisObject = session.getObjectByPath(contentPath);
            if (cmisObject != null) {
                if (BaseTypeId.CMIS_FOLDER.equals(cmisObject.getBaseTypeId())) {
                    throw new CmisPathNotFoundException();
                } else if (CMIS_DOCUMENT.equals(cmisObject.getBaseTypeId())) {
                    org.apache.chemistry.opencmis.client.api.Document cmisDoc =
                            (org.apache.chemistry.opencmis.client.api.Document)cmisObject;
                    String fileName = cmisDoc.getName();
                    String savePath = studioPath + FILE_SEPARATOR + fileName;
                    ContentStream cs = cmisDoc.getContentStream();
                    logger.debug("Save CMIS file to: " + savePath);
                    contentService.writeContent(siteId, savePath, cs.getStream());
                }
            } else {
                throw new CmisPathNotFoundException();
            }
        } else {
            throw new CmisUnauthorizedException();
        }
    }
}
 
Example #11
Source File: TestRemovePermissions.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param session Session
 * @param name String
 * @return Folder
 */
private Folder createFolder(Session session, String name)
{
    Folder testFolder;
    Folder folder = session.getRootFolder();
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
    properties.put(PropertyIds.NAME, name);

    testFolder = folder.createFolder(properties);

    return testFolder;
}
 
Example #12
Source File: CMISSessionHelper.java    From cloud-espm-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to return the {@link Session} used to connect to the
 * document repository. If connection to the document repository was not
 * possible, then a <b> null </b> object is returned.
 * 
 * @return
 */
public Session getSession() {
	/*
	 * if (helper == null) { helper = new CMISSessionHelper(); }
	 */

	return openCmisSession;
}
 
Example #13
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testDownloadEvent() throws InterruptedException
{
    Repository repository = getRepository("admin", "admin");
    Session session = repository.createSession();
    Folder rootFolder = session.getRootFolder();
    String docname = "mydoc-" + GUID.generate() + ".txt";
    Map<String, String> props = new HashMap<String, String>();
    {
        props.put(PropertyIds.OBJECT_TYPE_ID, "D:cmiscustom:document");
        props.put(PropertyIds.NAME, docname);
    }
    
    // content
    byte[] byteContent = "Hello from Download testing class".getBytes();
    InputStream stream = new ByteArrayInputStream(byteContent);
    ContentStream contentStream = new ContentStreamImpl(docname, BigInteger.valueOf(byteContent.length), "text/plain", stream);

    Document doc1 = rootFolder.createDocument(props, contentStream, VersioningState.MAJOR);
    NodeRef doc1NodeRef = cmisIdToNodeRef(doc1.getId());
    
    ContentStream content = doc1.getContentStream();
    assertNotNull(content);
    
    //range request
    content = doc1.getContentStream(BigInteger.valueOf(2),BigInteger.valueOf(4));
    assertNotNull(content);
}
 
Example #14
Source File: CmisSessionBuilder.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static String getRepositoryInfo(Session cmisSession) {
	RepositoryInfo ri = cmisSession.getRepositoryInfo();
	String id = ri.getId();
	String productName = ri.getProductName();
	String productVersion = ri.getProductVersion();
	String cmisVersion = ri.getCmisVersion().value();
	return "id [" + id + "] cmis version [" + cmisVersion + "] product ["
			+ productName + "] version [" + productVersion + "]";
}
 
Example #15
Source File: CmisSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a session during JMV runtime, tries to retrieve parameters and falls back on the defaults when they can't be found
 * @param pvl TODO
 */
public Session createCmisSession(ParameterValueList pvl) throws SenderException {
	String authAlias_work = null;
	String userName_work = null;
	String password_work = null;

	if (pvl != null) {
		ParameterValue pv = pvl.getParameterValue("authAlias");
		if (pv != null) {
			authAlias_work = (String) pv.getValue();
		}
		pv = pvl.getParameterValue("userName");
		if (pv != null) {
			userName_work = (String) pv.getValue();
		}
		pv = pvl.getParameterValue("password");
		if (pv != null) {
			password_work = (String) pv.getValue();
		}
	}

	if (authAlias_work == null) {
		authAlias_work = getAuthAlias();
	}
	if (userName_work == null) {
		userName_work = getUserName();
	}
	if (password_work == null) {
		password_work = getPassword();
	}

	CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work);
	try {
		return getSessionBuilder().build(cf.getUsername(), cf.getPassword());
	}
	catch (CmisSessionException e) {
		throw new SenderException(e);
	}
}
 
Example #16
Source File: TestCreateAction.java    From iaf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
	@Override
	public CmisSender createSender() throws ConfigurationException {
		CmisSender sender = spy(new CmisSender());

		sender.setUrl("http://dummy.url");
		sender.setRepository("dummyRepository");
		sender.setUsername("test");
		sender.setPassword("test");
		sender.setKeepSession(false);

		Session cmisSession = mock(Session.class);
		ObjectFactory objectFactory = mock(ObjectFactoryImpl.class);
		doReturn(objectFactory).when(cmisSession).getObjectFactory();

//			GENERIC cmis object
		ObjectId objectId = mock(ObjectIdImpl.class);
		doReturn(objectId).when(cmisSession).createObjectId(anyString());
		CmisObject cmisObject = spy(new CmisTestObject());
		doReturn(cmisObject).when(cmisSession).getObject(any(ObjectId.class));
		doReturn(cmisObject).when(cmisSession).getObject(any(ObjectId.class), any(OperationContext.class));
		
//			CREATE
		Folder folder = mock(FolderImpl.class);
		doReturn(cmisObject).when(folder).createDocument(anyMap(), any(ContentStreamImpl.class), any(VersioningState.class));
		doReturn(folder).when(cmisSession).getRootFolder();
		doReturn(objectId).when(cmisSession).createDocument(anyMap(), any(ObjectId.class), any(ContentStreamImpl.class), any(VersioningState.class));
		doReturn("dummy_id").when(objectId).getId();
		
		try {
			doReturn(cmisSession).when(sender).createCmisSession(any(ParameterValueList.class));
		} catch (SenderException e) {
			//Since we stub the entire session it won't throw exceptions
		}

		return sender;
	}
 
Example #17
Source File: CmisIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private Session createSession() {
    SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
    Map<String, String> parameter = new HashMap<String, String>();
    parameter.put(SessionParameter.ATOMPUB_URL, "http://127.0.0.1:8080/chemistry-opencmis-server-inmemory/atom11/atom11");
    parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
    Repository repository = sessionFactory.getRepositories(parameter).get(0);
    return repository.createSession();
}
 
Example #18
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void DISABLED_testBasicFileOps()
{
    Repository repository = getRepository("admin", "admin");
    Session session = repository.createSession();
    Folder rootFolder = session.getRootFolder();
    // create folder
    Map<String,String> folderProps = new HashMap<String, String>();
    {
        folderProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
        folderProps.put(PropertyIds.NAME, getName() + "-" + GUID.generate());
    }
    Folder folder = rootFolder.createFolder(folderProps, null, null, null, session.getDefaultContext());
    
    Map<String, String> fileProps = new HashMap<String, String>();
    {
        fileProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
        fileProps.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
    }
    ContentStreamImpl fileContent = new ContentStreamImpl();
    {
        ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(getName(), ".txt"));
        writer.putContent("Ipsum and so on");
        ContentReader reader = writer.getReader();
        fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        fileContent.setStream(reader.getContentInputStream());
    }
    folder.createDocument(fileProps, fileContent, VersioningState.MAJOR);
}
 
Example #19
Source File: AbstractE2EFunctionalTest.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
private FileModel getCustomModel(String fileName)
{
    FileModel customModel = null;

    try
    {
        if ((fileName != null) && (fileName.endsWith("-model.xml")))

        {
            Session session = contentService.getCMISSession(dataUser.getAdminUser().getUsername(), dataUser.getAdminUser().getPassword());

            CmisObject modelInRepo = session.getObjectByPath(String.format("/Data Dictionary/Models/%s", fileName));

            if (modelInRepo != null)
            {
                customModel = new FileModel(modelInRepo.getName());
                customModel.setNodeRef(modelInRepo.getId());
                customModel.setNodeRef(customModel.getNodeRefWithoutVersion());
                customModel.setCmisLocation(String.format("/Data Dictionary/Models/%s", fileName));
                LOGGER.info("Custom Model file: " + customModel.getCmisLocation());
            }
            else
            {
                LOGGER.info("Custom Content Model [{}] is not available under [/Data Dictionary/Models/] location", fileName);
            }
        }
    }
    catch (Exception e)
    {
        LOGGER.warn("Error Getting Custom Model: " + fileName, e);
    }

    return customModel;
}
 
Example #20
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testEncodingForCreateContentStream()
{
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    FileFolderService ffs = serviceRegistry.getFileFolderService();
    // Authenticate as system
    AuthenticationComponent authenticationComponent = (AuthenticationComponent) ctx
            .getBean(BEAN_NAME_AUTHENTICATION_COMPONENT);
    authenticationComponent.setSystemUserAsCurrentUser();
    try
    {
        /* Create the document using openCmis services */
        Repository repository = getRepository("admin", "admin");
        Session session = repository.createSession();
        Folder rootFolder = session.getRootFolder();
        Document document = createDocument(rootFolder, "test_file_" + GUID.generate() + ".txt", session);

        ContentStream content = document.getContentStream();
        assertNotNull(content);

        content = document.getContentStream(BigInteger.valueOf(2), BigInteger.valueOf(4));
        assertNotNull(content);

        NodeRef doc1NodeRef = cmisIdToNodeRef(document.getId());
        FileInfo fileInfo = ffs.getFileInfo(doc1NodeRef);
        Map<QName, Serializable> properties = fileInfo.getProperties();
        ContentDataWithId contentData = (ContentDataWithId) properties
                .get(QName.createQName("{http://www.alfresco.org/model/content/1.0}content"));
        String encoding = contentData.getEncoding();

        assertEquals("ISO-8859-1", encoding);
    }
    finally
    {
        authenticationComponent.clearCurrentSecurityContext();
    }
}
 
Example #21
Source File: CMISDataCreatorTest.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testCreate()
{
    Session session = getSession("admin", "admin");
    
    String folderName = getRootFolderName();
    Folder root = session.getRootFolder();
    
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
    properties.put(PropertyIds.NAME, folderName);

    // create the folder
    Folder newFolder = root.createFolder(properties);
    
    for(int i = 0; i < 50; i++)
    {
        AccessControlPrincipalDataImpl principal = new AccessControlPrincipalDataImpl("user"+i);
        List<String> permissions = new ArrayList<String>(1);
        permissions.add(BasicPermissions.READ);
        List<Ace> addAces = new ArrayList<Ace>(1);
        addAces.add(new AccessControlEntryImpl(principal, permissions));
        newFolder.addAcl(addAces, AclPropagation.PROPAGATE);
        
        Map<String, Object> updateProperties = new HashMap<String, Object>();
        updateProperties.put("cm:title", "Update title "+i);
        newFolder.updateProperties(properties);
        
        if(i % 10 == 0)
        {
            System.out.println("@ "+i);
        }
    }
    ItemIterable<QueryResult> result = session.query("select * from cmis:folder", false);
    assertTrue(result.getTotalNumItems() > 0);
    
    result = session.query("select * from cmis:folder where cmis:name = '"+folderName+"'", false);
    assertTrue(result.getTotalNumItems() > 0);
    
}
 
Example #22
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void testCanConnectCMISUsingDefaultTenantImpl(Binding binding, String cmisVersion)
{
    String url = httpClient.getPublicApiCmisUrl(TenantUtil.DEFAULT_TENANT, binding, cmisVersion, null);
    
    Map<String, String> parameters = new HashMap<String, String>();
    
    // user credentials
    parameters.put(SessionParameter.USER, "admin");
    parameters.put(SessionParameter.PASSWORD, "admin");
    
    parameters.put(SessionParameter.ATOMPUB_URL, url);
    parameters.put(SessionParameter.BROWSER_URL, url);
    parameters.put(SessionParameter.BINDING_TYPE, binding.getOpenCmisBinding().value());
    
    SessionFactory factory = SessionFactoryImpl.newInstance();
    // perform request : http://host:port/alfresco/api/-default-/public/cmis/versions/${cmisVersion}/${binding}
    List<Repository> repositories = factory.getRepositories(parameters);
    
    assertTrue(repositories.size() > 0);
    
    parameters.put(SessionParameter.REPOSITORY_ID, TenantUtil.DEFAULT_TENANT);
    Session session = factory.createSession(parameters);
    // perform request : http://host:port/alfresco/api/-default-/public/cmis/versions/${cmisVersion}/${binding}/type?id=cmis:document
    ObjectType objectType = session.getTypeDefinition("cmis:document");
    
    assertNotNull(objectType);
}
 
Example #23
Source File: CMISDataCreatorTest.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testQueryFolderProperties()
{
    Session session = getSession("admin", "admin");
    
    String folderName = getRootFolderName();
    Folder root = session.getRootFolder();
    
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
    properties.put(PropertyIds.NAME, folderName);

    // create the folder
    Folder newFolder = root.createFolder(properties);
    
    ItemIterable<QueryResult>  result = session.query("select * from cmis:folder where cmis:name = '"+folderName+"'", false);
    assertEquals(1, result.getTotalNumItems());
    
    
    String uniqueName = getUniqueName();
    Map<String, Object> uProperties = new HashMap<String, Object>();
    uProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
    uProperties.put(PropertyIds.NAME, uniqueName);
    Folder uniqueFolder = newFolder.createFolder(uProperties);
    
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"'", false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND IN_FOLDER('"+ uniqueFolder.getParentId() + "')" , false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where IN_FOLDER('"+ uniqueFolder.getParentId() + "')" , false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:createdBy = '"+ uniqueFolder.getCreatedBy()+"'"  , false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:objectId = '"+ uniqueFolder.getId()+"'"  , false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:lastModifiedBy = '"+ uniqueFolder.getLastModifiedBy()+"'"  , false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where cmis:name = '"+ uniqueFolder.getName()+"'"  , false);
    assertEquals(1, result.getTotalNumItems());
    
    String creationDate = ISO8601DateFormat.format(uniqueFolder.getCreationDate().getTime());
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:creationDate = '"+ creationDate +"'"  , false);
    assertEquals(1, result.getTotalNumItems());
    
    String modificationDate = ISO8601DateFormat.format(uniqueFolder.getLastModificationDate().getTime());
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:lastModificationDate = '"+ modificationDate+"'"  , false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:objectTypeId = '"+ uniqueFolder.getType().getQueryName()+"'"  , false);
    assertEquals(1, result.getTotalNumItems());
    
    result = session.query("select * from cmis:folder where cmis:name = '"+uniqueName+"' AND cmis:baseTypeId = '"+ uniqueFolder.getBaseType().getQueryName()+"'"  , false);
    assertEquals(1, result.getTotalNumItems());
}
 
Example #24
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testALF10085() throws InterruptedException
{
    Repository repository = getRepository("admin", "admin");
    Session session = repository.createSession();
    Folder rootFolder = session.getRootFolder();

    Map<String, String> props = new HashMap<String, String>();
    {
        props.put(PropertyIds.OBJECT_TYPE_ID, "D:cmiscustom:document");
        props.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
    }
    Document doc1 = rootFolder.createDocument(props, null, null);
    
    props = new HashMap<String, String>();
    {
        props.put(PropertyIds.OBJECT_TYPE_ID, "D:cmiscustom:document");
        props.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
    }
    Document doc2 = rootFolder.createDocument(props, null, null);
    
    Thread.sleep(6000); 
    
    session.getObject(doc1);

    doc1.refresh();
    Calendar doc1LastModifiedBefore = (Calendar)doc1.getProperty(PropertyIds.LAST_MODIFICATION_DATE).getFirstValue();
    assertNotNull(doc1LastModifiedBefore);

    doc2.refresh();
    Calendar doc2LastModifiedBefore = (Calendar)doc2.getProperty(PropertyIds.LAST_MODIFICATION_DATE).getFirstValue();
    assertNotNull(doc2LastModifiedBefore);

    // Add relationship A to B
    props = new HashMap<String, String>();
    {
        props.put(PropertyIds.OBJECT_TYPE_ID, "R:cmiscustom:assoc");
        props.put(PropertyIds.NAME, "A Relationship"); 
        props.put(PropertyIds.SOURCE_ID, doc1.getId()); 
        props.put(PropertyIds.TARGET_ID, doc2.getId()); 
    }
    session.createRelationship(props); 

    doc1.refresh();
    Calendar doc1LastModifiedAfter = (Calendar)doc1.getProperty(PropertyIds.LAST_MODIFICATION_DATE).getFirstValue();
    assertNotNull(doc1LastModifiedAfter);
    
    doc2.refresh();
    Calendar doc2LastModifiedAfter = (Calendar)doc2.getProperty(PropertyIds.LAST_MODIFICATION_DATE).getFirstValue();
    assertNotNull(doc2LastModifiedAfter);

    assertEquals(doc1LastModifiedBefore, doc1LastModifiedAfter);
    assertEquals(doc2LastModifiedBefore, doc2LastModifiedAfter);
}
 
Example #25
Source File: CmisIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
private CmisObject retrieveCMISObjectByIdFromServer(String nodeId) throws Exception {
    Session session = createSession();
    return session.getObject(nodeId);
}
 
Example #26
Source File: TestBindingTypes.java    From iaf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
	@Override
	public CmisSender createSender() throws ConfigurationException {
		CmisSender sender = spy(new CmisSender());

		sender.setUrl("http://dummy.url");
		sender.setRepository("dummyRepository");
		sender.setFileContentSessionKey("fileContent");
		sender.setFileNameSessionKey("my-file");
		sender.setUsername("test");
		sender.setPassword("test");
		sender.setKeepSession(false);

		byte[] base64 = Base64.encodeBase64("dummy data".getBytes());
		session.put("fileContent", new String(base64));
		HttpServletResponse response = mock(HttpServletResponse.class);
		session.put(IPipeLineSession.HTTP_RESPONSE_KEY, response);

		Session cmisSession = mock(Session.class);
		ObjectFactory objectFactory = mock(ObjectFactoryImpl.class);
		doReturn(objectFactory).when(cmisSession).getObjectFactory();

//		GENERIC cmis object
		ObjectId objectId = mock(ObjectIdImpl.class);
		doReturn(objectId).when(cmisSession).createObjectId(anyString());
		CmisObject cmisObject = spy(new CmisTestObject());
		doReturn(cmisObject).when(cmisSession).getObject(any(ObjectId.class));
		doReturn(cmisObject).when(cmisSession).getObject(any(ObjectId.class), any(OperationContext.class));

//		GET
		OperationContext operationContext = mock(OperationContextImpl.class);
		doReturn(operationContext).when(cmisSession).createOperationContext();

//		CREATE
		Folder folder = mock(FolderImpl.class);
		doReturn(cmisObject).when(folder).createDocument(anyMap(), any(ContentStreamImpl.class), any(VersioningState.class));
		doReturn(folder).when(cmisSession).getRootFolder();

//		FIND
		ItemIterable<QueryResult> query = new EmptyItemIterable<QueryResult>();
		doReturn(query).when(cmisSession).query(anyString(), anyBoolean(), any(OperationContext.class));

		try {
			doReturn(cmisSession).when(sender).createCmisSession(any(ParameterValueList.class));
		} catch (SenderException e) {
			//Since we stub the entire session it won't throw exceptions
		}

		return sender;
	}
 
Example #27
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * MNT-14687 - Creating a document as checkedout and then cancelling the
 * checkout should delete the document.
 * 
 * This test would have fit better within CheckOutCheckInServiceImplTest but
 * was added here to make use of existing methods
 */
public void testCancelCheckoutWhileInCheckedOutState()
{
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    CheckOutCheckInService cociService = serviceRegistry.getCheckOutCheckInService();

    // Authenticate as system
    AuthenticationComponent authenticationComponent = (AuthenticationComponent) ctx.getBean(BEAN_NAME_AUTHENTICATION_COMPONENT);
    authenticationComponent.setSystemUserAsCurrentUser();

    /* Create the document using openCmis services */
    Repository repository = getRepository("admin", "admin");
    Session session = repository.createSession();
    Folder rootFolder = session.getRootFolder();

    // Set file properties
    String docname = "myDoc-" + GUID.generate() + ".txt";
    Map<String, String> props = new HashMap<String, String>();
    {
        props.put(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_DOCUMENT.value());
        props.put(PropertyIds.NAME, docname);
    }

    // Create some content
    byte[] byteContent = "Some content".getBytes();
    InputStream stream = new ByteArrayInputStream(byteContent);
    ContentStream contentStream = new ContentStreamImpl(docname, BigInteger.valueOf(byteContent.length), MIME_PLAIN_TEXT, stream);

    // Create the document
    Document doc1 = rootFolder.createDocument(props, contentStream, VersioningState.CHECKEDOUT);
    NodeRef doc1NodeRef = cmisIdToNodeRef(doc1.getId());
    NodeRef doc1WorkingCopy = cociService.getWorkingCopy(doc1NodeRef);

    /* Cancel Checkout */
    cociService.cancelCheckout(doc1WorkingCopy);

    /* Check if both the working copy and the document were deleted */
    NodeService nodeService = serviceRegistry.getNodeService();
    assertFalse(nodeService.exists(doc1NodeRef));
    assertFalse(nodeService.exists(doc1WorkingCopy));
}
 
Example #28
Source File: CmisSessionBuilder.java    From iaf with Apache License 2.0 4 votes vote down vote up
/**
 * @return a {@link Session} connected to the CMIS repository
 * @throws CmisSessionException when the CmisSessionBuilder fails to connect to cmis repository
 */
public Session build() throws CmisSessionException {
	CredentialFactory cf = new CredentialFactory(authAlias, username, password);
	return build(cf.getUsername(), cf.getPassword());
}
 
Example #29
Source File: CMISDataCreatorTest.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testCreateLots() throws Exception
{
    Session session = getSession("admin", "admin");
    
    Folder root = session.getRootFolder();
    String folderNameBase = getRootFolderName();

    
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
    properties.put(PropertyIds.NAME, folderNameBase);
    
    Folder base = root.createFolder(properties);
    for(int i = 0; i < 10; i++)
    {
       AccessControlPrincipalDataImpl principal = new AccessControlPrincipalDataImpl(""+i+i+i);
       List<String> permissions = new ArrayList<String>(1);
       permissions.add(BasicPermissions.ALL);
       List<Ace> addAces = new ArrayList<Ace>(1);
       addAces.add(new AccessControlEntryImpl(principal, permissions));
       base.addAcl(addAces, AclPropagation.PROPAGATE);
    }
    
    
    Thread last = null;
    
    for(int i = 0; i < 10; i++)
    {
        Creator creator = new Creator(base.getPath(), i);
        Thread thread = new Thread(creator);
        thread.start();
        last = thread;
    }
    
    if(last != null)
    {
        last.join();
    }
  
    ItemIterable<QueryResult> result = session.query("select * from cmis:folder", false);
    assertTrue(result.getTotalNumItems() > 0);
    
    //result = session.query("select * from cmis:folder where cmis:name = '"+folderName+"'", false);
    //assertTrue(result.getTotalNumItems() > 0);
    
}
 
Example #30
Source File: CmisServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
@HasPermission(type = DefaultPermission.class, action = "search_cmis")
public List<CmisContentItem> search(@ProtectedResourceId(SITE_ID_RESOURCE_ID) String siteId, String cmisRepo,
                                    String searchTerm, String path)
        throws CmisRepositoryNotFoundException, CmisUnavailableException, CmisTimeoutException {
    List<CmisContentItem> toRet = new ArrayList<CmisContentItem>();
    DataSourceRepository repositoryConfig = getConfiguration(siteId, cmisRepo);
    if (repositoryConfig != null) {
        Session session = createCMISSession(repositoryConfig);
        if (session != null) {
            String contentPath = Paths.get(repositoryConfig.getBasePath(), path).toString();
            CmisObject cmisObject = session.getObjectByPath(contentPath);
            if (cmisObject != null) {
                if (CMIS_FOLDER.equals(cmisObject.getBaseTypeId())) {
                    String queryString = CMIS_SEARCH_QUERY.replace(CMIS_SEARCH_QUERY_FOLDER_ID_VARIABLE,
                            cmisObject.getId()).replace(CMIS_SEARCH_QUERY_SEARCH_TERM_VARIABLE, searchTerm);
                    ItemIterable<QueryResult> result = session.query(queryString, false);
                    Iterator<QueryResult> iterator = result.iterator();
                    int count = 0;
                    while (iterator.hasNext()) {
                        CmisContentItem item = new CmisContentItem();
                        QueryResult qr = iterator.next();

                        String contentId = qr.getPropertyById(OBJECT_ID).getFirstValue().toString();
                        StringTokenizer st = new StringTokenizer(contentId, ";");
                        if (st.hasMoreTokens()) {
                            item.setItemId(st.nextToken());
                        }
                        CmisObject qrObject = session.getObject(item.getItemId());
                        org.apache.chemistry.opencmis.client.api.Document cmisDoc =
                                (org.apache.chemistry.opencmis.client.api.Document)qrObject;
                        item.setItemName(cmisDoc.getName());
                        item.setItemPath(cmisDoc.getPaths().get(0));
                        item.setMimeType(cmisDoc.getContentStreamMimeType());
                        item.setSize(cmisDoc.getContentStreamLength());
                        toRet.add(item);
                    }
                }
            }
        }
    }
    return toRet;
}