/**
  * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4).
  *
  * @param pattern string
  * @param locale Locale
  * @return MessageFormat
  */
 private MessageFormat createMessageFormat(final String pattern, final Locale locale) {
   final MessageFormat result = new MessageFormat(pattern);
   if (locale != null) {
     result.setLocale(locale);
     result.applyPattern(pattern);
   }
   return result;
 }
Ejemplo n.º 2
0
  @Override
  protected String format(Locale locale, String message) {
    MessageFormat formatter = new MessageFormat(message);
    formatter.setLocale(locale);

    Object[] args = new Object[] {identity};

    return formatter.format(args);
  }
Ejemplo n.º 3
0
 /**
  * adds arbitrary number of data items to a log file
  *
  * @param level defines the log that will data
  * @param resourceID is used to load a string from a resource bundle
  * @param obj Array of data items to be logged
  */
 public static void add(int level, String resourceID, Object[] obj) {
   if (logLevel >= level) {
     MessageFormat mf = new MessageFormat(I18N.loadString(resourceID));
     mf.setLocale(I18N.locale);
     for (int i = 0; i < obj.length; i++) {
       obj[i] = obj[i].toString();
     }
     addInfo(mf.format(obj));
   }
 }
Ejemplo n.º 4
0
  /**
   * Get a string from the underlying resource bundle and format it with the given set of arguments.
   *
   * @param key
   * @param args
   */
  public String getString(final String key, final Object... args) {
    String value = getString(key);
    if (value == null) {
      value = key;
    }

    MessageFormat mf = new MessageFormat(value);
    mf.setLocale(locale);
    return mf.format(args, new StringBuffer(), null).toString();
  }
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     method = "applyPattern",
     args = {java.lang.String.class})
 public void test_applyPatternLjava_lang_String_AndroidFailure() {
   MessageFormat format = new MessageFormat("test");
   format.setLocale(Locale.FRENCH); // use French since English has the
   // same LONG and FULL time patterns
   format.applyPattern("{0,time, Full}");
   assertEquals("Wrong full time pattern", "{0,time,full}", format.toPattern());
 }
Ejemplo n.º 6
0
 /**
  * Get the message bundle and get the value according to the key and then format it all of this
  * using the dynamic Locale.
  *
  * @param key the identifying key for the message
  * @param classLoader, the classloader used to look for the basename resource.
  * @param baseName, used to create the underlying resource bundle, see {@link
  *     ResourceBundle#getBundle(String)}
  * @param arguments, used for the formatting the return message using the {@link
  *     java.text.MessageFormat}
  * @return the formatted message, never null
  * @exception MissingResourceException if not message was found with the key.
  */
 protected String getFormattedMessage(
     String key, ClassLoader classLoader, String baseName, Object... arguments)
     throws MissingResourceException {
   Locale locale = getLocale();
   ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, classLoader);
   String bundleValue = bundle.getString(key);
   // format it now
   formatter.setLocale(locale);
   formatter.applyPattern(bundleValue);
   return formatter.format(arguments);
 }
Ejemplo n.º 7
0
 /**
  * ** Gets the Localized value for the specified key. The default String text is return if ** the
  * specified key does not exist ** @param key The LocalStrings key ** @param dft The default
  * String text to return if the LocalStrings key does not exist ** @param args An array of
  * replacement fields ** @return The Localized String text
  */
 public String getString(String key, String dft, Object args[]) {
   String val = this.getString(key, dft);
   if ((args != null) && (args.length > 0) && (val != null)) {
     try {
       MessageFormat mf = new MessageFormat(val);
       mf.setLocale(this.locale);
       StringBuffer sb = mf.format(args, new StringBuffer(), null);
       return I18N.decodeNewLine(sb).toString();
     } catch (Throwable th) {
       Print.logInfo("Exception: " + key + " ==> " + val);
     }
   }
   return I18N.decodeNewLine(val);
 }
