Example usage for java.text DateFormat getDateInstance

List of usage examples for java.text DateFormat getDateInstance

Introduction

In this page you can find the example usage for java.text DateFormat getDateInstance.

Prototype

public static final DateFormat getDateInstance(int style, Locale aLocale) 

Source Link

Document

Gets the date formatter with the given formatting style for the given locale.

Usage

From source file:org.mifos.accounts.business.AccountBO.java

protected void addcustomFields(final List<CustomFieldDto> customFields) throws InvalidDateException {
    if (customFields != null) {
        for (CustomFieldDto view : customFields) {
            if (CustomFieldType.DATE.getValue().equals(view.getFieldType())
                    && org.apache.commons.lang.StringUtils.isNotBlank(view.getFieldValue())) {
                SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                        getUserContext().getPreferredLocale());
                String userfmt = DateUtils.convertToCurrentDateFormat(format.toPattern());
                this.getAccountCustomFields().add(new AccountCustomFieldEntity(this, view.getFieldId(),
                        DateUtils.convertUserToDbFmt(view.getFieldValue(), userfmt)));
            } else {
                this.getAccountCustomFields()
                        .add(new AccountCustomFieldEntity(this, view.getFieldId(), view.getFieldValue()));
            }//from w w  w . ja  v  a2s  .co m
        }
    }
}

From source file:fr.paris.lutece.plugins.suggest.utils.SuggestUtils.java

/**
 * return a timestamp Object which correspond with the string specified in
 * parameter./*from  w w w .j  ava2 s. c  o  m*/
 * @param strDate the date who must convert
 * @param locale the locale
 * @return a timestamp Object which correspond with the string specified in
 *         parameter.
 */
public static Timestamp getFirstMinute(String strDate, Locale locale) {
    try {
        Date date;
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate.trim());

        Calendar caldate = new GregorianCalendar();
        caldate.setTime(date);
        caldate.set(Calendar.MILLISECOND, 0);
        caldate.set(Calendar.SECOND, 0);
        caldate.set(Calendar.HOUR_OF_DAY, caldate.getActualMinimum(Calendar.HOUR_OF_DAY));
        caldate.set(Calendar.MINUTE, caldate.getActualMinimum(Calendar.MINUTE));

        Timestamp timeStamp = new Timestamp(caldate.getTimeInMillis());

        return timeStamp;
    } catch (ParseException e) {
        return null;
    }
}

From source file:org.opencms.workflow.CmsExtendedWorkflowManager.java

/**
 * Generates the name for a new workflow project based on the user for whom it is created.<p>
 *
 * @param userCms the user's current CMS context
 * @param shortTime if true, the short time format will be used, else the medium time format
 *
 * @return the workflow project name/*w  w w. ja  va2s. c  o m*/
 */
protected String generateProjectName(CmsObject userCms, boolean shortTime) {

    CmsUser user = userCms.getRequestContext().getCurrentUser();
    long time = System.currentTimeMillis();
    Date date = new Date(time);
    OpenCms.getLocaleManager();
    Locale locale = CmsLocaleManager.getDefaultLocale();
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    DateFormat timeFormat = DateFormat.getTimeInstance(shortTime ? DateFormat.SHORT : DateFormat.MEDIUM,
            locale);
    String dateStr = dateFormat.format(date) + " " + timeFormat.format(date);
    String username = user.getName();
    String result = Messages.get().getBundle(locale).key(Messages.GUI_WORKFLOW_PROJECT_NAME_2, username,
            dateStr);
    result = result.replaceAll("/", "|");

    return result;
}

From source file:org.hoteia.qalingo.core.service.EmailService.java

/**
 * @throws Exception //  w  w  w .ja v a2 s  .c  om
 */
