View Javadoc

1   /**
2    *    Copyright 2012 meltmedia
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *        http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package com.meltmedia.cadmium.email.jersey;
17  
18  import java.io.BufferedReader;
19  import java.io.File;
20  import java.io.FileInputStream;
21  import java.io.FileNotFoundException;
22  import java.io.IOException;
23  import java.io.InputStreamReader;
24  
25  import javax.inject.Inject;
26  import javax.servlet.http.HttpServletRequest;
27  import javax.ws.rs.Consumes;
28  import javax.ws.rs.FormParam;
29  import javax.ws.rs.POST;
30  import javax.ws.rs.Path;
31  import javax.ws.rs.Produces;
32  import javax.ws.rs.core.Context;
33  import javax.ws.rs.core.MediaType;
34  import javax.ws.rs.core.Response;
35  
36  import org.slf4j.Logger;
37  import org.slf4j.LoggerFactory;
38  
39  import com.meltmedia.cadmium.core.CadmiumApiEndpoint;
40  import com.meltmedia.cadmium.core.ContentService;
41  import com.meltmedia.cadmium.email.model.EmailForm;
42  import com.meltmedia.cadmium.email.EmailException;
43  import com.meltmedia.cadmium.email.VelocityHtmlTextEmail;
44  import com.meltmedia.cadmium.email.internal.EmailServiceImpl;
45  
46  @CadmiumApiEndpoint
47  @Path("/email")
48  public class EmailResource {
49  	
50  	private Logger log = LoggerFactory.getLogger(getClass());
51  	
52  	@Inject
53  	private EmailServiceImpl emailService;
54  	
55  	@Inject
56  	private ContentService contentService;
57  	
58  	public EmailResource() {
59  	  log.debug("Initialized EmailResource...");
60  	}
61  
62   	
63  	@POST
64    @Consumes("application/x-www-form-urlencoded")
65    @Produces(MediaType.APPLICATION_JSON)
66  	public Response emailThisPage(@Context HttpServletRequest request,@FormParam(Constants.DIR) String dir,@FormParam(Constants.TO_NAME) String toName,
67  			                          @FormParam(Constants.TO_ADDRESS) String toAddress,@FormParam(Constants.FROM_NAME) String fromName,
68  			                          @FormParam(Constants.FROM_ADDRESS) String fromAddress,@FormParam(Constants.MESSAGE) String message,
69  			                          @FormParam(Constants.PAGE_PATH) String pagePath,@FormParam(Constants.SUBJECT) String subject) {
70  
71    	log.info("Entering Email This Method");
72    	VelocityHtmlTextEmail email = new VelocityHtmlTextEmail();
73    	
74    	// Setting up template location/files
75    	File absoluteTemplateDir = new File(contentService.getContentRoot(),"META-INF");
76    	absoluteTemplateDir = new File(absoluteTemplateDir,dir);
77  	  File textTemplateFile = new File(absoluteTemplateDir,Constants.TEMPLATE_NAME + ".txt");
78  	  log.info("textTemplateFile: {}", textTemplateFile.getPath());
79    	File htmlTemplateFile = new File(absoluteTemplateDir,Constants.TEMPLATE_NAME + ".html");
80    	log.info("htmlTemplateFile: {}", htmlTemplateFile.getPath());
81    	if (textTemplateFile.exists() && htmlTemplateFile.exists()) {
82    		if (pageExists(pagePath)) {
83  		  	try { 
84  		  		EmailForm emailForm = new EmailForm(toName, toAddress, fromName, fromAddress, message, pagePath,subject);
85  		  		log.info("Email Form: {}", emailForm.toString());
86  					EmailFormValidator.validate(emailForm);
87  			  	
88  			  	email.addTo(emailForm.getToAddress());
89  			  	email.setReplyTo(emailForm.getFromAddress());
90  			  	email.setFrom(emailForm.getFromAddress()); 
91  			  	email.setSubject(emailForm.getSubject());
92  			  	// Set HTML Template
93  			  	email.setHtml(readFromFile(htmlTemplateFile.getAbsolutePath()));
94  			  	
95  			  	// Set Text Template
96  			  	email.setText(readFromFile(textTemplateFile.getAbsolutePath()));
97  			  	
98  			  	// Set Properties
99  			  	email.setProperty(Constants.TO_NAME, emailForm.getToName());
100 			  	email.setProperty(Constants.FROM_NAME, emailForm.getFromName());
101 			  	
102 			    // setting message to at least empty string to assure that ${message} gets replaced on the email form.
103 			  	if (emailForm.getMessage() == null) { 
104 			  		emailForm.setMessage("");
105 	        }
106 			  	email.setProperty(Constants.MESSAGE, emailForm.getMessage());
107 			  	
108 			  	// Set up link
109 			  	String link = "http://" + request.getServerName() + "/"  + emailForm.getPagePath();
110 			  	log.info("Email This Page Link: {}",link);
111 			  	email.setProperty(Constants.PATH,link);
112 								  	
113 			  	// Send Email
114 			  	log.debug("Before Sending Email");  		
115 			  	emailService.send(email);
116 			  	log.debug("After Sending Email");
117 				} catch (EmailException e) {
118 					log.info("EmailException Caught " + e.getMessage(), e);
119 					return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
120 				} catch (ValidationException e) {
121 					log.info("ValidationException Caught");
122 					log.info("First Error {}",e.getErrors()[0].getMessage());
123 					return Response.status(Response.Status.BAD_REQUEST).entity(e.getErrors()).build();
124 				} 	
125 				return Response.ok().build();
126   		} else {
127     		log.info("Invalid Page");
128     		return Response.status(Response.Status.BAD_REQUEST).entity("Invalid Page").build();	
129   		}
130   	} else {
131   		log.info("Couldn't Find Email Templates");
132   		return Response.status(Response.Status.BAD_REQUEST).entity("Invalid Template Location").build();		  		
133   	}
134 	}
135 	
136 	private boolean pageExists(String pagePath) {
137 		if (pagePath.contains("-INF")) {
138 			return false;
139 		}
140 		File pagePathFile = new File(contentService.getContentRoot(),pagePath);
141 		return pagePathFile.exists();
142 	}
143 
144 	/*
145    * Reads data from a given file
146    */
147   public String readFromFile(String fileName) {
148     String content = null;
149     BufferedReader br = null;
150     try {
151       File inFile = new File(fileName);
152       br = new BufferedReader(new InputStreamReader(
153           new FileInputStream(inFile)));
154       content = "";
155       while(br.ready()) {
156       	content += br.readLine();
157       }
158       br.close();
159     } catch (FileNotFoundException ex) {
160     	log.error("Failed to find file.", ex);
161     } catch (IOException ex) {
162     	log.error("Failed to read file.", ex);
163     } finally {
164     	if(br != null) {
165     		try {
166     			br.close();
167     		} catch(Exception e){}
168     	}
169     }
170     return content;
171   }
172   
173 }