Ejemplo n.º 8
0
    private String getFormattedString(String msgtext, Object[] params) {
      String localizedStr = null;

      if (params == null || msgtext == null) {
        return msgtext;
      }
      StringBuffer b = new StringBuffer(100);
      MessageFormat mf = new MessageFormat(msgtext);
      if (locale != null) {
        mf.setLocale(locale);
        b.append(mf.format(params));
        localizedStr = b.toString();
      }
      return localizedStr;
    }
 /** @tests java.text.MessageFormat#setLocale(java.util.Locale) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "setLocale",
     args = {java.util.Locale.class})
 public void test_setLocaleLjava_util_Locale() {
   // Test for method void
   // java.text.MessageFormat.setLocale(java.util.Locale)
   MessageFormat format = new MessageFormat("date {0,date}");
   format.setLocale(Locale.CHINA);
   assertEquals("Wrong locale1", Locale.CHINA, format.getLocale());
   format.applyPattern("{1,date}");
   assertEquals(
       "Wrong locale3",
       DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.CHINA),
       format.getFormats()[0]);
 }
Ejemplo n.º 10
0
  static SQLException createSQLException(
      Locale msgLocale, String messageId, Object[] messageArguments) {
    Locale currentLocale;
    int sqlcode;

    if (msgLocale == null) currentLocale = Locale.getDefault();
    else currentLocale = msgLocale;
    try {
      PropertyResourceBundle messageBundle =
          (PropertyResourceBundle)
              ResourceBundle.getBundle(
                  "SQLMXT2Messages",
                  currentLocale); // R321 changed property file name to
                                  // SQLMXT2Messages_en.properties
      MessageFormat formatter = new MessageFormat("");
      formatter.setLocale(currentLocale);
      formatter.applyPattern(messageBundle.getString(messageId + "_msg"));
      String message = formatter.format(messageArguments);
      String sqlState = messageBundle.getString(messageId + "_sqlstate");
      String sqlcodeStr = messageBundle.getString(messageId + "_sqlcode");
      if (sqlcodeStr != null) {
        try {
          sqlcode = Integer.parseInt(sqlcodeStr);
          sqlcode = -sqlcode;
        } catch (NumberFormatException e1) {
          sqlcode = -1;
        }
      } else sqlcode = -1;
      return new SQLException(message, sqlState, sqlcode);
    } catch (MissingResourceException e) {
      // If the resource bundle is not found, concatenate the messageId and the parameters
      String message;
      int i = 0;

      message = "The message id: " + messageId;
      if (messageArguments != null) {
        message = message.concat(" With parameters: ");
        while (true) {
          message = message.concat(messageArguments[i++].toString());
          if (i >= messageArguments.length) break;
          else message = message.concat(",");
        }
      }
      return new SQLException(message, "HY000", -1);
    }
  }
Ejemplo n.º 11
0
  public JasperPrintLP getReport(String sDrucktype) throws Throwable {

    WochenabschlussReportDto wochenabschlussReportDto = null;
    wochenabschlussReportDto =
        DelegateFactory.getInstance()
            .getZeiterfassungDelegate()
            .printWochenabschluss(
                internalFrameZeiterfassung.getPersonalDto().getIId(), wdfKW.getTimestamp());
    wbuZeitenAbschliessen.setToolTipText("");
    if (wochenabschlussReportDto.isBFehlerVorhanden() == false) {

      java.sql.Timestamp tLetzterAbschluss =
          DelegateFactory.getInstance()
              .getZeiterfassungDelegate()
              .gibtEsBereitseinenZeitabschlussBisZurKW(
                  internalFrameZeiterfassung.getPersonalDto().getIId(), wdfKW.getTimestamp());

      if (tLetzterAbschluss != null) {
        wbuZeitenAbschliessen.setEnabled(false);

        MessageFormat mf =
            new MessageFormat(
                LPMain.getTextRespectUISPr("pers.wochenabschluss.fehler.zeitabschlussvorhanden"));
        mf.setLocale(LPMain.getTheClient().getLocUi());

        Object pattern[] = {
          Helper.formatDatum(tLetzterAbschluss, LPMain.getTheClient().getLocUi())
        };
        String sMsg = mf.format(pattern);

        wbuZeitenAbschliessen.setToolTipText(sMsg);
      } else {
        wbuZeitenAbschliessen.setEnabled(true);
      }

    } else {
      wbuZeitenAbschliessen.setEnabled(false);

      wbuZeitenAbschliessen.setToolTipText(
          LPMain.getTextRespectUISPr("pers.wochenabschluss.fehler.vorhanden"));
    }

    return wochenabschlussReportDto.getJasperPrintLP();
  }
  /**
   * @tests java.text.MessageFormat#getLocale() Test of method java.text.MessageFormat#getLocale().
   */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "getLocale",
      args = {})
  public void test_getLocale() {
    try {
      Locale[] l = {
        Locale.FRANCE,
        Locale.KOREA,
        new Locale(Locale.FRANCE.getCountry(), Locale.FRANCE.getLanguage()),
        new Locale("mk"),
        new Locale("mk", "MK"),
        Locale.US,
        new Locale("#ru", "@31230")
      };

      String pattern = "getLocale test {0,number,#,####}";
      MessageFormat mf;

      for (int i = 0; i < 0; i++) {
        mf = new MessageFormat(pattern, l[i]);
        Locale result = mf.getLocale();
        assertEquals("Returned local: " + result + " instead of " + l[i], l[i], result);
        assertEquals(
            "Returned language: " + result.getLanguage() + " instead of " + l[i].getLanguage(),
            l[i].getLanguage(),
            result.getLanguage());
        assertEquals(
            "Returned country: " + result.getCountry() + " instead of " + l[i].getCountry(),
            l[i].getCountry(),
            result.getCountry());
      }

      mf = new MessageFormat(pattern);
      mf.setLocale(null);
      Locale result = mf.getLocale();
      assertEquals("Returned local: " + result + " instead of null", null, result);
    } catch (Exception e) {
      fail("unexpected exception " + e.toString());
    }
  }
 private MessageFormat getMessageFormat(String pattern) {
   MessageFormat messageFormat = new MessageFormat("");
   messageFormat.setLocale((Locale) locale.getValue());
   messageFormat.applyPattern(pattern);
   return messageFormat;
 }
  /**
   * Parse a string <code>sourceStr</code> against the pattern specified to the MessageFormat
   * constructor.
   *
   * @param sourceStr the string to be parsed.
   * @param pos the current parse position (and eventually the error position).
   * @return the array of parsed objects sorted according to their argument number in the pattern.
   */
  public Object[] parse(String sourceStr, ParsePosition pos) {
    // Check initial text.
    int index = pos.getIndex();
    if (!sourceStr.startsWith(leader, index)) {
      pos.setErrorIndex(index);
      return null;
    }
    index += leader.length();

    Vector results = new Vector(elements.length, 1);
    // Now check each format.
    for (int i = 0; i < elements.length; ++i) {
      Format formatter = null;
      if (elements[i].setFormat != null) formatter = elements[i].setFormat;
      else if (elements[i].format != null) formatter = elements[i].format;

      Object value = null;
      if (formatter instanceof ChoiceFormat) {
        // We must special-case a ChoiceFormat because it might
        // have recursive formatting.
        ChoiceFormat cf = (ChoiceFormat) formatter;
        String[] formats = (String[]) cf.getFormats();
        double[] limits = (double[]) cf.getLimits();
        MessageFormat subfmt = new MessageFormat();
        subfmt.setLocale(locale);
        ParsePosition subpos = new ParsePosition(index);

        int j;
        for (j = 0; value == null && j < limits.length; ++j) {
          subfmt.applyPattern(formats[j]);
          subpos.setIndex(index);
          value = subfmt.parse(sourceStr, subpos);
        }
        if (value != null) {
          index = subpos.getIndex();
          value = new Double(limits[j]);
        }
      } else if (formatter != null) {
        pos.setIndex(index);
        value = formatter.parseObject(sourceStr, pos);
        if (value != null) index = pos.getIndex();
      } else {
        // We have a String format.  This can lose in a number
        // of ways, but we give it a shot.
        int next_index = sourceStr.indexOf(elements[i].trailer, index);
        if (next_index == -1) {
          pos.setErrorIndex(index);
          return null;
        }
        value = sourceStr.substring(index, next_index);
        index = next_index;
      }

      if (value == null || !sourceStr.startsWith(elements[i].trailer, index)) {
        pos.setErrorIndex(index);
        return null;
      }

      if (elements[i].argNumber >= results.size()) results.setSize(elements[i].argNumber + 1);
      results.setElementAt(value, elements[i].argNumber);

      index += elements[i].trailer.length();
    }

    Object[] r = new Object[results.size()];
    results.copyInto(r);
    return r;
  }
  /** @tests java.text.MessageFormat#applyPattern(java.lang.String) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      method = "applyPattern",
      args = {java.lang.String.class})
  public void test_applyPatternLjava_lang_String() {
    // Test for method void
    // java.text.MessageFormat.applyPattern(java.lang.String)
    MessageFormat format = new MessageFormat("test");
    format.applyPattern("xx {0}");
    assertEquals("Invalid number", "xx 46", format.format(new Object[] {new Integer(46)}));
    Date date = new Date();
    String result = format.format(new Object[] {date});
    String expected = "xx " + DateFormat.getInstance().format(date);
    assertTrue("Invalid date:\n" + result + "\n" + expected, result.equals(expected));
    format = new MessageFormat("{0,date}{1,time}{2,number,integer}");
    format.applyPattern("nothing");
    assertEquals("Found formats", "nothing", format.toPattern());

    format.applyPattern("{0}");
    assertNull("Wrong format", format.getFormats()[0]);
    assertEquals("Wrong pattern", "{0}", format.toPattern());

    format.applyPattern("{0, \t\u001ftime }");
    assertTrue("Wrong time format", format.getFormats()[0].equals(DateFormat.getTimeInstance()));
    assertEquals("Wrong time pattern", "{0,time}", format.toPattern());
    format.applyPattern("{0,Time, Short\n}");
    assertTrue(
        "Wrong short time format",
        format.getFormats()[0].equals(DateFormat.getTimeInstance(DateFormat.SHORT)));
    assertEquals("Wrong short time pattern", "{0,time,short}", format.toPattern());
    format.applyPattern("{0,TIME,\nmedium  }");
    assertTrue(
        "Wrong medium time format",
        format.getFormats()[0].equals(DateFormat.getTimeInstance(DateFormat.MEDIUM)));
    assertEquals("Wrong medium time pattern", "{0,time}", format.toPattern());
    format.applyPattern("{0,time,LONG}");
    assertTrue(
        "Wrong long time format",
        format.getFormats()[0].equals(DateFormat.getTimeInstance(DateFormat.LONG)));
    assertEquals("Wrong long time pattern", "{0,time,long}", format.toPattern());
    format.setLocale(Locale.FRENCH); // use French since English has the
    // same LONG and FULL time patterns
    format.applyPattern("{0,time, Full}");
    assertTrue(
        "Wrong full time format",
        format.getFormats()[0].equals(DateFormat.getTimeInstance(DateFormat.FULL, Locale.FRENCH)));
    // Outsourced to _AndroidFailure:
    //
    //        assertEquals("Wrong full time pattern", "{0,time,full}", format
    //                .toPattern());
    format.setLocale(Locale.getDefault());

    format.applyPattern("{0, date}");
    assertTrue("Wrong date format", format.getFormats()[0].equals(DateFormat.getDateInstance()));
    assertEquals("Wrong date pattern", "{0,date}", format.toPattern());
    format.applyPattern("{0, date, short}");
    assertTrue(
        "Wrong short date format",
        format.getFormats()[0].equals(DateFormat.getDateInstance(DateFormat.SHORT)));
    assertEquals("Wrong short date pattern", "{0,date,short}", format.toPattern());
    format.applyPattern("{0, date, medium}");
    assertTrue(
        "Wrong medium date format",
        format.getFormats()[0].equals(DateFormat.getDateInstance(DateFormat.MEDIUM)));
    assertEquals("Wrong medium date pattern", "{0,date}", format.toPattern());
    format.applyPattern("{0, date, long}");
    assertTrue(
        "Wrong long date format",
        format.getFormats()[0].equals(DateFormat.getDateInstance(DateFormat.LONG)));
    assertEquals("Wrong long date pattern", "{0,date,long}", format.toPattern());
    format.applyPattern("{0, date, full}");
    assertTrue(
        "Wrong full date format",
        format.getFormats()[0].equals(DateFormat.getDateInstance(DateFormat.FULL)));
    assertEquals("Wrong full date pattern", "{0,date,full}", format.toPattern());

    format.applyPattern("{0, date, MMM d {hh:mm:ss}}");
    assertEquals(
        "Wrong time/date format",
        " MMM d {hh:mm:ss}",
        ((SimpleDateFormat) (format.getFormats()[0])).toPattern());
    assertEquals("Wrong time/date pattern", "{0,date, MMM d {hh:mm:ss}}", format.toPattern());

    format.applyPattern("{0, number}");
    assertTrue(
        "Wrong number format", format.getFormats()[0].equals(NumberFormat.getNumberInstance()));
    assertEquals("Wrong number pattern", "{0,number}", format.toPattern());
    format.applyPattern("{0, number, currency}");
    assertTrue(
        "Wrong currency number format",
        format.getFormats()[0].equals(NumberFormat.getCurrencyInstance()));
    assertEquals("Wrong currency number pattern", "{0,number,currency}", format.toPattern());
    format.applyPattern("{0, number, percent}");
    assertTrue(
        "Wrong percent number format",
        format.getFormats()[0].equals(NumberFormat.getPercentInstance()));
    assertEquals("Wrong percent number pattern", "{0,number,percent}", format.toPattern());
    format.applyPattern("{0, number, integer}");
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(0);
    nf.setParseIntegerOnly(true);
    assertTrue("Wrong integer number format", format.getFormats()[0].equals(nf));
    assertEquals("Wrong integer number pattern", "{0,number,integer}", format.toPattern());

    format.applyPattern("{0, number, {'#'}##0.0E0}");

    /*
     * TODO validate these assertions String actual =
     * ((DecimalFormat)(format.getFormats()[0])).toPattern();
     * assertEquals("Wrong pattern number format", "' {#}'##0.0E0", actual);
     * assertEquals("Wrong pattern number pattern", "{0,number,'
     * {#}'##0.0E0}", format.toPattern());
     *
     */

    format.applyPattern("{0, choice,0#no|1#one|2#{1,number}}");
    assertEquals(
        "Wrong choice format",
        "0.0#no|1.0#one|2.0#{1,number}",
        ((ChoiceFormat) format.getFormats()[0]).toPattern());
    assertEquals(
        "Wrong choice pattern", "{0,choice,0.0#no|1.0#one|2.0#{1,number}}", format.toPattern());
    assertEquals(
        "Wrong formatted choice",
        "3.6",
        format.format(new Object[] {new Integer(2), new Float(3.6)}));

    try {
      format.applyPattern("WRONG MESSAGE FORMAT {0,number,{}");
      fail("Expected IllegalArgumentException for invalid pattern");
    } catch (IllegalArgumentException e) {
    }

    // Regression for HARMONY-65
    MessageFormat mf = new MessageFormat("{0,number,integer}");
    String badpattern = "{0,number,#";
    try {
      mf.applyPattern(badpattern);
      fail("Assert 0: Failed to detect unmatched brackets.");
    } catch (IllegalArgumentException e) {
      // expected
    }
  }
  private StringBuffer formatInternal(
      Object arguments[],
      StringBuffer appendBuf,
      FieldPosition fp,
      FormatCharacterIterator output_iterator) {
    appendBuf.append(leader);
    if (output_iterator != null) output_iterator.append(leader);

    for (int i = 0; i < elements.length; ++i) {
      Object thisArg = null;
      boolean unavailable = false;
      if (arguments == null || elements[i].argNumber >= arguments.length) unavailable = true;
      else thisArg = arguments[elements[i].argNumber];

      AttributedCharacterIterator iterator = null;

      Format formatter = null;

      if (fp != null && i == fp.getField() && fp.getFieldAttribute() == Field.ARGUMENT)
        fp.setBeginIndex(appendBuf.length());

      if (unavailable) appendBuf.append("{" + elements[i].argNumber + "}");
      else {
        if (elements[i].setFormat != null) formatter = elements[i].setFormat;
        else if (elements[i].format != null) {
          if (elements[i].formatClass != null && !elements[i].formatClass.isInstance(thisArg))
            throw new IllegalArgumentException("Wrong format class");

          formatter = elements[i].format;
        } else if (thisArg instanceof Number) formatter = NumberFormat.getInstance(locale);
        else if (thisArg instanceof Date)
          formatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        else appendBuf.append(thisArg);
      }

      if (fp != null && fp.getField() == i && fp.getFieldAttribute() == Field.ARGUMENT)
        fp.setEndIndex(appendBuf.length());

      if (formatter != null) {
        // Special-case ChoiceFormat.
        if (formatter instanceof ChoiceFormat) {
          StringBuffer buf = new StringBuffer();
          formatter.format(thisArg, buf, fp);
          MessageFormat mf = new MessageFormat();
          mf.setLocale(locale);
          mf.applyPattern(buf.toString());
          mf.format(arguments, appendBuf, fp);
        } else {
          if (output_iterator != null) iterator = formatter.formatToCharacterIterator(thisArg);
          else formatter.format(thisArg, appendBuf, fp);
        }

        elements[i].format = formatter;
      }

      if (output_iterator != null) {
        HashMap hash_argument = new HashMap();
        int position = output_iterator.getEndIndex();

        hash_argument.put(MessageFormat.Field.ARGUMENT, new Integer(elements[i].argNumber));

        if (iterator != null) {
          output_iterator.append(iterator);
          output_iterator.addAttributes(hash_argument, position, output_iterator.getEndIndex());
        } else output_iterator.append(thisArg.toString(), hash_argument);

        output_iterator.append(elements[i].trailer);
      }

      appendBuf.append(elements[i].trailer);
    }

    return appendBuf;
  }