public Email buildAndSaveNewsletterUnsubscriptionConfirmationMail(final RequestData requestData,
        final String velocityPath, final NewsletterEmailBean newsletterEmailBean) throws Exception {
    Email email = null;
    try {
        final String contextNameValue = requestData.getContextNameValue();
        final Localization localization = requestData.getMarketAreaLocalization();
        final Locale locale = localization.getLocale();

        // SANITY CHECK
        checkEmailAddresses(newsletterEmailBean);

        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("newsletterEmailBean", newsletterEmailBean);
        model.put(WORDING, coreMessageSource.loadWording(Email.WORDING_SCOPE_EMAIL, locale));

        Map<String, String> urlParams = new HashMap<String, String>();
        urlParams.put(RequestConstants.REQUEST_PARAMETER_NEWSLETTER_EMAIL,
                URLEncoder.encode(newsletterEmailBean.getToEmail(), Constants.ANSI));
        String subscribeUrl = urlService.generateUrl(FoUrls.NEWSLETTER_REGISTER, requestData, urlParams);
        model.put("subscribeUrl", urlService.buildAbsoluteUrl(requestData, subscribeUrl));

        String unsubscribeUrl = urlService.generateUrl(FoUrls.NEWSLETTER_UNREGISTER, requestData, urlParams);
        String fullUnsubscribeUrl = urlService.buildAbsoluteUrl(requestData, unsubscribeUrl);

        model.put("unsubscribeUrlOrEmail", fullUnsubscribeUrl);

        String fromAddress = handleFromAddress(newsletterEmailBean.getFromAddress(), contextNameValue);
        String fromName = handleFromName(newsletterEmailBean.getFromName(), locale);
        String toEmail = newsletterEmailBean.getToEmail();

        MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData,
                Email.EMAIl_TYPE_NEWSLETTER_SUBSCRIPTION, model);
        //           mimeMessagePreparator.setUnsubscribeUrlOrEmail(fullUnsubscribeUrl);
        mimeMessagePreparator.setTo(toEmail);
        mimeMessagePreparator.setFrom(fromAddress);
        mimeMessagePreparator.setFromName(fromName);
        mimeMessagePreparator.setReplyTo(fromAddress);
        Object[] parameters = {};
        mimeMessagePreparator.setSubject(coreMessageSource
                .getMessage("email.newsletter_unsubscription.email_subject", parameters, locale));
        mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                velocityPath + "newsletter-unsubscription-confirmation-html-content.vm", model));
        mimeMessagePreparator
                .setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
                        velocityPath + "newsletter-unsubscription-confirmation-text-content.vm", model));

        email = new Email();
        email.setType(Email.EMAIl_TYPE_NEWSLETTER_SUBSCRIPTION);
        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:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java

/**
 * localize a string value depending on datatype and locale
 *
 * @param owner the BindingElement which is localized
 * @param type  the datatype of the bound Node
 * @param value the string value to convert
 * @return returns a localized representation of the input string
 *///ww w .ja  v a  2s .com
public static String localiseValue(BindingElement owner, Element state, String type, String value)
        throws XFormsException {
    if (value == null || value.equals("")) {
        return value;
    }
    String tmpType = type;
    if (tmpType != null && tmpType.contains(":")) {
        tmpType = tmpType.substring(tmpType.indexOf(":") + 1, tmpType.length());
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N, "true").equals("true")) {

        Locale locale = (Locale) owner.getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        if (tmpType == null) {
            tmpType = owner.getModelItem().getDeclarationView().getDatatype();
        }
        if (tmpType == null) {
            LOGGER.debug(DOMUtil.getCanonicalPath(owner.getInstanceNode()) + " has no type, assuming 'string'");
            return value;
        }
        if (tmpType.equalsIgnoreCase("float") || tmpType.equalsIgnoreCase("decimal")
                || tmpType.equalsIgnoreCase("double")) {
            if (value.equals(""))
                return value;
            if (value.equals("NaN"))
                return value; //do not localize 'NaN' as it returns strange characters
            try {
                NumberFormat formatter = NumberFormat.getNumberInstance(locale);
                if (formatter instanceof DecimalFormat) {
                    //get original number format
                    int separatorPos = value.indexOf(".");
                    if (separatorPos == -1) {
                        formatter.setMaximumFractionDigits(0);
                    } else {
                        int fractionDigitCount = value.length() - separatorPos - 1;
                        formatter.setMinimumFractionDigits(fractionDigitCount);
                    }

                    Double num = Double.parseDouble(value);
                    return formatter.format(num.doubleValue());
                }
            } catch (NumberFormatException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("date")) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date d = sf.parse(value);
                return DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(d);
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("dateTime")) {

            //hackery due to lacking pattern for ISO 8601 Timezone representation in SimpleDateFormat
            String timezone = "";
            String dateTime = null;
            if (value.contains("GMT")) {
                timezone = " GMT" + value.substring(value.lastIndexOf(":") - 3, value.length());
                int devider = value.lastIndexOf(":");
                dateTime = value.substring(0, devider) + value.substring(devider + 1, value.length());
            } else if (value.contains("Z")) {
                timezone = "";
                dateTime = value.substring(0, value.indexOf("Z"));

            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());
                dateTime = value.substring(0, value.indexOf("+"));

            } else {
                dateTime = value;
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

            try {
                Date d = sf.parse(dateTime);
                return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale).format(d)
                        + timezone;
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else {
            //not logging for type 'string'
            if (LOGGER.isTraceEnabled() && !(tmpType.equals("string"))) {
                LOGGER.trace("Type " + tmpType + " cannot be localized");
            }
        }
    }
    return value;
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static Date localeStringToDate(String date) throws ParseException {
    if (StringUtils.trimToEmpty(date).isEmpty()) {
        return null;
    }/*from   w ww  .j a v  a2  s . co  m*/
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, LocaleSelector.instance().getLocale());
    return dateFormat.parse(date);
}

