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) 

Source Link

Document

Constructs a MessageFormat for the default java.util.Locale.Category#FORMAT FORMAT locale and the specified pattern.

Usage

From source file:io.lavagna.service.Ldap.java

public Pair<Boolean, List<String>> authenticateWithParams(String providerUrl, String ldapManagerDn,
        String ldapManagerPwd, String base, String filter, String username, String password) {
    requireNonNull(username);/* w w w .j a va  2  s  .  c o  m*/
    requireNonNull(password);
    List<String> msgs = new ArrayList<>();

    msgs.add(format("connecting to %s with managerDn %s", providerUrl, ldapManagerDn));
    try (InitialDirContextCloseable dctx = ldapConnection.context(providerUrl, ldapManagerDn, ldapManagerPwd)) {
        msgs.add(format("connected [ok]"));
        msgs.add(format("now searching user \"%s\" with base %s and filter %s", username, base, filter));

        SearchControls sc = new SearchControls();
        sc.setReturningAttributes(null);
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

        List<SearchResult> srs = Ldap.search(dctx, base,
                new MessageFormat(filter).format(new Object[] { Ldap.escapeLDAPSearchFilter(username) }), sc);
        if (srs.size() != 1) {
            String msg = format("error for username \"%s\" we have %d results instead of 1 [error]", username,
                    srs.size());
            msgs.add(msg);
            LOG.info(msg, username, srs.size());
            return Pair.Companion.of(false, msgs);
        }

        msgs.add("user found, now will connect with given password [ok]");

        SearchResult sr = srs.get(0);

        try (InitialDirContextCloseable uctx = ldapConnection.context(providerUrl, sr.getNameInNamespace(),
                password)) {
            msgs.add("user authenticated, everything seems ok [ok]");
            return Pair.Companion.of(true, msgs);
        } catch (NamingException e) {
            String msg = format("error while checking with username \"%s\" with message: %s [error]", username,
                    e.getMessage());
            msgs.add(msg);
            LOG.info(msg, e);
            return Pair.Companion.of(false, msgs);
        }
    } catch (Throwable e) {
        String errMsg = format(
                "error while opening the connection with message: %s [error], check the logs for a more complete trace",
                e.getMessage());
        msgs.add(errMsg);
        msgs.add("Full stacktrace is:");
        msgs.add(ExceptionUtils.getStackTrace(e));
        LOG.error(errMsg, e);
        return Pair.Companion.of(false, msgs);
    }
}

From source file:libepg.epg.section.sectionreconstructor.SectionReconstructor.java

/**
 * @param parcels ????//from  w  w w  . j  a va  2  s  .  c  o m
 * @param pid ?pid
 * @throws IllegalArgumentException ??pid?pid?????????
 */
public SectionReconstructor(List<TsPacketParcel> parcels, int pid) throws IllegalArgumentException {
    this.pid = pid;
    List<TsPacketParcel> tempParcels = new ArrayList<>();
    tempParcels.addAll(parcels);
    for (TsPacketParcel parcel : tempParcels) {
        if (this.pid == parcel.getPacket().getPid()) {
        } else {
            MessageFormat WRONG_PID = new MessageFormat(
                    "??Pid?Pid???????????Pid={0} ={1}");
            Object[] parameters = { Integer.toHexString(this.getPid()), parcel.getPacket().toString() };
            throw new IllegalArgumentException(WRONG_PID.format(parameters));
        }
    }
    this.parcels = Collections.unmodifiableList(tempParcels);
}

From source file:org.eclipse.jubula.tools.i18n.CompSystemI18n.java

/**
 * returns an internationalized string for the given key
 * @param key the key/* w w  w  . j a va 2 s.  c  om*/
 * @param args the arguments needed to generate the string
 * @return the internationalized string
 */
public static String getString(String key, Object[] args) {
    try {
        MessageFormat formatter = new MessageFormat(getStringInternal(key));
        return formatter.format(args);
    } catch (MissingResourceException e) {
        logError(key, e);
        StringBuffer buf = new StringBuffer(key);
        for (int i = 0; i < args.length; i++) {
            if (args[i] != null) {
                buf.append(" "); //$NON-NLS-1$
                buf.append(args[i]);
            }
        }
        return buf.toString();
    }
}

From source file:org.apereo.portal.portlets.dynamicskin.FileSystemDynamicSkinService.java

public void setSkinTemplateIncludeFile(String skinTemplateIncludeFile) {
    this.skinTemplateIncludeFile = new MessageFormat(skinTemplateIncludeFile);
}

