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; }
/** * Añade un hijo al arbol. * * @param result XML resultado * @param parent Elemento padre del xml * @param root Documento raíz. * @param depth profundidad * @return devuelve un elemento XML */ private Element addChildren(DOMDocument result, Element parent, DocumentModel root, int depth) { try { List<DocumentModel> hijos = documentManager.getChildren(root.getRef()); for (DocumentModel documento : hijos) { String estado = documento.getCurrentLifeCycleState(); if (!"deleted".equals(estado) && documento.isFolder()) { Element hijo = result.createElement("document"); hijo.setAttribute("title", documento.getTitle()); hijo.setAttribute("type", documento.getType()); hijo.setAttribute("id", documento.getId()); parent.appendChild(hijo); if (depth > ArchivoConstantes.NUMERO_UNO) { addChildren(result, hijo, documento, depth - ArchivoConstantes.NUMERO_UNO); } } } } catch (ClientException e) { LOG.error("No se pudo añadir elementos al xml ", e); } return parent; }
/** * Identifies whether a document matches a supplied document type. * * @param docModel a document model. * @param docType a document type string. * @return true if the document matches the supplied document type; false if it does not. */ protected static boolean documentMatchesType(DocumentModel docModel, String docType) { if (docModel == null || Tools.isBlank(docType)) { return false; } if (docModel.getType().startsWith(docType)) { return true; } else { return false; } }
public static final Page sitePage(DocumentModel doc, CoreSession session) throws ClientException { Page page = null; if (LabsSiteConstants.Docs.SITE.type().equals(doc.getType())) { DocumentModel homePage = Tools.getAdapter(LabsSite.class, doc, session).getIndexDocument(); page = Tools.getAdapter(Page.class, homePage, session); } else { page = Tools.getAdapter(Page.class, doc, session); } return page; }
@Override public DocumentObject newDocument(String path) { try { PathRef pathRef = new PathRef(site.getTree().getPathAsString() + "/" + path); DocumentModel doc = ctx.getCoreSession().getDocument(pathRef); return (DocumentObject) ctx.newObject(doc.getType(), doc); } catch (Exception e) { throw new WebResourceNotFoundException(e.getMessage(), e); } }
@Test public void testCreateBlobWithCalculatedBlobMimetype() throws Exception { File file = getTestFile("test-data/hello.doc"); Blob blob = Blobs.createBlob(file); blob.setFilename("hello.plouf"); blob.setMimeType("pif/paf"); DocumentModel doc = service.createDocumentFromBlob( coreSession, blob, workspace.getPathAsString(), true, "test-data/hello.plouf"); assertNotNull(doc); assertEquals("File", doc.getType()); }
@Test public void testCreateBlobWithAmbiguousMimetype() throws Exception { File file = getTestFile("test-data/hello.xml"); Blob blob = Blobs.createBlob(file); blob.setMimeType("text/plain"); DocumentModel doc = service.createDocumentFromBlob( coreSession, blob, workspace.getPathAsString(), true, "test-data/hello.xml"); assertNotNull(doc); assertEquals("text/plain", blob.getMimeType()); assertEquals("Note", doc.getType()); }
/** * Retrieves a certain number of blog posts with information about the last <b>BlogPost</b>-s that * are made under an <b>BlogSite</b> that is received as parameter. */ @Override public Model getModel() throws ModelException { BlogPostListModel model = new BlogPostListModel(); if (WebEngine.getActiveContext() != null) { WebContext ctx = WebEngine.getActiveContext(); CoreSession session = ctx.getCoreSession(); DocumentModel documentModel = ctx.getTargetObject().getAdapter(DocumentModel.class); SimpleDateFormat simpleMonthFormat = new SimpleDateFormat("dd MMMM yyyy", WebEngine.getActiveContext().getLocale()); try { DocumentModel blogSite = SiteUtils.getFirstWebSiteParent(session, documentModel); DocumentModelList blogPosts = SiteQueriesCollection.queryLastModifiedPages( session, blogSite.getPathAsString(), BLOG_POST_DOC_TYPE, BLOG_POST_DOC_TYPE.equals(documentModel.getType()) ? noForBlogPost : noForBlogSite); for (DocumentModel blogPost : blogPosts) { String title = SiteUtils.getString(blogPost, "dc:title"); String path = SiteUtils.getPagePath(blogSite, blogPost); String description = SiteUtils.getString(blogPost, "dc:description"); String content = SiteUtils.getFistNWordsFromString( SiteUtils.getString(blogPost, WEBPAGE_CONTENT), Integer.MAX_VALUE); String author = SiteUtils.getString(blogPost, "dc:creator"); GregorianCalendar creationDate = SiteUtils.getGregorianCalendar(blogPost, "dc:created"); String day = getWeekDay(creationDate.get(Calendar.DAY_OF_WEEK)); BlogSiteArchiveDayModel dayModel = getYearModel(model, day); if (dayModel == null) { dayModel = new BlogSiteArchiveDayModel( day, simpleMonthFormat.format(creationDate.getTime()), 0); model.addItem(dayModel); } dayModel.increaseCount(); BlogPostModel blogPostModel = new BlogPostModel(title, path, description, content, author); dayModel.addItem(blogPostModel); } } catch (Exception e) { throw new ModelException(e); } } return model; }
@Test public void testCreateBlobWithBlobMimetypeFallback() throws Exception { // don't use a binary file, we store it in a text field and PostgreSQL doesn't accept 0x00 bytes File file = getTestFile("test-data/hello.xml"); Blob blob = Blobs.createBlob(file); blob.setFilename("hello.plouf"); blob.setMimeType("text/plain"); DocumentModel doc = service.createDocumentFromBlob( coreSession, blob, workspace.getPathAsString(), true, "test-data/hello.plouf"); assertNotNull(doc); assertEquals("text/plain", blob.getMimeType()); assertEquals("Note", doc.getType()); }
protected List<String> computeAllowedTypes(DocumentModel currentDoc) { List<String> types = new ArrayList<String>(); DocumentModel parent = documentManager.getRootDocument(); DocumentRef parentRef = currentDoc.getParentRef(); if (parentRef != null && documentManager.hasPermission(parentRef, SecurityConstants.READ)) { parent = documentManager.getDocument(parentRef); } for (Type type : typeManager.findAllAllowedSubTypesFrom(currentDoc.getType(), parent)) { types.add(type.getId()); } return types; }
public AnnotatedResult(DocumentModel doc, UriInfo info, String baseURL) { this.doc = doc; this.uriInfo = info; this.baseURL = baseURL; this.backofficeURL = URLHelper.documentUrl(doc, baseURL); this.translation = new SamarTranslationAdapter(doc); if (doc.getType().equals("Video")) { videoDocument = doc.getAdapter(VideoDocument.class); webmTranscodedVideo = videoDocument.getTranscodedVideo("WebM 480p"); mp4TranscodedVideo = videoDocument.getTranscodedVideo("MP4 480p"); } else { videoDocument = null; webmTranscodedVideo = null; mp4TranscodedVideo = null; } }
/** * publish a page or site * * @param document to publish * @throws NoPublishException if no published with a problem */ public static void publish(DocumentModel document, CoreSession session) throws NoPublishException { try { if (LabsSiteConstants.State.DRAFT.getState().equals(document.getCurrentLifeCycleState())) { LabsPublisher publisherAdapter = Tools.getAdapter(LabsPublisher.class, document, session); publisherAdapter.publish(); if (Docs.SITE.type().equals(document.getType())) { LabsSite site = Tools.getAdapter(LabsSite.class, document, session); LabsPublisher publisher = Tools.getAdapter(LabsPublisher.class, site.getIndexDocument(), session); if (publisher.isDraft()) { publisher.publish(); } } } } catch (ClientException e) { throw new NoPublishException(LabsPublishService.NOT_PUBLISHED); } }
/** * Returns a List of type not selected for the domain given as parameter * * @param document the domain to configure * @return a List of type of document, not currently selected for the domain * @since 5.5 */ public List<Type> getNotSelectedTypes(DocumentModel document) { if (!document.hasFacet(UI_TYPES_CONFIGURATION_FACET)) { return Collections.emptyList(); } List<String> allowedTypes = getAllowedTypes(document); List<Type> notSelectedTypes = new ArrayList<Type>(typeManager.findAllAllowedSubTypesFrom(document.getType())); for (Iterator<Type> it = notSelectedTypes.iterator(); it.hasNext(); ) { Type type = it.next(); if (allowedTypes.contains(type.getId())) { it.remove(); } } Collections.sort(notSelectedTypes, new TypeLabelAlphabeticalOrder(messages)); return notSelectedTypes; }
@Test public void testIntegrationTestsSetupAndTearDown() throws Exception { // --------------------------------------------------------- // Setup the integration tests environment as Administrator // --------------------------------------------------------- Blob testUserCredentialsBlob = (Blob) clientSession .newRequest(NuxeoDriveSetupIntegrationTests.ID) .set("userNames", "joe,jack") .execute(); assertNotNull(testUserCredentialsBlob); // Check test users String testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8"); assertNotNull(testUserCredentials); String[] testUserCrendentialsArray = StringUtils.split(testUserCredentials, ","); assertEquals(2, testUserCrendentialsArray.length); assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_joe:")); assertTrue(testUserCrendentialsArray[1].startsWith("nuxeoDriveTestUser_jack:")); // useMembersGroup is false by default NuxeoPrincipal joePrincipal = userManager.getPrincipal("nuxeoDriveTestUser_joe"); assertNotNull(joePrincipal); assertFalse(joePrincipal.getGroups().contains("members")); NuxeoPrincipal jackPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_jack"); assertNotNull(jackPrincipal); assertFalse(jackPrincipal.getGroups().contains("members")); // Check test workspace DocumentRef testWorkspaceRef = new PathRef(TEST_WORKSPACE_PATH); DocumentModel testWorkspace = session.getDocument(testWorkspaceRef); assertEquals("Workspace", testWorkspace.getType()); assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle()); assertTrue(session.hasPermission(joePrincipal, testWorkspaceRef, SecurityConstants.WRITE)); assertTrue(session.hasPermission(jackPrincipal, testWorkspaceRef, SecurityConstants.WRITE)); // Create test users' personal workspaces for cleanup check userWorkspaceService.getUserPersonalWorkspace( "nuxeoDriveTestUser_joe", session.getRootDocument()); userWorkspaceService.getUserPersonalWorkspace( "nuxeoDriveTestUser_jack", session.getRootDocument()); assertNotNull( session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe"))); assertNotNull( session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack"))); // ---------------------------------------------------------------------- // Setup the integration tests environment with other user names without // having teared it down previously => should start by cleaning it up // ---------------------------------------------------------------------- testUserCredentialsBlob = (Blob) clientSession .newRequest(NuxeoDriveSetupIntegrationTests.ID) .set("userNames", "sarah") .set("useMembersGroup", true) .execute(); assertNotNull(testUserCredentialsBlob); // Check cleanup assertNull(userManager.getPrincipal("nuxeoDriveTestUser_joe")); assertNull(userManager.getPrincipal("nuxeoDriveTestUser_jack")); // Invalid VCS cache session.save(); try { session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe")); fail("User workspace should not exist."); } catch (ClientException e) { assertEquals( "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe", e.getMessage()); } try { session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack")); fail("User workspace should not exist."); } catch (ClientException e) { assertEquals( "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack", e.getMessage()); } // Check test users testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8"); assertNotNull(testUserCredentials); testUserCrendentialsArray = StringUtils.split(testUserCredentials, ","); assertEquals(1, testUserCrendentialsArray.length); assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_sarah:")); NuxeoPrincipal sarahPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_sarah"); assertNotNull(sarahPrincipal); assertTrue(sarahPrincipal.getGroups().contains("members")); // Check test workspace testWorkspace = session.getDocument(testWorkspaceRef); assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle()); assertTrue(session.hasPermission(sarahPrincipal, testWorkspaceRef, SecurityConstants.WRITE)); // Create test users' personal workspaces for cleanup check userWorkspaceService.getUserPersonalWorkspace( "nuxeoDriveTestUser_sarah", session.getRootDocument()); assertNotNull( session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah"))); // ---------------------------------------------------------------------- // Try to setup the integration tests environment as an unauthorized // user => should fail // ---------------------------------------------------------------------- Session unauthorizedSession = automationClient.getSession("nuxeoDriveTestUser_sarah", testUserCrendentialsArray[0]); try { unauthorizedSession .newRequest(NuxeoDriveSetupIntegrationTests.ID) .set("userNames", "john,bob") .execute(); fail( "NuxeoDrive.SetupIntegrationTests operation should not be callable by a non administrator."); } catch (Exception e) { // Expected } // ---------------------------------------------------------------------- // Try to tear down the integration tests environment as an unauthorized // user => should fail // ---------------------------------------------------------------------- try { unauthorizedSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute(); fail( "NuxeoDrive.TearDownIntegrationTests operation should not be callable by a non administrator."); } catch (Exception e) { // Expected } // ---------------------------------------------------------------------- // Tear down the integration tests environment as Administrator // ---------------------------------------------------------------------- clientSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute(); assertTrue(userManager.searchUsers("nuxeoDriveTestUser_").isEmpty()); // Invalid VCS cache session.save(); try { session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah")); fail("User workspace should not exist."); } catch (ClientException e) { assertEquals( "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah", e.getMessage()); } assertFalse(session.exists(testWorkspaceRef)); }
@Test public void testWriteOperations() throws Exception { // ------------------------------------------------------ // Check #createFolder // ------------------------------------------------------ // Not allowed to create a folder in a non FolderItem try { fileSystemItemManagerService.createFolder( DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), "A new folder", principal); fail("Folder creation in a non folder item should fail."); } catch (NuxeoException e) { assertEquals( String.format( "Cannot create a folder in file system item with id %s because it is not a folder but is: " + "DocumentBackedFileItem(id=\"%s\", name=\"Joe.odt\")", DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId()), e.getMessage()); } // Folder creation FolderItem newFolderItem = fileSystemItemManagerService.createFolder( DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), "A new folder", principal); assertNotNull(newFolderItem); assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), newFolderItem.getParentId()); assertEquals("A new folder", newFolderItem.getName()); DocumentModelList folderChildren = session.query( String.format( "select * from Document where ecm:parentId = '%s' and ecm:primaryType = 'Folder' order by dc:title asc", folder.getId())); DocumentModel newFolder = folderChildren.get(0); assertTrue(newFolder.isFolder()); assertEquals("A new folder", newFolder.getTitle()); // Parent folder children check assertEquals( 6, fileSystemItemManagerService .getChildren(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal) .size()); // ------------------------------------------------------ // Check #createFile // ------------------------------------------------------ // File creation Blob blob = new StringBlob("Content of a new file."); blob.setFilename("New file.odt"); blob.setMimeType("application/vnd.oasis.opendocument.text"); FileItem fileItem = fileSystemItemManagerService.createFile(newFolderItem.getId(), blob, principal); assertNotNull(fileItem); assertEquals(newFolderItem.getId(), fileItem.getParentId()); assertEquals("New file.odt", fileItem.getName()); folderChildren = session.query( String.format("select * from Document where ecm:parentId = '%s'", newFolder.getId())); assertEquals(1, folderChildren.size()); DocumentModel newFile = folderChildren.get(0); assertEquals("File", newFile.getType()); assertEquals("New file.odt", newFile.getTitle()); assertEquals("/syncRoot1/aFolder/A new folder/New file.odt", newFile.getPathAsString()); Blob newFileBlob = (Blob) newFile.getPropertyValue("file:content"); assertEquals("New file.odt", newFileBlob.getFilename()); assertEquals("Content of a new file.", newFileBlob.getString()); assertEquals( "nxfile/test/" + newFile.getId() + "/blobholder:0/New%20file.odt", fileItem.getDownloadURL()); assertEquals("MD5", fileItem.getDigestAlgorithm()); assertEquals(newFileBlob.getDigest(), fileItem.getDigest()); // Parent folder children check assertEquals( 1, fileSystemItemManagerService.getChildren(newFolderItem.getId(), principal).size()); // ------------------------------------------------------ // Check #updateFile // ------------------------------------------------------ String fileItemId = fileItem.getId(); String fileItemParentId = fileItem.getParentId(); blob = new StringBlob("Modified content of an existing file."); fileItem = fileSystemItemManagerService.updateFile(fileItemId, blob, principal); assertNotNull(fileItem); assertEquals(fileItemId, fileItem.getId()); assertEquals(fileItemParentId, fileItem.getParentId()); assertEquals("New file.odt", fileItem.getName()); folderChildren = session.query( String.format("select * from Document where ecm:parentId = '%s'", newFolder.getId())); assertEquals(1, folderChildren.size()); DocumentModel updatedFile = folderChildren.get(0); assertEquals("File", updatedFile.getType()); assertEquals("New file.odt", updatedFile.getTitle()); assertEquals("/syncRoot1/aFolder/A new folder/New file.odt", updatedFile.getPathAsString()); Blob updatedFileBlob = (Blob) updatedFile.getPropertyValue("file:content"); assertEquals("New file.odt", updatedFileBlob.getFilename()); assertEquals("Modified content of an existing file.", updatedFileBlob.getString()); assertEquals( "nxfile/test/" + updatedFile.getId() + "/blobholder:0/New%20file.odt", fileItem.getDownloadURL()); assertEquals("MD5", fileItem.getDigestAlgorithm()); assertEquals(updatedFileBlob.getDigest(), fileItem.getDigest()); // ------------------------------------------------------ // Check #delete // ------------------------------------------------------ // File deletion fileSystemItemManagerService.delete( DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + updatedFile.getId(), principal); updatedFile = session.getDocument(new IdRef(updatedFile.getId())); assertEquals("deleted", updatedFile.getCurrentLifeCycleState()); // Parent folder children check assertTrue( fileSystemItemManagerService.getChildren(newFolderItem.getId(), principal).isEmpty()); // ------------------------------------------------------ // Check #rename // ------------------------------------------------------ // Folder rename String fsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(); FileSystemItem fsItem = fileSystemItemManagerService.rename(fsItemId, "Jack's folder has a new name", principal); assertEquals(fsItemId, fsItem.getId()); String expectedSyncRoot1Id = DEFAULT_SYNC_ROOT_ITEM_ID_PREFIX + syncRoot1.getId(); assertEquals(expectedSyncRoot1Id, fsItem.getParentId()); assertEquals("Jack's folder has a new name", fsItem.getName()); folder = session.getDocument(folder.getRef()); assertEquals("Jack's folder has a new name", folder.getTitle()); // File rename with title != filename // => should rename filename but not title assertEquals("aFile", file.getTitle()); assertEquals("Joe.odt", ((Blob) file.getPropertyValue("file:content")).getFilename()); fsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(); fsItem = fileSystemItemManagerService.rename(fsItemId, "File new name.odt", principal); assertEquals(fsItemId, fsItem.getId()); assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId()); assertEquals("File new name.odt", fsItem.getName()); file = session.getDocument(file.getRef()); assertEquals("aFile", file.getTitle()); Blob fileBlob = (Blob) file.getPropertyValue("file:content"); assertEquals("File new name.odt", fileBlob.getFilename()); fileItem = (FileItem) fsItem; assertEquals( "nxfile/test/" + file.getId() + "/blobholder:0/File%20new%20name.odt", fileItem.getDownloadURL()); assertEquals("MD5", fileItem.getDigestAlgorithm()); assertEquals(fileBlob.getDigest(), fileItem.getDigest()); // File rename with title == filename // => should rename filename and title blob = new StringBlob("File for a doc with title == filename."); blob.setFilename("Title-filename equality.odt"); blob.setMimeType("application/vnd.oasis.opendocument.text"); fileItem = fileSystemItemManagerService.createFile(newFolderItem.getId(), blob, principal); // Note that the PathSegmentService truncates doc title at 24 characters newFile = session.getDocument( new PathRef("/syncRoot1/aFolder/A new folder/Title-filename equality.")); assertEquals("Title-filename equality.odt", newFile.getTitle()); assertEquals( "Title-filename equality.odt", ((Blob) newFile.getPropertyValue("file:content")).getFilename()); fileItem = (FileItem) fileSystemItemManagerService.rename( DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + newFile.getId(), "Renamed title-filename equality.odt", principal); assertEquals("Renamed title-filename equality.odt", fileItem.getName()); newFile = session.getDocument(newFile.getRef()); assertEquals("Renamed title-filename equality.odt", newFile.getTitle()); newFileBlob = (Blob) newFile.getPropertyValue("file:content"); assertEquals("Renamed title-filename equality.odt", newFileBlob.getFilename()); assertEquals( "nxfile/test/" + newFile.getId() + "/blobholder:0/Renamed%20title-filename%20equality.odt", fileItem.getDownloadURL()); assertEquals("MD5", fileItem.getDigestAlgorithm()); assertEquals(newFileBlob.getDigest(), fileItem.getDigest()); // ------------------------------------------------------ // Check #move // ------------------------------------------------------ // Not allowed to move a file system item to a non FolderItem String srcFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + note.getId(); String destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(); try { fileSystemItemManagerService.move(srcFsItemId, destFsItemId, principal); fail("Move to a non folder item should fail."); } catch (NuxeoException e) { assertEquals( String.format( "Cannot move a file system item to file system item with id %s because it is not a folder.", DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId()), e.getMessage()); } // Move to a FolderItem destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(); FileSystemItem movedFsItem = fileSystemItemManagerService.move(srcFsItemId, destFsItemId, principal); assertEquals(srcFsItemId, movedFsItem.getId()); assertEquals(destFsItemId, movedFsItem.getParentId()); assertEquals("aNote.txt", movedFsItem.getName()); note = session.getDocument(note.getRef()); assertEquals("/syncRoot1/aFolder/aSubFolder/aNote", note.getPathAsString()); assertEquals("aNote", note.getTitle()); }
@Override protected void doHandleStatelessRequest(Request req, Response res) { String repo = (String) req.getAttributes().get("repo"); String docid = (String) req.getAttributes().get("docid"); DOMDocumentFactory domFactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domFactory.createDocument(); if (repo == null || repo.equals("*")) { try { Element serversNode = result.createElement("avalaibleServers"); result.setRootElement((org.dom4j.Element) serversNode); RepositoryManager repositoryManager = Framework.getLocalService(RepositoryManager.class); for (String repositoryName : repositoryManager.getRepositoryNames()) { Element server = result.createElement("server"); server.setAttribute("title", repositoryName); server.setAttribute("url", getRelURL(repositoryName, "*")); serversNode.appendChild(server); } res.setEntity(result.asXML(), MediaType.TEXT_XML); res.getEntity().setCharacterSet(CharacterSet.UTF_8); return; } catch (DOMException e) { handleError(result, res, e); return; } } else { DocumentModel dm; boolean init = initRepository(res, repo); boolean isRoot = false; try { if (init) { if (docid == null || docid.equals("*")) { dm = session.getRootDocument(); isRoot = true; } else { dm = session.getDocument(new IdRef(docid)); } } else { handleError(res, "Unable to init repository"); return; } } catch (NuxeoException e) { handleError(res, e); return; } Element current = result.createElement("document"); try { current.setAttribute("title", dm.getTitle()); } catch (DOMException | NuxeoException e) { handleError(res, e); } current.setAttribute("type", dm.getType()); current.setAttribute("id", dm.getId()); current.setAttribute("name", dm.getName()); if (isRoot) { current.setAttribute("url", getRelURL(repo, "")); } else { current.setAttribute("url", getRelURL(repo, dm.getRef().toString())); } result.setRootElement((org.dom4j.Element) current); if (dm.isFolder()) { // Element childrenElem = result.createElement("children"); // root.appendChild(childrenElem); DocumentModelList children; try { children = session.getChildren(dm.getRef()); } catch (NuxeoException e) { handleError(result, res, e); return; } for (DocumentModel child : children) { Element el = result.createElement("document"); try { el.setAttribute("title", child.getTitle()); } catch (DOMException e) { handleError(res, e); } catch (NuxeoException e) { handleError(res, e); } el.setAttribute("type", child.getType()); el.setAttribute("id", child.getId()); el.setAttribute("name", child.getName()); el.setAttribute("url", getRelURL(repo, child.getRef().toString())); current.appendChild(el); } } res.setEntity(result.asXML(), MediaType.TEXT_XML); res.getEntity().setCharacterSet(CharacterSet.UTF_8); } }
public boolean isMailFolder() { DocumentModel currentDocument = navigationContext.getCurrentDocument(); return MAIL_FOLDER_TYPE.equals(currentDocument.getType()); }
protected void processDocAttributes( DocumentModel doc, Element el, AttributeConfigDescriptor conf) { String targetDocProperty = conf.getTargetDocProperty(); if (log.isDebugEnabled()) { log.debug( String.format( MSG_UPDATE_PROPERTY, targetDocProperty, el.getUniquePath(), doc.getPathAsString(), doc.getType(), conf.toString())); } Property property = doc.getProperty(targetDocProperty); if (property.isScalar()) { Object value = resolveAndEvaluateXmlNode(el, conf.getSingleXpath()); if (log.isTraceEnabled()) { log.trace( String.format( MSG_UPDATE_PROPERTY_TRACE, targetDocProperty, el.getUniquePath(), value, conf.toString())); } property.setValue(value); } else if (property.isComplex()) { if (property instanceof BlobProperty) { Object value = resolveBlob(el, conf); if (log.isTraceEnabled()) { log.trace( String.format( MSG_UPDATE_PROPERTY_TRACE, targetDocProperty, el.getUniquePath(), value, conf.toString())); } property.setValue(value); } else { Object value = resolveComplex(el, conf); if (log.isTraceEnabled()) { log.trace( String.format( MSG_UPDATE_PROPERTY_TRACE, targetDocProperty, el.getUniquePath(), value, conf.toString())); } property.setValue(value); } } else if (property.isList()) { ListType lType = (ListType) property.getType(); Serializable value; if (lType.getFieldType().isSimpleType()) { value = (Serializable) resolveAndEvaluateXmlNode(el, conf.getSingleXpath()); if (value != null) { Object values = property.getValue(); if (values instanceof List) { ((List) values).add(value); property.setValue(values); } else if (values instanceof Object[]) { List<Object> valuesList = new ArrayList<>(); Collections.addAll(valuesList, (Object[]) property.getValue()); valuesList.add(value); property.setValue(valuesList.toArray()); } else { log.error( "Simple multi value property " + targetDocProperty + " is neither a List nor an Array"); } } } else { value = (Serializable) resolveComplex(el, conf); if (value != null && !conf.getMapping().isEmpty()) { property.addValue(value); } } if (log.isTraceEnabled()) { log.trace( String.format( MSG_UPDATE_PROPERTY_TRACE, targetDocProperty, el.getUniquePath(), value, conf.toString())); } } }
/** * Manejador principal del restlet. * * @param req Request * @param res Response */ @Override public void handle(Request req, Response res) { /* Conflicto con Checkstyle. No se pueden declarar como final los métodos de * beans EJB que hagan uso de dependencias inyectadas, ya que dichas * dependencias toman el valor null. * No se declara como final debido a que en ese caso * la inyección de dependencias dejaría de funcionar. */ String repo = (String) req.getAttributes().get("repo"); String cdcDocId = (String) req.getAttributes().get("docid"); if (cdcDocId == null) { handleError(res, "you must specify a CdC source document Id."); } else { String depth = getQueryParamValue(req, "depth", "1"); if (repo == null || repo.equals("*")) { handleError(res, "you must specify a repository"); } else { int profundidad = Integer.parseInt(depth); // String cdcPath = // Framework.getProperty(ArchivoConstantes.PROPIEDAD_CDC_PATH); DOMDocumentFactory domFactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domFactory.createDocument(); try { navigationContext.setCurrentServerLocation(new RepositoryLocation(repo)); documentManager = navigationContext.getOrCreateDocumentManager(); DocumentModel cdcRoot = documentManager.getDocument(new IdRef(cdcDocId)); if (cdcRoot != null) { Element current = result.createElement("document"); current.setAttribute("title", cdcRoot.getTitle()); current.setAttribute("type", cdcRoot.getType()); current.setAttribute("id", cdcRoot.getId()); current.setAttribute("path", cdcRoot.getPathAsString()); result.setRootElement((org.dom4j.Element) current); addChildren(result, current, cdcRoot, profundidad); } else { Element noEncontrado = result.createElement("cdCNoRegistrado"); noEncontrado.setAttribute("variable", ArchivoConstantes.PROPIEDAD_CDC_PATH); noEncontrado.setAttribute("valor", cdcDocId); result.setRootElement((org.dom4j.Element) noEncontrado); LOG.error( "No se ha configurado la ruta del CdC; por favor configure la ruta en la propiedad " + ArchivoConstantes.PROPIEDAD_CDC_PATH); } res.setEntity(result.asXML(), MediaType.TEXT_XML); res.getEntity().setCharacterSet(CharacterSet.UTF_8); } /** * Conflicto con checkstyle. Es necesario capturar la excepción Exception, dado que * el código nativo de Nuxeo lanza dicha excepción. En caso contrario, este * código no compilaría */ catch (Exception e) { LOG.error(e); handleError(res, e); } } } }
@Override public void work() throws Exception { if (ids.isEmpty()) { return; } initSession(repositoryName); // if the runtime has shutdown (normally because tests are finished) // this can happen, see NXP-4009 if (session.getPrincipal() == null) { return; } fulltextInfo = RepositoryResolver.getModelFulltext(repositoryName); fulltextParserClass = RepositoryResolver.getFulltextParserClass(repositoryName); initFulltextParser(); // we have all the info from the bundle, now do the extraction BlobsExtractor extractor = new BlobsExtractor(); Collection<FulltextUpdaterInfo> infos = new ArrayList<FulltextUpdaterInfo>(); int n = 0; setStatus("Extracting"); for (String id : ids) { setProgress(new Progress(++n, ids.size())); IdRef docRef = new IdRef(id); if (!session.exists(docRef)) { // doc is gone continue; } DocumentModel doc = session.getDocument(docRef); if (doc.isProxy()) { // proxies don't have any fulltext attached, it's // the target document that carries it continue; } if (!fulltextInfo.isFulltextIndexable(doc.getType())) { // excluded by config continue; } // Iterate on each index to set the binaryText column for (String indexName : fulltextInfo.indexNames) { if (!fulltextInfo.indexesAllBinary.contains(indexName) && fulltextInfo.propPathsByIndexBinary.get(indexName) == null) { // nothing to do: index not configured for blob continue; } extractor.setExtractorProperties( fulltextInfo.propPathsByIndexBinary.get(indexName), fulltextInfo.propPathsExcludedByIndexBinary.get(indexName), fulltextInfo.indexesAllBinary.contains(indexName)); List<Blob> blobs = extractor.getBlobs(doc); String text = blobsToText(blobs, id); fulltextParser.setStrings(new ArrayList<String>()); fulltextParser.parse(text, null); text = StringUtils.join(fulltextParser.getStrings(), " "); FulltextUpdaterInfo info = new FulltextUpdaterInfo(); info.jobId = doc.getId(); info.indexName = indexName; info.text = text; infos.add(info); } } if (!infos.isEmpty()) { // false = binary text Work work = new FulltextUpdaterWork(false, repositoryName, infos); Framework.getLocalService(WorkManager.class).schedule(work); } setStatus(null); }