From source file:net.massbank.validator.RecordValidator.java

/**
 * ??//from   ww  w .j  a  v  a  2  s .com
 * 
 * @param db
 *            DB
 * @param op
 *            PrintWriter?
 * @param dataPath
 *            ?
 * @param registPath
 *            
 * @param ver
 *            ?
 * @return ??Map<??, ?>
 * @throws IOException
 *             
 */
private static TreeMap<String, String> validationRecord(DatabaseAccess dbx, PrintStream op, String dataPath,
        String registPath, int ver) throws IOException {

    if (ver == 1) {
        op.println(msgInfo("check record format version is [version 1]."));
    }

    final String[] dataList = (new File(dataPath)).list();
    TreeMap<String, String> validationMap = new TreeMap<String, String>();

    if (dataList.length == 0) {
        op.println(msgWarn("no file for validation."));
        return validationMap;
    }

    // ----------------------------------------------------
    // ???
    // ----------------------------------------------------
    String[] requiredList = new String[] { // Ver.2
            "ACCESSION: ", "RECORD_TITLE: ", "DATE: ", "AUTHORS: ", "LICENSE: ", "CH$NAME: ",
            "CH$COMPOUND_CLASS: ", "CH$FORMULA: ", "CH$EXACT_MASS: ", "CH$SMILES: ", "CH$IUPAC: ",
            "AC$INSTRUMENT: ", "AC$INSTRUMENT_TYPE: ", "AC$MASS_SPECTROMETRY: MS_TYPE ",
            "AC$MASS_SPECTROMETRY: ION_MODE ", "PK$NUM_PEAK: ", "PK$PEAK: " };
    if (ver == 1) { // Ver.1
        requiredList = new String[] { "ACCESSION: ", "RECORD_TITLE: ", "DATE: ", "AUTHORS: ", "COPYRIGHT: ",
                "CH$NAME: ", "CH$COMPOUND_CLASS: ", "CH$FORMULA: ", "CH$EXACT_MASS: ", "CH$SMILES: ",
                "CH$IUPAC: ", "AC$INSTRUMENT: ", "AC$INSTRUMENT_TYPE: ", "AC$ANALYTICAL_CONDITION: MODE ",
                "PK$NUM_PEAK: ", "PK$PEAK: " };
    }
    for (int i = 0; i < dataList.length; i++) {
        String name = dataList[i];
        String status = "";
        StringBuilder detailsErr = new StringBuilder();
        StringBuilder detailsWarn = new StringBuilder();

        // ????
        File file = new File(dataPath + name);
        if (file.isDirectory()) {
            // ??
            status = STATUS_ERR;
            detailsErr.append("[" + name + "] is directory.");
            validationMap.put(name, status + "\t" + detailsErr.toString());
            continue;
        } else if (file.isHidden()) {
            // ???
            status = STATUS_ERR;
            detailsErr.append("[" + name + "] is hidden.");
            validationMap.put(name, status + "\t" + detailsErr.toString());
            continue;
        } else if (name.lastIndexOf(REC_EXTENSION) == -1) {
            // ????
            status = STATUS_ERR;
            detailsErr.append("file extension of [" + name + "] is not [" + REC_EXTENSION + "].");
            validationMap.put(name, status + "\t" + detailsErr.toString());
            continue;
        }

        // ??
        boolean isEndTagRead = false;
        boolean isInvalidInfo = false;
        boolean isDoubleByte = false;
        ArrayList<String> fileContents = new ArrayList<String>();
        boolean existLicense = false; // LICENSE?Ver.1
        ArrayList<String> workChName = new ArrayList<String>(); // RECORD_TITLE??CH$NAME??Ver.1?
        String workAcInstrumentType = ""; // RECORD_TITLE??AC$INSTRUMENT_TYPE??Ver.1?
        String workAcMsType = ""; // RECORD_TITLE??AC$MASS_SPECTROMETRY:
        // MS_TYPE??Ver.2
        String line = "";
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                if (isEndTagRead) {
                    if (!line.equals("")) {
                        isInvalidInfo = true;
                    }
                }

                // 
                if (line.startsWith("//")) {
                    isEndTagRead = true;
                }
                fileContents.add(line);

                // LICENSE?Ver.1
                if (line.startsWith("LICENSE: ")) {
                    existLicense = true;
                }
                // CH$NAME?Ver.1?
                else if (line.startsWith("CH$NAME: ")) {
                    workChName.add(line.trim().replaceAll("CH\\$NAME: ", ""));
                }
                // AC$INSTRUMENT_TYPE?Ver.1?
                else if (line.startsWith("AC$INSTRUMENT_TYPE: ")) {
                    workAcInstrumentType = line.trim().replaceAll("AC\\$INSTRUMENT_TYPE: ", "");
                }
                // AC$MASS_SPECTROMETRY: MS_TYPE?Ver.2
                else if (ver != 1 && line.startsWith("AC$MASS_SPECTROMETRY: MS_TYPE ")) {
                    workAcMsType = line.trim().replaceAll("AC\\$MASS_SPECTROMETRY: MS_TYPE ", "");
                }

                // ?
                if (!isDoubleByte) {
                    byte[] bytes = line.getBytes("MS932");
                    if (bytes.length != line.length()) {
                        isDoubleByte = true;
                    }
                }
            }
        } catch (IOException e) {
            Logger.getLogger("global").severe("file read failed." + NEW_LINE + "    " + file.getPath());
            e.printStackTrace();
            op.println(msgErr("server error."));
            validationMap.clear();
            return validationMap;
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
            }
        }
        if (isInvalidInfo) {
            // ?????
            if (status.equals(""))
                status = STATUS_WARN;
            detailsWarn.append("invalid after the end tag [//].");
        }
        if (isDoubleByte) {
            // ?????
            if (status.equals(""))
                status = STATUS_ERR;
            detailsErr.append("double-byte character included.");
        }
        if (ver == 1 && existLicense) {
            // LICENSE???Ver.1
            if (status.equals(""))
                status = STATUS_ERR;
            detailsErr.append("[LICENSE: ] tag can not be used in record format  [version 1].");
        }

        // ----------------------------------------------------
        // ????
        // ----------------------------------------------------
        boolean isNameCheck = false;
        int peakNum = -1;
        for (int j = 0; j < requiredList.length; j++) {
            String requiredStr = requiredList[j];
            ArrayList<String> valStrs = new ArrayList<String>(); // 
            boolean findRequired = false; // 
            boolean findValue = false; // 
            boolean isPeakMode = false; // 
            for (int k = 0; k < fileContents.size(); k++) {
                String lineStr = fileContents.get(k);

                // ????RELATED_RECORD??????
                if (lineStr.startsWith("//")) { // Ver.1?
                    break;
                } else if (ver == 1 && lineStr.startsWith("RELATED_RECORD:")) { // Ver.1
                    break;
                }
                // ?????
                else if (isPeakMode) {
                    findRequired = true;
                    if (!lineStr.trim().equals("")) {
                        valStrs.add(lineStr);
                    }
                }
                // ??????
                else if (lineStr.indexOf(requiredStr) != -1) {
                    // 
                    findRequired = true;
                    if (requiredStr.equals("PK$PEAK: ")) {
                        isPeakMode = true;
                        findValue = true;
                        valStrs.add(lineStr.replace(requiredStr, ""));
                    } else {
                        // 
                        String tmpVal = lineStr.replace(requiredStr, "");
                        if (!tmpVal.trim().equals("")) {
                            findValue = true;
                            valStrs.add(tmpVal);
                        }
                        break;
                    }
                }
            }
            if (!findRequired) {
                // ??????
                status = STATUS_ERR;
                detailsErr.append("no required item [" + requiredStr + "].");
            } else {
                if (!findValue) {
                    // ?????
                    status = STATUS_ERR;
                    detailsErr.append("no value of required item [" + requiredStr + "].");
                } else {
                    // ???

                    // ----------------------------------------------------
                    // ??
                    // ----------------------------------------------------
                    String val = (valStrs.size() > 0) ? valStrs.get(0) : "";
                    // ACESSIONVer.1?
                    if (requiredStr.equals("ACCESSION: ")) {
                        if (!val.equals(name.replace(REC_EXTENSION, ""))) {
                            status = STATUS_ERR;
                            detailsErr.append("value of required item [" + requiredStr
                                    + "] not correspond to file name.");
                        }
                        if (val.length() != 8) {
                            status = STATUS_ERR;
                            detailsErr.append(
                                    "value of required item [" + requiredStr + "] is 8 digits necessary.");
                        }
                    }
                    // RECORD_TITLEVer.1?
                    else if (requiredStr.equals("RECORD_TITLE: ")) {
                        if (!val.equals(DEFAULT_VALUE)) {
                            if (val.indexOf(";") != -1) {
                                String[] recTitle = val.split(";");
                                if (!workChName.contains(recTitle[0].trim())) {
                                    if (status.equals(""))
                                        status = STATUS_WARN;
                                    detailsWarn.append("value of required item [" + requiredStr
                                            + "], compound name is not included in the [CH$NAME].");
                                }
                                if (!workAcInstrumentType.equals(recTitle[1].trim())) {
                                    if (status.equals(""))
                                        status = STATUS_WARN;
                                    detailsWarn.append("value of required item [" + requiredStr
                                            + "], instrument type is different from [AC$INSTRUMENT_TYPE].");
                                }
                                if (ver != 1 && !workAcMsType.equals(recTitle[2].trim())) { // Ver.2
                                    if (status.equals(""))
                                        status = STATUS_WARN;
                                    detailsWarn.append("value of required item [" + requiredStr
                                            + "], ms type is different from [AC$MASS_SPECTROMETRY: MS_TYPE].");
                                }
                            } else {
                                if (status.equals(""))
                                    status = STATUS_WARN;
                                detailsWarn.append("value of required item [" + requiredStr
                                        + "] is not record title format.");

                                if (!workChName.contains(val)) {
                                    detailsWarn.append("value of required item [" + requiredStr
                                            + "], compound name is not included in the [CH$NAME].");
                                }
                                if (!workAcInstrumentType.equals(DEFAULT_VALUE)) {
                                    detailsWarn.append("value of required item [" + requiredStr
                                            + "], instrument type is different from [AC$INSTRUMENT_TYPE].");
                                }
                                if (ver != 1 && !workAcMsType.equals(DEFAULT_VALUE)) { // Ver.2
                                    detailsWarn.append("value of required item [" + requiredStr
                                            + "], ms type is different from [AC$MASS_SPECTROMETRY: MS_TYPE].");
                                }
                            }
                        } else {
                            if (!workAcInstrumentType.equals(DEFAULT_VALUE)) {
                                if (status.equals(""))
                                    status = STATUS_WARN;
                                detailsWarn.append("value of required item [" + requiredStr
                                        + "], instrument type is different from [AC$INSTRUMENT_TYPE].");
                            }
                            if (ver != 1 && !workAcMsType.equals(DEFAULT_VALUE)) { // Ver.2
                                if (status.equals(""))
                                    status = STATUS_WARN;
                                detailsWarn.append("value of required item [" + requiredStr
                                        + "], ms type is different from [AC$MASS_SPECTROMETRY: MS_TYPE].");
                            }
                        }
                    }
                    // DATEVer.1?
                    else if (requiredStr.equals("DATE: ") && !val.equals(DEFAULT_VALUE)) {
                        val = val.replace(".", "/");
                        val = val.replace("-", "/");
                        try {
                            DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN).parse(val);
                        } catch (ParseException e) {
                            if (status.equals(""))
                                status = STATUS_WARN;
                            detailsWarn
                                    .append("value of required item [" + requiredStr + "] is not date format.");
                        }
                    }
                    // CH$COMPOUND_CLASSVer.1?
                    else if (requiredStr.equals("CH$COMPOUND_CLASS: ") && !val.equals(DEFAULT_VALUE)) {
                        if (!val.startsWith("Natural Product") && !val.startsWith("Non-Natural Product")) {

                            if (status.equals(""))
                                status = STATUS_WARN;
                            detailsWarn.append("value of required item [" + requiredStr
                                    + "] is not compound class format.");
                        }
                    }
                    // CH$EXACT_MASSVer.1?
                    else if (requiredStr.equals("CH$EXACT_MASS: ") && !val.equals(DEFAULT_VALUE)) {
                        try {
                            Double.parseDouble(val);
                        } catch (NumberFormatException e) {
                            if (status.equals(""))
                                status = STATUS_WARN;
                            detailsWarn.append("value of required item [" + requiredStr + "] is not numeric.");
                        }
                    }
                    // AC$INSTRUMENT_TYPEVer.1?
                    else if (requiredStr.equals("AC$INSTRUMENT_TYPE: ") && !val.equals(DEFAULT_VALUE)) {
                        if (val.trim().indexOf(" ") != -1) {
                            if (status.equals(""))
                                status = STATUS_WARN;
                            detailsWarn
                                    .append("value of required item [" + requiredStr + "] is space included.");
                        }
                        if (val.trim().indexOf(" ") != -1) {
                            if (status.equals(""))
                                status = STATUS_WARN;
                            detailsWarn
                                    .append("value of required item [" + requiredStr + "] is space included.");
                        }
                    }
                    // AC$MASS_SPECTROMETRY: MS_TYPEVer.2
                    else if (ver != 1 && requiredStr.equals("AC$MASS_SPECTROMETRY: MS_TYPE ")
                            && !val.equals(DEFAULT_VALUE)) {
                        boolean isMsType = true;
                        if (val.startsWith("MS")) {
                            val = val.replace("MS", "");
                            if (!val.equals("")) {
                                try {
                                    Integer.parseInt(val);
                                } catch (NumberFormatException e) {
                                    isMsType = false;
                                }
                            }
                        } else {
                            isMsType = false;
                        }
                        if (!isMsType) {
                            if (status.equals(""))
                                status = STATUS_WARN;
                            detailsWarn.append("value of required item [" + requiredStr + "] is not \"MSn\".");
                        }
                    }
                    // AC$MASS_SPECTROMETRY:
                    // ION_MODEVer.2?AC$ANALYTICAL_CONDITION: MODEVer.1
                    else if ((ver != 1 && requiredStr.equals("AC$MASS_SPECTROMETRY: ION_MODE ")
                            && !val.equals(DEFAULT_VALUE))
                            || (ver == 1 && requiredStr.equals("AC$ANALYTICAL_CONDITION: MODE ")
                                    && !val.equals(DEFAULT_VALUE))) {
                        if (!val.equals("POSITIVE") && !val.equals("NEGATIVE")) {
                            if (status.equals(""))
                                status = STATUS_WARN;
                            detailsWarn.append("value of required item [" + requiredStr
                                    + "] is not \"POSITIVE\" or \"NEGATIVE\".");
                        }
                    }
                    // PK$NUM_PEAKVer.1?
                    else if (requiredStr.equals("PK$NUM_PEAK: ") && !val.equals(DEFAULT_VALUE)) {
                        try {
                            peakNum = Integer.parseInt(val);
                        } catch (NumberFormatException e) {
                            status = STATUS_ERR;
                            detailsErr.append("value of required item [" + requiredStr + "] is not numeric.");
                        }
                    }
                    // PK$PEAK:Ver.1?
                    else if (requiredStr.equals("PK$PEAK: ")) {
                        if (valStrs.size() == 0 || !valStrs.get(0).startsWith("m/z int. rel.int.")) {
                            status = STATUS_ERR;
                            detailsErr.append(
                                    "value of required item [PK$PEAK: ] , the first line is not \"PK$PEAK: m/z int. rel.int.\".");
                        } else {
                            boolean isNa = false;
                            String peak = "";
                            String mz = "";
                            String intensity = "";
                            boolean mzDuplication = false;
                            boolean mzNotNumeric = false;
                            boolean intensityNotNumeric = false;
                            boolean invalidFormat = false;
                            HashSet<String> mzSet = new HashSet<String>();
                            for (int l = 0; l < valStrs.size(); l++) {
                                peak = valStrs.get(l).trim();
                                // N/A
                                if (peak.indexOf(DEFAULT_VALUE) != -1) {
                                    isNa = true;
                                    break;
                                }
                                if (l == 0) {
                                    continue;
                                } // m/z int. rel.int.??????????

                                if (peak.indexOf(" ") != -1) {
                                    mz = peak.split(" ")[0];
                                    if (!mzSet.add(mz)) {
                                        mzDuplication = true;
                                    }
                                    try {
                                        Double.parseDouble(mz);
                                    } catch (NumberFormatException e) {
                                        mzNotNumeric = true;
                                    }
                                    intensity = peak.split(" ")[1];
                                    try {
                                        Double.parseDouble(intensity);
                                    } catch (NumberFormatException e) {
                                        intensityNotNumeric = true;
                                    }
                                } else {
                                    invalidFormat = true;
                                }
                                if (mzDuplication && mzNotNumeric && intensityNotNumeric && invalidFormat) {
                                    break;
                                }
                            }
                            if (isNa) {// PK$PEAK:?N/A??
                                if (peakNum != -1) { // PK$NUM_PEAK:N/A??
                                    if (status.equals(""))
                                        status = STATUS_WARN;
                                    detailsWarn
                                            .append("value of required item [PK$NUM_PEAK: ] is mismatch or \""
                                                    + DEFAULT_VALUE + "\".");
                                }
                                if (valStrs.size() - 1 > 0) { // PK$PEAK:????????
                                    if (status.equals(""))
                                        status = STATUS_WARN;
                                    detailsWarn.append(
                                            "value of required item [PK$NUM_PEAK: ] is invalid peak information exists.");
                                }
                            } else {
                                if (mzDuplication) {
                                    status = STATUS_ERR;
                                    detailsErr.append(
                                            "mz value of required item [" + requiredStr + "] is duplication.");
                                }
                                if (mzNotNumeric) {
                                    status = STATUS_ERR;
                                    detailsErr.append(
                                            "mz value of required item [" + requiredStr + "] is not numeric.");
                                }
                                if (intensityNotNumeric) {
                                    status = STATUS_ERR;
                                    detailsErr.append("intensity value of required item [" + requiredStr
                                            + "] is not numeric.");
                                }
                                if (invalidFormat) {
                                    status = STATUS_ERR;
                                    detailsErr.append(
                                            "value of required item [" + requiredStr + "] is not peak format.");
                                }
                                if (peakNum != 0 && valStrs.size() - 1 == 0) { // ?????N/A????PK$NUM_PEAK:?0???????
                                    if (status.equals(""))
                                        status = STATUS_WARN;
                                    detailsWarn.append(
                                            "value of required item [PK$PEAK: ] is no value.  at that time, please add \""
                                                    + DEFAULT_VALUE + "\". ");
                                }
                                if (peakNum != valStrs.size() - 1) {
                                    if (status.equals(""))
                                        status = STATUS_WARN;
                                    detailsWarn
                                            .append("value of required item [PK$NUM_PEAK: ] is mismatch or \""
                                                    + DEFAULT_VALUE + "\".");
                                }
                            }
                        }
                    }
                }
            }
        }
        String details = detailsErr.toString() + detailsWarn.toString();
        if (status.equals("")) {
            status = STATUS_OK;
            details = " ";
        }
        validationMap.put(name, status + "\t" + details);
    }

    //      // ----------------------------------------------------
    //      // ????
    //      // ----------------------------------------------------
    //      // ?ID?DB
    //      HashSet<String> regIdList = new HashSet<String>();
    //      String[] sqls = { "SELECT ID FROM SPECTRUM ORDER BY ID",
    //            "SELECT ID FROM RECORD ORDER BY ID",
    //            "SELECT ID FROM PEAK GROUP BY ID ORDER BY ID",
    //            "SELECT ID FROM CH_NAME ID ORDER BY ID",
    //            "SELECT ID FROM CH_LINK ID ORDER BY ID",
    //            "SELECT ID FROM TREE WHERE ID IS NOT NULL AND ID<>'' ORDER BY ID" };
    //      for (int i = 0; i < sqls.length; i++) {
    //         String execSql = sqls[i];
    //         ResultSet rs = null;
    //         try {
    //            rs = db.executeQuery(execSql);
    //            while (rs.next()) {
    //               String idStr = rs.getString("ID");
    //               regIdList.add(idStr);
    //            }
    //         } catch (SQLException e) {
    //            Logger.getLogger("global").severe("    sql : " + execSql);
    //            e.printStackTrace();
    //            op.println(msgErr("database access error."));
    //            return new TreeMap<String, String>();
    //         } finally {
    //            try {
    //               if (rs != null) {
    //                  rs.close();
    //               }
    //            } catch (SQLException e) {
    //            }
    //         }
    //      }
    //      // ?ID?
    //      final String[] recFileList = (new File(registPath)).list();
    //      for (int i = 0; i < recFileList.length; i++) {
    //         String name = recFileList[i];
    //         File file = new File(registPath + File.separator + name);
    //         if (!file.isFile() || file.isHidden()
    //               || name.lastIndexOf(REC_EXTENSION) == -1) {
    //            continue;
    //         }
    //         String idStr = name.replace(REC_EXTENSION, "");
    //         regIdList.add(idStr);
    //      }

    //      // ??
    //      for (Map.Entry<String, String> e : validationMap.entrySet()) {
    //         String statusStr = e.getValue().split("\t")[0];
    //         if (statusStr.equals(STATUS_ERR)) {
    //            continue;
    //         }
    //         String nameStr = e.getKey();
    //         String idStr = e.getKey().replace(REC_EXTENSION, "");
    //         String detailsStr = e.getValue().split("\t")[1];
    //         if (regIdList.contains(idStr)) {
    //            statusStr = STATUS_WARN;
    //            detailsStr += "id ["
    //                  + idStr + "] of file name ["
    //                  + nameStr
    //                  + "] already registered.";
    //            validationMap.put(nameStr, statusStr + "\t" + detailsStr);
    //         }
    //      }

    return validationMap;
}

