org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl Java Examples

The following examples show how to use org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl. 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: CMISDataCreatorTest.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Document createUniqueDocument(Folder newFolder)
		throws UnsupportedEncodingException {
	String uniqueName = getUniqueName();
       Map<String, Object> uProperties = new HashMap<String, Object>();
       uProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
       uProperties.put(PropertyIds.NAME, uniqueName);
       
       ContentStreamImpl contentStream = new ContentStreamImpl();
       contentStream.setFileName("bob");
       String shortString = "short";
       contentStream.setStream(new ByteArrayInputStream(shortString.getBytes("UTF-8")));
       contentStream.setLength(new BigInteger("5"));
       contentStream.setMimeType("text/plain");
       
       Document uniqueDocument = newFolder.createDocument(uProperties, contentStream, VersioningState.MAJOR);
       return uniqueDocument;
}
 
Example #2
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 #3
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 #4
Source File: OpenCmisLocalTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ContentStreamImpl makeContentStream(String filename, String mimetype, String content) throws IOException
{
    TempStoreOutputStream tos = streamFactory.newOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(tos);
    writer.write(content);
    ContentStreamImpl contentStream = new ContentStreamImpl(filename, BigInteger.valueOf(tos.getLength()), MimetypeMap.MIMETYPE_TEXT_PLAIN, tos.getInputStream());
    return contentStream;
}
 
Example #5
Source File: PublicApiClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void putContent(String objectId, String filename, BigInteger length, String mimetype, InputStream content, boolean overwrite)
{
    CmisObject o = getObject(objectId);
    if(o instanceof Document)
    {
        Document d = (Document)o;
        ContentStream contentStream = new ContentStreamImpl(filename, length, mimetype, content);
        try
        {
            d.setContentStream(contentStream, overwrite);
        }
        finally
        {
            try
            {
                contentStream.getStream().close();
            }
            catch (Exception e)
            {
            }
        }
    }
    else
    {
        throw new IllegalArgumentException("Object does not exist or is not a document");
    }
}
 
Example #6
Source File: IbisObjectService.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public ContentStream getContentStream(String repositoryId, String objectId,
		String streamId, BigInteger offset, BigInteger length, ExtensionsData extension) {

	if(!eventDispatcher.contains(CmisEvent.GET_CONTENTSTREAM)) {
		return objectService.getContentStream(repositoryId, objectId, streamId, offset, length, extension);
	}
	else {
		XmlBuilder cmisXml = new XmlBuilder("cmis");
		cmisXml.addSubElement(buildXml("repositoryId", repositoryId));
		cmisXml.addSubElement(buildXml("objectId", objectId));
		cmisXml.addSubElement(buildXml("streamId", streamId));
		cmisXml.addSubElement(buildXml("offset", offset));
		cmisXml.addSubElement(buildXml("length", length));

		IPipeLineSession context = new PipeLineSessionBase();
		context.put(CmisUtils.CMIS_CALLCONTEXT_KEY, callContext);
		Element cmisResult = eventDispatcher.trigger(CmisEvent.GET_CONTENTSTREAM, cmisXml.toXML(), context);

		Element contentStreamXml = XmlUtils.getFirstChildTag(cmisResult, "contentStream");
		InputStream stream = (InputStream) context.get("ContentStream");
		String fileName = contentStreamXml.getAttribute("filename");
		String mediaType = contentStreamXml.getAttribute("mimeType");
		long longLength = Long.parseLong(contentStreamXml.getAttribute("length"));
		BigInteger fileLength = BigInteger.valueOf(longLength);

		return new ContentStreamImpl(fileName, fileLength, mediaType, stream);
	}
}
 
Example #7
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 #8
Source File: CMISConnector.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Gets the content from the repository.
 */
