List of usage examples for java.text DateFormat getDateInstance
public static final DateFormat getDateInstance(int style, Locale aLocale)
From source file:org.glom.app.libglom.Document.java
/** * @param element/*from ww w.jav a 2 s.c o m*/ * @param type * @return */ private DataItem getNodeTextChildAsValue(final Element element, final GlomFieldType type) { final DataItem result = new DataItem(); final String str = element.getTextContent(); // Unescape "" to ", because to_file_format() escaped ", as specified by the CSV RFC: String unescaped; if (type == GlomFieldType.TYPE_IMAGE) { unescaped = str; // binary data does not have quote characters so we do not bother to escape or unescape it. } else { unescaped = str.replace(QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT); } switch (type) { case TYPE_BOOLEAN: { final boolean value = (unescaped.equals("true")); result.setBoolean(value); break; } case TYPE_DATE: { final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT); Date value = null; try { value = dateFormat.parse(unescaped); } catch (final ParseException e) { // e.printStackTrace(); } result.setDate(value); break; } case TYPE_IMAGE: { //Glom (at least since 2.23/24) uses base64 for the images: //This is only used on the server-side, //either to create a database, during tests, //or to return the full data from our OnlineGlomImage service. //It is removed before being passed to the client-side. /* This does not seem to work with the text from g_base64_encode() that Glom uses, * maybe because of the newlines, which are apparently OK: * http://en.wikipedia.org/wiki/Base64#MIME * final byte[] bytes = com.google.gwt.user.server.Base64Utils.fromBase64(unescaped); */ /* Use org.apache.commons.codec.binary.Base64: */ final Base64 decoder = new Base64(); byte[] bytes = decoder.decode(unescaped.getBytes()); result.setImageData(bytes); break; } case TYPE_NUMERIC: { double value = 0; try { value = Double.valueOf(unescaped); } catch (final NumberFormatException e) { // e.printStackTrace(); } result.setNumber(value); break; } case TYPE_TEXT: result.setText(unescaped); break; case TYPE_TIME: // TODO break; default: Log.e("android-glom", documentID + ": getNodeTextChildAsValue(): unexpected or invalid field type."); break; } return result; }
From source file:org.glom.web.server.libglom.Document.java
/** * @param elementValue//from ww w . ja va 2 s .c o m * @param glomType * @return */ private DataItem getNodeTextChildAsValue(final Element element, final GlomFieldType type) { final DataItem result = new DataItem(); final String str = element.getTextContent(); // Unescape "" to ", because to_file_format() escaped ", as specified by the CSV RFC: String unescaped = ""; if (type == GlomFieldType.TYPE_IMAGE) { unescaped = str; // binary data does not have quote characters so we do not bother to escape or unescape it. } else { unescaped = str.replace(QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT); } switch (type) { case TYPE_BOOLEAN: { final boolean value = (unescaped.equals("true")); result.setBoolean(value); break; } case TYPE_DATE: { final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT); Date value = null; try { value = dateFormat.parse(unescaped); } catch (final ParseException e) { // e.printStackTrace(); } result.setDate(value); break; } case TYPE_IMAGE: { //Glom (at least since 2.23/24) uses base64 for the images: //This is only used on the server-side, //either to create a database, during tests, //or to return the full data from our OnlineGlomImage service. //It is removed before being passed to the client-side. /* This does not seem to work with the text from g_base64_encode() that Glom uses, * maybe because of the newlines, which are apparently OK: * http://en.wikipedia.org/wiki/Base64#MIME * final byte[] bytes = com.google.gwt.user.server.Base64Utils.fromBase64(unescaped); */ /* Use org.apache.commons.codec.binary.Base64: */ final Base64 decoder = new Base64(); byte[] bytes = (byte[]) decoder.decode(unescaped.getBytes()); result.setImageData(bytes); break; } case TYPE_NUMERIC: { double value = 0; try { value = Double.valueOf(unescaped); } catch (final NumberFormatException e) { // e.printStackTrace(); } result.setNumber(value); break; } case TYPE_TEXT: result.setText(unescaped); break; case TYPE_TIME: // TODO break; default: Log.error(documentID, "getNodeTextChildAsValue(): unexpected or invalid field type."); break; } return result; }
From source file:com.appeaser.sublimepickerlibrary.recurrencepicker.RecurrenceOptionCreator.java
void initializeLayout() { int weekButtonUnselectedTextColor, weekButtonSelectedTextColor, weekButtonSelectedCircleColor; final TypedArray a = getContext().obtainStyledAttributes(R.styleable.RecurrenceOptionCreator); try {//from ww w . j av a2s. com mHeaderBackgroundColor = a.getColor(R.styleable.RecurrenceOptionCreator_spHeaderBackground, 0); int endDateFormat = a.getInt(R.styleable.RecurrenceOptionCreator_spEndDateFormat, 1); mEndDateFormatter = DateFormat.getDateInstance( endDateFormat == 0 ? DateFormat.SHORT : DateFormat.MEDIUM, Locale.getDefault()); weekButtonUnselectedTextColor = a.getColor( R.styleable.RecurrenceOptionCreator_spWeekButtonUnselectedTextColor, SUtils.COLOR_ACCENT); weekButtonSelectedTextColor = a.getColor( R.styleable.RecurrenceOptionCreator_spWeekButtonSelectedTextColor, SUtils.COLOR_TEXT_PRIMARY_INVERSE); weekButtonSelectedCircleColor = a.getColor( R.styleable.RecurrenceOptionCreator_spWeekButtonSelectedCircleColor, SUtils.COLOR_ACCENT); } finally { a.recycle(); } mResources = getResources(); LayoutInflater.from(getContext()).inflate(R.layout.recurrence_picker, this); mRecurrencePicker = findViewById(R.id.recurrence_picker); mDateOnlyPicker = (RecurrenceEndDatePicker) findViewById(R.id.date_only_picker); mDateOnlyPicker.setVisibility(View.GONE); // OK/Cancel buttons mButtonLayout = (DecisionButtonLayout) findViewById(R.id.roc_decision_button_layout); mButtonLayout.applyOptions(mButtonLayoutCallback); SUtils.setViewBackground(findViewById(R.id.freqSpinnerHolder), mHeaderBackgroundColor, SUtils.CORNER_TOP_LEFT | SUtils.CORNER_TOP_RIGHT); /** EFrequency Spinner {Repeat daily, Repeat weekly, Repeat monthly, Repeat yearly} **/ mFreqSpinner = (Spinner) findViewById(R.id.freqSpinner); mFreqSpinner.setOnItemSelectedListener(this); ArrayAdapter<CharSequence> freqAdapter = ArrayAdapter.createFromResource(getContext(), R.array.recurrence_freq, R.layout.roc_freq_spinner_item); freqAdapter.setDropDownViewResource(R.layout.roc_spinner_dropdown_item); mFreqSpinner.setAdapter(freqAdapter); Drawable freqSpinnerBg = ContextCompat.getDrawable(getContext(), R.drawable.abc_spinner_mtrl_am_alpha); PorterDuffColorFilter cfFreqSpinner = new PorterDuffColorFilter(SUtils.COLOR_TEXT_PRIMARY_INVERSE, PorterDuff.Mode.SRC_IN); if (freqSpinnerBg != null) { freqSpinnerBg.setColorFilter(cfFreqSpinner); SUtils.setViewBackground(mFreqSpinner, freqSpinnerBg); } mInterval = (EditText) findViewById(R.id.interval); mInterval.addTextChangedListener(new minMaxTextWatcher(1, INTERVAL_DEFAULT, INTERVAL_MAX) { @Override void onChange(int v) { if (mIntervalResId != -1 && mInterval.getText().toString().length() > 0) { mModel.interval = v; updateIntervalText(); mInterval.requestLayout(); } } }); mIntervalPreText = (TextView) findViewById(R.id.intervalPreText); mIntervalPostText = (TextView) findViewById(R.id.intervalPostText); /** End Spinner {Forever, Until a date, For a number of events} **/ mEndNeverStr = mResources.getString(R.string.recurrence_end_continously); mEndDateLabel = mResources.getString(R.string.recurrence_end_date_label); mEndCountLabel = mResources.getString(R.string.recurrence_end_count_label); mEndSpinnerArray.add(mEndNeverStr); mEndSpinnerArray.add(mEndDateLabel); mEndSpinnerArray.add(mEndCountLabel); mEndSpinner = (Spinner) findViewById(R.id.endSpinner); mEndSpinner.setOnItemSelectedListener(this); mEndSpinnerAdapter = new EndSpinnerAdapter(getContext(), mEndSpinnerArray, R.layout.roc_end_spinner_item, R.id.spinner_item, R.layout.roc_spinner_dropdown_item); mEndSpinner.setAdapter(mEndSpinnerAdapter); mEndCount = (EditText) findViewById(R.id.endCount); mEndCount.addTextChangedListener(new minMaxTextWatcher(1, COUNT_DEFAULT, COUNT_MAX) { @Override void onChange(int v) { if (mModel.endCount != v) { mModel.endCount = v; updateEndCountText(); mEndCount.requestLayout(); } } }); mPostEndCount = (TextView) findViewById(R.id.postEndCount); mEndDateTextView = (TextView) findViewById(R.id.endDate); mEndDateTextView.setOnClickListener(this); SUtils.setViewBackground(mEndDateTextView, SUtils.createButtonBg(getContext(), SUtils.COLOR_BUTTON_NORMAL, SUtils.COLOR_CONTROL_HIGHLIGHT)); // set default & checked state colors WeekButton.setStateColors(weekButtonUnselectedTextColor, weekButtonSelectedTextColor); // AOSP code handled this differently. It has been refactored to // let Android decide if we have enough space to show // all seven 'WeekButtons' inline. In this case, 'mWeekGroup2' // will be null (see @layout-w460dp/week_buttons). mWeekGroup = (LinearLayout) findViewById(R.id.weekGroup); mWeekGroup2 = (LinearLayout) findViewById(R.id.weekGroup2); // Only non-null when available width is < 460dp // Used only for positioning 'WeekButtons' in two rows // of 4 & 3. View eighthWeekDay = findViewById(R.id.week_day_8); if (eighthWeekDay != null) eighthWeekDay.setVisibility(View.INVISIBLE); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 //String[] dayOfWeekString = new DateFormatSymbols().getWeekdays(); mMonthRepeatByDayOfWeekStrs = new String[7][]; // from Time.SUNDAY as 0 through Time.SATURDAY as 6 mMonthRepeatByDayOfWeekStrs[0] = mResources.getStringArray(R.array.repeat_by_nth_sun); mMonthRepeatByDayOfWeekStrs[1] = mResources.getStringArray(R.array.repeat_by_nth_mon); mMonthRepeatByDayOfWeekStrs[2] = mResources.getStringArray(R.array.repeat_by_nth_tues); mMonthRepeatByDayOfWeekStrs[3] = mResources.getStringArray(R.array.repeat_by_nth_wed); mMonthRepeatByDayOfWeekStrs[4] = mResources.getStringArray(R.array.repeat_by_nth_thurs); mMonthRepeatByDayOfWeekStrs[5] = mResources.getStringArray(R.array.repeat_by_nth_fri); mMonthRepeatByDayOfWeekStrs[6] = mResources.getStringArray(R.array.repeat_by_nth_sat); // In Time.java day of week order e.g. Sun = 0 int idx = RecurrenceUtils.getFirstDayOfWeek(); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 String[] dayOfWeekString = new DateFormatSymbols().getShortWeekdays(); // CheckableDrawable's width & height int expandedWidthHeight = mResources.getDimensionPixelSize(R.dimen.week_button_state_on_circle_size); WeekButton[] tempWeekButtons = new WeekButton[7]; tempWeekButtons[0] = (WeekButton) findViewById(R.id.week_day_1); tempWeekButtons[1] = (WeekButton) findViewById(R.id.week_day_2); tempWeekButtons[2] = (WeekButton) findViewById(R.id.week_day_3); tempWeekButtons[3] = (WeekButton) findViewById(R.id.week_day_4); tempWeekButtons[4] = (WeekButton) findViewById(R.id.week_day_5); tempWeekButtons[5] = (WeekButton) findViewById(R.id.week_day_6); tempWeekButtons[6] = (WeekButton) findViewById(R.id.week_day_7); for (int i = 0; i < mWeekByDayButtons.length; i++) { mWeekByDayButtons[idx] = tempWeekButtons[i]; SUtils.setViewBackground(mWeekByDayButtons[idx], new CheckableDrawable(weekButtonSelectedCircleColor, false, expandedWidthHeight)); mWeekByDayButtons[idx].setTextColor(weekButtonUnselectedTextColor); mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setOnCheckedChangeListener(this); if (++idx >= 7) { idx = 0; } } mMonthRepeatByRadioGroup = (RadioGroup) findViewById(R.id.monthGroup); mMonthRepeatByRadioGroup.setOnCheckedChangeListener(this); mRepeatMonthlyByNthDayOfWeek = (RadioButton) findViewById(R.id.repeatMonthlyByNthDayOfTheWeek); mRepeatMonthlyByNthDayOfMonth = (RadioButton) findViewById(R.id.repeatMonthlyByNthDayOfMonth); }
From source file:org.glom.libglom.Document.java
private void setNodeTextChildAsValue(final Element element, final DataItem value, final GlomFieldType type) { String str = ""; switch (type) { case TYPE_BOOLEAN: { str = value.getBoolean() ? "true" : "false"; break;//from www .j av a 2 s. c om } case TYPE_DATE: { // TODO: This is not really the format used by the Glom document: final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT); str = dateFormat.format(value.getDate()); break; } case TYPE_IMAGE: { str = ""; // TODO break; } case TYPE_NUMERIC: { str = getStringForDecimal(value.getNumber()); break; } case TYPE_TEXT: str = value.getText(); break; case TYPE_TIME: str = ""; // TODO break; default: Logger.log(documentID + ": setNodeTextChildAsValue(): unexpected or invalid field type."); break; } final String escaped = str.replace(QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT); element.setTextContent(escaped); }
From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java
/** * Import lock box files.//from www . j ava2 s.com * * @param now The current date. * @param isNowHoliday Indicate whether current is holiday * @return true if execution is successful; false to retry. * @throws BatchProcessingException If major error occurred. */ private boolean importFiles(Date now, boolean isNowHoliday) throws BatchProcessingException { StringBuilder procMessage = new StringBuilder(); procMessage.append("Service Credit Batch started at "); procMessage.append(DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(now)); procMessage.append(" on "); procMessage.append(DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(now)); procMessage.append(". Batch done at @#$%EndingTime%$#@."); procMessage.append(CRLF).append(CRLF); File inputDirectory = new File(inputDirectoryPath); if (!inputDirectory.exists() || !inputDirectory.isDirectory() || !inputDirectory.canRead()) { logger.error("Can not read folder: " + inputDirectory); procMessage.append("THE NETWORK IS DOWN! "); procMessage.append(CRLF); procMessage.append("Network Services not Available for Service Credit. Cannot access the "); procMessage.append(inputDirectoryPath); procMessage.append(" network folder. Please ask the Help Desk to investigate. "); procMessage.append("SERVICE CREDIT IS SHUT DOWN UNTIL THIS ERROR IS FIXED! "); notifyByEmail(procMessage.toString(), "SERVICE CREDIT BATCH CANNOT ACCESS NETWORK", "Testing Network"); auditError("SERVICE CREDIT BATCH CANNOT ACCESS NETWORK", procMessage.toString()); return false; } // Filter the input lockbox files final String regex = wildCardInput.replace("?", ".?").replace("*", ".*?"); File[] inputFiles = inputDirectory.listFiles(new FileFilter() { @Override public boolean accept(File inputFile) { if (inputFile.getName().matches(regex)) { if (inputFile.isFile() && inputFile.canRead() && inputFile.canWrite()) { return true; } logger.warn("Does not have read/write permission to file: " + inputFile); } return false; } }); if (inputFiles.length == 0) { if (!isNowHoliday && Boolean.TRUE != todayAuditBatch.getFileReceived()) { logger.error("No files arrived today in: " + inputDirectory); procMessage.append("Today's Lockbox Bank File has not arrived. Please notify Production Control" + " and BSG that the data file is not in the "); procMessage.append(inputDirectoryPath); procMessage.append(" network share. The nightly batch process is scheduled to run at "); procMessage.append(DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(now)); procMessage.append(" and today's import should run before that time. "); notifyByEmail(procMessage.toString(), "SERVICE CREDIT LOCKBOX FILE IS LATE!", "ERROR"); auditError("SERVICE CREDIT LOCKBOX FILE IS LATE!", procMessage.toString()); return false; } return true; } // Mark file arrived if (Boolean.TRUE != todayAuditBatch.getFileReceived()) { todayAuditBatch.setFileReceived(true); try { todayAuditBatch = mergeEntity(todayAuditBatch); } catch (PersistenceException pe) { throw new BatchProcessingException( "Database error while updating audit batch log when importing files", pe); } } // Import files logger.info("Start importing files in: " + inputDirectory); for (File inputFile : inputFiles) { if (!inputFile.exists() || !inputFile.isFile() || !inputFile.canRead()) { // Just make sure logger.warn("Lockbox file is not a readable file: " + inputFile); continue; } importFile(procMessage, inputFile); } logger.info("End importing files in: " + inputDirectory); return true; }
From source file:org.hoteia.qalingo.core.service.impl.EmailServiceImpl.java
/** * @see org.hoteia.qalingo.core.service.EmailService#buildAndSaveCustomerResetPasswordConfirmationMail(Localization localization, Customer customer, String velocityPath, CustomerResetPasswordConfirmationEmailBean customerResetPasswordConfirmationEmailBean) *///w w w . j ava2 s .co m public void buildAndSaveCustomerResetPasswordConfirmationMail(final RequestData requestData, final Customer customer, final String velocityPath, final CustomerResetPasswordConfirmationEmailBean customerResetPasswordConfirmationEmailBean) throws Exception { try { final Localization localization = requestData.getMarketAreaLocalization(); final Locale locale = localization.getLocale(); // SANITY CHECK checkEmailAddresses(customerResetPasswordConfirmationEmailBean); Map<String, Object> model = new HashMap<String, Object>(); DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, locale); java.sql.Timestamp currentDate = new java.sql.Timestamp((new java.util.Date()).getTime()); model.put(CURRENT_DATE, dateFormatter.format(currentDate)); model.put(CUSTOMER, customer); model.put("customerResetPasswordConfirmationEmailBean", customerResetPasswordConfirmationEmailBean); model.put(WORDING, coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale)); String loginUrl = urlService.generateUrl(FoUrls.LOGIN, requestData); model.put("loginUrl", urlService.buildAbsoluteUrl(requestData, loginUrl)); String fromAddress = handleFromAddress(customerResetPasswordConfirmationEmailBean.getFromAddress(), locale); String fromName = handleFromName(customerResetPasswordConfirmationEmailBean.getFromName(), locale); String toEmail = customer.getEmail(); MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData, Email.EMAIl_TYPE_RESET_PASSWORD_CONFIRMATION, model); mimeMessagePreparator.setTo(toEmail); mimeMessagePreparator.setFrom(fromAddress); mimeMessagePreparator.setFromName(fromName); mimeMessagePreparator.setReplyTo(fromAddress); Object[] parameters = { customer.getLastname(), customer.getFirstname() }; mimeMessagePreparator.setSubject(coreMessageSource .getMessage("email.reset_password_confirmation.email_subject", parameters, locale)); mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "reset-password-confirmation-html-content.vm", model)); mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "reset-password-confirmation-text-content.vm", model)); Email email = new Email(); email.setType(Email.EMAIl_TYPE_RESET_PASSWORD_CONFIRMATION); email.setStatus(Email.EMAIl_STATUS_PENDING); saveOrUpdateEmail(email, mimeMessagePreparator); } catch (MailException e) { logger.error("Error, can't save the message :", e); throw e; } catch (VelocityException e) { logger.error("Error, can't build the message :", e); throw e; } catch (IOException e) { logger.error("Error, can't serializable the message :", e); throw e; } }
From source file:org.glom.app.libglom.Document.java
private void setNodeTextChildAsValue(final Element element, final DataItem value, final GlomFieldType type) { String str = ""; switch (type) { case TYPE_BOOLEAN: { str = value.getBoolean() ? "true" : "false"; break;//from ww w. j a v a 2s.c om } case TYPE_DATE: { // TODO: This is not really the format used by the Glom document: final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT); str = dateFormat.format(value.getDate()); break; } case TYPE_IMAGE: { str = ""; // TODO break; } case TYPE_NUMERIC: { str = getStringForDecimal(value.getNumber()); break; } case TYPE_TEXT: str = value.getText(); break; case TYPE_TIME: str = ""; // TODO break; default: Log.e("android-glom", documentID + ": setNodeTextChildAsValue(): unexpected or invalid field type."); break; } final String escaped = str.replace(QUOTE_FOR_FILE_FORMAT, QUOTE_FOR_FILE_FORMAT + QUOTE_FOR_FILE_FORMAT); element.setTextContent(escaped); }
From source file:org.mifos.framework.util.helpers.DateUtils.java
public static String convertToDbFormat(Locale locale, String givenDate) throws InvalidDateException { SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale); String userfmt = convertToCurrentDateFormat(format.toPattern()); return convertUserToDbFmt(givenDate, userfmt); }
From source file:org.hoteia.qalingo.core.service.EmailService.java
/** * @throws Exception //from w ww. ja v a 2 s. co m */ public Email buildAndSaveCustomerForgottenPasswordMail(final RequestData requestData, final Customer customer, final String velocityPath, final CustomerForgottenPasswordEmailBean customerForgottenPasswordEmailBean) throws Exception { Email email = null; try { final String contextNameValue = requestData.getContextNameValue(); final Localization localization = requestData.getMarketAreaLocalization(); final Locale locale = localization.getLocale(); // SANITY CHECK checkEmailAddresses(customerForgottenPasswordEmailBean); Map<String, Object> model = new HashMap<String, Object>(); DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, locale); java.sql.Timestamp currentDate = new java.sql.Timestamp((new java.util.Date()).getTime()); model.put(CURRENT_DATE, dateFormatter.format(currentDate)); model.put(CUSTOMER, customer); model.put("customerForgottenPasswordEmailBean", customerForgottenPasswordEmailBean); model.put(WORDING, coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale)); Map<String, String> urlParams = new HashMap<String, String>(); urlParams.put(RequestConstants.REQUEST_PARAMETER_PASSWORD_RESET_EMAIL, URLEncoder.encode(customer.getEmail(), Constants.ANSI)); urlParams.put(RequestConstants.REQUEST_PARAMETER_PASSWORD_RESET_TOKEN, customerForgottenPasswordEmailBean.getToken()); String resetPasswordUrl = urlService.generateUrl(FoUrls.RESET_PASSWORD, requestData, urlParams); model.put("activeChangePasswordUrl", urlService.buildAbsoluteUrl(requestData, resetPasswordUrl)); String canceResetPasswordUrl = urlService.generateUrl(FoUrls.CANCEL_RESET_PASSWORD, requestData, urlParams); model.put("cancelChangePasswordUrl", urlService.buildAbsoluteUrl(requestData, canceResetPasswordUrl)); String fromAddress = handleFromAddress(customerForgottenPasswordEmailBean.getFromAddress(), contextNameValue); String fromName = handleFromName(customerForgottenPasswordEmailBean.getFromName(), locale); String toEmail = customer.getEmail(); MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData, Email.EMAIl_TYPE_FORGOTTEN_PASSWORD, model); mimeMessagePreparator.setTo(toEmail); mimeMessagePreparator.setFrom(fromAddress); mimeMessagePreparator.setFromName(fromName); mimeMessagePreparator.setReplyTo(fromAddress); Object[] parameters = { customer.getLastname(), customer.getFirstname() }; mimeMessagePreparator.setSubject( coreMessageSource.getMessage("email.forgotten_password.email_subject", parameters, locale)); mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(), velocityPath + "forgotten-password-html-content.vm", model)); mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString( getVelocityEngine(), velocityPath + "forgotten-password-text-content.vm", model)); email = new Email(); email.setType(Email.EMAIl_TYPE_FORGOTTEN_PASSWORD); email.setStatus(Email.EMAIl_STATUS_PENDING); saveOrUpdateEmail(email, mimeMessagePreparator); } catch (MailException e) { logger.error("Error, can't save the message :", e); throw e; } catch (VelocityException e) { logger.error("Error, can't build the message :", e); throw e; } catch (IOException e) { logger.error("Error, can't serializable the message :", e); throw e; } return email; }
From source file:fr.hoteia.qalingo.core.service.impl.EmailServiceImpl.java
/** * @see fr.hoteia.qalingo.core.service.EmailService#buildAndSaveNewOrderConfirmationMail(Localization localization, Customer customer, String velocityPath, OrderConfirmationEmailBean orderConfirmationEmailBean) *///from w ww . j av a2 s.co m public void buildAndSaveNewOrderConfirmationMail(final RequestData requestData, final Customer customer, final String velocityPath, final OrderConfirmationEmailBean orderConfirmationEmailBean) throws Exception { try { final Localization localization = requestData.getLocalization(); final Locale locale = localization.getLocale(); // SANITY CHECK checkEmailAddresses(orderConfirmationEmailBean); Map<String, Object> model = new HashMap<String, Object>(); DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, locale); java.sql.Timestamp currentDate = new java.sql.Timestamp((new java.util.Date()).getTime()); model.put("currentDate", dateFormatter.format(currentDate)); model.put("customer", customer); model.put("orderConfirmationEmailBean", orderConfirmationEmailBean); model.put("wording", coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale)); String fromEmail = orderConfirmationEmailBean.getFromEmail(); MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData, Email.EMAIl_TYPE_ORDER_CONFIRMATION, model); mimeMessagePreparator.setTo(customer.getEmail()); mimeMessagePreparator.setFrom(fromEmail); mimeMessagePreparator.setFromName(coreMessageSource.getMessage("email.common.from_name", locale)); mimeMessagePreparator.setReplyTo(fromEmail); Object[] parameters = { customer.getLastname(), customer.getFirstname() }; mimeMessagePreparator.setSubject( coreMessageSource.getMessage("email.order.confirmation_email_subject", parameters, locale)); mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "order-confirmation-html-content.vm", model)); mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityPath + "order-confirmation-text-content.vm", model)); Email email = new Email(); email.setType(Email.EMAIl_TYPE_ORDER_CONFIRMATION); email.setStatus(Email.EMAIl_STATUS_PENDING); saveOrUpdateEmail(email, mimeMessagePreparator); } catch (MailException e) { LOG.error("Error, can't save the message :", e); throw e; } catch (VelocityException e) { LOG.error("Error, can't build the message :", e); throw e; } catch (IOException e) { LOG.error("Error, can't serializable the message :", e); throw e; } }