Example usage for java.text MessageFormat MessageFormat

List of usage examples for java.text MessageFormat MessageFormat

Introduction

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

Prototype

public MessageFormat(String pattern, Locale locale) 

Source Link

Document

Constructs a MessageFormat for the specified locale and pattern.

Usage

From source file:name.gumartinm.weather.information.activity.MainTabsActivity.java

@Override
public void onResume() {
    super.onResume();

    final SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());

    final String APPID = sharedPreferences.getString(this.getString(R.string.weather_preferences_app_id_key),
            "");//from   ww w . j a v a2s. c  om

    final String noticeKeyPreference = this.getString(R.string.api_id_key_notice_preference_key);
    final boolean notice = sharedPreferences.getBoolean(noticeKeyPreference, true);

    if (notice && APPID.isEmpty()) {
        final FragmentManager fm = this.getSupportFragmentManager();
        final Fragment buttonsFragment = fm.findFragmentByTag("noticeDialog");
        if (buttonsFragment == null) {
            final DialogFragment newFragment = APIKeyNoticeDialogFragment
                    .newInstance(R.string.api_id_key_notice_title);
            newFragment.setRetainInstance(true);
            newFragment.setCancelable(false);
            newFragment.show(fm, "noticeDialog");
        }
    }

    final ActionBar actionBar = this.getActionBar();

    // 1. Update title.
    final DatabaseQueries query = new DatabaseQueries(this.getApplicationContext());
    final WeatherLocation weatherLocation = query.queryDataBase();
    if (weatherLocation != null) {
        final String[] array = new String[2];
        array[0] = weatherLocation.getCity();
        array[1] = weatherLocation.getCountry();
        final MessageFormat message = new MessageFormat("{0},{1}", Locale.US);
        final String cityCountry = message.format(array);
        actionBar.setTitle(cityCountry);
    } else {
        actionBar.setTitle(this.getString(R.string.text_field_no_chosen_location));
    }

    // 2. Update forecast tab text.
    final String keyPreference = this.getString(R.string.weather_preferences_day_forecast_key);
    final String value = sharedPreferences.getString(keyPreference, "");
    String humanValue = "";
    if (value.equals(this.getString(R.string.weather_preferences_day_forecast_five_day))) {
        humanValue = this.getString(R.string.text_tab_five_days_forecast);
    } else if (value.equals(this.getString(R.string.weather_preferences_day_forecast_ten_day))) {
        humanValue = this.getString(R.string.text_tab_ten_days_forecast);
    } else if (value.equals(this.getString(R.string.weather_preferences_day_forecast_fourteen_day))) {
        humanValue = this.getString(R.string.text_tab_fourteen_days_forecast);
    }
    actionBar.getTabAt(1).setText(humanValue);
}

From source file:org.apache.myfaces.renderkit.html.ext.HtmlMessageRenderer.java

protected String getDetail(FacesContext facesContext, UIComponent message, FacesMessage facesMessage,
        String msgClientId) {/* w w  w .  j a v a  2 s.co m*/
    String msgDetail = facesMessage.getDetail();
    if (msgDetail == null)
        return null;

    String inputLabel = null;
    if (msgClientId != null)
        inputLabel = findInputLabel(facesContext, msgClientId);
    if (inputLabel == null)
        inputLabel = "";

    if (((message instanceof HtmlMessages && ((HtmlMessages) message).isReplaceIdWithLabel())
            || (message instanceof HtmlMessage && ((HtmlMessage) message).isReplaceIdWithLabel()))
            && inputLabel.length() != 0)
        msgDetail = msgDetail.replaceAll(findInputId(facesContext, msgClientId), inputLabel);

    String detailFormat;
    if (message instanceof HtmlMessage) {
        detailFormat = ((HtmlMessage) message).getDetailFormat();
    } else {
        detailFormat = (String) message.getAttributes().get("detailFormat");
    }

    if (detailFormat == null)
        return msgDetail;

    MessageFormat format = new MessageFormat(detailFormat, facesContext.getViewRoot().getLocale());
    return format.format(new Object[] { msgDetail, inputLabel });
}