public ContentStream getContentStream(CMISNodeInfo info, String streamId, BigInteger offset, BigInteger length)
{
    // get the type and check if the object can have content
    TypeDefinitionWrapper type = info.getType();
    checkDocumentTypeForContent(type);

    // looks like a document, now get the content
    ContentStreamImpl result = new ContentStreamImpl();
    result.setFileName(info.getName());

    // if streamId is set, fetch other content
    NodeRef streamNodeRef = info.getNodeRef();
    if ((streamId != null) && (streamId.length() > 0))
    {
        CMISNodeInfo streamInfo = createNodeInfo(streamId);
        if (!streamInfo.isVariant(CMISObjectVariant.CURRENT_VERSION))
        {
            throw new CmisInvalidArgumentException("Stream id is invalid: " + streamId + ", expected variant " + CMISObjectVariant.CURRENT_VERSION + ", got variant " + streamInfo.getObjectVariant());
        }

        streamNodeRef = streamInfo.getNodeRef();
        type = streamInfo.getType();
        checkDocumentTypeForContent(type);
    }

    // get the stream now
    try
    {
        ContentReader contentReader = contentService.getReader(streamNodeRef, ContentModel.PROP_CONTENT);
        if (contentReader == null)
        {
            throw new CmisConstraintException("Document has no content!");
        }

        result.setMimeType(contentReader.getMimetype());
        long contentSize = contentReader.getSize();

        if ((offset == null) && (length == null))
        {
            result.setStream(contentReader.getContentInputStream());
            result.setLength(BigInteger.valueOf(contentSize));
            publishReadEvent(streamNodeRef, info.getName(), result.getMimeType(), contentSize, contentReader.getEncoding(), null);
        }
        else
        {
            long off = (offset == null ? 0 : offset.longValue());
            long len = (length == null ? contentSize : length.longValue());
            if (off + len > contentSize)
            {
                len = contentReader.getSize() - off;
            }

            result.setStream(new RangeInputStream(contentReader.getContentInputStream(), off, len));
            result.setLength(BigInteger.valueOf(len));
            publishReadEvent(streamNodeRef, info.getName(), result.getMimeType(), contentSize, contentReader.getEncoding(), off+" - "+len);
        }
    }
    catch (Exception e)
    {
        if (e instanceof CmisBaseException)
        {
            throw (CmisBaseException) e;
        }
        else
        {
            StringBuilder msg = new StringBuilder("Failed to retrieve content: " + e.getMessage());
            Throwable cause = e.getCause();
            if(cause != null)
            {
                // add the cause to the CMIS exception
                msg.append(", ");
                msg.append(cause.getMessage());
            }
            throw new CmisRuntimeException(msg.toString(), e);
        }
    }

    return result;
}
 
Example #9
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 #10
Source File: CMISTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test auto version behavior for setContentStream, deleteContentStream and appendContentStream according to ALF-21852.
 */
