@Test public void testReadAclAfterCopy() { DocumentModel folder1 = new DocumentModelImpl("/", "folder1", "Folder"); folder1 = session.createDocument(folder1); DocumentModel folder2 = new DocumentModelImpl("/", "folder2", "Folder"); folder2 = session.createDocument(folder2); DocumentModel doc = new DocumentModelImpl("/folder1", "doc", "File"); doc = session.createDocument(doc); // set ACL on folder2 ACL acl = new ACLImpl(); acl.add(new ACE("Everyone", "Read", true)); ACP acp = new ACPImpl(); acp.addACL(acl); folder2.setACP(acp, true); session.save(); // doc under folder1 cannot be read by joe try (CoreSession joeSession = openSessionAs("joe")) { DocumentModelList list = joeSession.query("SELECT * FROM File"); assertEquals(0, list.size()); } // copy doc under folder2 session.copy(doc.getRef(), folder2.getRef(), "doccopy"); session.save(); // check doc copy now readable by joe try (CoreSession joeSession = openSessionAs("joe")) { DocumentModelList list = joeSession.query("SELECT * FROM File"); assertEquals(1, list.size()); assertEquals("doccopy", list.get(0).getName()); } }
@Test public void testEndpointConsumptionRelations() throws Exception { // Create endpoint consumption SoaNodeId endpointConsumptionId = new SoaNodeId(EndpointConsumption.DOCTYPE, "MyConsumption"); DocumentModel endpointConsumptionModel = documentService.create(documentManager, endpointConsumptionId); EndpointConsumption endpointConsumption = endpointConsumptionModel.getAdapter(EndpointConsumption.class); Assert.assertNotNull("EndpointConsumption adapter must be available", endpointConsumption); documentManager.save(); // Manipulate and test it Assert.assertNull( "EndpointConsumption must not initially consume endpoints", endpointConsumption.getConsumedEndpoint()); SoaNodeId consumedEndpoint = new EndpointId("myenv", "myurl"); endpointConsumption.setConsumedEndpoint(consumedEndpoint); Assert.assertEquals( "EndpointConsumption must be set as expected", consumedEndpoint, endpointConsumption.getConsumedEndpoint()); DocumentModel foundEndpointModel = documentService.findSoaNode(documentManager, consumedEndpoint); Assert.assertNotNull("Consumed endpoint must be created", foundEndpointModel); endpointConsumption.setConsumedEndpoint(null); Assert.assertNull( "EndpointConsumption must be removed", endpointConsumption.getConsumedEndpoint()); }
/** * Tests that we cannot add a document to a document which is not a document of type Collection. */ @Test public void testCanAddCollectionNotCollection() throws ClientException { DocumentModel testWorkspace = session.createDocumentModel("/default-domain/workspaces", "testWorkspace", "Workspace"); testWorkspace = session.createDocument(testWorkspace); DocumentModel testFile = session.createDocumentModel(testWorkspace.getPathAsString(), TEST_FILE_NAME, "File"); testFile = session.createDocument(testFile); collectionManager.addToNewCollection( COLLECTION_NAME, COLLECTION_DESCRIPTION, testFile, session); DocumentModel testFile2 = session.createDocumentModel(testWorkspace.getPathAsString(), TEST_FILE_NAME + 2, "File"); testFile2 = session.createDocument(testFile2); collectionManager.addToNewCollection( COLLECTION_NAME, COLLECTION_DESCRIPTION, testFile2, session); try { collectionManager.addToCollection(testFile, testFile2, session); } catch (IllegalArgumentException e) { // Expeted behaviour return; } fail("File is not a Collection"); }
private String extractQueryFromRequest(final HttpServletRequest request) { String query = request.getParameter("query"); if (query == null) { String fullText = request.getParameter("fullText"); if (fullText == null) { throw new IllegalParameterException("Expecting a query or a fullText parameter"); } String orderBy = request.getParameter("orderBy"); String orderClause = ""; if (orderBy != null) { orderClause = " ORDER BY " + orderBy; } String path; DocumentModel doc = getTarget().getAdapter(DocumentModel.class); if (doc.isFolder()) { path = doc.getPathAsString(); } else { path = doc.getPath().removeLastSegments(1).toString(); } query = "SELECT * FROM Document WHERE (ecm:fulltext = \"" + fullText + "\") AND (ecm:isCheckedInVersion = 0) AND (ecm:path STARTSWITH \"" + path + "\")" + orderClause; } return query; }
public String navigateToCurrentUserPersonalWorkspace() { if (!initialized) { initialize(); } String returnView = DOCUMENT_VIEW; // force return to Documents tab webActions.setCurrentTabId(WebActions.MAIN_TABS_CATEGORY, DOCUMENT_MANAGEMENT_ACTION); // Rux INA-221: separated links for going to workspaces DocumentModel currentUserPersonalWorkspace = getCurrentUserPersonalWorkspace(); DocumentModel currentDocument = navigationContext.getCurrentDocument(); if (!isShowingPersonalWorkspace() && currentDocument != null && currentDocument.getPath().segment(0) != null) { lastAccessedDocument = mainTabsActions.getDocumentFor( DOCUMENT_MANAGEMENT_ACTION, navigationContext.getCurrentDocument()); } navigationContext.setCurrentDocument(currentUserPersonalWorkspace); showingPersonalWorkspace = true; Events.instance().raiseEvent(EventNames.GO_PERSONAL_WORKSPACE); return returnView; }
@Override public void handleEvent(Event event) throws ClientException { if (!DOCUMENT_CREATED.equals(event.getName())) { return; } EventContext ctx = event.getContext(); if (ctx instanceof DocumentEventContext) { DocumentEventContext docCtx = (DocumentEventContext) ctx; DocumentModel doc = docCtx.getSourceDocument(); if (doc.isProxy() || doc.isVersion()) { // a proxy or version keeps the uid of the document // being proxied or versioned => we're not allowed // to modify its field. return; } String eventId = event.getName(); log.debug("eventId : " + eventId); try { addUIDtoDoc(doc); } catch (DocumentException e) { log.error("Error occurred while generating UID for doc: " + doc, e); } } }
protected DocumentModel createNode(DocumentModel route, String name, CoreSession session) throws PropertyException { DocumentModel node = session.createDocumentModel(route.getPathAsString(), name, TYPE_ROUTE_NODE); node.setPropertyValue(GraphNode.PROP_NODE_ID, name); return session.createDocument(node); }
protected void getAllTasks() { error = null; errorMessage = null; userTasks = new ArrayList<>(); CoreSession coreSession = getCoreSession(); boolean filterTrashDocs = getFilterDocumentsInTrash(); NuxeoPrincipal pal = (NuxeoPrincipal) coreSession.getPrincipal(); TaskService taskService = Framework.getService(TaskService.class); List<Task> tasks = taskService.getAllCurrentTaskInstances(coreSession, getSortInfos()); if (tasks != null) { for (Task task : tasks) { List<String> targetDocumentsIds = task.getTargetDocumentsIds(); boolean hasTargetDocuments = targetDocumentsIds != null && !targetDocumentsIds.isEmpty(); if (task.hasEnded() || task.isCancelled() || !hasTargetDocuments) { continue; } DocumentModel doc = taskService.getTargetDocumentModel(task, coreSession); if (doc != null) { if (filterTrashDocs && LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState())) { continue; } else { userTasks.add(new DashBoardItemImpl(task, doc, getLocale())); } } else { log.warn( String.format( "User '%s' has a task of type '%s' on a missing or deleted document", pal.getName(), task.getName())); } } } }
@Test public void testUpdateReadonlyMultidir() throws Exception { MultiDirectory readonlyMultidir = (MultiDirectory) directoryService.getDirectory("readonlymulti"); MultiDirectorySession readonlyDir = (MultiDirectorySession) readonlyMultidir.getSession(); Session dir1 = memdir1.getSession(); Session dir2 = memdir2.getSession(); Session dir3 = memdir3.getSession(); // multi-subdirs update DocumentModel e = readonlyDir.getEntry("1"); assertEquals("foo1", e.getProperty("schema3", "thefoo")); assertEquals("bar1", e.getProperty("schema3", "thebar")); e.setProperty("schema3", "thefoo", "fffooo1"); e.setProperty("schema3", "thebar", "babar1"); readonlyDir.updateEntry(e); e = readonlyDir.getEntry("1"); // the multidirectory entry was not updated assertEquals("foo1", e.getProperty("schema3", "thefoo")); assertEquals("bar1", e.getProperty("schema3", "thebar")); // neither the underlying directories assertEquals("foo1", dir1.getEntry("1").getProperty("schema1", "foo")); assertEquals("bar1", dir2.getEntry("1").getProperty("schema2", "bar")); assertNull(dir3.getEntry("1")); }
protected void process(Element el) { DocConfigDescriptor createConf = getDocCreationConfig(el); if (createConf != null) { createNewDocument(el, createConf); } List<AttributeConfigDescriptor> configs = getAttributConfigs(el); if (configs != null) { for (AttributeConfigDescriptor config : configs) { processDocAttributes(docsStack.peek(), el, config); } DocumentModel doc = popStack(); doc.putContextData(XML_IMPORTER_INITIALIZATION, Boolean.TRUE); if (!deferSave) { doc = session.saveDocument(doc); } pushInStack(doc); if (createConf != null) { String chain = createConf.getAutomationChain(); if (chain != null && !"".equals(chain.trim())) { OperationContext ctx = new OperationContext(session, mvelCtx); ctx.setInput(docsStack.peek()); try { getAutomationService().run(ctx, chain); } catch (OperationException e) { throw new NuxeoException(e); } } } } for (Object e : el.elements()) { process((Element) e); } }
@Override public PublishedDocument publishDocument( DocumentModel doc, PublicationNode targetNode, Map<String, String> params) throws ClientException { Snapshot snapshot = null; if (doc.isFolder()) { Snapshotable snapshotable = doc.getAdapter(Snapshotable.class); if (snapshotable != null) { snapshot = snapshotable.createSnapshot(VersioningOption.MINOR); } } PublishedDocument result = super.publishDocument(doc, targetNode, params); if (snapshot != null) { final Snapshot tree = snapshot; final DocumentModel parent = ((SimpleCorePublishedDocument) result).getProxy(); UnrestrictedSessionRunner runner = new UnrestrictedSessionRunner(doc.getCoreSession()) { @Override public void run() throws ClientException { // force cleanup of the tree !!! session.removeChildren(parent.getRef()); subPublish(session, parent, tree, true); } }; runner.runUnrestricted(); } return result; }
protected String resolvePath(Element el, String xpr) { Object ob = resolve(el, xpr); if (ob == null) { for (int i = 0; i < docsStack.size(); i++) { if (docsStack.get(i).isFolder()) { return docsStack.get(i).getPathAsString(); } } } else { if (ob instanceof DocumentModel) { return ((DocumentModel) ob).getPathAsString(); } else if (ob instanceof Node) { if (ob instanceof Element) { Element targetElement = (Element) ob; DocumentModel target = elToDoc.get(targetElement); if (target != null) { return target.getPathAsString(); } else { return targetElement.getText(); } } else if (ob instanceof Attribute) { return ((Attribute) ob).getValue(); } else if (ob instanceof Text) { return ((Text) ob).getText(); } else if (ob.getClass().isAssignableFrom(Attribute.class)) { return ((Attribute) ob).getValue(); } } else { return ob.toString(); } } return rootDoc.getPathAsString(); }
private DocumentModel createSite() throws ClientException, PropertyException { DocumentModel site = session.createDocumentModel("/", "site1", LabsSiteConstants.Docs.SITE.type()); site.setPropertyValue("dc:title", "le titre"); site = session.createDocument(site); return site; }
@Test public void iCanGetLatestUploadsPageProvider() throws Exception { DocumentModel site = createSite(); PageClasseur classeur = new PageClasseurAdapter.Model( session, site.getPathAsString() + "/" + LabsSiteConstants.Docs.TREE.docName(), "ma page classeur") .desc("desc page classeur") .create(); assertThat(classeur.getFolders().size(), is(0)); classeur.addFolder("My Folder", null); session.save(); PageClasseurFolder folder = classeur.getFolders().get(0); assertThat(folder.getFiles().size(), is(0)); folder.addFile(getTestBlob(), "Pomodoro cheat sheet", "title"); session.save(); assertThat(folder.getFiles().size(), is(1)); session.save(); Tools.getAdapter(LabsPublisher.class, classeur.getDocument(), null).publish(); PageProvider<DocumentModel> latestUploadsPageProvider = LabsSiteWebAppUtils.getLatestUploadsPageProvider(site, 0, session); assertNotNull(latestUploadsPageProvider); List<DocumentModel> lastUploadedDoc = latestUploadsPageProvider.getCurrentPage(); assertNotNull(lastUploadedDoc); assertEquals(1, lastUploadedDoc.size()); }
private static void updateSubDirectoryEntry( SubDirectoryInfo dirInfo, Map<String, Object> fieldMap, String id, boolean canCreateIfOptional) { DocumentModel dirEntry = dirInfo.getSession().getEntry(id); if (dirInfo.getSession().isReadOnly() || (dirEntry != null && isReadOnlyEntry(dirEntry))) { return; } if (dirEntry == null && !canCreateIfOptional) { // entry to update doesn't belong to this directory return; } Map<String, Object> map = new HashMap<String, Object>(); map.put(dirInfo.idField, id); for (Entry<String, String> e : dirInfo.fromSource.entrySet()) { map.put(e.getValue(), fieldMap.get(e.getKey())); } if (map.size() > 1) { if (canCreateIfOptional && dirInfo.isOptional && dirEntry == null) { // if entry does not exist, create it dirInfo.getSession().createEntry(map); } else { final DocumentModel entry = BaseSession.createEntryModel(null, dirInfo.dirSchemaName, id, null); // Do not set dataModel values with constructor to force fields // dirty entry.getDataModel(dirInfo.dirSchemaName).setMap(map); dirInfo.getSession().updateEntry(entry); } } }
@Test public void testCopy() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc = session.createDocument(doc); session.save(); String versionSeriesId = doc.getVersionSeriesId(); // copy DocumentModel copy = session.copy(doc.getRef(), session.getRootDocument().getRef(), "fileCopied"); // check different version series id assertNotSame(versionSeriesId, copy.getVersionSeriesId()); // create version and proxy DocumentModel folder = session.createDocumentModel("/", "folder", "Folder"); folder = session.createDocument(folder); DocumentModel proxy = session.publishDocument(doc, folder); // check same version series id assertEquals(versionSeriesId, proxy.getVersionSeriesId()); // copy proxy DocumentModel proxyCopy = session.copy(proxy.getRef(), session.getRootDocument().getRef(), "proxyCopied"); // check same version series id assertEquals(versionSeriesId, proxyCopy.getVersionSeriesId()); }
@Override public void updateEntry(DocumentModel docModel) { if (!isCurrentUserAllowed(SecurityConstants.WRITE)) { return; } if (isReadOnly() || isReadOnlyEntry(docModel)) { return; } init(); final String id = docModel.getId(); Map<String, Object> fieldMap = docModel.getDataModel(schemaName).getMap(); for (SourceInfo sourceInfo : sourceInfos) { // check if entry exists in this source, in case it can be created // in optional subdirectories boolean canCreateIfOptional = false; for (SubDirectoryInfo dirInfo : sourceInfo.requiredSubDirectoryInfos) { if (!canCreateIfOptional) { canCreateIfOptional = dirInfo.getSession().getEntry(id) != null; } updateSubDirectoryEntry(dirInfo, fieldMap, id, false); } for (SubDirectoryInfo dirInfo : sourceInfo.optionalSubDirectoryInfos) { updateSubDirectoryEntry(dirInfo, fieldMap, id, canCreateIfOptional); } } }
public void processSelectRow( String docRef, String contentViewName, String listName, Boolean selection) throws ClientException { List<DocumentModel> documents = getCurrentPageDocuments(contentViewName); DocumentModel doc = null; if (documents != null) { for (DocumentModel pagedDoc : documents) { if (pagedDoc.getRef().toString().equals(docRef)) { doc = pagedDoc; break; } } } if (doc == null) { log.error( String.format( "could not find doc '%s' in the current page of " + "content view page provider '%s'", docRef, contentViewName)); return; } String lName = (listName == null) ? DocumentsListsManager.CURRENT_DOCUMENT_SELECTION : listName; if (Boolean.TRUE.equals(selection)) { documentsListsManager.addToWorkingList(lName, doc); } else { documentsListsManager.removeFromWorkingList(lName, doc); } }
@Test public void shouldFilterLogEntriesOnEventId() throws Exception { DocumentModel doc = RestServerInit.getFile(1, session); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.putSingle("eventId", "documentModified"); ClientResponse response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); JsonNode node = mapper.readTree(response.getEntityInputStream()); List<JsonNode> nodes = getLogEntries(node); assertEquals(1, nodes.size()); assertEquals("documentModified", nodes.get(0).get("eventId").getValueAsText()); queryParams.putSingle("principalName", "bender"); response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); node = mapper.readTree(response.getEntityInputStream()); nodes = getLogEntries(node); assertEquals(0, nodes.size()); }
/** * Processes the version selection row. * * @param versionModelSelection the version model selection * @throws ClientException the client exception */ protected final void processVersionSelectRow(PageSelection<VersionModel> versionModelSelection) throws ClientException { DocumentModel currentDocument = navigationContext.getCurrentDocument(); if (currentDocument == null) { throw new ClientException( "Cannot process version select row since current document is null."); } DocumentModel version = documentManager.getDocumentWithVersion( currentDocument.getRef(), versionModelSelection.getData()); if (version == null) { throw new ClientException( "Cannot process version select row since selected version document is null."); } if (Boolean.TRUE.equals(versionModelSelection.isSelected())) { documentsListsManager.addToWorkingList( DocumentsListsManager.CURRENT_VERSION_SELECTION, version); } else { documentsListsManager.removeFromWorkingList( DocumentsListsManager.CURRENT_VERSION_SELECTION, version); } }
@GET @Path("@sharedElementTreeview") @Produces(MediaType.APPLICATION_JSON) public Response doSharedElementTreeview( @QueryParam("root") String root, @QueryParam("view") String view, @QueryParam("id") String id) throws ClientException { LabsSite site = (LabsSite) ctx.getProperty("site"); if (site != null) { AbstractDocumentTree siteTree = new SharedElementTree(ctx, site.getDocument()); String result = ""; if (root == null || "source".equals(root)) { if (id != null && !"0".equals(id)) { DocumentModel document = getCoreSession().getDocument(new IdRef(id)); String entryPoint = document.getPathAsString().replaceFirst(site.getDocument().getPathAsString(), ""); result = siteTree.enter(ctx, entryPoint); } else { siteTree.enter(ctx, ""); result = siteTree.getTreeAsJSONArray(ctx); } } else { result = siteTree.enter(ctx, root); } return Response.ok().entity(result).type(MediaType.APPLICATION_JSON).build(); } return null; }
@Override public Serializable getReference(Object entity) throws IllegalStateException { checkConfig(); DocumentModel entry = null; if (entity != null) { if (entity instanceof DirectoryEntry) { entry = ((DirectoryEntry) entity).getDocumentModel(); } else if (entity instanceof DocumentModel) { entry = (DocumentModel) entity; } if (entry != null) { if (!entry.hasSchema(schema)) { return null; } String result = (String) entry.getProperty(schema, idField); if (hierarchical) { String parent = (String) entry.getProperty(schema, parentField); try (Session session = directory.getSession()) { while (parent != null) { entry = session.getEntry(parent); if (entry == null) { break; } result = parent + separator + result; parent = (String) entry.getProperty(schema, parentField); } } } return result; } } return null; }
@Override protected void doIndexingWork(ElasticSearchIndexing esi, List<IndexingCommand> cmds) { if (cmds.isEmpty()) { return; } IndexingCommand cmd = cmds.get(0); DocumentModel doc = getDocument(cmd); if (doc == null) { return; } DocumentModelIterator iter = session.getChildrenIterator(doc.getRef()); while (iter.hasNext()) { // Add a session save to process cache invalidation session.save(); DocumentModel child = iter.next(); IndexingCommand childCommand = cmd.clone(child); if (!esi.isAlreadyScheduled(childCommand)) { esi.indexNonRecursive(childCommand); } if (child.isFolder()) { ChildrenIndexingWorker subWorker = new ChildrenIndexingWorker(monitor, childCommand); WorkManager wm = Framework.getLocalService(WorkManager.class); wm.schedule(subWorker); } } }
/** * If no short identifier was provided in the input payload, generate a short identifier from the * preferred term display name or term name. */ private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception { String result = (String) docModel.getProperty( authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER); if (Tools.isEmpty(result)) { String termDisplayName = getPrimaryDisplayName( docModel, authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME); String termName = getPrimaryDisplayName( docModel, authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_NAME); String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName( termDisplayName, termName); docModel.setProperty( authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER, generatedShortIdentifier); result = generatedShortIdentifier; } return result; }
@Factory(value = "isInsidePersonalWorkspace", scope = ScopeType.EVENT) public boolean isShowingPersonalWorkspace() { if (!initialized) { initialize(); } // NXP-9813 : navigating to a tab different than Documents should not change // the value for showingPersonalWorkspace if (mainTabsActions.isOnMainTab(DOCUMENT_MANAGEMENT_ACTION)) { DocumentModel currentDoc = navigationContext.getCurrentDocument(); if (currentDoc == null || currentDoc.getPath().segmentCount() < 2) { return false; } String rootChild = currentDoc.getPath().segment(1); String wsName = currentDoc.getPath().segment(2); showingPersonalWorkspace = rootChild != null && rootChild.startsWith(UserWorkspaceConstants.USERS_PERSONAL_WORKSPACES_ROOT) && wsName != null && wsName.equals(currentUser.getName()); } return showingPersonalWorkspace; }
public AuthorityRefDocList getReferencingObjects( ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, UriTemplateRegistry uriTemplateRegistry, List<String> serviceTypes, String propertyName, String itemcsid) throws Exception { AuthorityRefDocList authRefDocList = null; RepositoryInstanceInterface repoSession = null; boolean releaseRepoSession = false; try { RepositoryJavaClientImpl repoClient = (RepositoryJavaClientImpl) this.getRepositoryClient(ctx); repoSession = this.getRepositorySession(); if (repoSession == null) { repoSession = repoClient.getRepositorySession(ctx); releaseRepoSession = true; } DocumentFilter myFilter = getDocumentFilter(); try { DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid); DocumentModel docModel = wrapper.getWrappedObject(); String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME); authRefDocList = RefNameServiceUtils.getAuthorityRefDocs( repoSession, ctx, uriTemplateRegistry, repoClient, serviceTypes, refName, propertyName, myFilter, true /*computeTotal*/); } catch (PropertyException pe) { throw pe; } catch (DocumentException de) { throw de; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } finally { // If we got/aquired a new seesion then we're responsible for releasing it. if (releaseRepoSession && repoSession != null) { repoClient.releaseRepositorySession(ctx, repoSession); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Caught exception ", e); } throw new DocumentException(e); } return authRefDocList; }
@Test @SuppressWarnings("unchecked") public void testGroupsPageProviderSearchMode() { Map<String, Serializable> properties = new HashMap<String, Serializable>(); properties.put( AbstractGroupsPageProvider.GROUPS_LISTING_MODE_PROPERTY, AbstractGroupsPageProvider.SEARCH_ONLY_MODE); PageProvider<DocumentModel> groupsProvider = (PageProvider<DocumentModel>) ppService.getPageProvider(PROVIDER_NAME, null, null, null, properties, "gr"); List<DocumentModel> groups = groupsProvider.getCurrentPage(); assertNotNull(groups); assertEquals(2, groups.size()); DocumentModel group = groups.get(0); assertEquals("group1", group.getId()); group = groups.get(1); assertEquals("group2", group.getId()); // check computed groups groupsProvider = (PageProvider<DocumentModel>) ppService.getPageProvider(PROVIDER_NAME, null, null, null, properties, "Grp"); groups = groupsProvider.getCurrentPage(); assertNotNull(groups); assertEquals(2, groups.size()); group = groups.get(0); assertEquals("Grp1", group.getId()); group = groups.get(1); assertEquals("Grp2", group.getId()); }
protected boolean useTiling(Blob blob, DocumentModel dm) { Long width = Long.valueOf(0); Long height = Long.valueOf(0); if ("Picture".equals(dm.getType())) { try { PictureResourceAdapter adapter = dm.getAdapter(PictureResourceAdapter.class); String xpath = adapter.getViewXPath(ORIGINAL_JPEG_VIEW_NAME); if (xpath == null) { xpath = adapter.getViewXPath(ORIGINAL_VIEW_NAME); if (xpath == null) { xpath = adapter.getFirstViewXPath(); } } width = (Long) dm.getPropertyValue(xpath + "width"); height = (Long) dm.getPropertyValue(xpath + "height"); } catch (ClientException e) { log.error("Failed to get picture dimensions", e); } } else { ImagingService imagingService = Framework.getLocalService(ImagingService.class); if (imagingService != null) { Map<String, Object> imageMetadata = imagingService.getImageMetadata(blob); width = ((Integer) imageMetadata.get(MetadataConstants.META_WIDTH)).longValue(); height = ((Integer) imageMetadata.get(MetadataConstants.META_HEIGHT)).longValue(); } } Integer widthThreshold = Integer.valueOf(PictureTilingComponent.getEnvValue("WidthThreshold", "1200")); Integer heightThreshold = Integer.valueOf(PictureTilingComponent.getEnvValue("HeightThreshold", "1200")); return width > widthThreshold || height > heightThreshold; }
protected BlobHolder getBlobHolderToConvert() { Blob blob = getTarget().getAdapter(Blob.class); BlobHolder bh = null; if (blob == null) { DocumentModel doc = getTarget().getAdapter(DocumentModel.class); if (doc != null) { bh = doc.getAdapter(BlobHolder.class); if (bh != null) { blob = bh.getBlob(); } } } if (blob == null) { throw new IllegalParameterException("No Blob found"); } if (getTarget().isInstanceOf("blob")) { bh = ((BlobObject) getTarget()).getBlobHolder(); } if (bh == null) { bh = new SimpleBlobHolder(blob); } return bh; }
@Test public void testReadAclAfterSetACP() { DocumentModel folder = new DocumentModelImpl("/", "folder", "Folder"); folder = session.createDocument(folder); DocumentModel doc = new DocumentModelImpl("/folder", "doc", "File"); doc = session.createDocument(doc); session.save(); // nothing can be seen by joe try (CoreSession joeSession = openSessionAs("joe")) { DocumentModelList list = joeSession.query("SELECT * FROM Folder"); assertEquals(0, list.size()); list = joeSession.query("SELECT * FROM File"); assertEquals(0, list.size()); } // set ACL on folder ACL acl = new ACLImpl(); acl.add(new ACE("Everyone", "Read", true)); ACP acp = new ACPImpl(); acp.addACL(acl); folder.setACP(acp, true); session.save(); // now joe sees things try (CoreSession joeSession = openSessionAs("joe")) { DocumentModelList list = joeSession.query("SELECT * FROM Folder"); assertEquals(1, list.size()); assertEquals(folder.getId(), list.get(0).getId()); list = joeSession.query("SELECT * FROM File"); assertEquals(1, list.size()); assertEquals(doc.getId(), list.get(0).getId()); } }