From source file:com.idega.block.cal.renderer.ScheduleDetailedDayRenderer.java

protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer,
        int index) throws IOException {
    //final String clientId = schedule.getClientId(context);
    //FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context);
    //String formId = parentFormInfo == null ? null : parentFormInfo.getFormName();

    TreeSet entrySet = new TreeSet();

    for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) {
        entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day));
    }/*from w  ww.ja va2 s  .  co  m*/

    EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]);

    //determine overlaps
    scanEntries(entries, 0);

    //determine the number of columns within this day
    int maxColumn = 0;

    for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) {
        EntryWrapper wrapper = (EntryWrapper) entryIterator.next();
        maxColumn = Math.max(wrapper.column, maxColumn);
    }

    int numberOfColumns = maxColumn + 1;

    //make sure the entries take up all available space horizontally
    maximizeEntries(entries, numberOfColumns);

    //now determine the width in percent of 1 column
    float columnWidth = 100 / numberOfColumns;

    //and now draw the entries in the columns
    for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) {
        EntryWrapper wrapper = (EntryWrapper) entryIterator.next();
        boolean selected = isSelected(schedule, wrapper);
        //compose the CSS style for the entry box
        StringBuffer entryStyle = new StringBuffer();
        entryStyle.append(wrapper.getBounds(schedule, columnWidth, index));

        if (selected) {
            writer.startElement(HTML.DIV_ELEM, schedule);
            writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null);

            //draw the tooltip
            if (showTooltip(schedule)) {
                getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected);
            }

            //draw the content
            getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false,
                    selected);
            writer.endElement(HTML.DIV_ELEM);
        } else {
            //if the schedule is read-only, the entries should not be
            //hyperlinks

            writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule);

            //draw the tooltip
            if (showTooltip(schedule)) {
                getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected);
            }

            if (!schedule.isReadonly()) {

                DateFormat format;
                String pattern = null;

                if ((pattern != null) && (pattern.length() > 0)) {
                    format = new SimpleDateFormat(pattern);
                } else {
                    if (context.getApplication().getDefaultLocale() != null) {
                        format = DateFormat.getDateInstance(DateFormat.MEDIUM,
                                context.getApplication().getDefaultLocale());
                    } else {
                        format = DateFormat.getDateInstance(DateFormat.MEDIUM);
                    }
                }

                String startTime = format.format(wrapper.entry.getStartTime());
                startTime += " ";
                startTime += wrapper.entry.getStartTime().getHours();
                startTime += ":";
                if (wrapper.entry.getStartTime().getMinutes() < 10) {
                    startTime += "0";
                    startTime += wrapper.entry.getStartTime().getMinutes();
                } else {
                    startTime += wrapper.entry.getStartTime().getMinutes();
                }

                String endTime = "";
                endTime += wrapper.entry.getEndTime().getHours();
                endTime += ":";
                if (wrapper.entry.getEndTime().getMinutes() < 10) {
                    endTime += "0";
                    endTime += wrapper.entry.getEndTime().getMinutes();
                } else {
                    endTime += wrapper.entry.getEndTime().getMinutes();
                }

                writer.writeAttribute(HTML.HREF_ATTR, "javascript:void(0)", null);
                writer.writeAttribute("entryid", wrapper.entry.getId(), null);
            }
            if (schedule.getModel().size() == 1) {
                writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry"), null);
            } else {
                writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "workweekEntry"), null);
            }
            writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null);

            //draw the content
            getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false,
                    selected);

            writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : "a");
        }
    }
}