@Test
public void testSetDeleteAppendContentStreamVersioning() throws Exception
{
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    final String DOC1 = "documentProperties1-" + GUID.generate();

    try
    {
        final FileInfo doc = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<FileInfo>()
        {
            @Override
            public FileInfo execute() throws Throwable
            {
                FileInfo document;
                // create document
                document = fileFolderService.create(repositoryHelper.getCompanyHome(), DOC1, ContentModel.TYPE_CONTENT);
                nodeService.setProperty(document.getNodeRef(), ContentModel.PROP_NAME, DOC1);

                Map<QName, Serializable> props = new HashMap<QName, Serializable>();
                props.put(ContentModel.PROP_TITLE, "Initial Title");
                props.put(ContentModel.PROP_DESCRIPTION, "Initial Description");

                nodeService.addAspect(document.getNodeRef(), ContentModel.ASPECT_TITLED, props);

                // apply versionable aspect with properties
                props = new HashMap<QName, Serializable>();
                // ContentModel.PROP_INITIAL_VERSION always true
                props.put(ContentModel.PROP_INITIAL_VERSION, true);
                props.put(ContentModel.PROP_AUTO_VERSION, true);
                props.put(ContentModel.PROP_AUTO_VERSION_PROPS, true);
                versionService.ensureVersioningEnabled(document.getNodeRef(), props);

                return document;
            }
        });
        withCmisService(new CmisServiceCallback<Void>()
        {
            @Override public Void execute(CmisService cmisService)
            {
                final String documentNodeRefId = doc.getNodeRef().toString();
                final String repositoryId = cmisService.getRepositoryInfos(null).get(0).getId();

                ObjectInfo objInfoInitialVersion = cmisService.getObjectInfo(repositoryId, documentNodeRefId);
                assertTrue("We had just created the document - it should be version 1.0", objInfoInitialVersion.getId().endsWith("1.0"));

                ContentStreamImpl contentStream = new ContentStreamImpl(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, "Content " + GUID.generate());
                Holder<String> objectIdHolder = new Holder<>(documentNodeRefId);
                // Test setContentStream
                cmisService.setContentStream(repositoryId, objectIdHolder, true, null, contentStream, null);
                assertTrue("The \"output\" parameter should returns the newly created version id: 1.1", objectIdHolder.getValue().endsWith("1.1"));
                // we can use this new version id to get information about the cmis object
                ObjectInfo objInfoAfterSetContentStream = cmisService.getObjectInfo(repositoryId, objectIdHolder.getValue());
                assertTrue("The object info should reflect the version requested: 1.1", objInfoAfterSetContentStream.getId().endsWith("1.1"));

                // Test deleteContentStream
                cmisService.deleteContentStream(repositoryId, objectIdHolder, null, null);
                assertTrue("The \"output\" parameter should returns the newly created version id: 1.2", objectIdHolder.getValue().endsWith("1.2"));
                // we can use this new version id to get information about the cmis object
                objInfoAfterSetContentStream = cmisService.getObjectInfo(repositoryId, objectIdHolder.getValue());
                assertTrue("The object info should reflect the version requested: 1.2", objInfoAfterSetContentStream.getId().endsWith("1.2"));

                // Test appendContentStream
                cmisService.appendContentStream(repositoryId, objectIdHolder, null, contentStream, true, null);
                assertTrue("The \"output\" parameter should returns the newly created version id: 1.3", objectIdHolder.getValue().endsWith("1.3"));
                // we can use this new version id to get information about the cmis object
                objInfoAfterSetContentStream = cmisService.getObjectInfo(repositoryId, objectIdHolder.getValue());
                assertTrue("The object info should reflect the version requested: 1.3", objInfoAfterSetContentStream.getId().endsWith("1.3"));

                return null;
            }
        }, CmisVersion.CMIS_1_1);
    }
    finally
    {
        AuthenticationUtil.popAuthentication();
    }
}
 
Example #11
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
  public void testALF19320() throws Exception
  {
      final TestNetwork network1 = getTestFixture().getRandomNetwork();

      String username = "user" + System.currentTimeMillis();
PersonInfo personInfo = new PersonInfo(username, username, username, TEST_PASSWORD, null, null, null, null, null, null, null);
      TestPerson person1 = network1.createUser(personInfo);
      String person1Id = person1.getId();

      final String siteName = "site" + System.currentTimeMillis();

      TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>()
      {
          @Override
          public NodeRef doWork() throws Exception
          {
              SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
              TestSite site = repoService.createSite(null, siteInfo);

              String name = GUID.generate();
		NodeRef folderNodeRef = repoService.createFolder(site.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), name);
              return folderNodeRef;
          }
      }, person1Id, network1.getId());

      // Create a document...
      publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10, AlfrescoObjectFactoryImpl.class.getName());
      AlfrescoFolder docLibrary = (AlfrescoFolder)cmisSession.getObjectByPath("/Sites/" + siteName + "/documentLibrary");
      Map<String, String> properties = new HashMap<String, String>();
      {
          // create a document with 2 aspects
          properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:cm:titled,P:cm:author");
          properties.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
      }
      ContentStreamImpl fileContent = new ContentStreamImpl();
      {
          ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
          writer.putContent("Ipsum and so on");
          ContentReader reader = writer.getReader();
          fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
          fileContent.setStream(reader.getContentInputStream());
      }
      
      AlfrescoDocument doc = (AlfrescoDocument)docLibrary.createDocument(properties, fileContent, VersioningState.MAJOR);
      String versionLabel = doc.getVersionLabel();
