List of usage examples for javax.mail MessagingException printStackTrace
public void printStackTrace()
From source file:com.niroshpg.android.gmail.CronHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Check if we have stored credentials using the Authorization Flow. // Note that we only check if there are stored credentials, but not if they are still valid. // The user may have revoked authorization, in which case we would need to go through the // authorization flow again, which this implementation does not handle. GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow(); Credential credential = null;/*from ww w . j a v a2 s . c o m*/ String userId = Datastore.getUserId(); credential = authFlow.loadCredential(userId); if (credential == null) { // // If we don't have a token in store, redirect to authorization screen. logger.warning("auth flow started ..."); resp.sendRedirect( authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build()); return; } // Create a new authorized Gmail API client Gmail service = new Gmail.Builder(GmailUtils.HTTP_TRANSPORT, GmailUtils.JSON_FACTORY, credential) .setApplicationName(APP_NAME).build(); List<Label> lableList = listLabels(service, "me"); List<Message> messegeList = listMessagesWithLabels(service, "me", Arrays.asList(getLableIdForName(lableList, "EQM"))); logger.warning("store messages for processing ... "); for (Message message : messegeList) { String messageBody = ""; try { MimeMessage mimeMessage = getMimeMessage(service, "me", message.getId()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); messageBody = baos.toString(); } catch (MessagingException e) { e.printStackTrace(); } String extractedMsgBody = MessageUtility.extractData(messageBody); Datastore.addMessage(extractedMsgBody); } logger.warning("invoke send all"); sendMessagesToAll(); logger.warning("removing label from messages ..."); removeUnRead(service, "me", messegeList); }
From source file:com.riq.MailHandlerServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("Inside MailServlet doPost"); // TODO get path information to determine target Department for this email PersistenceManager pm = PMF.get().getPersistenceManager(); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try {//from w w w . ja v a 2 s . co m MimeMessage msg = new MimeMessage(session, req.getInputStream()); Address sender = msg.getFrom()[0]; Address replyTo = msg.getReplyTo()[0]; // DEBUG // log.info("Message Class: " + msg.getClass()); // log.info("Message Stream: " + msg.getInputStream()); // log.info("Message RawStream: " + msg.getRawInputStream()); // log.info("Message Flags: " + msg.getFlags()); // log.info("Message Content: " + msg.getContent().toString()); // log.info("Message ContentID: " + msg.getContentID()); // log.info("Message ContentMD: " + msg.getContentMD5()); // log.info("Message ContentType: " + msg.getContentType()); // log.info("Message Description: " + msg.getDescription()); // log.info("Message Disposition: " + msg.getDisposition()); // log.info("Message Encoding: " + msg.getEncoding()); // log.info("Message Filename: " + msg.getFileName()); // log.info("Message Line Count: " + msg.getLineCount()); // log.info("Message ID: " + msg.getMessageID()); // log.info("Message Number: " + msg.getMessageNumber()); // log.info("Message Size: " + msg.getSize()); // log.info("Message Subject: " + msg.getSubject()); // log.info("Message RawInputStream: " + msg.getRawInputStream().toString()); // log.info("Message ReplyTo: " + replyTo); // log.info("Message Sender: " + sender.toString()); // log.info("Request URL TO: " + getServletContext()); String alertMsgString = getText(msg); alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", ""); alertMsgString = alertMsgString.replaceAll("Forwarded message", ""); alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", ""); alertMsgString = alertMsgString.replaceAll("Date:", ""); alertMsgString = alertMsgString.replaceAll(">", ""); alertMsgString = alertMsgString.replaceAll("::", "-"); alertMsgString = alertMsgString.replaceAll("< ", ""); alertMsgString = alertMsgString.replaceAll("----------", ""); alertMsgString = alertMsgString.replaceAll("Subject:", ""); alertMsgString = alertMsgString.replaceAll("To:", ""); alertMsgString = alertMsgString.replaceAll("From:", ""); // Added to grab gmail confirmations // alertMsgString = alertMsgString.substring(50, 300); try { String queryDept = "select from " + Department.class.getName() + // TODO: johnreilly workaround for getting allRecipients... // " where dispatchId == '" + toAddressDigitsOnly + "' " + " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' "; log.info("queryDept: " + queryDept); List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute(); if (depts.size() != 0) { for (Department d : depts) { // need to filter further e.g. last two hours String queryAlert = "select from " + Alert.class.getName() + " where deptId == " + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' "; log.info("queryAlert: " + queryAlert); List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute(); log.info("queryAlert Result Qty: " + alerts.size()); if (alerts.size() == 0) { riqGeocode(alertMsgString); // geocode the address from the Alert Map<String, String> geoResults = riqGeocode(alertMsgString); log.info("lat print: " + geoResults.get("lat")); log.info("lng print: " + geoResults.get("lng")); // create the alert Long deptId = depts.get(0).getid(); Long timeStamp = System.currentTimeMillis(); Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(), "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID()); pm.makePersistent(a); // query to get id of this alert String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == " + deptId + " " + " && timeStamp == " + timeStamp; log.info("queryThisAlert: " + queryThisAlert); List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute(); log.info("queryCurrentAlert Result Qty: " + thisAlert.size()); // create Tracking records for "special" Locations String querySpecialLocs = "select from " + Location.class.getName() + " where special == 'yes' && deptId == " + deptId; log.info("querySpecialLocs: " + querySpecialLocs); List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute(); log.info("querySpecialLocs qty: " + specialLocs.size()); for (Location specL : specialLocs) { Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "location", specL.getid(), null, "autoAddLocation"); pm.makePersistent(tSL); } // search Dept for Location where distant Members presumed not to be responding are set String queryFarawayLocs = "select from " + Location.class.getName() + " where vru == '2' && deptId == " + deptId; log.info("querySpecialLocs: " + queryFarawayLocs); List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute(); log.info("queryFarawayLocs qty: " + farawayLoc.size()); // create Tracking records for Members presumed not to be responder due to fresh ETA String queryFarAwayResponders = "select from " + Member.class.getName() + " where distGroup == '4' "; log.info("queryFarAwayResponders: " + queryFarAwayResponders); List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders) .execute(); log.info("queryFarAwayResponders qty: " + farawayMembers.size()); if (farawayMembers.size() != 0) { for (Member far : farawayMembers) { Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(), farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd "farawayAddMember", far.getid(), null, responseType); pm.makePersistent(tMFAR); } } // TODO: testing restriction HACKER - remove at launch // send alert email String queryMember = "select from " + Member.class.getName() + " where deptId == " + deptId + " && type == 'Hacker' "; List<Member> members = (List<Member>) pm.newQuery(queryMember).execute(); //TODO Geocode address to insure easy navigation //TODO johnreilly: add street and town fields to Alert msg.setFrom( new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder")); msg.setSubject("Alert!"); msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() + // "&3=" + d.getinboundVRU3() + "&A=" + thisAlert.get(0).getalertMsgString()); // send message to all dept members who permit tracking (and sending email alerts) for (Member m : members) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(), m.getfirstName() + "" + m.getlastName())); log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName()); } } // only process for one department - should only be one department break; } } } catch (MessagingException me) { log.info("Error: Messaging"); } catch (IndexOutOfBoundsException mi) { log.info("Error: Out of Bounds"); } // Do not send alert notification if email is a Google Confirmation // if (! sender.toString().contains("mail-noreply@google.com")) { // Transport.send(msg); // } } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { pm.close(); } }
From source file:fsi_admin.JSmtpConn.java
private boolean sendMsg(String HOST, String USERNAME, String PASSWORD, StringBuffer msj, Session session, MimeMessage mmsg, MimeMultipart multipart) { try {/*from w ww .ja v a 2 s . c om*/ mmsg.setContent(multipart); // Create a transport. Transport transport = session.getTransport(); // Send the message. System.out.println(HOST + " " + USERNAME + " " + PASSWORD); transport.connect(HOST, USERNAME, PASSWORD); // Send the email. transport.sendMessage(mmsg, mmsg.getAllRecipients()); transport.close(); return true; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al enviar SMTP: " + e.getMessage()); return false; } catch (Exception ex) { ex.printStackTrace(); msj.append("Error general de mensaje al enviar SMTP: " + ex.getMessage()); return false; } }
From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java
@Override protected FetchMessagesResult executeInternal(A action, ExecutionContext context) throws ActionException { User user = getUser();// w ww . j a v a 2 s.c o m IMAPFolder folder = action.getFolder(); if (folder == null) { folder = new IMAPFolder(user.getSettings().getInboxFolderName()); } com.sun.mail.imap.IMAPFolder f = null; int start = action.getStart(); int offset = action.getOffset(); try { IMAPStore store = cache.get(user); f = (com.sun.mail.imap.IMAPFolder) store.getFolder(folder.getFullName()); // check if the folder is open, if not open it read only if (f.isOpen() == false) { f.open(com.sun.mail.imap.IMAPFolder.READ_ONLY); } // if the folder is empty we have no need to process int exists = f.getMessageCount(); if (exists == 0) { return new FetchMessagesResult(new ArrayList<org.apache.hupa.shared.data.Message>(), start, offset, 0, 0); } MessageConvertArray convArray = getMessagesToConvert(f, action); return new FetchMessagesResult(convert(offset, f, convArray.getMesssages()), start, offset, convArray.getRealCount(), f.getUnreadMessageCount()); } catch (MessagingException e) { logger.info("Error fetching messages in folder: " + folder.getFullName() + " " + e.getMessage()); // Folder can not contain messages return new FetchMessagesResult(new ArrayList<org.apache.hupa.shared.data.Message>(), start, offset, 0, 0); } catch (Exception e) { e.printStackTrace(); logger.error("Error while fetching headers for user " + user.getName() + " in folder " + folder, e); throw new ActionException( "Error while fetching headers for user " + user.getName() + " in folder " + folder); } finally { if (f != null && f.isOpen()) { try { f.close(false); } catch (MessagingException e) { // we don't care to much about an exception on close here... } } } }
From source file:emea.summit.architects.HackathlonAPIResource.java
public String sendEmailNotification(EmailPayload email) { try {//from w w w . ja va 2 s . c o m String emailContent = (email.getContent() == null ? "" : email.getContent().toString()); JavaMailService.generateAndSendEmail(emailContent.toString(), email.getSubject(), email.getEmailAddresses()); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); return "Email Failed due to " + e.getMessage(); } return "Email was submitted successfully"; }
From source file:org.cgiar.ccafs.marlo.action.TestSMTPAction.java
@Override public String execute() throws Exception { Properties properties = System.getProperties(); properties.put("mail.smtp.host", config.getEmailHost()); properties.put("mail.smtp.port", config.getEmailPort()); Session session = Session.getInstance(properties, new Authenticator() { @Override//from w ww. j av a2 s .c o m protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getEmailUsername(), config.getEmailPassword()); } }); // Create a new message MimeMessage msg = new MimeMessage(session) { @Override protected void updateMessageID() throws MessagingException { if (this.getHeader("Message-ID") == null) { super.updateMessageID(); } } }; msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("h.jimenez@cgiar.org", false)); msg.setSubject("Test email"); msg.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent("If you receive this email, it means that the server is working correctly.", "text; charset=utf-8"); Thread thread = new Thread() { @Override public void run() { sent = false; int i = 0; while (!sent) { try { Transport.send(sendMail); LOG.info("Message sent TRIED#: " + i + " \n" + "Test email"); sent = true; } catch (MessagingException e) { LOG.info("Message DON'T sent: \n" + "Test email"); i++; if (i == 10) { break; } try { Thread.sleep(1 * // minutes to sleep 60 * // seconds to a minute 1000); } catch (InterruptedException e1) { e1.printStackTrace(); } e.printStackTrace(); } } }; }; thread.run(); if (sent) { return SUCCESS; } else { return INPUT; } }
From source file:com.intranet.intr.proveedores.EmpControllerGestion.java
public void enviarProvUC(proveedores proveedor) { String cuerpo = ""; String servidorSMTP = "smtp.1and1.es"; String puertoEnvio = "465"; Properties props = new Properties();//propiedades a agragar props.put("mail.smtp.user", miCorreo);//correo origen props.put("mail.smtp.host", servidorSMTP);//tipo de servidor props.put("mail.smtp.port", puertoEnvio);//puesto de salida props.put("mail.smtp.starttls.enable", "true");//inicializar el servidor props.put("mail.smtp.auth", "true");//autentificacion props.put("mail.smtp.password", "angel2010");//autentificacion props.put("mail.smtp.socketFactory.port", puertoEnvio);//activar el puerto props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); SecurityManager security = System.getSecurityManager(); Authenticator auth = new autentificadorSMTP();//autentificar el correo Session session = Session.getInstance(props, auth);//se inica una session // session.setDebug(true); try {//from w w w . j ava2s . c o m // Creamos un objeto mensaje tipo MimeMessage por defecto. MimeMessage mensajeE = new MimeMessage(session); // Asignamos el de o from? al header del correo. mensajeE.setFrom(new InternetAddress(miCorreo)); // Asignamos el para o to? al header del correo. mensajeE.addRecipient(Message.RecipientType.TO, new InternetAddress(proveedor.getEmail())); // Asignamos el asunto mensajeE.setSubject("Su Perfil Personal"); // Creamos un cuerpo del correo con ayuda de la clase BodyPart //BodyPart cuerpoMensaje = new MimeBodyPart(); // Asignamos el texto del correo String text = "Acceda con usuario: " + proveedor.getUsuario() + " y contrasea: " + proveedor.getContrasenna() + ", al siguiente link http://decorakia.ddns.net/Intranet/login.htm"; // Asignamos el texto del correo cuerpo = "<!DOCTYPE html><html>" + "<head> " + "<title></title>" + "</head>" + "<body>" + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>" + "</html>"; mensajeE.setContent("<!DOCTYPE html>" + "<html>" + "<head> " + "<title></title>" + "</head>" + "<body>" + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>" + "</html>", "text/html"); //mensaje.setText(text); // Creamos un multipart al correo // Enviamos el correo Transport.send(mensajeE); System.out.println("Mensaje enviado"); } catch (MessagingException e) { e.printStackTrace(); } }
From source file:com.niroshpg.android.gmail.PlusSampleServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Check if we have stored credentials using the Authorization Flow. // Note that we only check if there are stored credentials, but not if they are still valid. // The user may have revoked authorization, in which case we would need to go through the // authorization flow again, which this implementation does not handle. GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow(); UserService userService = UserServiceFactory.getUserService(); Credential credential = null;// w ww. java 2s. c o m if (userService != null) { String userId = userService.getCurrentUser().getUserId(); Datastore.saveUserId(userId); credential = authFlow.loadCredential(userId); // if (credential == null) { // // If we don't have a token in store, redirect to authorization screen. logger.warning("auth flow started ..."); resp.sendRedirect( authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build()); return; } // try{ // credential.refreshToken(); // } // catch(TokenResponseException e){ // resp.sendRedirect( // authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build()); // return; // } // Create a new authorized Gmail API client Gmail service = new Gmail.Builder(GmailUtils.HTTP_TRANSPORT, GmailUtils.JSON_FACTORY, credential) .setApplicationName(APP_NAME).build(); // Make the API call BigInteger startHistoryId = null; //service.users().getProfile("me").setRequestHeaders(service.users().getProfile("me").getRequestHeaders().) startHistoryId = getHistoryId(service, "me", credential); logger.warning("hid[url]= " + startHistoryId); List<Label> lableList = listLabels(service, "me"); List<Message> messegeList = listMessagesWithLabels(service, "me", Arrays.asList(getLableIdForName(lableList, "EQM")/*, getLableIdForName(lableList,"UNREAD")*/ )); logger.warning("store messages for processing ... "); for (Message message : messegeList) { //Message detailMessage = getMessage(service, "me", message.getId()); String messageBody = ""; try { MimeMessage mimeMessage = getMimeMessage(service, "me", message.getId()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); messageBody = baos.toString(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //logger.warning("working "+detailMessage.getSnippet()+" ... "); //logger.warning("messageBody= "+messageBody+" ... "); //String messageBody = StringUtils.newStringUtf8(Base64.decodeBase64(detailMessage.getRaw()));//StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData()/*Base64.decodeBase64(detailMessage.getPayload().getBody().decodeData())*/); //String messageBody = StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData()); String extractedMsgBody = MessageUtility.extractData(messageBody); //logger.warning("adding "+extractedMsgBody+" ... "); Datastore.addMessage(extractedMsgBody); } logger.warning("invoke send all"); sendMessagesToAll(); logger.warning("removing label from messages ..."); removeUnRead(service, "me", messegeList); //List<History> historyList = null; //if(messegeList != null && messegeList.size() > 1) //{ // logger.warning("messege count = " + messegeList.size()); // // for(Message amsg : messegeList) // { //logger.warning("id= " + amsg.getId()); // if(amsg.getHistoryId() != null) // { // startHistoryId = amsg.getHistoryId(); //logger.warning("hid= " + amsg.getHistoryId()); // break; // } //} // if(startHistoryId != null) // { // historyList = listHistory(service, "me", startHistoryId); // } // else // { // logger.warning("could not find start history id"); // // //historyList = listHistory(service, "me", BigInteger.valueOf(1)); // // } // } resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); PrintWriter writer = resp.getWriter(); writer.println("<!doctype html><html><head>"); writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); writer.println("<title>" + APP_NAME + "</title>"); writer.println("</head><body>"); //printThreadIds(service,writer); if (messegeList != null && messegeList.size() > 0) { writer.println("<p> msg count = " + messegeList.size() + "</p>"); //for(Message msg : messegeList){ //writer.println("<p>"+msg.toPrettyString()+"</p>"); //} } // if(historyList != null && historyList.size() >0) // { // for(History history : historyList){ // writer.println("<p>"+history.toPrettyString()+"</p>"); // } // } else { writer.println("<p>history not found</p>"); } writer.println("<div class=\"header\"><b>" + req.getUserPrincipal().getName() + "</b> | " + "<a href=\"" + userService.createLogoutURL(req.getRequestURL().toString()) + "\">Log out</a> | " + "<a href=\"http://code.google.com/p/google-api-java-client/source/browse" + "/calendar-appengine-sample?repo=samples\">See source code for " + "this sample</a></div>"); writer.println("<div id=\"main\"/>"); writer.println("</body></html>"); } else { PrintWriter writer = resp.getWriter(); writer.println("<!doctype html><html><head>"); writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"); writer.println("<title>" + APP_NAME + "</title>"); writer.println("</head><body>"); writer.println("<h2>user service not found</h2>"); writer.println("</body></html>"); } }
From source file:com.krawler.spring.profileHandler.profileHandlerController.java
public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response) { JSONObject jobj = new JSONObject(); //Create transaction DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("JE_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED); TransactionStatus status = txnManager.getTransaction(def); KWLTimeZone timeZone = null;//from w ww. j a v a 2 s .c om try { KwlReturnObject kmsg = null; HashMap hm = null; if (ServletFileUpload.isMultipartContent(request)) { hm = new FileUploadHandler().getItems(request); } if (hm == null) throw new Exception("Form does not support file upload"); String id = (String) hm.get("userid"); String auditDetails = ""; User user = null; String pwd = null; if (id != null && id.length() > 0) { user = (User) KwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User", id); } String companyid = sessionHandlerImpl.getCompanyid(request); HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("userid", id); requestParams.put("companyid", companyid); ArrayList filter_names = new ArrayList(); ArrayList filter_params = new ArrayList(); filter_names.add("u.userLogin.userName"); filter_names.add("u.company.companyID"); filter_names.add("!u.userID"); filter_params.add(hm.get("username")); filter_params.add(sessionHandlerImpl.getCompanyid(request)); filter_params.add(id); kmsg = profileHandlerDAOObj.getUserDetails(requestParams, filter_names, filter_params); if (kmsg.getRecordTotalCount() > 0) { throw new Exception("User Name already exists"); } String name = (String) hm.get("username"); String oldname = user.getUserLogin().getUserName(); if (!name.equals(oldname)) auditDetails += "User Name '" + oldname + "' updated to '" + name + "',"; name = (String) hm.get("fname"); oldname = user.getFirstName(); if (!name.equals(oldname)) if (!StringUtil.isNullOrEmpty(oldname)) auditDetails += " First Name '" + oldname + "' updated to '" + name + "',"; else auditDetails += " First Name '" + name + "' added,"; name = (String) hm.get("lname"); oldname = user.getLastName(); if (!name.equals(oldname)) if (!StringUtil.isNullOrEmpty(oldname)) auditDetails += " Last Name '" + oldname + "' updated to '" + name + "',"; else auditDetails += " Last Name '" + name + "' added,"; name = (String) hm.get("emailid"); oldname = user.getEmailID(); if (!name.equals(oldname)) if (!StringUtil.isNullOrEmpty(oldname)) auditDetails += " E-mail '" + oldname + "' updated to '" + name + "',"; else auditDetails += " E-mail '" + name + "' added,"; name = StringUtil.serverHTMLStripper((String) hm.get("address")); oldname = user.getAddress(); if (!name.equals(oldname)) if (!StringUtil.isNullOrEmpty(oldname)) auditDetails += " Address '" + oldname + "' updated to '" + name + "',"; else auditDetails += " Address '" + name + "' added,"; if (hm.get("callwithid") != null) { int callid = Integer.parseInt(hm.get("callwithid").toString()); if (callid != user.getCallwith()) auditDetails += " Call With updated,"; } if (hm.get("timeformat") != null) { int timeformat = Integer.parseInt(hm.get("timeformat").toString()); if (timeformat != user.getTimeformat()) auditDetails += " Time format updated,"; } name = (String) hm.get("contactno"); oldname = user.getContactNumber(); if (!name.equals(oldname)) if (!StringUtil.isNullOrEmpty(oldname)) auditDetails += " Contact Number '" + oldname + "' updated to '" + name + "',"; else auditDetails += " Contact Number '" + name + "' added,"; if (StringUtil.isNullOrEmpty((String) hm.get("formatid")) == false) { KWLDateFormat kdf = (KWLDateFormat) KwlCommonTablesDAOObj .getClassObject("com.krawler.common.admin.KWLDateFormat", (String) hm.get("formatid")); if (!kdf.equals(user.getDateFormat())) auditDetails += " Date format updated to '" + kdf.getJavaForm() + "',"; } String diff = null, tzid = null; if (StringUtil.isNullOrEmpty((String) hm.get("tzid")) == false) { timeZone = (KWLTimeZone) KwlCommonTablesDAOObj .getClassObject("com.krawler.common.admin.KWLTimeZone", (String) hm.get("tzid")); diff = timeZone.getDifference(); tzid = timeZone.getTzID(); if (!timeZone.equals(user.getTimeZone())) auditDetails += " Timezone updated to " + timeZone.getName() + ","; } if (StringUtil.isNullOrEmpty((String) hm.get("aboutuser")) == false) { name = (String) hm.get("aboutuser"); oldname = user.getAboutUser(); if (!name.equals(oldname)) if (!StringUtil.isNullOrEmpty(oldname)) auditDetails += " About User '" + oldname + "' updated to '" + name + "',"; else auditDetails += " About User '" + name + "' added,"; } requestParams.put("username", hm.get("username")); requestParams.put("firstName", hm.get("fname")); requestParams.put("lastName", hm.get("lname")); requestParams.put("emailID", hm.get("emailid")); requestParams.put("address", (String) hm.get("address")); requestParams.put("callwith", hm.get("callwithid")); requestParams.put("timeformat", hm.get("timeformat")); requestParams.put("contactNumber", hm.get("contactno")); requestParams.put("dateFormat", hm.get("formatid")); requestParams.put("timeZone", hm.get("tzid")); requestParams.put("aboutUser", hm.get("aboutuser")); requestParams.put("image", hm.get("userimage")); int notificationtype = 0; if (hm.containsKey("notificationtype") && hm.get("notificationtype").equals("on")) notificationtype = 1; requestParams.put("notificationtype", notificationtype); sessionHandlerImpl.updateNotifyOnFlag(request, notificationtype == 1 ? true : false); requestParams.put("addUser", false); sessionHandlerImpl.updatePreferences(request, null, (StringUtil.isNullOrEmpty((String) hm.get("formatid")) ? null : (String) hm.get("formatid")), (StringUtil.isNullOrEmpty((String) hm.get("tzid")) ? null : (String) hm.get("tzid")), diff, tzid, true); sessionHandlerImpl.updatePreferences(request, null, (StringUtil.isNullOrEmpty((String) hm.get("formatid")) ? null : (String) hm.get("formatid")), (StringUtil.isNullOrEmpty((String) hm.get("tzid")) ? null : (String) hm.get("tzid")), diff, (StringUtil.isNullOrEmpty((String) hm.get("timeformat")) ? null : (String) hm.get("timeformat"))); if (id == null || id.length() <= 0) { //permissionHandlerDAOObj.setDefaultPermissions(1,newuser.getUserID()); HashMap<String, Object> userRoleParams = new HashMap<String, Object>(); userRoleParams.put("userid", sessionHandlerImpl.getUserid(request)); userRoleParams.put("roleid", 4); permissionHandlerDAOObj.saveRoleList(userRoleParams); User creater = (User) KwlCommonTablesDAOObj.getClassObject("com.krawler.common.admin.User", sessionHandlerImpl.getUserid(request)); //String fullnameCreator = (creater.getFirstName() + " " + creater.getLastName()).trim(); String fullnameCreator = creater.getFirstName(); if (fullnameCreator != null && creater.getLastName() != null) fullnameCreator += " " + creater.getLastName(); if (StringUtil.isNullOrEmpty(creater.getFirstName()) && StringUtil.isNullOrEmpty(creater.getLastName())) { fullnameCreator = creater.getUserLogin().getUserName(); } String uri = URLUtil.getPageURL(request, Links.loginpageFull); String pmsg = String.format(KWLErrorMsgs.msgMailInvite, user.getFirstName(), fullnameCreator, user.getUserLogin().getUserName(), pwd, uri, fullnameCreator); String htmlmsg = String.format(KWLErrorMsgs.msgMailInviteUsernamePassword, user.getFirstName(), fullnameCreator, sessionHandlerImplObj.getCompanyName(request), user.getUserLogin().getUserName(), pwd, uri, uri, fullnameCreator); try { SendMailHandler.postMail(new String[] { user.getEmailID() }, "[Deskera] Welcome to Deskera CRM", htmlmsg, pmsg, creater.getEmailID()); } catch (MessagingException e) { e.printStackTrace(); } } kmsg = profileHandlerDAOObj.saveUser(requestParams); if (kmsg.isSuccessFlag()) { jobj.put("msg", messageSource.getMessage("crm.userprofile.updateusersuccessmsg", null, RequestContextUtils.getLocale(request)));//"Profile has been updated successfully."); if (!StringUtil.isNullObject(timeZone)) { jobj.put("tzdiff", timeZone.getDifference()); } // create user entry for emails in krawlercrm database if (StringUtil.isNullOrEmpty(id)) { mailIntDAOObj.addUserEntryForEmails(sessionHandlerImpl.getUserid(request), user, user.getUserLogin(), pwd, true); } } else { jobj.put("msg", messageSource.getMessage("crm.userprofile.updateuserfailuremsg", null, RequestContextUtils.getLocale(request)));//"Sorry! User information could not be saved successfully. Please try again."); } if (auditDetails.length() > 0) { auditDetails = auditDetails.substring(0, auditDetails.length() - 1); if (!sessionHandlerImpl.getUserid(request).equals(id)) { auditDetails += " for user " + user.getFirstName() + " " + user.getLastName() + " "; } auditTrailDAOObj.insertAuditLog(AuditAction.User_Profile_update, auditDetails, request, id); } txnManager.commit(status); } catch (Exception e) { logger.warn("General exception in saveUser()", e); txnManager.rollback(status); } return new ModelAndView("jsonView", "model", jobj.toString()); }
From source file:org.emmanet.controllers.requestsUpdateInterfaceFormController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws ServletException, Exception { model.put("BASEURL", BASEURL); System.out.println("BASEURL VALUE FROM MODEL IS::" + model.get("BASEURL")); WebRequestsDAO webRequest = (WebRequestsDAO) command; if (!request.getParameter("noTAinfo").equals("true")) { String panelDecision = webRequest.getTa_panel_decision(); String applicationType = webRequest.getApplication_type(); if (panelDecision.equals("yes") || panelDecision.equals("no") && applicationType.contains("ta")) { //check if mail already sent by checking notes for string if (!webRequest.getNotes().contains("TA mail sent")) { //Decision has been made therefore decision mails should be triggered //SimpleMailMessage msg = getSimpleMailMessage(); MimeMessage msg = getJavaMailSender().createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8"); String content = ""; String toAddress = webRequest.getSci_e_mail(); // msg.setTo(toAddress); helper.setTo(toAddress); helper.setFrom(getFromAddress()); String[] ccs = getCc(); List lCc = new ArrayList(); for (int i = 0; i < ccs.length; i++) { //add configurated cc addresses to list String CcElement = ccs[i]; lCc.add(CcElement);//from w w w . ja v a 2 s .c o m } lCc.add(webRequest.getCon_e_mail()); List ccCentre = wr.ccArchiveMailAddresses("" + webRequest.getStr_id_str(), "strains"); Object[] o = null; Iterator it = ccCentre.iterator(); while (it.hasNext()) { o = (Object[]) it.next(); lCc.add(o[1].toString()); } String[] ar = new String[lCc.size()]; for (int i = 0; i < lCc.size(); i++) { Object oo = lCc.get(i); ar[i] = oo.toString(); System.out.println(oo.toString()); } String[] bccs = getBcc(); //msg. helper.setBcc(bccs); //msg. helper.setCc(ar); /* format date string */ String date = webRequest.getTimestamp().toString(); String yyyy = date.substring(0, 4); String MM = date.substring(5, 7); String dd = date.substring(8, 10); date = dd + "-" + MM + "-" + yyyy; model.put("name", webRequest.getSci_firstname() + " " + webRequest.getSci_surname()); model.put("emmaid", webRequest.getStrain_id().toString()); model.put("strainname", webRequest.getStrain_name()); model.put("timestamp", date); model.put("sci_title", webRequest.getSci_title()); model.put("sci_firstname", webRequest.getSci_firstname()); model.put("sci_surname", webRequest.getSci_surname()); model.put("sci_e_mail", webRequest.getSci_e_mail()); model.put("strain_id", webRequest.getStrain_id()); model.put("strain_name", webRequest.getStrain_name()); model.put("common_name_s", webRequest.getCommon_name_s()); model.put("req_material", webRequest.getReq_material()); //new mta file inclusion model.put("requestID", webRequest.getId_req()); model.put("BASEURL", BASEURL); StrainsManager sm = new StrainsManager(); StrainsDAO sd = sm.getStrainByID(webRequest.getStr_id_str()); if (!webRequest.getLab_id_labo().equals("4")) { /* * FOR LEGAL REASONS MTA FILE AND USAGE TEXT SHOULD NOT BE SHOWN FOR MRC STOCK. * MRC WILL SEND MTA SEPARATELY (M.FRAY EMMA IT MEETING 28-29 OCT 2010) */ model.put("mtaFile", sd.getMta_file()); } //######################################################## String rtoolsID = ""; List rtools = wr.strainRToolID(webRequest.getStr_id_str()); it = rtools.iterator(); while (it.hasNext()) { Object oo = it.next(); rtoolsID = oo.toString(); } model.put("rtoolsID", rtoolsID); //TEMPLATE SELECTION if (panelDecision.equals("yes")) { //we need to send a mail if (webRequest.getApplication_type().contains("ta_")) { System.out.println(getTemplatePath() + getTaOrRequestYesTemplate()); content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), getTemplatePath() + getTaOrRequestYesTemplate(), model); } } /* webRequest.getTa_panel_decision().equals("no") */ if (panelDecision.equals("no")) { System.out.println("panel decision == no =="); if (applicationType.equals("ta_or_request")) { System.out.println("path to template for ta_or_req and no==" + getTemplatePath() + getTaOrRequestNoTemplate()); content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), getTemplatePath() + getTaOrRequestNoTemplate(), model); } if (applicationType.equals("ta_only")) { //TODO IF NO AND TA_ONLY THEN REQ_STATUS=CANC webRequest.setReq_status("CANC"); System.out.println("path to template for ta_only and no==" + getTemplatePath() + getTaOnlyNoTemplate()); content = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), getTemplatePath() + getTaOnlyNoTemplate(), model); } } //send message //msg. helper.setSubject( msgSubject + webRequest.getStrain_name() + "(" + webRequest.getStrain_id() + ")"); //msg. helper.setText(content); //###/add mta file if associated with strain id String mtaFile = ""; mtaFile = (new StringBuilder()).append(mtaFile).append(sd.getMta_file()).toString(); if (mtaFile != null || model.get("mtaFile").toString().equals("")) { FileSystemResource fileMTA = new FileSystemResource(new File(getPathToMTA() + mtaFile)); //need to check for a valid mta filename use period extension separator, all mtas are either .doc or .pdf if (fileMTA.exists() && fileMTA.toString().contains(".")) { //M Hagn decided now to not send an MTA at this point as users should have already received one. Was confusing users to receive another philw@ebi.ac.uk 05042011 //helper.addAttachment(model.get("mtaFile").toString(), fileMTA); } } System.out.println("Rtools=" + model.get("rtoolsID") + " and labID=" + model.get("labID")); if (request.getParameter("TEST") != null) { // TESTER SUBMITTED EMAIL ADDRESS //msg. helper.setTo(request.getParameter("TEST")); //msg. helper.setCc(request.getParameter("TEST")); String Ccs = ""; for (int i = 0; i < ar.length; i++) { Ccs = Ccs + ", " + ar[i]; } //msg. helper.setText("TEST EMAIL, LIVE EMAIL SENT TO " + toAddress + " CC'D TO :\n\n " + Ccs + " LIVE MESSAGE TEXT FOLLOWS BELOW::\n\n" + content); } if (!toAddress.equals("")) { //Set notes to contain ta mail sent trigger String notes = webRequest.getNotes(); notes = notes + "TA mail sent"; webRequest.setNotes(notes); } getJavaMailSender().send(msg); } } } if (request.getParameter("fSourceID") != null || !request.getParameter("fSourceID").equals("")) { //save requestfunding source ID boolean saveOnly = false; int sour_id = Integer.parseInt(request.getParameter("fSourceID")); int srcID = Integer.parseInt(webRequest.getId_req()); System.out.println("fSourceID==" + srcID); srd = wr.getReqSourcesByID(srcID);//sm.getSourcesByID(srcID); // try { srd.getSour_id();//ssd.getSour_id(); srd.setSour_id(sour_id); } catch (NullPointerException np) { srd = new Sources_RequestsDAO(); int reqID = Integer.parseInt(webRequest.getId_req()); srd.setReq_id_req(reqID); srd.setSour_id(sour_id); //save only here not save or update saveOnly = true; } if (saveOnly) { wr.saveOnly(srd); System.out.println("THIS IS NOW SAVED:: SAVEONLY"); } else if (!saveOnly) { //save or update System.out.println("SAVEORUPDATEONLY + value is.." + srd); wr.save(srd); System.out.println("THIS IS NOW SAVED:: SAVEORUPDATEONLY"); } } wr.saveRequest(webRequest); request.getSession().setAttribute("message", getMessageSourceAccessor().getMessage("Message", "Your update submitted successfully")); if (webRequest.getProjectID().equals("3") && webRequest.getLab_id_labo().equals("1961")) { //OK this is a Sanger/Eucomm strain and could be subject to charging so may need to send xml if (request.getParameter("currentReqStatus").contains("PR") && webRequest.getReq_status().equals("SHIP")) { //status changed to shipped from a non cancelled request so subject to a charge model.put("name", webRequest.getSci_firstname() + " " + webRequest.getSci_surname()); model.put("emmaid", webRequest.getStrain_id().toString()); model.put("strainname", webRequest.getStrain_name()); model.put("timestamp", webRequest.getTimestamp()); model.put("ftimestamp", webRequest.getFtimestamp()); model.put("sci_title", webRequest.getSci_title()); model.put("sci_firstname", webRequest.getSci_firstname()); model.put("sci_surname", webRequest.getSci_surname()); model.put("sci_e_mail", webRequest.getSci_e_mail()); model.put("sci_phone", webRequest.getSci_phone()); model.put("sci_fax", webRequest.getSci_fax()); model.put("con_title", webRequest.getCon_title()); model.put("con_firstname", webRequest.getCon_firstname()); model.put("con_surname", webRequest.getCon_surname()); model.put("con_e_mail", webRequest.getCon_e_mail()); model.put("con_phone", webRequest.getCon_phone()); model.put("con_fax", webRequest.getCon_fax()); model.put("con_institution", webRequest.getCon_institution()); model.put("con_dept", webRequest.getCon_dept()); model.put("con_addr_1", webRequest.getCon_addr_1()); model.put("con_addr_2", webRequest.getCon_addr_2()); model.put("con_province", webRequest.getCon_province()); model.put("con_town", webRequest.getCon_town()); model.put("con_postcode", webRequest.getCon_postcode()); model.put("con_country", webRequest.getCon_country()); //billing details if (!webRequest.getRegister_interest().equals("1")) { model.put("PO_ref", webRequest.getPO_ref()); model.put("bil_title", webRequest.getBil_title()); model.put("bil_firstname", webRequest.getBil_firstname()); model.put("bil_surname", webRequest.getBil_surname()); model.put("bil_e_mail", webRequest.getBil_e_mail()); model.put("bil_phone", webRequest.getBil_phone()); model.put("bil_fax", webRequest.getBil_fax()); model.put("bil_institution", webRequest.getBil_institution()); model.put("bil_dept", webRequest.getBil_dept()); model.put("bil_addr_1", webRequest.getBil_addr_1()); model.put("bil_addr_2", webRequest.getBil_addr_2()); model.put("bil_province", webRequest.getBil_province()); model.put("bil_town", webRequest.getBil_town()); model.put("bil_postcode", webRequest.getBil_postcode()); model.put("bil_country", webRequest.getBil_country()); model.put("bil_vat", webRequest.getBil_vat()); } //end biling details model.put("strain_id", webRequest.getStrain_id()); model.put("strain_name", escapeXml(webRequest.getStrain_name())); model.put("common_name_s", webRequest.getCommon_name_s()); model.put("req_material", webRequest.getReq_material()); model.put("live_animals", webRequest.getLive_animals()); model.put("frozen_emb", webRequest.getFrozen_emb()); model.put("frozen_spe", webRequest.getFrozen_spe()); // TA application details model.put("application_type", webRequest.getApplication_type()); model.put("ta_eligible", webRequest.getEligible_country()); if (webRequest.getApplication_type().contains("ta")) { model.put("ta_proj_desc", webRequest.getProject_description()); model.put("ta_panel_sub_date", webRequest.getTa_panel_sub_date()); model.put("ta_panel_decision_date", webRequest.getTa_panel_decision_date()); model.put("ta_panel_decision", webRequest.getTa_panel_decision()); } else { model.put("ta_proj_desc", ""); model.put("ta_panel_sub_date", ""); model.put("ta_panel_decision_date", ""); model.put("ta_panel_decision", ""); } model.put("ROI", webRequest.getRegister_interest()); model.put("europhenome", webRequest.getEurophenome()); model.put("wtsi_mouse_portal", webRequest.getWtsi_mouse_portal()); //now create xml file String xmlFileContent = VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), "org/emmanet/util/velocitytemplates/requestXml-Template.vm", model); File file = new File(Configuration.get("sangerLineDistribution")); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8")); out.write(xmlFileContent); out.close(); //email file now MimeMessage message = getJavaMailSender().createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); helper.setReplyTo("emma@infrafrontier.eu"); helper.setFrom("emma@infrafrontier.eu"); helper.setBcc(bcc); helper.setTo(sangerLineDistEmail); helper.setSubject("Sanger Line Distribution " + webRequest.getStrain_id()); helper.addAttachment("sangerlinedistribution.xml", file); getJavaMailSender().send(message); } catch (MessagingException ex) { ex.printStackTrace(); } } } System.out.println("BASEURL VALUE FROM MODEL IS::" + model.get("BASEURL")); return new ModelAndView( "redirect:requestsUpdateInterface.emma?Edit=" + request.getParameter("Edit").toString() + "&strainID=" + request.getParameter("strainID").toString() + "&archID=" + request.getParameter("archID").toString()); }