From source file:fr.hoteia.qalingo.core.service.impl.EmailServiceImpl.java

/**
 * @throws Exception /*w  ww .j ava 2 s  . c  o  m*/
 * @see fr.hoteia.qalingo.core.service.EmailService#buildAndSaveCustomerForgottenPasswordMail(Localization localization, Customer customer, String velocityPath, CustomerForgottenPasswordEmailBean customerForgottenPasswordEmailBean)
 */
public void buildAndSaveCustomerForgottenPasswordMail(final RequestData requestData, final Customer customer,
        final String velocityPath, final CustomerForgottenPasswordEmailBean customerForgottenPasswordEmailBean)
        throws Exception {
    try {
        final Localization localization = requestData.getLocalization();
        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("currentDate", dateFormatter.format(currentDate));
        model.put("customer", customer);
        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, customer.getEmail());
        urlParams.put(RequestConstants.REQUEST_PARAMETER_PASSWORD_RESET_TOKEN,
                customerForgottenPasswordEmailBean.getToken());
        String resetPasswordUrl = urlService.generateUrl(FoUrls.RESET_PASSWORD, requestData, urlParams);
        model.put("resetPasswordUrl", resetPasswordUrl);
        model.put("customerForgottenPasswordEmailBean", customerForgottenPasswordEmailBean);

        String fromEmail = customerForgottenPasswordEmailBean.getFromEmail();
        MimeMessagePreparatorImpl mimeMessagePreparator = getMimeMessagePreparator(requestData,
                Email.EMAIl_TYPE_FORGOTTEN_PASSWORD, 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.forgotten_password.email_subject", parameters, locale));
        mimeMessagePreparator.setHtmlContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "forgotten-password-html-content.vm", model));
        mimeMessagePreparator.setPlainTextContent(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                velocityPath + "forgotten-password-text-content.vm", model));

        Email email = new Email();
        email.setType(Email.EMAIl_TYPE_FORGOTTEN_PASSWORD);
        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;
    }
}