From source file:com.ultrapower.eoms.common.plugin.ecside.resource.TableResourceBundle.java

 /**
 * Get the resource property./*ww w.j  av a 2s  . c o  m*/
 */
 public String getMessage(String code, Object[] args) {
   String result = null;
   ResourceBundle customResourceBundle;
   for (int i = 0; i < customResourceBundleList.size(); i++) {
      customResourceBundle = (ResourceBundle) customResourceBundleList
            .get(i);
      result = findResource(customResourceBundle, code);
      if (result != null) {
         break;
      }
   }

   if (result == null) {
      result = findResource(defaultResourceBundle, code);
   }

   if (result != null && args != null) {
      MessageFormat formatter = new MessageFormat("");
      formatter.setLocale(locale);
      formatter.applyPattern(result);
      result = formatter.format(args);
   }

   return result;
}

From source file:libepg.epg.section.Section.java

/**
 * ??????ID????+3?????????????//w w  w. j ava2  s .c o m
 *
 * @param data ?
 * @throws IllegalArgumentException
 * 1:???????ID????3???????<br>
 * 2:?2?0?????<br>
 * 3:???????preferedTableID???????????<br>
 */
public Section(byte[] data) throws IllegalArgumentException {
    byte[] temp = Arrays.copyOf(data, data.length);
    final int id = ByteConverter.byteToInt(temp[0]);
    tableId = TABLE_ID.reverseLookUp(id);

    String hexValue = Hex.encodeHexString(data);

    //ID??ID????????????ID?????????????(?????ID???????????)
    if (tableId == null) {
        MessageFormat msg2 = new MessageFormat(
                "????? ???={0}");
        Object[] parameters2 = { hexValue };
        LOG.trace(msg2.format(parameters2));
        throw new IllegalArgumentException(msg2.format(parameters2));
    }

    byte[] t = new byte[2];
    System.arraycopy(temp, 1, t, 0, t.length);
    int sectionLength = ByteConverter.bytesToInt(t);

    if (LOG.isTraceEnabled()) {
        LOG.trace("b1 = " + Integer.toHexString(sectionLength));
    }

    sectionLength = sectionLength & 0x0FFF;

    if (LOG.isTraceEnabled()) {
        LOG.trace("b2 = " + Integer.toHexString(sectionLength));
    }

    //???????
    if (sectionLength > tableId.getMaxSectionLength().getMaxSectionBodyLength()) {
        MessageFormat msg3 = new MessageFormat(
                "?????????={0} ?={1} ???={2}");
        Object[] parameters3 = { tableId.getMaxSectionLength().getMaxSectionBodyLength(), sectionLength,
                hexValue };
        LOG.trace(msg3.format(parameters3));
        throw new IllegalArgumentException(msg3.format(parameters3));
    }

    //???????????
    int targetLength = sectionLength + 3;
    byte[] sectionByteArray = new byte[targetLength];
    System.arraycopy(temp, 0, sectionByteArray, 0, sectionByteArray.length);

    if (LOG.isTraceEnabled()) {
        MessageFormat msg1 = new MessageFormat("\n??={0}\n?={1}");
        Object[] parameters1 = { Hex.encodeHexString(temp), Hex.encodeHexString(sectionByteArray) };
        LOG.trace(msg1.format(parameters1));
    }

    this.data = new ByteDataBlock(sectionByteArray);
}

From source file:org.jvnet.localizer.Generator.java

