001: /**********************************************************************************
002: * $URL: https://source.sakaiproject.org/svn/sam/trunk/component/src/java/org/sakaiproject/tool/assessment/services/ItemService.java $
003: * $Id: ItemService.java 9273 2006-05-10 22:34:28Z daisyf@stanford.edu $
004: ***********************************************************************************
005: *
006: * Copyright (c) 2006 The Sakai Foundation.
007: *
008: * Licensed under the Educational Community License, Version 1.0 (the"License");
009: * you may not use this file except in compliance with the License.
010: * You may obtain a copy of the License at
011: *
012: * http://www.opensource.org/licenses/ecl1.php
013: *
014: * Unless required by applicable law or agreed to in writing, software
015: * distributed under the License is distributed on an "AS IS" BASIS,
016: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017: * See the License for the specific language governing permissions and
018: * limitations under the License.
019: *
020: **********************************************************************************/package org.sakaiproject.tool.assessment.util;
021:
022: import java.io.File;
023: import java.io.FileNotFoundException;
024: import java.io.FileOutputStream;
025: import java.io.IOException;
026: import java.io.UnsupportedEncodingException;
027: import java.util.ArrayList;
028: import java.util.Iterator;
029: import java.util.List;
030: import java.util.Properties;
031:
032: import javax.activation.DataHandler;
033: import javax.activation.FileDataSource;
034: import javax.mail.Message;
035: import javax.mail.MessagingException;
036: import javax.mail.Multipart;
037: import javax.mail.Session;
038: import javax.mail.Transport;
039: import javax.mail.internet.InternetAddress;
040: import javax.mail.internet.MimeBodyPart;
041: import javax.mail.internet.MimeMessage;
042: import javax.mail.internet.MimeMultipart;
043:
044: import org.apache.commons.logging.Log;
045: import org.apache.commons.logging.LogFactory;
046: import org.sakaiproject.component.cover.ServerConfigurationService;
047: import org.sakaiproject.content.api.ContentResource;
048: import org.sakaiproject.content.cover.ContentHostingService;
049: import org.sakaiproject.exception.IdUnusedException;
050: import org.sakaiproject.exception.PermissionException;
051: import org.sakaiproject.exception.ServerOverloadException;
052: import org.sakaiproject.exception.TypeException;
053: import org.sakaiproject.tool.assessment.data.dao.assessment.AttachmentData;
054: import org.sakaiproject.tool.assessment.ui.bean.util.EmailBean;
055: import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
056:
057: /**
058: * The ItemService calls persistent service locator to reach the
059: * manager on the back end.
060: */
061: public class SamigoEmailService {
062: private static Log log = LogFactory
063: .getLog(SamigoEmailService.class);
064:
065: private String fromName;
066: private String fromEmailAddress;
067: private String toName;
068: private String toEmailAddress;
069: private String ccMe;
070: private String subject;
071: private String message;
072: private String smtpServer;
073: private String smtpPort;
074: private String bypassAuth;
075: private String username;
076: private String password;
077: private String prefixedPath;
078:
079: /**
080: * Creates a new SamigoEmailService object.
081: */
082: public SamigoEmailService(String fromName, String fromEmailAddress,
083: String toName, String toEmailAddress, String ccMe,
084: String subject, String message) {
085: this .fromName = fromName;
086: this .fromEmailAddress = fromEmailAddress;
087: this .toName = toName;
088: this .toEmailAddress = toEmailAddress;
089: this .ccMe = ccMe;
090: this .subject = subject;
091: this .message = message;
092: this .smtpServer = ServerConfigurationService
093: .getString("samigo.smtp.server");
094: this .smtpPort = ServerConfigurationService
095: .getString("samigo.smtp.port");
096: this .bypassAuth = ServerConfigurationService
097: .getString("samigo.email.bypassAuth");
098: this .username = ServerConfigurationService
099: .getString("samigo.email.username");
100: this .password = ServerConfigurationService
101: .getString("samigo.email.password");
102: this .prefixedPath = ServerConfigurationService
103: .getString("samigo.email.prefixedPath");
104: }
105:
106: public String send() {
107: List attachmentList = null;
108: AttachmentData a = null;
109: try {
110: Properties props = new Properties();
111:
112: // Server
113: if (smtpServer == null || smtpServer.equals("")) {
114: log.error("samigo.email.smtpServer is not set");
115: return "error";
116: }
117: props.setProperty("mail.smtp.host", smtpServer);
118:
119: // Port
120: if (smtpPort == null || smtpPort.equals("")) {
121: log
122: .warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
123: } else {
124: props.setProperty("mail.smtp.port", smtpPort);
125: }
126:
127: Session session;
128: // Authentication
129: if (bypassAuth != null && bypassAuth.equals("true")) {
130: log.info("samigo.email.bypassAuth is set to true");
131: session = Session.getInstance(props, null);
132: } else {
133: if ((username == null || username.equals(""))
134: || (password == null || password.equals(""))) {
135: log
136: .error("At least one of samigo.email.username and samigo.email.password is not set");
137: return "error";
138: } else {
139: SamigoEmailAuthenticator samigoEmailAuthenticator = new SamigoEmailAuthenticator();
140: session = Session.getInstance(props,
141: samigoEmailAuthenticator);
142: }
143: }
144:
145: session.setDebug(true);
146: MimeMessage msg = new MimeMessage(session);
147:
148: InternetAddress fromIA = new InternetAddress(
149: fromEmailAddress, fromName);
150: msg.setFrom(fromIA);
151: InternetAddress[] toIA = { new InternetAddress(
152: toEmailAddress, toName) };
153: msg.setRecipients(Message.RecipientType.TO, toIA);
154:
155: if (ccMe.equals("yes")) {
156: InternetAddress[] ccIA = { new InternetAddress(
157: fromEmailAddress, fromName) };
158: msg.setRecipients(Message.RecipientType.CC, ccIA);
159: }
160: msg.setSubject(subject);
161:
162: EmailBean emailBean = (EmailBean) ContextUtil
163: .lookupBean("email");
164: attachmentList = emailBean.getAttachmentList();
165: StringBuffer content = new StringBuffer(message);
166: ArrayList fileList = new ArrayList();
167: ArrayList fileNameList = new ArrayList();
168: if (attachmentList != null) {
169: if (prefixedPath == null || prefixedPath.equals("")) {
170: log.error("samigo.email.prefixedPath is not set");
171: return "error";
172: }
173: Iterator iter = attachmentList.iterator();
174: while (iter.hasNext()) {
175: a = (AttachmentData) iter.next();
176: if (a.getIsLink().booleanValue()) {
177: log.debug("send(): url");
178: content.append("<br/>\n\r");
179: content.append("<br/>"); // give a new line
180: content.append(a.getFilename());
181: } else {
182: log.debug("send(): file");
183: File attachedFile = getAttachedFile(a
184: .getResourceId());
185: fileList.add(attachedFile);
186: fileNameList.add(a.getFilename());
187: }
188: }
189: }
190:
191: Multipart multipart = new MimeMultipart();
192: MimeBodyPart messageBodyPart = new MimeBodyPart();
193: messageBodyPart.setContent(content.toString(), "text/html");
194: multipart.addBodyPart(messageBodyPart);
195: msg.setContent(multipart);
196:
197: for (int i = 0; i < fileList.size(); i++) {
198: messageBodyPart = new MimeBodyPart();
199: FileDataSource source = new FileDataSource(
200: (File) fileList.get(i));
201: messageBodyPart.setDataHandler(new DataHandler(source));
202: messageBodyPart.setFileName((String) fileNameList
203: .get(i));
204: multipart.addBodyPart(messageBodyPart);
205: }
206: msg.setContent(multipart);
207:
208: Transport.send(msg);
209: } catch (UnsupportedEncodingException e) {
210: log.error("Exception throws from send()" + e.getMessage());
211: return "error";
212: } catch (MessagingException e) {
213: log.error("Exception throws from send()" + e.getMessage());
214: return "error";
215: } catch (ServerOverloadException e) {
216: log.error("Exception throws from send()" + e.getMessage());
217: return "error";
218: } catch (PermissionException e) {
219: log.error("Exception throws from send()" + e.getMessage());
220: return "error";
221: } catch (IdUnusedException e) {
222: log.error("Exception throws from send()" + e.getMessage());
223: return "error";
224: } catch (TypeException e) {
225: log.error("Exception throws from send()" + e.getMessage());
226: return "error";
227: } catch (IOException e) {
228: log.error("Exception throws from send()" + e.getMessage());
229: return "error";
230: } finally {
231: if (attachmentList != null) {
232: if (prefixedPath != null && !prefixedPath.equals("")) {
233: StringBuffer sbPrefixedPath;
234: Iterator iter = attachmentList.iterator();
235: while (iter.hasNext()) {
236: sbPrefixedPath = new StringBuffer(prefixedPath);
237: sbPrefixedPath.append("/email_tmp/");
238: a = (AttachmentData) iter.next();
239: if (!a.getIsLink().booleanValue()) {
240: deleteAttachedFile(sbPrefixedPath.append(
241: a.getResourceId()).toString());
242: }
243: }
244: }
245: }
246: }
247: return "send";
248: }
249:
250: private File getAttachedFile(String resourceId)
251: throws PermissionException, IdUnusedException,
252: TypeException, ServerOverloadException, IOException {
253: ContentResource cr = ContentHostingService
254: .getResource(resourceId);
255: log.debug("getAttachedFile(): resourceId = " + resourceId);
256: byte[] data = cr.getContent();
257: StringBuffer sbPrefixedPath = new StringBuffer(prefixedPath);
258: sbPrefixedPath.append("/email_tmp/");
259: sbPrefixedPath.append(resourceId);
260: String filename = sbPrefixedPath.toString().replace(" ", "");
261: log.debug("getAttachedFile(): filename = " + filename);
262: String path = filename.substring(0, filename.lastIndexOf("/"));
263: log.debug("getAttachedFile(): path = " + path);
264: File dir = new File(path);
265: boolean success = dir.mkdirs();
266: // Shouldn't come to here because resourceId is unique
267: if (!success) {
268: log
269: .error("getAttachedFile(): File exists already! This should not heppen. Please check for resourceId.");
270: }
271: File file = new File(filename);
272: success = file.createNewFile();
273: // Shouldn't come to here because resourceId is unique
274: if (!success) {
275: log
276: .error("getAttachedFile(): File exists already! This should not heppen. Please check for resourceId.");
277: }
278: FileOutputStream fileOutputStream = null;
279: try {
280: fileOutputStream = new FileOutputStream(file);
281: fileOutputStream.write(data);
282: } catch (FileNotFoundException e) {
283: throw e;
284: } catch (IOException e) {
285: throw e;
286: } finally {
287: if (fileOutputStream != null) {
288: fileOutputStream.close();
289: }
290: }
291: return file;
292: }
293:
294: private void deleteAttachedFile(String filename) {
295: log.debug("deleteAttachedFile(): filename = " + filename);
296: // delete the file
297: String tunedFilename = filename.replace(" ", "");
298: log.debug("deleteAttachedFile(): tunedFilename = "
299: + tunedFilename);
300: File file = new File(tunedFilename);
301: boolean success = file.delete();
302: if (!success) {
303: log.error("Fail to delete file: " + tunedFilename);
304: }
305: // delete the last directory
306: String directoryName = tunedFilename.substring(0, tunedFilename
307: .lastIndexOf("/"));
308: log.debug("deleteAttachedFile(): directoryName = "
309: + directoryName);
310: File dir = new File(directoryName);
311: success = dir.delete();
312: if (!success) {
313: log.error("Fail to delete directory: " + directoryName);
314: }
315: }
316: }
|