Ejemplo n.º 17
0
 /**
  * Sets the locale to be used when creating or comparing subformats. This affects subsequent calls
  *
  * <ul>
  *   <li>to the {@link #applyPattern applyPattern} and methods if format elements specify a format
  *       type and therefore have the subformats created in the <code>applyPattern</code> method,
  *       as well as
  *   <li>to the <code>format</code> and {@link #formatToCharacterIterator
  *       formatToCharacterIterator} methods if format elements do not specify a format type and
  *       therefore have the subformats created in the formatting methods.
  * </ul>
  *
  * Subformats that have already been created are not affected.
  *
  * @param locale the locale to be used when creating or comparing subformats
  */
 public void setLocale(Locale locale) {
   inner.setLocale(locale);
 }
Ejemplo n.º 18
0
 /**
  * Constructs a MessageFormat for the specified locale and pattern. The constructor first sets the
  * locale, then parses the pattern and creates a list of subformats for the format elements
  * contained in it. Patterns and their interpretation are specified in the <a
  * href="#patterns">class description</a>.
  *
  * @param pattern the pattern for this message format
  * @param locale the locale for this message format
  * @exception IllegalArgumentException if the pattern is invalid
  * @since 1.4
  */
 public BeanMessageFormat(String pattern, Locale locale) {
   this(pattern);
   inner.setLocale(locale);
 }