From source file:org.sakaiproject.util.ResourceLoader.java

/**
 ** Return formatted message based on locale-specific pattern
 **//  w w w . ja  v  a  2s  .c  o m
 ** @param key maps to locale-specific pattern in properties file
 ** @param args parameters to format and insert according to above pattern
 ** @return  formatted message
 ** 
 ** @author Sugiura, Tatsuki (University of Nagoya)
 ** @author Jean-Francois Leveque (Universite Pierre et Marie Curie - Paris 6)
 **
 **/
public String getFormattedMessage(String key, Object... args) {
    if (getLocale().toString().equals(DEBUG_LOCALE))
        return formatDebugPropertiesString(key);

    String pattern = (String) get(key);
    if (M_log.isDebugEnabled()) {
        M_log.debug("getFormattedMessage(key,args) bundle name=" + this.baseName + ", locale="
                + getLocale().toString() + ", key=" + key + ", pattern=" + pattern);
    }

    return (new MessageFormat(pattern, getLocale())).format(args, new StringBuffer(), null).toString();
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Returns the localized text of a key./*w  w  w .  j  a va  2 s .  c  om*/
 */
public static String getMessage(String key, Object... pars) {
    ResourceBundle res = ResourceBundle.getBundle(UploadServlet.class.getName(),
            getThreadLocalRequest().getLocale());
    return new MessageFormat(res.getString(key), getThreadLocalRequest().getLocale()).format(pars);
}

From source file:com.kenshoo.freemarker.resources.FreeMarkerOnlineExecuteResource.java

private String formatMessage(String key, Object... params) {
    return new MessageFormat(key, Locale.US).format(params);
}

From source file:com.redhat.rhn.common.localization.XmlMessages.java

/**
 * Method to format a string from the resource bundle.  This
 * method allows the user of this class to directly specify the
 * bundle package name to be used.  Allows us to have
 * resource bundles in packages without classes.  Eliminates
 * the need for "Dummy" classes./*from   ww  w.j a v  a2 s  .co m*/
 *
 * @param clazz the class to which the string belongs
 * @param locale the locale used to find the resource bundle
 * @param key the key for the string to be obtained from the resource bundle
 * @param args the arguments that should be applied to the string obtained
 * from the resource bundle. Can be null, to represent no arguments
 * @return the formatted message for the given key and arguments
 */
public String format(final Class clazz, final Locale locale, final String key, final Object... args) {

    // Fetch the bundle
    ResourceBundle bundle = getBundle(getBundleName(clazz), locale);
    String pattern = StringEscapeUtils.unescapeHtml(bundle.getString(key));

    pattern = pattern.replaceAll(PRODUCT_NAME_MACRO, Config.get().getString("web.product_name"));

    if (args == null || args.length == 0) {
        return pattern;
    }

    //MessageFormat uses single quotes to escape text. Therefore, we have to
    //escape the single quote so that MessageFormat keeps the single quote and
    //does replace all arguments after it.
    String escapedPattern = pattern.replaceAll("'", "''");
    MessageFormat mf = new MessageFormat(escapedPattern, locale);
    return mf.format(args);
}

From source file:it.govpay.web.utils.Utils.java

public String getMessageFromResourceBundle(String bundleName, String key, Object params[], Locale locale) {

    String text = null;//w  w w. jav  a  2s.  c o m
    try {
        ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale,
                this.getCurrentClassLoader(params));

        text = bundle.getString(key);
    } catch (MissingResourceException e) {
        text = MISSING_RESOURCE_START_PLACEHOLDER + key + MISSING_RESOURCE_END_PLACEHOLDER;
    }
    if (params != null) {
        MessageFormat mf = new MessageFormat(text, locale);
        text = mf.format(params, new StringBuffer(), null).toString();
    }
    return text;
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * Returns the localized text of a key./*from w w  w  . j a  v a2s. c o  m*/
 */
public static String getMessage(String key, Object... pars) {
    Locale loc = getThreadLocalRequest() == null || getThreadLocalRequest().getLocale() == null
            ? new Locale("en")
            : getThreadLocalRequest().getLocale();

    ResourceBundle res = ResourceBundle.getBundle(UploadServlet.class.getName(), loc);

    String msg = res.getString(key);
    return new MessageFormat(msg, loc).format(pars);
}

From source file:de.acosix.alfresco.site.hierarchy.repo.service.SiteHierarchyServiceImpl.java

/**
 *
 * {@inheritDoc}/*  www.j a  v a2  s . co  m*/
 */
@Override
public List<SiteInfo> listTopLevelSites(final boolean respectShowInHierarchyMode) {
    LOGGER.debug("Listing top level sites");

    final SearchParameters sp = new SearchParameters();
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    sp.setQueryConsistency(QueryConsistency.TRANSACTIONAL_IF_POSSIBLE);
    sp.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);

    final MessageFormat queryFormat = new MessageFormat("TYPE:\"{0}\" AND ASPECT:\"{1}\"", Locale.ENGLISH);
    String query = queryFormat.format(new Object[] { SiteModel.TYPE_SITE.toPrefixString(this.namespaceService),
            SiteHierarchyModel.ASPECT_TOP_LEVEL_SITE.toPrefixString(this.namespaceService) });

    if (respectShowInHierarchyMode) {
        // this will cause db-fts not to be used
        final MessageFormat queryFilterFormat = new MessageFormat("={0}:{1} OR (={0}:{2} AND ASPECT:\"{3}\")",
                Locale.ENGLISH);
        final String queryFilter = queryFilterFormat.format(new Object[] {
                SiteHierarchyModel.PROP_SHOW_IN_HIERARCHY_MODE.toPrefixString(this.namespaceService),
                SiteHierarchyModel.CONSTRAINT_SHOW_IN_HIERARCHY_MODES_ALWAYS,
                SiteHierarchyModel.CONSTRAINT_SHOW_IN_HIERARCHY_MODES_IF_PARENT_OR_CHILD,
                SiteHierarchyModel.ASPECT_PARENT_SITE.toPrefixString(this.namespaceService) });
        // if we did not want to support 5.0.d we could use filter query support
        // TODO find a way to dynamically use filter query support WITHOUT reflection
        query = query + " AND (" + queryFilter + ")";
    }

    sp.setQuery(query);

    LOGGER.debug("Using FTS query \"{}\" to list top level sites", query);

    // we use short name sort since that is properly handled in either db-fts or fts
    // and might be specific enough so that in-memory post sort does not have to do that much
    final String shortNameSort = "@" + ContentModel.PROP_NAME.toPrefixString(this.namespaceService);
    sp.addSort(shortNameSort, true);

    List<SiteInfo> sites;
    final ResultSet resultSet = this.searchService.query(sp);
    try {
        sites = new ArrayList<>(resultSet.length());
        resultSet.forEach(resultRow -> {
            final NodeRef nodeRef = resultRow.getNodeRef();
            final SiteInfo site = this.siteService.getSite(nodeRef);
            if (site != null) {
                sites.add(site);
            }
        });
    } finally {
        resultSet.close();
    }

    final Collator collator = Collator.getInstance(I18NUtil.getLocale());
    Collections.sort(sites, (siteA, siteB) -> {
        final int titleCompareResult = collator.compare(siteA.getTitle(), siteB.getTitle());
        return titleCompareResult;
    });

    LOGGER.debug("Listed top level sites {}", sites);

    return sites;
}

From source file:org.vulpe.controller.struts.interceptor.VulpeExceptionMappingInterceptor.java

/**
 *
 * @param pattern// w w w . ja v a2 s.  com
 * @param locale
 * @return
 */
protected MessageFormat buildMessageFormat(final String pattern, final Locale locale) {
    return new MessageFormat(pattern, locale);
}