assertEquals(CMIS_VERSION_10, versionLabel);

      AlfrescoDocument doc1 = (AlfrescoDocument)doc.getObjectOfLatestVersion(false);
      String versionLabel1 = doc1.getVersionLabel();
assertEquals(CMIS_VERSION_10, versionLabel1);
  }
 
Example #12
Source File: TestCMIS.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * <p>Related to REPO-4613.</p>
 * <p>A checkout should not lock the private working copy.</p>
 * <p>Adding aspects or properties to a pwc should remain possible after a checkout.</p>
 * @throws Exception
 */
@Test
public void aPrivateCopyShouldAllowTheAdditionOfAspects_CMIS_1_1_Version() throws Exception
{
    final String aspectName = "P:cm:summarizable";
    final String propertyName = "cm:summary";
    final String propertyValue = "My summary";

    final TestNetwork network1 = getTestFixture().getRandomNetwork();

    String username = "user" + System.currentTimeMillis();
    PersonInfo personInfo = new PersonInfo(username, username, username, TEST_PASSWORD, null, null, null, null, null, null, null);
    TestPerson person1 = network1.createUser(personInfo);
    String person1Id = person1.getId();

    final String siteName = "site" + System.currentTimeMillis();

    TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>()
    {
        @Override
        public NodeRef doWork() throws Exception
        {
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
            TestSite site = repoService.createSite(null, siteInfo);

            String name = GUID.generate();
            NodeRef folderNodeRef = repoService.createFolder(site.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), name);
            return folderNodeRef;
        }
    }, person1Id, network1.getId());

    // Create a document...
    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

    CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_11);
    Folder folder = (Folder) cmisSession.getObjectByPath(String.format(DOCUMENT_LIBRARY_PATH_PATTERN, siteName));
    String fileName = String.format(TEST_DOCUMENT_NAME_PATTERN, GUID.generate());

    // Create a document...
    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

    HashMap<String, Object> props = new HashMap<>();
    props.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
    props.put(PropertyIds.NAME, fileName);

    final ContentStream cs = new ContentStreamImpl(fileName, "text/plain",
            "This is just a test");

    final Document document = folder.createDocument(props, cs, VersioningState.MAJOR);

    ObjectId pwcObjectId = document.checkOut();

    CmisObject cmisObject = cmisSession.getObject(pwcObjectId.getId());
    final Document pwc = (Document) cmisObject;

    List<Object> aspects = pwc.getProperty(PropertyIds.SECONDARY_OBJECT_TYPE_IDS).getValues();

    // asserts that we have the right aspect for the private working copy
    assertTrue(aspects.contains("P:cm:workingcopy"));

    aspects.add(aspectName);

    props = new HashMap<>();
    props.put(PropertyIds.SECONDARY_OBJECT_TYPE_IDS, aspects);
    props.put(propertyName, propertyValue);


    pwc.updateProperties(props);

    final ObjectId id = pwc.checkIn(true, null, null, "CheckIn comment");
    Document checkedInDocument = (Document) cmisSession.getObject(id.getId());

    List<String> secondaryTypeIds = checkedInDocument.getPropertyValue(PropertyIds.SECONDARY_OBJECT_TYPE_IDS);

    // asserts the new aspect has been added to the original copy, via the check in from the private copy
    assertTrue(secondaryTypeIds.contains(aspectName));
    assertEquals(checkedInDocument.getPropertyValue(propertyName),  propertyValue);
}
 
Example #13
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;
	}