@Override public NodeRef createNode( Resource resource, RepositoryLocation targetLocation, String encoding, String mimetype, QName nodeType) throws IOException { NodeRef rootNode = nodeService.getRootNode(targetLocation.getStoreRef()); final List<NodeRef> parentNodes = searchService.selectNodes( rootNode, targetLocation.getPath(), null, namespaceService, false); Assert.isTrue(parentNodes.size() == 1, "Target location leads to not 1 unique Node reference"); final String fileName = resource.getFilename(); final FileInfo fileInfo = fileFolderService.create(parentNodes.get(0), fileName, nodeType); final NodeRef nodeRef = fileInfo.getNodeRef(); final ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true); writer.putContent(resource.getInputStream()); if (mimetype == null) { mimetype = guessMimetype(resource); } if (encoding == null) { encoding = guessEncoding(resource.getInputStream(), mimetype); } writer.setMimetype(mimetype); writer.setEncoding(encoding); return nodeRef; }
/** * preparing data to send to applet for sign process * * @param dataFromApplet encoded64 data received from applet certificate choice * @return the data to passa to sign applet */ protected void prepareDataToAppletSign() { // calcolo impronte documenti selezionati SinekartaUtility su = SinekartaUtility.getCurrentInstance(); try { // copio il file per la conversione NodeRef folder = su.getNodeService().getPrimaryParent(selectedDocumentNode).getParentRef(); FileInfo newFile = su.getFileFolderService().copy(selectedDocumentNode, folder, documentNamePdf); selectedDocumentNodePdf = newFile.getNodeRef(); // conversione documento in PDF/A Action documentToPDFA = su.getActionService().createAction(DocumentToPDFA.ACTION_NAME_DOCUMENT_TO_PDFA); try { su.getActionService().executeAction(documentToPDFA, selectedDocumentNodePdf, false, false); } catch (Throwable t) { tracer.error("Unable to execute PDF/A conversion : " + t.getMessage(), t); throw new SignFailedException("Unable to execute PDF/A conversion : " + t.getMessage(), t); } Action digitalSignaturePrepareAndAddDocument = su.getActionService() .createAction( DocumentDigitalSignaturePrepareAndAddDocument .ACTION_NAME_DOCUMENT_DIGITAL_SIGNATURE_PREPARE_AND_ADD_DOCUMENT); digitalSignaturePrepareAndAddDocument.setParameterValue( DocumentDigitalSignaturePrepareAndAddDocument.PARAM_SIGN_DESCRIPTION, description); digitalSignaturePrepareAndAddDocument.setParameterValue( DocumentDigitalSignaturePrepareAndAddDocument.PARAM_SIGN_LOCATION, Constants.SIGN_LOCATION_ITALY); digitalSignaturePrepareAndAddDocument.setParameterValue( DocumentDigitalSignaturePrepareAndAddDocument.PARAM_CLIENT_AREA, su.getDataFromAppletCertificateChoice()); try { su.getActionService() .executeAction( digitalSignaturePrepareAndAddDocument, selectedDocumentNodePdf, false, false); } catch (Throwable t) { tracer.error("Unable to prepare data for document sign : " + t.getMessage(), t); throw new SignFailedException( "Unable to prepare data for document sign : " + t.getMessage(), t); } su.setDataToAppletSign( (String) digitalSignaturePrepareAndAddDocument.getParameterValue( DocumentDigitalSignaturePrepareAndAddDocument.PARAM_RESULT)); } catch (SignFailedException e) { tracer.error(e.getMessage(), e); throw e; } catch (Exception e) { tracer.error("Unable to calculate document fingerprint.", e); throw new SignFailedException( "Unable to calculate document fingerprint : " + e.getMessage(), e); } }
/** Searches for the node or nodes that match the path element for the given parent node */ private List<NodeRef> getDirectDescendents(NodeRef pathRootNodeRef, String pathElement) { if (logger.isDebugEnabled()) { logger.debug( "Getting direct descendents: \n" + " Path Root: " + pathRootNodeRef + "\n" + " Path Element: " + pathElement); } List<NodeRef> results = null; // if this contains no wildcards, then we can fasttrack it if (!WildCard.containsWildcards(pathElement)) { // a specific name is required NodeRef foundNodeRef = fileFolderService.searchSimple(pathRootNodeRef, pathElement); if (foundNodeRef == null) { results = Collections.emptyList(); } else { results = Collections.singletonList(foundNodeRef); } } else { // escape for the Lucene syntax search String escapedPathElement = SearchLanguageConversion.convertCifsToLucene(pathElement); // do the lookup List<org.alfresco.service.cmr.model.FileInfo> childInfos = fileFolderService.search(pathRootNodeRef, escapedPathElement, false); // convert to noderefs results = new ArrayList<NodeRef>(childInfos.size()); for (org.alfresco.service.cmr.model.FileInfo info : childInfos) { results.add(info.getNodeRef()); } } // done return results; }
/** * @param ruleAction * @param filename * @return */ protected NodeRef createDestinationNode( String filename, NodeRef destinationParent, NodeRef target) { NodeRef destinationNode; FileInfo fileInfo = fileFolderService.create(destinationParent, filename, ContentModel.TYPE_CONTENT); destinationNode = fileInfo.getNodeRef(); return destinationNode; }
protected void onSetUpInTransaction() throws Exception { System.err.println("onSetUpInTransaction"); super.onSetUpInTransaction(); this.nodeService = (NodeService) super.applicationContext.getBean("dbNodeService"); assertNotNull(this.nodeService); final FileFolderService fileFolderService = (FileFolderService) super.applicationContext.getBean("fileFolderService"); assertNotNull(fileFolderService); this.formsService = (FormsService) super.applicationContext.getBean("FormsService"); assertNotNull(this.formsService); final MutableAuthenticationService authenticationService = (MutableAuthenticationService) applicationContext.getBean("authenticationService"); authenticationService.clearCurrentSecurityContext(); final MutableAuthenticationDao authenticationDAO = (MutableAuthenticationDao) applicationContext.getBean("authenticationDao"); // Create a workspace that contains the 'live' nodes final StoreRef testStoreRef = this.nodeService.createStore( StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis()); // Get a reference to the root node final NodeRef rootNodeRef = this.nodeService.getRootNode(testStoreRef); // Create an authenticate the user if (!authenticationDAO.userExists(AuthenticationUtil.getAdminUserName())) { authenticationService.createAuthentication( AuthenticationUtil.getAdminUserName(), "admin".toCharArray()); } TestWithUserUtils.authenticateUser( AuthenticationUtil.getAdminUserName(), "admin", rootNodeRef, authenticationService); // set up a faces context final MockExternalContext ec = new MockExternalContext( new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse()); final StaticWebApplicationContext ac = new StaticWebApplicationContext(); ac.setParent(this.applicationContext); this.applicationContext = ac; ec.getApplicationMap() .put(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); new MockFacesContext(ec); final FileInfo folderInfo = fileFolderService.create(rootNodeRef, "test_form", WCMAppModel.TYPE_FORMFOLDER); final HashMap<QName, Serializable> props = new HashMap<QName, Serializable>(); this.nodeService.addAspect(folderInfo.getNodeRef(), WCMAppModel.ASPECT_FORM, props); this.mockForm = new MockForm(folderInfo.getNodeRef(), this.formsService); }
@Override public boolean isFolder(String site, String path) { boolean toRet = false; PersistenceManagerService persistenceManagerService = _servicesManager.getService(PersistenceManagerService.class); String rootPath = SITE_REPO_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, site); NodeRef nodeRef = persistenceManagerService.getNodeRef(rootPath, path); if (nodeRef != null) { FileInfo fileInfo = persistenceManagerService.getFileInfo(nodeRef); toRet = fileInfo.isFolder(); } return toRet; }
private void setFlags(FileInfo messageFileInfo) throws Exception { imapService.setFlags(messageFileInfo, flags, true); NodeRef messageNodeRef = messageFileInfo.getNodeRef(); Map<QName, Serializable> props = nodeService.getProperties(messageNodeRef); assertTrue("Can't set SEEN flag", props.containsKey(ImapModel.PROP_FLAG_SEEN)); assertTrue("Can't set FLAGGED flag", props.containsKey(ImapModel.PROP_FLAG_FLAGGED)); assertTrue("Can't set ANSWERED flag", props.containsKey(ImapModel.PROP_FLAG_ANSWERED)); assertTrue("Can't set DELETED flag", props.containsKey(ImapModel.PROP_FLAG_DELETED)); }
@Test public void canPutFileWithResourceTag() throws ServletException, IOException { String fileName = "test_ALF-18821.txt"; // VtiIfHeaderAction PUT handler expects the file to have already been created (in most cases) FileInfo createdFile = fileFolderService.create(docLib, fileName, ContentModel.TYPE_CONTENT); request = new MockHttpServletRequest( "PUT", "/alfresco/" + shortSiteId + "/documentLibrary/" + fileName); String fileContent = "This is the test file's content."; request.setContent(fileContent.getBytes()); request.addHeader("If", "(<rt:792589C1-2E8F-410E-BC91-4EF42DA88D3C@00862604462>)"); dispatcher.service(request, response); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String retContent = fileFolderService.getReader(createdFile.getNodeRef()).getContentString(); assertEquals(fileContent, retContent); }
/** * get document from wcm content * * @param path * @return document * @throws ServiceException */ public InputStream getContent(String path) { InputStream retStream = null; PersistenceManagerService persistenceManagerService = _servicesManager.getService(PersistenceManagerService.class); NodeRef nodeRef = persistenceManagerService.getNodeRef(path); if (nodeRef != null) { FileInfo fileInfo = persistenceManagerService.getFileInfo(nodeRef); if (fileInfo.isFolder()) { logger.info(MSG_CONTENT_FOR_FOLDER_REQUESTED, path); } else { ContentReader reader = persistenceManagerService.getReader(nodeRef); retStream = reader.getContentInputStream(); } } else { logger.info(MSG_NODE_REF_IS_NULL_FOR_PATH, path); } return retStream; }
public void testSetFlag() throws Exception { NavigableMap<Long, FileInfo> fis = imapService.getFolderStatus( authenticationService.getCurrentUserName(), testImapFolderNodeRef, ImapViewMode.ARCHIVE) .search; if (fis != null && fis.size() > 0) { FileInfo messageFileInfo = fis.firstEntry().getValue(); reauthenticate(USER_NAME, USER_PASSWORD); permissionService.setPermission( testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true); reauthenticate(anotherUserName, anotherUserName); imapService.setFlag(messageFileInfo, Flags.Flag.RECENT, true); Serializable prop = nodeService.getProperty(messageFileInfo.getNodeRef(), ImapModel.PROP_FLAG_RECENT); assertNotNull("Can't set RECENT flag", prop); } }
/** * Relink the content data from a new node to an existing node to preserve the version history. * * @param tempNodeRef temp nodeRef * @param nodeToMoveRef NodeRef * @param newParentNodeRef NodeRef * @param newName new name */ public void relinkNode( NodeRef tempNodeRef, NodeRef nodeToMoveRef, NodeRef newParentNodeRef, String newName) throws FileNotFoundException, FileExistsException { // Get the properties for the old and new nodes org.alfresco.service.cmr.model.FileInfo tempFileInfo = fileFolderService.getFileInfo(tempNodeRef); org.alfresco.service.cmr.model.FileInfo fileToMoveInfo = fileFolderService.getFileInfo(nodeToMoveRef); // Save the current name of the old node String tempName = tempFileInfo.getName(); try { // Rename operation will add or remove the sys:temporary aspect appropriately // rename temp file to the new name fileFolderService.rename(tempNodeRef, newName); // rename new file to old name fileFolderService.rename(nodeToMoveRef, tempName); } catch (org.alfresco.service.cmr.model.FileNotFoundException e) { throw new FileNotFoundException(e.getMessage()); } catch (org.alfresco.service.cmr.model.FileExistsException e) { throw new FileExistsException(e.getMessage()); } if (!tempFileInfo.isFolder() && !fileToMoveInfo.isFolder()) { // swap the content between the two ContentData oldContentData = tempFileInfo.getContentData(); if (oldContentData == null) { String mimetype = mimetypeService.guessMimetype(tempName); oldContentData = ContentData.setMimetype(null, mimetype); } ContentData newContentData = fileToMoveInfo.getContentData(); // Reset the mime type // TODO Pass the content along when guessing the mime type, so we're more accurate String mimetype = mimetypeService.guessMimetype(newName); newContentData = ContentData.setMimetype(newContentData, mimetype); nodeService.setProperty(tempNodeRef, ContentModel.PROP_CONTENT, newContentData); nodeService.setProperty(nodeToMoveRef, ContentModel.PROP_CONTENT, oldContentData); } }
/** * Test attachment extraction with a TNEF message * * @throws Exception */ public void testAttachmentExtraction() throws Exception { AuthenticationUtil.setRunAsUserSystem(); /** Load a TNEF message */ ClassPathResource fileResource = new ClassPathResource("imap/test-tnef-message.eml"); assertNotNull("unable to find test resource test-tnef-message.eml", fileResource); InputStream is = new FileInputStream(fileResource.getFile()); MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), is); /** Create a test node containing the message */ String storePath = "workspace://SpacesStore"; String companyHomePathInStore = "/app:company_home"; StoreRef storeRef = new StoreRef(storePath); NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes( storeRootNodeRef, companyHomePathInStore, null, namespaceService, false); NodeRef companyHomeNodeRef = nodeRefs.get(0); FileInfo f1 = fileFolderService.create( companyHomeNodeRef, "ImapServiceImplTest", ContentModel.TYPE_FOLDER); FileInfo d2 = fileFolderService.create(f1.getNodeRef(), "ImapServiceImplTest", ContentModel.TYPE_FOLDER); FileInfo f2 = fileFolderService.create( f1.getNodeRef(), "test-tnef-message.eml", ContentModel.TYPE_CONTENT); ContentWriter writer = fileFolderService.getWriter(f2.getNodeRef()); writer.putContent(new FileInputStream(fileResource.getFile())); NodeRef folder = imapService.extractAttachments(f1.getNodeRef(), f2.getNodeRef(), message); assertNotNull(folder); List<FileInfo> files = fileFolderService.listFiles(folder); assertTrue("three files not found", files.size() == 3); }
private static void checkClustering( List<LoaderServerProxy> remoteServers, List<NodeRef> workingRootNodeRefs) throws Exception { List<String> problems = new ArrayList<String>(10); for (LoaderServerProxy remoteServer : remoteServers) { String ticket = remoteServer.ticket; for (NodeRef workingRootNodeRef : workingRootNodeRefs) { try { // Get the working root node. If the cluster is correctly configured, // it will be available on all the servers. FileInfo fileInfo = remoteServer.fileFolderRemote.getFileInfo(ticket, workingRootNodeRef); if (fileInfo == null) { problems.add("Cannot find the working root node on server: " + remoteServer.rmiUrl); continue; } // Now look for and create a file against which to store some content String sampleFilename = "InitialSample.txt"; String sampleContent = "Sample content"; NodeRef sampleNodeRef = remoteServer.fileFolderRemote.searchSimple( ticket, workingRootNodeRef, sampleFilename); if (sampleNodeRef == null) { FileInfo sampleFileInfo = remoteServer.fileFolderRemote.create( ticket, workingRootNodeRef, sampleFilename, ContentModel.TYPE_CONTENT); sampleNodeRef = sampleFileInfo.getNodeRef(); // Write some content byte[] bytes = sampleContent.getBytes("UTF-8"); remoteServer.fileFolderRemote.putContent(ticket, sampleNodeRef, bytes, sampleFilename); } // Get the content and ensure that it is the same byte[] bytes = remoteServer.fileFolderRemote.getContent(ticket, sampleNodeRef); if (bytes == null) { problems.add("Sample content was not found on server: " + remoteServer.rmiUrl); continue; } String checkContent = new String(bytes, "UTF-8"); if (!checkContent.equals(sampleContent)) { problems.add("The sample content differed from expected: " + remoteServer.rmiUrl); continue; } } catch (Throwable e) { System.err.println("ERROR: Failure whilst checking server: " + remoteServer.rmiUrl); e.printStackTrace(); problems.add(e.getMessage()); } } } // Check for issues if (problems.size() > 0) { StringBuilder sb = new StringBuilder(); sb.append("\n") .append( "The working root node references could not be found on all the remote servers.\n") .append( "Please ensure that all the remote servers listed are active in a single cluster."); for (String problem : problems) { sb.append("\n").append(" ").append(problem); } throw new LoaderClientException(sb.toString()); } }
/** * Helper method to extract file info from a specific node. * * <p>This method goes direct to the repo for all information and no data is cached here. * * @param nodeRef the node * @param readOnly, should the file be shown as "read only", regardless of its permissions? * @param lockedFilesAsOffline should a locked file be marked as offline * @return Returns the file information pertinent to the node * @throws FileNotFoundException if the path refers to a non-existent file */ private ContentFileInfo getFileInformationImpl( NodeRef nodeRef, boolean readOnly, boolean lockedFilesAsOffline) throws FileNotFoundException { // get the file info org.alfresco.service.cmr.model.FileInfo fileFolderInfo = fileFolderService.getFileInfo(nodeRef); // retrieve required properties and create new JLAN file info ContentFileInfo fileInfo = new ContentFileInfo(nodeRef); // Set the file id from the node's DBID long id = DefaultTypeConverter.INSTANCE.convert( Long.class, nodeService.getProperty(nodeRef, ContentModel.PROP_NODE_DBID)); fileInfo.setFileId((int) (id & 0xFFFFFFFFL)); // unset all attribute flags int fileAttributes = 0; fileInfo.setFileAttributes(fileAttributes); if (fileFolderInfo.isFolder()) { // add directory attribute fileAttributes |= FileAttribute.Directory; fileInfo.setFileAttributes(fileAttributes); fileInfo.setFileType(FileType.Directory); } else { Map<QName, Serializable> nodeProperties = fileFolderInfo.getProperties(); // Get the file size from the content ContentData contentData = (ContentData) nodeProperties.get(ContentModel.PROP_CONTENT); long size = 0L; if (contentData != null) { size = contentData.getSize(); } fileInfo.setSize(size); // Set the allocation size by rounding up the size to a 512 byte block boundary if (size > 0) { fileInfo.setAllocationSize((size + 512L) & 0xFFFFFFFFFFFFFE00L); } // Check whether the file is locked if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE)) { LockType lockType = lockService.getLockType(nodeRef); int attr = fileInfo.getFileAttributes(); if (lockType != null) { switch (lockType) { case NODE_LOCK: if ((attr & FileAttribute.ReadOnly) == 0) attr += FileAttribute.ReadOnly; break; case WRITE_LOCK: LockStatus lockStatus = lockService.getLockStatus(nodeRef); if (lockStatus == LockStatus.LOCK_OWNER) { } else { if ((attr & FileAttribute.ReadOnly) == 0) { attr += FileAttribute.ReadOnly; } if (lockedFilesAsOffline) { attr += FileAttribute.NTOffline; } } break; case READ_ONLY_LOCK: if ((attr & FileAttribute.ReadOnly) == 0) { attr += FileAttribute.ReadOnly; } if (lockedFilesAsOffline) { attr += FileAttribute.NTOffline; } break; } fileInfo.setFileAttributes(attr); } } // Check if it is a link node if (fileFolderInfo.isLink()) { fileInfo.setLinkNodeRef(fileFolderInfo.getLinkNodeRef()); } } // created Date createdDate = fileFolderInfo.getCreatedDate(); if (createdDate != null) { long created = DefaultTypeConverter.INSTANCE.longValue(createdDate); fileInfo.setCreationDateTime(created); } // modified Date modifiedDate = fileFolderInfo.getModifiedDate(); if (modifiedDate != null) { long modified = DefaultTypeConverter.INSTANCE.longValue(modifiedDate); fileInfo.setModifyDateTime(modified); fileInfo.setAccessDateTime(modified); fileInfo.setChangeDateTime(modified); } // name String name = fileFolderInfo.getName(); if (name != null) { fileInfo.setFileName(name); // Check for file names that should be hidden if (hiddenAspect.getVisibility(Client.cifs, fileInfo.getNodeRef()) == Visibility.HiddenAttribute) { // Add the hidden file attribute int attr = fileInfo.getFileAttributes(); if ((attr & FileAttribute.Hidden) == 0) { attr += FileAttribute.Hidden; fileInfo.setFileAttributes(attr); } } } // Read/write access if (!fileFolderInfo.isFolder() || isReadOnlyFlagOnFolders) { boolean deniedPermission = permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.DENIED; if (readOnly || deniedPermission) { int attr = fileInfo.getFileAttributes(); if ((attr & FileAttribute.ReadOnly) == 0) { attr += FileAttribute.ReadOnly; fileInfo.setFileAttributes(attr); } } } // Set the normal file attribute if no other attributes are set if (fileInfo.getFileAttributes() == 0) fileInfo.setFileAttributes(FileAttribute.NTNormal); // Debug if (logger.isDebugEnabled()) { logger.debug("Fetched file info: \n" + " info: " + fileInfo); } // Return the file information return fileInfo; }
/** * Send an email message * * @throws AlfrescoRuntimeExeption */ @SuppressWarnings("unchecked") @Override protected void executeImpl(final Action ruleAction, final NodeRef actionedUponNodeRef) { try { MimeMessage message = javaMailSender.createMimeMessage(); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); // set recipient String to = (String) ruleAction.getParameterValue(PARAM_TO); if (to != null && to.length() != 0) { helper.setTo(to); } else { // see if multiple recipients have been supplied - as a list of // authorities Serializable toManyMails = ruleAction.getParameterValue(PARAM_TO_MANY); List<String> recipients = new ArrayList<String>(); if (toManyMails instanceof List) { for (String mailAdress : (List<String>) toManyMails) { if (validateAddress(mailAdress)) { recipients.add(mailAdress); } } } else if (toManyMails instanceof String) { if (validateAddress((String) toManyMails)) { recipients.add((String) toManyMails); } } if (recipients != null && recipients.size() > 0) { helper.setTo(recipients.toArray(new String[recipients.size()])); } else { // No recipients have been specified logger.error("No recipient has been specified for the mail action"); } } // set subject line helper.setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT)); // See if an email template has been specified String text = null; NodeRef templateRef = (NodeRef) ruleAction.getParameterValue(PARAM_TEMPLATE); if (templateRef != null) { // build the email template model Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, ruleAction); // process the template against the model text = templateService.processTemplate("freemarker", templateRef.toString(), model); } // set the text body of the message if (text == null) { text = (String) ruleAction.getParameterValue(PARAM_TEXT); } // adding the boolean true to send as HTML helper.setText(text, true); FileFolderService fileFolderService = serviceRegistry.getFileFolderService(); /* add inline images. * "action.parameters.images is a ,-delimited string, containing a map of images and resources, from this example: message.setText("my text <img src='cid:myLogo'>", true); message.addInline("myLogo", new ClassPathResource("img/mylogo.gif")); so the "images" param can look like this: headerLogo|images/headerLogoNodeRef,footerLogo|footerLogoNodeRef */ String imageList = (String) ruleAction.getParameterValue(PARAM_IMAGES); System.out.println(imageList); String[] imageMap = imageList.split(","); // comma no spaces Map<String, String> images = new HashMap<String, String>(); for (String image : imageMap) { System.out.println(image); String map[] = image.split("\\|"); for (String key : map) { System.out.println(key); } System.out.println(map.length); images.put(map[0].trim(), map[1].trim()); System.out.println(images.size()); System.out.println("-" + map[0] + " " + map[1] + "-"); } NodeRef imagesFolderNodeRef = (NodeRef) ruleAction.getParameterValue(PARAM_IMAGES_FOLDER); if (null != imagesFolderNodeRef) { ContentService contentService = serviceRegistry.getContentService(); System.out.println("mapping"); for (Map.Entry<String, String> entry : images.entrySet()) { System.out.println( entry.getKey() + " " + entry.getValue() + " " + ruleAction.getParameterValue(PARAM_IMAGES_FOLDER)); NodeRef imageFile = fileFolderService.searchSimple(imagesFolderNodeRef, entry.getValue()); if (null != imageFile) { ContentReader reader = contentService.getReader(imageFile, ContentModel.PROP_CONTENT); ByteArrayResource resource = new ByteArrayResource(IOUtils.toByteArray(reader.getContentInputStream())); helper.addInline(entry.getKey(), resource, reader.getMimetype()); } else { logger.error("No image for " + entry.getKey()); } } } else { logger.error("No images folder"); } // set the from address NodeRef person = personService.getPerson(authService.getCurrentUserName()); String fromActualUser = null; if (person != null) { fromActualUser = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL); } if (fromActualUser != null && fromActualUser.length() != 0) { helper.setFrom(fromActualUser); } else { String from = (String) ruleAction.getParameterValue(PARAM_FROM); if (from == null || from.length() == 0) { helper.setFrom(fromAddress); } else { helper.setFrom(from); } } NodeRef attachmentsFolder = (NodeRef) ruleAction.getParameterValue(PARAM_ATTCHMENTS_FOLDER); if (attachmentsFolder != null) { List<FileInfo> attachFiles = fileFolderService.listFiles(attachmentsFolder); if (attachFiles != null && attachFiles.size() > 0) { for (FileInfo attachFile : attachFiles) { ContentReader contentReader = fileFolderService.getReader(attachFile.getNodeRef()); ByteArrayResource resource = new ByteArrayResource(IOUtils.toByteArray(contentReader.getContentInputStream())); helper.addAttachment(attachFile.getName(), resource, contentReader.getMimetype()); } } } // Send the message unless we are in "testMode" javaMailSender.send(message); } catch (Exception e) { String toUser = (String) ruleAction.getParameterValue(PARAM_TO); if (toUser == null) { Object obj = ruleAction.getParameterValue(PARAM_TO_MANY); if (obj != null) { toUser = obj.toString(); } } logger.error("Failed to send email to " + toUser, e); throw new AlfrescoRuntimeException("Failed to send email to:" + toUser, e); } }
public String getBoundaryValue(FileInfo messageFileInfo) { StringBuffer s = new StringBuffer(); s.append("----=_Part_").append(messageFileInfo.getNodeRef().getId()); return s.toString(); }
@Override public void copyToEnvironment(String site, String environment, String path) throws DeploymentException { ServicesConfig servicesConfig = getServicesManager().getService(ServicesConfig.class); PersistenceManagerService persistenceManagerService = getServicesManager().getService(PersistenceManagerService.class); String siteRepoRootPath = SITE_REPO_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, site); String envRepoPath = SITE_ENVIRONMENT_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, site); envRepoPath = envRepoPath.replaceAll(ENVIRONMENT_REPLACEMENT_PATTERN, environment); NodeRef envRepoRoot = persistenceManagerService.getNodeRef(envRepoPath); NodeRef envNode = persistenceManagerService.getNodeRef(envRepoRoot, path); NodeRef nodeRef = persistenceManagerService.getNodeRef(siteRepoRootPath, path); if (nodeRef != null) { if (envNode == null) { envNode = createLiveRepositoryCopy(envRepoRoot, path, nodeRef); } else { FileInfo envNodeInfo = persistenceManagerService.getFileInfo(envNode); if (envNodeInfo.isFolder()) { Map<QName, Serializable> copyNodeProps = persistenceManagerService.getProperties(nodeRef); copyNodeProps.put(ContentModel.PROP_NAME, envNodeInfo.getName()); persistenceManagerService.setProperties(envNode, copyNodeProps); } else { persistenceManagerService.copy(nodeRef, envNode); } } Serializable sendEmailValue = persistenceManagerService.getProperty( nodeRef, CStudioContentModel.PROP_WEB_WF_SEND_EMAIL); boolean sendEmail = (sendEmailValue != null) && (Boolean) sendEmailValue; if (sendEmail) { Serializable submittedByValue = persistenceManagerService.getProperty( nodeRef, CStudioContentModel.PROP_WEB_WF_SUBMITTED_BY); String submittedBy = ""; if (submittedByValue != null) { submittedBy = (String) submittedByValue; } else { logger.error("did not send approval notification as submitted by property is null"); return; } // DmPathTO path = new DmPathTO(nodePath); String approver = (String) persistenceManagerService.getProperty( nodeRef, CStudioContentModel.PROP_WEB_APPROVED_BY); NotificationService notificationService = getServicesManager().getService(NotificationService.class); notificationService.sendApprovalNotification(site, submittedBy, path, approver); /* * Remove this sendmail property as we are done sending email */ persistenceManagerService.removeProperty( nodeRef, CStudioContentModel.PROP_WEB_WF_SEND_EMAIL); } Map<QName, Serializable> nodeProps = persistenceManagerService.getProperties(envNode); for (QName propName : DmConstants.SUBMITTED_PROPERTIES) { nodeProps.remove(propName); } persistenceManagerService.setProperties(envNode, nodeProps); nodeProps = persistenceManagerService.getProperties(nodeRef); for (QName propName : DmConstants.SUBMITTED_PROPERTIES) { nodeProps.remove(propName); } persistenceManagerService.setProperties(nodeRef, nodeProps); } }
protected String getFilename(NodeRef actionedUponNodeRef) { FileInfo fileInfo = serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef); String filename = fileInfo.getName(); return filename; }