View Javadoc

1   package de.tivsource.page.user.actions.request;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   import java.io.UnsupportedEncodingException;
6   import java.net.URL;
7   import java.util.Date;
8   import java.util.Iterator;
9   import java.util.List;
10  import java.util.Map;
11  import java.util.Properties;
12  import java.util.Set;
13  import java.util.UUID;
14  
15  import javax.mail.MessagingException;
16  import javax.mail.PasswordAuthentication;
17  import javax.mail.Session;
18  
19  import org.apache.logging.log4j.LogManager;
20  import org.apache.logging.log4j.Logger;
21  import org.apache.struts2.ServletActionContext;
22  import org.apache.struts2.convention.annotation.Action;
23  import org.apache.struts2.convention.annotation.Actions;
24  import org.apache.struts2.convention.annotation.InterceptorRef;
25  import org.apache.struts2.convention.annotation.Result;
26  import org.apache.struts2.tiles.annotation.TilesDefinition;
27  import org.apache.struts2.tiles.annotation.TilesDefinitions;
28  import org.apache.struts2.tiles.annotation.TilesPutAttribute;
29  
30  import de.tivsource.ejb3plugin.InjectEJB;
31  import de.tivsource.page.common.captcha.Captcha;
32  import de.tivsource.page.dao.captcha.CaptchaDaoLocal;
33  import de.tivsource.page.dao.location.LocationDaoLocal;
34  import de.tivsource.page.dao.page.PageDaoLocal;
35  import de.tivsource.page.dao.property.PropertyDaoLocal;
36  import de.tivsource.page.dao.reason.ReasonDaoLocal;
37  import de.tivsource.page.dao.request.RequestDaoLocal;
38  import de.tivsource.page.entity.location.Location;
39  import de.tivsource.page.entity.page.Page;
40  import de.tivsource.page.entity.request.Reason;
41  import de.tivsource.page.entity.request.Request;
42  import de.tivsource.page.helper.EmailSender;
43  import de.tivsource.page.helper.EmailTemplate;
44  import de.tivsource.page.user.actions.EmptyAction;
45  
46  /**
47   * 
48   * @author Marc Michele
49   *
50   */
51  @InterceptorRef(value="uploadStack")
52  @TilesDefinitions({
53    @TilesDefinition(name="request", extend = "userTemplate", putAttributes = {
54      @TilesPutAttribute(name = "content",    value = "/WEB-INF/tiles/active/view/request/form.jsp")
55    }),
56    @TilesDefinition(name="page", extend = "userTemplate", putAttributes = {
57      @TilesPutAttribute(name = "meta",       value = "/WEB-INF/tiles/active/meta/content.jsp"),
58      @TilesPutAttribute(name = "twitter",    value = "/WEB-INF/tiles/active/twitter/content.jsp"),
59      @TilesPutAttribute(name = "content",    value = "/WEB-INF/tiles/active/view/page/page.jsp")
60    })
61  })
62  public class RequestAction extends EmptyAction {
63  
64      /**
65       * Serial Version UID.
66       */
67      private static final long serialVersionUID = -899397629172153047L;
68  
69      /**
70  	 * Statischer Logger der Klasse.
71  	 */
72      private static final Logger LOGGER = LogManager.getLogger(RequestAction.class);
73  
74      @InjectEJB(name="CaptchaDao")
75      private CaptchaDaoLocal captchaDaoLocal;
76  
77      @InjectEJB(name="PageDao")
78      private PageDaoLocal pageDaoLocal;
79  
80      @InjectEJB(name="PropertyDao")
81      private PropertyDaoLocal propertyDaoLocal;
82  
83      @InjectEJB(name="RequestDao")
84      private RequestDaoLocal requestDaoLocal;
85  
86      @InjectEJB(name="LocationDao")
87      private LocationDaoLocal locationDaoLocal;
88  
89      @InjectEJB(name="ReasonDao")
90      private ReasonDaoLocal reasonDaoLocal;
91  
92  	private Request requestInput;
93  
94  	private Page page;
95  
96      private Captcha captcha;
97  
98      private String answer;
99  
100     @Actions({
101         @Action(
102         		value = "sent", 
103         		results = { 
104         				@Result(name = "success", type="tiles", location = "page"), 
105         				@Result(name = "input", type="tiles", location = "request")
106         				}
107         )
108     })
109 	public String execute() {
110         LOGGER.info("execute() aufgerufen.");
111         LOGGER.info("Anrede: " + requestInput.getGender());
112 
113         // Hole Action Locale
114     	this.getLanguageFromActionContext();
115 
116 
117         if(answer != null && captcha != null && !answer.trim().equals("") && captcha.getContent().equals(answer)) {
118             //sendMail();
119             // Speichere Message Objekt
120             String remoteAddress = ServletActionContext.getRequest().getRemoteAddr();
121             requestInput.setCreated(new Date());
122             requestInput.setCreatedAddress(remoteAddress);
123             requestInput.setUuid(UUID.randomUUID().toString());
124             requestInput.generate();
125             requestDaoLocal.merge(requestInput);
126 
127             return SUCCESS;            
128         } else {
129             captcha = captchaDaoLocal.random();
130             addFieldError("answer", "Bitte geben Sie die Hausnummer ein.");
131             return INPUT;
132         }
133 	}
134 
135     @Override
136     public Page getPage() {
137         if(page == null) {
138             setUpPage();
139         }
140         return page;
141     }// Ende getPage()
142 
143     /**
144      * @return the requestInput
145      */
146     public Request getRequestInput() {
147         return requestInput;
148     }
149 
150     /**
151      * @param requestInput the requestInput to set
152      */
153     public void setRequestInput(Request requestInput) {
154         this.requestInput = requestInput;
155     }
156 
157     public List<Location> getLocationList() {
158         return locationDaoLocal.findAllVisible(0, locationDaoLocal.countAllVisible());
159     }
160 
161     public List<Reason> getReasonList() {
162         return reasonDaoLocal.findAllVisible(0, reasonDaoLocal.countAllVisible());
163     }
164 
165     /**
166      * @return the captcha
167      */
168     public Captcha getCaptcha() {
169         return captcha;
170     }
171 
172     /**
173      * @param captcha the captcha to set
174      */
175     public void setCaptcha(Captcha captcha) {
176         this.captcha = captcha;
177     }
178 
179     /**
180      * @param answer the answer to set
181      */
182     public void setAnswer(String answer) {
183         this.answer = answer;
184     }
185 
186     private void sendMail() {
187 		LOGGER.info("sendMail() aufgerufen.");
188 		
189 		javax.mail.Authenticator auth = new javax.mail.Authenticator() {
190 			@Override
191 			public PasswordAuthentication getPasswordAuthentication() {
192 				return new PasswordAuthentication(
193 				        propertyDaoLocal.findByKey("mail.user").getValue(),
194 				        propertyDaoLocal.findByKey("mail.password").getValue());
195 			}
196 		};
197 		
198 		InputStream template;
199 		try {
200 		    URL templatePath = new URL(propertyDaoLocal.findByKey("request.template.path").getValue());
201 			LOGGER.info("Pfad zur template Datei: " + templatePath);
202             template = templatePath.openStream();
203             LOGGER.info("Template eingelesen");
204             Object notification = EmailTemplate.getEmailTemplate(template);
205             LOGGER.info("Template eingelesen");
206 
207             // Get session
208             Session session = Session.getInstance(getProperties(), auth);
209             session.setDebug(false);
210             
211             EmailSender sendIt = new EmailSender();
212             String[] argu = {
213                     requestInput.getGender() == 'F' ? "Frau" :
214                         requestInput.getGender() == 'M' ? "Herr" :
215                             "",
216                     requestInput.getFirstname(), 
217                     requestInput.getLastname(), 
218                     requestInput.getMail(),
219                     requestInput.getCreatedAddress(),
220                     requestInput.getBirthday().toString(),
221                     requestInput.getCreated().toString(),
222                     requestInput.getLocation().getName("DE"),
223                     requestInput.getReason().getName("DE"),
224                     requestInput.getComment(),
225                     requestInput.getComment().replace("\n", "<br/>")
226             		};
227 
228             new Thread(new Runnable() {
229                 public void run(){
230                     try {
231                         sendIt.send("Kartenantrag", (EmailTemplate)notification, argu, session);
232                     } catch (UnsupportedEncodingException | MessagingException e) {
233                         // TODO Auto-generated catch block
234                         e.printStackTrace();
235                     }
236                     return; // to stop the thread
237                 }
238             }).start();
239 
240 		} catch (UnsupportedEncodingException e) {
241             e.printStackTrace();
242         } catch (IOException e) {
243 			// TODO Auto-generated catch block
244 			e.printStackTrace();
245 		}
246 		 
247 		
248 	}// Ende sendMail()
249 
250     private Properties getProperties() {
251         LOGGER.info("getProperties() aufgerufen.");
252 
253         // Get system properties
254         Properties props = System.getProperties();
255 
256         // Setup mail server
257         props.put("mail.transport.protocol", 
258                 propertyDaoLocal.findByKey("mail.transport.protocol").getValue());
259         props.put("mail.host", 
260                 propertyDaoLocal.findByKey("mail.host").getValue());
261         props.put("mail.port", 
262                 propertyDaoLocal.findByKey("mail.port").getValue());
263         props.put("mail.smtp.auth", 
264                 propertyDaoLocal.findByKey("mail.smtp.auth").getValue());
265         props.put("mail.smtp.tls", 
266                 propertyDaoLocal.findByKey("mail.smtp.tls").getValue());
267         props.put("mail.smtp.starttls.enable",
268                 propertyDaoLocal.findByKey("mail.smtp.starttls.enable").getValue());
269         props.put("mail.smtp.localhost", 
270                 propertyDaoLocal.findByKey("mail.smtp.localhost").getValue());
271         props.put("mail.user", 
272                 propertyDaoLocal.findByKey("mail.user").getValue());
273         props.put("mail.password", 
274                 propertyDaoLocal.findByKey("mail.password").getValue());
275         props.put("mail.mime.charset", 
276                 propertyDaoLocal.findByKey("mail.mime.charset").getValue());
277         props.put("mail.use8bit", 
278                 propertyDaoLocal.findByKey("mail.use8bit").getValue());
279         
280         return props;
281     } // Ende getProperties()
282 
283     private void setUpPage() {
284         LOGGER.info("Action Errors: " + this.getFieldErrors().size());
285         if(this.getFieldErrors().size() > 0) {
286             Set<Map.Entry<String,List<String>>> errorSet = this.getFieldErrors().entrySet();
287             Iterator<Map.Entry<String,List<String>>> setIterator = errorSet.iterator();
288             while(setIterator.hasNext()) {
289                 Map.Entry<String,List<String>> next = setIterator.next();
290                 LOGGER.info("Action Error Key: " + next.getKey());
291             }
292             page = pageDaoLocal.findByTechnical("request");
293         } else {
294             page = pageDaoLocal.findByTechnical("requestsent");
295         }
296     }
297     
298 }// Ende class