protected void generateImpl(String className, Properties props) throws AssertionError {
    try {//  w  ww  .ja  va  2  s .com
        JDefinedClass c = cm._class(className);
        c.annotate(SuppressWarnings.class).paramArray("value").param("").param("PMD").param("all");
        if (accessModifierAnnotations) {
            c.annotate(Restricted.class).param("value", NoExternalUse.class);
        }
        c.javadoc().add("Generated localization support class.");

        // [RESULT]
        // private static final ResourceBundleHolder holder = BundleHolder.get(Messages.class);

        JFieldVar holder = c.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, ResourceBundleHolder.class,
                "holder", cm.ref(ResourceBundleHolder.class).staticInvoke("get").arg(c.dotclass()));
        holder.javadoc().add("The resource bundle reference");

        for (Entry<Object, Object> e : props.entrySet()) {
            String key = e.getKey().toString();
            String value = e.getValue().toString();

            final Format[] formats = new MessageFormat(value).getFormatsByArgumentIndex();
            Map<String, String> params = new HashMap<String, String>();

            // generate the default format method
            List<JVar> args = new ArrayList<JVar>();
            JMethod m = c.method(JMod.PUBLIC | JMod.STATIC, cm.ref(String.class), toJavaIdentifier(key));
            for (int i = 0; i < formats.length; i++) {
                String argName = String.format("arg%d", i);
                args.add(m.param(inferType(formats[i]), argName));
                if (formats[i] instanceof NumberFormat) {
                    params.put(argName, String.format("%s format parameter, {@code {%d}}, a number.",
                            positionalName(i), i));
                } else if (formats[i] instanceof DateFormat) {
                    params.put(argName,
                            String.format("%s format parameter, {@code {%d}}, a {@link java.util.Date}.",
                                    positionalName(i), i));
                } else {
                    params.put(argName,
                            String.format(
                                    "%s format parameter, {@code {%d}}, as {@link String#valueOf(Object)}.",
                                    positionalName(i), i));
                }
            }

            JInvocation inv = holder.invoke("format").arg(key);
            for (JVar arg : args)
                inv.arg(arg);
            m.body()._return(inv);

            m.javadoc().add(WordUtils.wrap(String.format("Key %s: %s.", code(key), code(value)), 70));
            for (Map.Entry<String, String> p : params.entrySet()) {
                m.javadoc().addParam(p.getKey()).add(p.getValue());
            }
            m.javadoc().addReturn().add(WordUtils.wrap(code(value), 70));

            // generate localizable factory
            args.clear();
            params.clear();
            m = c.method(JMod.PUBLIC | JMod.STATIC, cm.ref(Localizable.class), '_' + toJavaIdentifier(key));
            for (int i = 0; i < formats.length; i++) {
                String argName = String.format("arg%d", i);
                args.add(m.param(inferType(formats[i]), argName));
                if (formats[i] instanceof NumberFormat) {
                    params.put(argName, String.format("%s format parameter, {@code {%d}}, a number.",
                            positionalName(i), i));
                } else if (formats[i] instanceof DateFormat) {
                    params.put(argName,
                            String.format("%s format parameter, {@code {%d}}, a {@link java.util.Date}.",
                                    positionalName(i), i));
                } else {
                    params.put(argName,
                            String.format(
                                    "%s format parameter, {@code {%d}}, as {@link String#valueOf(Object)}.",
                                    positionalName(i), i));
                }
            }

            inv = JExpr._new(cm.ref(Localizable.class)).arg(holder).arg(key);
            for (JVar arg : args)
                inv.arg(arg);
            m.body()._return(inv);

            m.javadoc().add(WordUtils.wrap(String.format("Key %s: %s.", code(key), code(value)), 70));
            for (Map.Entry<String, String> p : params.entrySet()) {
                m.javadoc().addParam(p.getKey()).add(p.getValue());
            }
            m.javadoc().addReturn().add(WordUtils.wrap(code(value), 70));
        }

    } catch (JClassAlreadyExistsException e) {
        throw new AssertionError(e);
    }
}

From source file:com.googlecode.jtiger.modules.ecside.resource.TableResourceBundle.java

/**
* Get the resource property.//  w  ww . j  ava  2 s .  c  om
*/
public String getMessage(String code, Object[] args) {
    String result = null;
    ResourceBundle customResourceBundle;
    for (int i = 0; i < customResourceBundleList.size(); i++) {
        customResourceBundle = (ResourceBundle) customResourceBundleList.get(i);
        result = findResource(customResourceBundle, code);
        if (result != null) {
            break;
        }
    }

    if (result == null) {
        result = findResource(defaultResourceBundle, code);
    }

    if (result != null && args != null) {
        MessageFormat formatter = new MessageFormat("");
        formatter.setLocale(locale);
        formatter.applyPattern(result);
        result = formatter.format(args);
    }

    return result;
}

From source file:com.taobao.tddl.common.ConfigServerHelper.java

/**
 * /*from   w  w w. j a v a 2  s.  c o m*/
 */
public static Object subscribeReplicationConfig(String appName, DataListener listener) {
    if (appName == null || appName.length() == 0) {
        throw new IllegalStateException("appName");
    }
    String dataId = new MessageFormat(DATA_ID_REPLICATION).format(new Object[] { appName });
    return ConfigServerHelper.subscribePersistentData(getCallerClassName(), dataId, listener);
}