use of org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl in project alfresco-remote-api by Alfresco.
the class TestCMIS method testScenario1.
/**
* Tests CMIS and non-CMIS public api interactions
*/
@SuppressWarnings("deprecation")
@Test
public void testScenario1() throws Exception {
final TestNetwork network1 = getTestFixture().getRandomNetwork();
Iterator<String> personIt = network1.getPersonIds().iterator();
final String person = personIt.next();
assertNotNull(person);
Sites sitesProxy = publicApiClient.sites();
Comments commentsProxy = publicApiClient.comments();
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person));
CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10, AlfrescoObjectFactoryImpl.class.getName());
ListResponse<MemberOfSite> sites = sitesProxy.getPersonSites(person, null);
assertTrue(sites.getList().size() > 0);
MemberOfSite siteMember = sites.getList().get(0);
String siteId = siteMember.getSite().getSiteId();
Folder documentLibrary = (Folder) cmisSession.getObjectByPath("/Sites/" + siteId + "/documentLibrary");
System.out.println("documentLibrary id = " + documentLibrary.getId());
Map<String, String> fileProps = new HashMap<String, String>();
{
fileProps.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
fileProps.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());
}
Document doc = documentLibrary.createDocument(fileProps, fileContent, VersioningState.MAJOR);
System.out.println("Document id = " + doc.getId());
Comment c = commentsProxy.createNodeComment(doc.getId(), new Comment("comment title 1", "comment 1"));
System.out.println("Comment = " + c);
// Now lock the document
String nodeRefStr = (String) doc.getPropertyValue("alfcmis:nodeRef");
final NodeRef nodeRef = new NodeRef(nodeRefStr);
final TenantRunAsWork<Void> runAsWork = new TenantRunAsWork<Void>() {
@Override
public Void doWork() throws Exception {
lockService.lock(nodeRef, LockType.WRITE_LOCK);
return null;
}
};
RetryingTransactionCallback<Void> txnWork = new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
TenantUtil.runAsUserTenant(runAsWork, "bob", network1.getId());
return null;
}
};
transactionHelper.doInTransaction(txnWork);
// Now attempt to update the document's metadata
try {
doc.delete();
} catch (CmisUpdateConflictException e) {
// Expected: ACE-762 BM-0012: NodeLockedException not handled by CMIS
}
}
use of org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl in project alfresco-remote-api by Alfresco.
the class TestCMIS method testVersioningUsingUpdateProperties.
/**
* Test that updating properties does automatically create a new version if
* <b>autoVersion</b>, <b>initialVersion</b> and <b>autoVersionOnUpdateProps</b> are TRUE
*/
@Test
public void testVersioningUsingUpdateProperties() throws Exception {
final TestNetwork network1 = getTestFixture().getRandomNetwork();
String username = "user" + System.currentTimeMillis();
PersonInfo personInfo = new PersonInfo(username, username, username, "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("documentLibrary"), name);
return folderNodeRef;
}
}, person1Id, network1.getId());
// Create a document...
publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, "1.0", AlfrescoObjectFactoryImpl.class.getName());
AlfrescoFolder docLibrary = (AlfrescoFolder) cmisSession.getObjectByPath("/Sites/" + siteName + "/documentLibrary");
Map<String, String> properties = new HashMap<String, String>();
{
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
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();
String nodeRefStr = doc.getPropertyValue(NodeRefProperty.NodeRefPropertyId).toString();
final NodeRef nodeRef = new NodeRef(nodeRefStr);
TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>() {
@Override
public NodeRef doWork() throws Exception {
// ensure autoversioning is enabled
assertTrue(nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE));
Map<QName, Serializable> versionProperties = new HashMap<QName, Serializable>();
versionProperties.put(ContentModel.PROP_AUTO_VERSION, true);
versionProperties.put(ContentModel.PROP_INITIAL_VERSION, true);
versionProperties.put(ContentModel.PROP_AUTO_VERSION_PROPS, true);
nodeService.addProperties(nodeRef, versionProperties);
return null;
}
}, person1Id, network1.getId());
// ...and check that updating its properties creates a new minor version...
properties = new HashMap<String, String>();
{
properties.put(PropertyIds.DESCRIPTION, GUID.generate());
}
AlfrescoDocument doc1 = (AlfrescoDocument) doc.getObjectOfLatestVersion(false).updateProperties(properties);
doc1 = (AlfrescoDocument) doc.getObjectOfLatestVersion(false);
String versionLabel1 = doc1.getVersionLabel();
assertTrue(Double.parseDouble(versionLabel) < Double.parseDouble(versionLabel1));
// ...and check that updating its content creates a new version
fileContent = new ContentStreamImpl();
{
ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
writer.putContent("Ipsum and so on and so on");
ContentReader reader = writer.getReader();
fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
fileContent.setStream(reader.getContentInputStream());
}
doc1.setContentStream(fileContent, true);
AlfrescoDocument doc2 = (AlfrescoDocument) doc1.getObjectOfLatestVersion(false);
String versionLabel2 = doc2.getVersionLabel();
assertTrue("Set content stream should create a new version automatically", Double.parseDouble(versionLabel1) < Double.parseDouble(versionLabel2));
assertTrue("It should be latest version : " + versionLabel2, doc2.isLatestVersion());
doc2.deleteContentStream();
AlfrescoDocument doc3 = (AlfrescoDocument) doc2.getObjectOfLatestVersion(false);
String versionLabel3 = doc3.getVersionLabel();
assertTrue("Delete content stream should create a new version automatically", Double.parseDouble(versionLabel1) < Double.parseDouble(versionLabel3));
assertTrue("It should be latest version : " + versionLabel3, doc3.isLatestVersion());
}
use of org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl in project copper-cms by PogeyanOSS.
the class FileSystemStorageService method getContent.
@Override
public org.apache.chemistry.opencmis.commons.data.ContentStream getContent(String objectName, String path, String mimeType, BigInteger length) {
LOG.info("getConetent file name:{}" + objectName);
try {
String objectNameWithExtension = objectName;
if (LOG.isDebugEnabled()) {
LOG.debug("getConetent file name:{}" + objectName);
}
if (!getFileExtensionExists(objectName)) {
objectNameWithExtension = objectName + MimeUtils.guessExtensionFromMimeType(mimeType);
}
ContentStream contentStream = null;
File file = new File(gettingFolderPath(this.storeSettings.getFileLocation(), gettingDocNamePath(path)) + File.separator + objectNameWithExtension);
if (!file.isFile()) {
return contentStream;
}
if (file.length() == 0) {
return new ContentStreamImpl(objectName, length, MimeTypes.getMIMEType(file), new FileInputStream(file));
}
contentStream = new ContentStreamImpl(objectName, length, MimeTypes.getMIMEType(file), new FileInputStream(file));
return contentStream;
} catch (Exception e) {
LOG.error("getContent exception: {}, {}", e.getMessage(), ExceptionUtils.getStackTrace(e));
throw new CmisObjectNotFoundException(e.getMessage(), e);
}
}
use of org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl in project copper-cms by PogeyanOSS.
the class CreateInvalidTypeTest method run.
@Override
public void run(Session session) {
// create a test folder
Folder testFolder = createTestFolder(session);
try {
// test document creation
try {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.NAME, "never.txt");
properties.put(PropertyIds.OBJECT_TYPE_ID, getFolderTestTypeId());
byte[] contentBytes = IOUtils.toUTF8Bytes("nothing");
ContentStream contentStream = new ContentStreamImpl("never.txt", BigInteger.valueOf(contentBytes.length), "text/plain", new ByteArrayInputStream(contentBytes));
testFolder.createDocument(properties, contentStream, null);
addResult(createResult(FAILURE, "Creation of a document with a folder type shouldn't work!"));
} catch (Exception e) {
if (!(e instanceof CmisInvalidArgumentException) && !(e instanceof CmisConstraintException)) {
addResult(createResult(WARNING, "Creation of a document with a folder type threw an unexcpeted exception: " + e.toString()));
}
}
// test folder creation
try {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.NAME, "never");
properties.put(PropertyIds.OBJECT_TYPE_ID, getDocumentTestTypeId());
testFolder.createFolder(properties);
addResult(createResult(FAILURE, "Creation of a folder with a document type shouldn't work!"));
} catch (Exception e) {
if (!(e instanceof CmisInvalidArgumentException) && !(e instanceof CmisConstraintException)) {
addResult(createResult(WARNING, "Creation of a folder with a document type threw an unexcpeted exception: " + e.toString()));
}
}
} finally {
// delete the test folder
deleteTestFolder();
}
}
use of org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl in project copper-cms by PogeyanOSS.
the class AsyncCreateAndDeleteDocumentTest method run.
@Override
public void run(Session session) {
CmisTestResult f;
int numOfDocuments = 100;
String mimeType = "text/plain";
byte[] contentBytes = new byte[64 * 1024];
for (int i = 0; i < contentBytes.length; i++) {
contentBytes[i] = (byte) ('0' + i % 10);
}
// create an async session
AsyncSession asyncSession = AsyncSessionFactoryImpl.newInstance().createAsyncSession(session, 10);
// create a test folder
Folder testFolder = createTestFolder(session);
try {
// create documents
List<Future<ObjectId>> docFutures = new ArrayList<Future<ObjectId>>();
for (int i = 0; i < numOfDocuments; i++) {
String name = "asyncdoc" + i + ".txt";
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.NAME, name);
properties.put(PropertyIds.OBJECT_TYPE_ID, getDocumentTestTypeId());
ContentStream contentStream = new ContentStreamImpl(name, BigInteger.valueOf(contentBytes.length), mimeType, new ByteArrayInputStream(contentBytes));
Future<ObjectId> newDocument = asyncSession.createDocument(properties, testFolder, contentStream, null);
docFutures.add(newDocument);
}
// wait for all document being created
List<ObjectId> docIds = new ArrayList<ObjectId>();
try {
for (Future<ObjectId> docFuture : docFutures) {
ObjectId id = docFuture.get();
docIds.add(id);
}
} catch (Exception e) {
addResult(createResult(UNEXPECTED_EXCEPTION, "Documents could not been created! Exception: " + e.getMessage(), e, true));
}
// check children of the test folder
int count = countChildren(testFolder);
f = createResult(FAILURE, "Test folder should have " + numOfDocuments + " children but has " + count + "!");
addResult(assertEquals(count, numOfDocuments, null, f));
// simple children test
addResult(checkChildren(session, testFolder, "Test folder children check"));
// get documents
Map<String, Future<CmisObject>> getObjectFutures = new HashMap<String, Future<CmisObject>>();
Map<String, Future<ContentStream>> contentStreamFutures = new HashMap<String, Future<ContentStream>>();
Map<String, ByteArrayOutputStream> content = new HashMap<String, ByteArrayOutputStream>();
for (ObjectId docId : docIds) {
Future<CmisObject> getObjectFuture = asyncSession.getObject(docId, SELECT_ALL_NO_CACHE_OC);
getObjectFutures.put(docId.getId(), getObjectFuture);
ByteArrayOutputStream out = new ByteArrayOutputStream(contentBytes.length);
content.put(docId.getId(), out);
Future<ContentStream> contentStreamFuture = asyncSession.storeContentStream(docId, out);
contentStreamFutures.put(docId.getId(), contentStreamFuture);
}
// wait for all document being fetched
try {
for (Map.Entry<String, Future<CmisObject>> getObjectFuture : getObjectFutures.entrySet()) {
CmisObject object = getObjectFuture.getValue().get();
f = createResult(FAILURE, "Fetching document failed!");
addResult(assertIsTrue(object instanceof Document, null, f));
if (object != null) {
f = createResult(FAILURE, "Fetched wrong document!");
addResult(assertEquals(getObjectFuture.getKey(), object.getId(), null, f));
}
}
} catch (Exception e) {
addResult(createResult(UNEXPECTED_EXCEPTION, "Documents could not been fetched! Exception: " + e.getMessage(), e, true));
}
// wait for all document content being fetched
try {
for (Map.Entry<String, Future<ContentStream>> contentStreamFuture : contentStreamFutures.entrySet()) {
ContentStream contentStream = contentStreamFuture.getValue().get();
f = createResult(FAILURE, "Fetching document content failed!");
addResult(assertNotNull(contentStream, null, f));
if (contentStream != null) {
if (contentStream.getMimeType() == null) {
addResult(createResult(FAILURE, "Content MIME type is null!"));
} else {
f = createResult(WARNING, "Content MIME types don't match!");
addResult(assertIsTrue(contentStream.getMimeType().trim().toLowerCase(Locale.ENGLISH).startsWith(mimeType.toLowerCase(Locale.ENGLISH)), null, f));
}
}
ByteArrayOutputStream out = content.get(contentStreamFuture.getKey());
byte[] readBytes = out.toByteArray();
f = createResult(FAILURE, "Read content length doesn't match document content length!");
addResult(assertEquals(contentBytes.length, readBytes.length, null, f));
f = createResult(FAILURE, "Read content doesn't match document content!");
addResult(assertEqualArray(contentBytes, readBytes, null, f));
}
} catch (Exception e) {
addResult(createResult(UNEXPECTED_EXCEPTION, "Document content could not been fetched! Exception: " + e.getMessage(), e, true));
}
// delete documents
List<Future<?>> delFutures = new ArrayList<Future<?>>();
for (ObjectId docId : docIds) {
Future<?> delFuture = asyncSession.delete(docId);
delFutures.add(delFuture);
}
// wait for all document being deleted
try {
for (Future<?> delFuture : delFutures) {
delFuture.get();
}
} catch (Exception e) {
addResult(createResult(UNEXPECTED_EXCEPTION, "Documents could not been deleted! Exception: " + e.getMessage(), e, true));
}
// check children of the test folder
count = countChildren(testFolder);
f = createResult(FAILURE, "Test folder should be empty but has " + count + " children!");
addResult(assertEquals(count, 0, null, f));
} finally {
// delete the test folder
deleteTestFolder();
if (asyncSession instanceof AbstractExecutorServiceAsyncSession<?>) {
((AbstractExecutorServiceAsyncSession<?>) asyncSession).shutdown();
}
}
addResult(createInfoResult("Tested the parallel creation and deletion of " + numOfDocuments + " documents."));
}
Aggregations