Java Code Examples for java.text.ChoiceFormat

The following examples show how to use java.text.ChoiceFormat. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Create a data file for this test.  The data file must be corrupted by hand.
 */
private static void prepTest() {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("Bug4185732.ser"));
        final double[] limits = {1,2,3,4,5,6,7};
        final String[] formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
        final ChoiceFormat fmt = new ChoiceFormat(limits, formats);
        out.writeObject(fmt);
        out.close();
        System.out.println("You must invalidate the output file before running the test");
        System.out.println("by modifying the length of one of the array");
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 2
Source Project: dragonwell8_jdk   Source File: Bug4387255.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ChoiceFormat choiceFormat1 = new ChoiceFormat(doubles, strings);
    ChoiceFormat choiceFormat2 = new ChoiceFormat(pattern);
    if (!choiceFormat1.equals(choiceFormat2)) {
        System.out.println("choiceFormat1: " + choiceFormat1.toPattern());
        System.out.println("choiceFormat2: " + choiceFormat2.toPattern());
        throw new RuntimeException();
    }

    for (int i = 0; i < doubles.length; i++) {
        String result = choiceFormat2.format(doubles[i]);
        if (!result.equals(strings[i])) {
            throw new RuntimeException("Wrong format result - expected " +
                    strings[i] + ", got " + result);
        }
    }
}
 
Example 3
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 4
Source Project: TencentKona-8   Source File: Bug4185732Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a data file for this test.  The data file must be corrupted by hand.
 */
private static void prepTest() {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("Bug4185732.ser"));
        final double[] limits = {1,2,3,4,5,6,7};
        final String[] formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
        final ChoiceFormat fmt = new ChoiceFormat(limits, formats);
        out.writeObject(fmt);
        out.close();
        System.out.println("You must invalidate the output file before running the test");
        System.out.println("by modifying the length of one of the array");
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 5
Source Project: TencentKona-8   Source File: Bug4387255.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ChoiceFormat choiceFormat1 = new ChoiceFormat(doubles, strings);
    ChoiceFormat choiceFormat2 = new ChoiceFormat(pattern);
    if (!choiceFormat1.equals(choiceFormat2)) {
        System.out.println("choiceFormat1: " + choiceFormat1.toPattern());
        System.out.println("choiceFormat2: " + choiceFormat2.toPattern());
        throw new RuntimeException();
    }

    for (int i = 0; i < doubles.length; i++) {
        String result = choiceFormat2.format(doubles[i]);
        if (!result.equals(strings[i])) {
            throw new RuntimeException("Wrong format result - expected " +
                    strings[i] + ", got " + result);
        }
    }
}
 
Example 6
Source Project: TencentKona-8   Source File: Bug4185816Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 7
Source Project: openjdk-jdk8u   Source File: Bug4185732Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a data file for this test.  The data file must be corrupted by hand.
 */
private static void prepTest() {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("Bug4185732.ser"));
        final double[] limits = {1,2,3,4,5,6,7};
        final String[] formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
        final ChoiceFormat fmt = new ChoiceFormat(limits, formats);
        out.writeObject(fmt);
        out.close();
        System.out.println("You must invalidate the output file before running the test");
        System.out.println("by modifying the length of one of the array");
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 8
Source Project: openjdk-jdk8u   Source File: Bug4387255.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ChoiceFormat choiceFormat1 = new ChoiceFormat(doubles, strings);
    ChoiceFormat choiceFormat2 = new ChoiceFormat(pattern);
    if (!choiceFormat1.equals(choiceFormat2)) {
        System.out.println("choiceFormat1: " + choiceFormat1.toPattern());
        System.out.println("choiceFormat2: " + choiceFormat2.toPattern());
        throw new RuntimeException();
    }

    for (int i = 0; i < doubles.length; i++) {
        String result = choiceFormat2.format(doubles[i]);
        if (!result.equals(strings[i])) {
            throw new RuntimeException("Wrong format result - expected " +
                    strings[i] + ", got " + result);
        }
    }
}
 
Example 9
Source Project: openjdk-jdk8u   Source File: Bug4185816Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 10
Source Project: netbeans   Source File: DiffSidebar.java    License: Apache License 2.0 6 votes vote down vote up
static String getShortDescription(Difference diff) {
    if (diff == null) {
        return null;
    }
    int n;
    switch (diff.getType()) {
        case Difference.ADD:
            n = diff.getSecondEnd() - diff.getSecondStart() + 1;
            return MessageFormat.format(new ChoiceFormat(NbBundle.getMessage(DiffSidebar.class, "TT_LinesAdded")).format(n), n); // NOI18N      
        case Difference.CHANGE:
            n = diff.getFirstEnd() - diff.getFirstStart() + 1;
            return MessageFormat.format(new ChoiceFormat(NbBundle.getMessage(DiffSidebar.class, "TT_LinesChanged")).format(n), n); // NOI18N      
        case Difference.DELETE:
            n = diff.getFirstEnd() - diff.getFirstStart() + 1;
            return MessageFormat.format(new ChoiceFormat(NbBundle.getMessage(DiffSidebar.class, "TT_LinesDeleted")).format(n), n); // NOI18N      
        default:
            throw new IllegalStateException("Unknown difference type: " + diff.getType()); // NOI18N
    }
}
 
Example 11
Source Project: openjdk-jdk9   Source File: Bug4185732Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a data file for this test.  The data file must be corrupted by hand.
 */
private static void prepTest() {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("Bug4185732.ser"));
        final double[] limits = {1,2,3,4,5,6,7};
        final String[] formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
        final ChoiceFormat fmt = new ChoiceFormat(limits, formats);
        out.writeObject(fmt);
        out.close();
        System.out.println("You must invalidate the output file before running the test");
        System.out.println("by modifying the length of one of the array");
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 12
Source Project: openjdk-jdk9   Source File: Bug4387255.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ChoiceFormat choiceFormat1 = new ChoiceFormat(doubles, strings);
    ChoiceFormat choiceFormat2 = new ChoiceFormat(pattern);
    if (!choiceFormat1.equals(choiceFormat2)) {
        System.out.println("choiceFormat1: " + choiceFormat1.toPattern());
        System.out.println("choiceFormat2: " + choiceFormat2.toPattern());
        throw new RuntimeException();
    }

    for (int i = 0; i < doubles.length; i++) {
        String result = choiceFormat2.format(doubles[i]);
        if (!result.equals(strings[i])) {
            throw new RuntimeException("Wrong format result - expected " +
                    strings[i] + ", got " + result);
        }
    }
}
 
Example 13
Source Project: openjdk-jdk9   Source File: Bug4185816Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 14
Source Project: jdk8u_jdk   Source File: Bug4185732Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a data file for this test.  The data file must be corrupted by hand.
 */
private static void prepTest() {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("Bug4185732.ser"));
        final double[] limits = {1,2,3,4,5,6,7};
        final String[] formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
        final ChoiceFormat fmt = new ChoiceFormat(limits, formats);
        out.writeObject(fmt);
        out.close();
        System.out.println("You must invalidate the output file before running the test");
        System.out.println("by modifying the length of one of the array");
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 15
Source Project: jdk8u_jdk   Source File: Bug4387255.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ChoiceFormat choiceFormat1 = new ChoiceFormat(doubles, strings);
    ChoiceFormat choiceFormat2 = new ChoiceFormat(pattern);
    if (!choiceFormat1.equals(choiceFormat2)) {
        System.out.println("choiceFormat1: " + choiceFormat1.toPattern());
        System.out.println("choiceFormat2: " + choiceFormat2.toPattern());
        throw new RuntimeException();
    }

    for (int i = 0; i < doubles.length; i++) {
        String result = choiceFormat2.format(doubles[i]);
        if (!result.equals(strings[i])) {
            throw new RuntimeException("Wrong format result - expected " +
                    strings[i] + ", got " + result);
        }
    }
}
 
Example 16
Source Project: jdk8u_jdk   Source File: Bug4185816Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void writeFormatToFile(final String name) {
    try {
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream(name));

        MessageFormat fmt = new MessageFormat("The disk \"{1}\" contains {0}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{0,number} files"};
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        fmt.setFormat(1,fileform); // NOT zero, see below

        out.writeObject(fmt);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}
 
Example 17
/**
 * Test the built in choice format.
 */
public void testBuiltInChoiceFormat() {
    Object[] values = new Number[] {new Integer(1), new Double("2.2"), new Double("1234.5")};
    String choicePattern = null;
    Locale[] availableLocales = ChoiceFormat.getAvailableLocales();

    choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
    for (int i = 0; i < values.length; i++) {
        checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales);
    }

    choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}";
    for (int i = 0; i < values.length; i++) {
        checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales);
    }
}
 
Example 18
/**
 * Test the built in choice format.
 */
public void testBuiltInChoiceFormat() {
    Object[] values = new Number[] {new Integer(1), new Double("2.2"), new Double("1234.5")};
    String choicePattern = null;
    Locale[] availableLocales = ChoiceFormat.getAvailableLocales();

    choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
    for (int i = 0; i < values.length; i++) {
        checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales);
    }

    choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}";
    for (int i = 0; i < values.length; i++) {
        checkBuiltInFormat(values[i] + ": " + choicePattern, new Object[] {values[i]}, availableLocales);
    }
}
 
Example 19
Source Project: j2objc   Source File: MessageRegressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void Test4106661()
{
    ChoiceFormat fmt = new ChoiceFormat(
      "-1#are negative| 0#are no or fraction | 1#is one |1.0<is 1+ |2#are two |2<are more than 2.");
    logln("Formatter Pattern : " + fmt.toPattern());

    logln("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY));
    logln("Format with -1.0 : " + fmt.format(-1.0));
    logln("Format with 0 : " + fmt.format(0));
    logln("Format with 0.9 : " + fmt.format(0.9));
    logln("Format with 1.0 : " + fmt.format(1));
    logln("Format with 1.5 : " + fmt.format(1.5));
    logln("Format with 2 : " + fmt.format(2));
    logln("Format with 2.1 : " + fmt.format(2.1));
    logln("Format with NaN : " + fmt.format(Double.NaN));
    logln("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY));
}
 
Example 20
Source Project: j2objc   Source File: MessageRegressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void Test4094906()
{
    ChoiceFormat fmt = new ChoiceFormat(
      "-\u221E<are negative|0<are no or fraction|1#is one|1.0<is 1+|\u221E<are many.");
    if (!fmt.toPattern().startsWith("-\u221E<are negative|0.0<are no or fraction|1.0#is one|1.0<is 1+|\u221E<are many."))
        errln("Formatter Pattern : " + fmt.toPattern());
    logln("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY));
    logln("Format with -1.0 : " + fmt.format(-1.0));
    logln("Format with 0 : " + fmt.format(0));
    logln("Format with 0.9 : " + fmt.format(0.9));
    logln("Format with 1.0 : " + fmt.format(1));
    logln("Format with 1.5 : " + fmt.format(1.5));
    logln("Format with 2 : " + fmt.format(2));
    logln("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY));
}
 
Example 21
Source Project: j2objc   Source File: MessageRegressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void Test4105380()
{
    String patternText1 = "The disk \"{1}\" contains {0}.";
    String patternText2 = "There are {0} on the disk \"{1}\"";
    MessageFormat form1 = new MessageFormat(patternText1);
    MessageFormat form2 = new MessageFormat(patternText2);
    double[] filelimits = {0,1,2};
    String[] filepart = {"no files","one file","{0,number} files"};
    ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
    form1.setFormat(1, fileform);
    form2.setFormat(0, fileform);
    Object[] testArgs = {new Long(12373), "MyDisk"};
    logln(form1.format(testArgs));
    logln(form2.format(testArgs));
}
 
Example 22
Source Project: j2objc   Source File: NumberFormatTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @tests java.text.NumberFormat#getCurrency()
 */
public void test_getCurrency() {
    // Test for method java.util.Currency getCurrency()

    // a subclass that supports currency formatting
    Currency currH = Currency.getInstance("HUF");
    NumberFormat format = NumberFormat.getInstance(new Locale("hu", "HU"));
    assertSame("Returned incorrect currency", currH, format.getCurrency());

    // a subclass that doesn't support currency formatting
    ChoiceFormat cformat = new ChoiceFormat(
            "0#Less than one|1#one|1<Between one and two|2<Greater than two");
    try {
        ((NumberFormat) cformat).getCurrency();
        fail("Expected UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
    }
}
 
Example 23
Source Project: j2objc   Source File: NumberFormatTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @tests java.text.NumberFormat#setCurrency(java.util.Currency)
 */
public void test_setCurrencyLjava_util_Currency() {
    // Test for method void setCurrency(java.util.Currency)
    // a subclass that supports currency formatting
    Currency currA = Currency.getInstance("ARS");
    NumberFormat format = NumberFormat.getInstance(new Locale("hu", "HU"));
    format.setCurrency(currA);
    assertSame("Returned incorrect currency", currA, format.getCurrency());

    // a subclass that doesn't support currency formatting
    ChoiceFormat cformat = new ChoiceFormat(
            "0#Less than one|1#one|1<Between one and two|2<Greater than two");
    try {
        ((NumberFormat) cformat).setCurrency(currA);
        fail("Expected UnsupportedOperationException");
    } catch (UnsupportedOperationException e) {
    }
}
 
Example 24
Source Project: j2objc   Source File: ChoiceFormatTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
   * @tests java.text.ChoiceFormat#parse(java.lang.String,
   *        java.text.ParsePosition)
   */
  public void test_parseLjava_lang_StringLjava_text_ParsePosition() {
      // Test for method java.lang.Number
      // java.text.ChoiceFormat.parse(java.lang.String,
      // java.text.ParsePosition)
      ChoiceFormat format = new ChoiceFormat("1#one|2#two|3#three");
assertEquals("Case insensitive", 0, format
		.parse("One", new ParsePosition(0)).intValue());

      ParsePosition pos = new ParsePosition(0);
      Number result = f1.parse("Greater than two", pos);
      assertTrue("Not a Double1", result instanceof Double);
      assertTrue("Wrong value ~>2", result.doubleValue() == ChoiceFormat
              .nextDouble(2));
assertEquals("Wrong position ~16", 16, pos.getIndex());
      pos = new ParsePosition(0);
      assertTrue("Incorrect result", Double.isNaN(f1.parse("12one", pos)
              .doubleValue()));
assertEquals("Wrong position ~0", 0, pos.getIndex());
      pos = new ParsePosition(2);
      result = f1.parse("12one and two", pos);
      assertTrue("Not a Double2", result instanceof Double);
assertEquals("Ignored parse position", 1.0D, result.doubleValue(), 0.0D);
assertEquals("Wrong position ~5", 5, pos.getIndex());
  }
 
Example 25
Source Project: j2objc   Source File: ChoiceFormatTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @tests java.text.ChoiceFormat#format(double)
 */
public void test_formatD() {
	ChoiceFormat fmt = new ChoiceFormat(
			"-1#NEGATIVE_ONE|0#ZERO|1#ONE|1<GREATER_THAN_ONE");
	assertEquals("NEGATIVE_ONE", fmt.format(Double.NEGATIVE_INFINITY));
	assertEquals("NEGATIVE_ONE", fmt.format(-999999999D));
	assertEquals("NEGATIVE_ONE", fmt.format(-1.1));
	assertEquals("NEGATIVE_ONE", fmt.format(-1.0));
	assertEquals("NEGATIVE_ONE", fmt.format(-0.9));
	assertEquals("ZERO", fmt.format(0.0));
	assertEquals("ZERO", fmt.format(0.9));
	assertEquals("ONE", fmt.format(1.0));
	assertEquals("GREATER_THAN_ONE", fmt.format(1.1));
	assertEquals("GREATER_THAN_ONE", fmt.format(999999999D));
	assertEquals("GREATER_THAN_ONE", fmt.format(Double.POSITIVE_INFINITY));
}
 
Example 26
Source Project: JavaRush   Source File: Solution.java    License: MIT License 6 votes vote down vote up
private static void printStocks(List<Stock> stocks, Date actualDate) {
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

  double[] filelimits = {0d, actualDate.getTime()};
  String[] filepart = {"closed {4}", "open {2} and last {3}"};

  ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
  Format[] testFormats = {null, null, dateFormat, fileform};
  MessageFormat pattform = new MessageFormat("{0}   {1} | {5} {6}");
  pattform.setFormats(testFormats);

  for (Stock stock : stocks) {
    String name = ((String) stock.get("name"));
    String symbol = (String) stock.get("symbol");
    double open = !stock.containsKey("open") ? 0 : ((double) stock.get("open"));
    double last = !stock.containsKey("last") ? 0 : ((double) stock.get("last"));
    double change = !stock.containsKey("change") ? 0 : ((double) stock.get("change"));
    Date date = (Date) stock.get("date");
    Object[] testArgs = {name, symbol, open, last, change, date, date.getTime()};
    System.out.println(pattform.format(testArgs));
  }
}
 
Example 27
Source Project: ph-commons   Source File: LocaleParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseBigDecimal ()
{
  final BigDecimal aBD1M = StringParser.parseBigDecimal ("1000000");
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1.000.000", L_DE, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1,000,000", L_EN, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1,000,000", (DecimalFormat) NumberFormat.getInstance (L_EN)));
  assertEquals (new BigDecimal ("1234567.8901"),
                LocaleParser.parseBigDecimal ("1.234.567,8901", L_DE, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (CGlobal.BIGDEC_MINUS_ONE,
                LocaleParser.parseBigDecimal ("... und denken", L_EN, CGlobal.BIGDEC_MINUS_ONE));
  final ChoiceFormat aCF = new ChoiceFormat ("-1#negative|0#zero|1.0#one");
  assertEquals (BigDecimal.valueOf (0.0), LocaleParser.parseBigDecimal ("zero", aCF, CGlobal.BIGDEC_MINUS_ONE));

  try
  {
    LocaleParser.parseBigDecimal ("0", (DecimalFormat) null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example 28
Source Project: cron-utils   Source File: TimeDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
private String describeEverySecond(final int second) {
    final double[] secondsLimit = {1, 2};
    final String[] secondsStrings = {
            resourceBundle.getString("oneSecond"),
            resourceBundle.getString("multipleSeconds")
    };
    final double[] everyLimit = {1,2};
    final String[] everyStrings = {
            resourceBundle.getString("every_one"),
            resourceBundle.getString("every_multi")
    };

    final ChoiceFormat secondsChoiceFormat = new ChoiceFormat(secondsLimit, secondsStrings);
    final ChoiceFormat everyChoiceFormat = new ChoiceFormat(everyLimit, everyStrings);
    final String pattern = resourceBundle.getString("pattern_every_seconds");

    final MessageFormat messageFormat = new MessageFormat(pattern, Locale.UK);

    final Format[] formats = { everyChoiceFormat, secondsChoiceFormat, NumberFormat.getInstance() };
    messageFormat.setFormats(formats);
    final Object[] messageArguments = {second, second, second };
    final String result = messageFormat.format(messageArguments);
    return result;
}
 
Example 29
/**
 * Resolve an artifact and return its location in the local repository. Aether performs the normal
 * Maven resolution process ensuring that the latest update is cached to the local repository.
 * In addition, if the {@link MavenProperties#resolvePom} flag is <code>true</code>,
 * the POM is also resolved and cached.
 * @param resource the {@link MavenResource} representing the artifact
 * @return a {@link FileSystemResource} representing the resolved artifact in the local repository
 * @throws IllegalStateException if the artifact does not exist or the resolution fails
 */
Resource resolve(MavenResource resource) {
	Assert.notNull(resource, "MavenResource must not be null");
	validateCoordinates(resource);
	RepositorySystemSession session = newRepositorySystemSession(this.repositorySystem,
			this.properties.getLocalRepository());
	ArtifactResult resolvedArtifact;
	try {
		List<ArtifactRequest> artifactRequests = new ArrayList<>(2);
		if (properties.isResolvePom()) {
			artifactRequests.add(new ArtifactRequest(toPomArtifact(resource),
					this.remoteRepositories,
					JavaScopes.RUNTIME));
		}
		artifactRequests.add(new ArtifactRequest(toJarArtifact(resource),
				this.remoteRepositories,
				JavaScopes.RUNTIME));

		List<ArtifactResult> results = this.repositorySystem.resolveArtifacts(session, artifactRequests);
		resolvedArtifact = results.get(results.size() - 1);
	}
	catch (ArtifactResolutionException e) {

		ChoiceFormat pluralizer = new ChoiceFormat(
				new double[] { 0d, 1d, ChoiceFormat.nextDouble(1d) },
				new String[] { "repositories: ", "repository: ", "repositories: " });
		MessageFormat messageFormat = new MessageFormat(
				"Failed to resolve MavenResource: {0}. Configured remote {1}: {2}");
		messageFormat.setFormat(1, pluralizer);
		String repos = properties.getRemoteRepositories().isEmpty()
				? "none"
				: StringUtils.collectionToDelimitedString(properties.getRemoteRepositories().keySet(), ",", "[", "]");
		throw new IllegalStateException(
				messageFormat.format(new Object[] { resource, properties.getRemoteRepositories().size(), repos }),
				e);
	}
	return toResource(resolvedArtifact);
}
 
Example 30
Source Project: j2objc   Source File: MessageRegressionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void Test4052223()
{
    ParsePosition pos = new ParsePosition(0);
    if (pos.getErrorIndex() != -1) {
        errln("ParsePosition.getErrorIndex initialization failed.");
    }
    MessageFormat fmt = new MessageFormat("There are {0} apples growing on the {1} tree.");
    String str = new String("There is one apple growing on the peach tree.");
    Object[] objs = fmt.parse(str, pos);
    logln("unparsable string , should fail at " + pos.getErrorIndex());
    if (pos.getErrorIndex() == -1)
        errln("Bug 4052223 failed : parsing string " + str);
    pos.setErrorIndex(4);
    if (pos.getErrorIndex() != 4)
        errln("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4");
    
    if (objs != null) {
        errln("objs should be null");
    }
    ChoiceFormat f = new ChoiceFormat(
        "-1#are negative|0#are no or fraction|1#is one|1.0<is 1+|2#are two|2<are more than 2.");
    pos.setIndex(0); pos.setErrorIndex(-1);
    Number obj = f.parse("are negative", pos);
    if (pos.getErrorIndex() != -1 && obj.doubleValue() == -1.0)
        errln("Parse with \"are negative\" failed, at " + pos.getErrorIndex());
    pos.setIndex(0); pos.setErrorIndex(-1);
    obj = f.parse("are no or fraction ", pos);
    if (pos.getErrorIndex() != -1 && obj.doubleValue() == 0.0)
        errln("Parse with \"are no or fraction\" failed, at " + pos.getErrorIndex());
    pos.setIndex(0); pos.setErrorIndex(-1);
    obj = f.parse("go postal", pos);
    if (pos.getErrorIndex() == -1 && !Double.isNaN(obj.doubleValue()))
        errln("Parse with \"go postal\" failed, at " + pos.getErrorIndex());
}
 
Example 31
Source Project: j2objc   Source File: MessageRegressionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void Test4104976()
{
    double[] limits = {1, 20};
    String[] formats = {"xyz", "abc"};
    ChoiceFormat cf = new ChoiceFormat(limits, formats);
    try {
        log("Compares to null is always false, returned : ");
        logln(cf.equals(null) ? "TRUE" : "FALSE");
    } catch (Exception foo) {
        errln("ChoiceFormat.equals(null) throws exception.");
    }
}
 
Example 32
Source Project: j2objc   Source File: MessageRegressionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void Test4106660()
{
    double[] limits = {3, 1, 2};
    String[] formats = {"Three", "One", "Two"};
    ChoiceFormat cf = new ChoiceFormat(limits, formats);
    double d = 5.0;
    String str = cf.format(d);
    if (!str.equals("Two"))
        errln("format(" + d + ") = " + cf.format(d));
}
 
Example 33
Source Project: j2objc   Source File: MessageRegressionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @bug 4142938
 * Test the applyPattern and toPattern handling of single quotes
 * by ChoiceFormat.  (This is in here because this was a bug reported
 * against MessageFormat.)  The single quote is used to quote the
 * pattern characters '|', '#', '<', and '\u2264'.  Two quotes in a row
 * is a quote literal.
 */
@Test
public void TestChoicePatternQuote() {
    String[] DATA = {
        // Pattern                  0 value           1 value
        "0#can''t|1#can",           "can't",          "can",
        "0#'pound(#)=''#'''|1#xyz", "pound(#)='#'",   "xyz",
        "0#'1<2 | 1\u22641'|1#''",  "1<2 | 1\u22641", "'",
    };
    for (int i=0; i<DATA.length; i+=3) {
        try {
            ChoiceFormat cf = new ChoiceFormat(DATA[i]);
            for (int j=0; j<=1; ++j) {
                String out = cf.format(j);
                if (!out.equals(DATA[i+1+j]))
                    errln("Fail: Pattern \"" + DATA[i] + "\" x "+j+" -> " +
                          out + "; want \"" + DATA[i+1+j] + '"');
            }
            String pat = cf.toPattern();
            String pat2 = new ChoiceFormat(pat).toPattern();
            if (!pat.equals(pat2))
                errln("Fail: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"');
            else
                logln("Ok: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"');
        }
        catch (IllegalArgumentException e) {
            errln("Fail: Pattern \"" + DATA[i] + "\" -> " + e);
        }
    }
}
 
Example 34
Source Project: j2objc   Source File: TestMessageFormat.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void TestBug1()
{
    final double limit[] = {0.0, 1.0, 2.0};
    final String formats[] = {"0.0<=Arg<1.0",
                              "1.0<=Arg<2.0",
                              "2.0<-Arg"};
    ChoiceFormat cf = new ChoiceFormat(limit, formats);
    assertEquals("ChoiceFormat.format", formats[1], cf.format(1));
}
 
Example 35
Source Project: j2objc   Source File: TestMessageFormat.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void TestMsgFormatChoice()
{
    MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
    double filelimits[] = {0,1,2};
    String filepart[] = {"no files","one file","{0,number} files"};
    ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
    form.setFormat(1, fileform); // NOT zero, see below

    FieldPosition ignore = new FieldPosition(FieldPosition_DONT_CARE);
    StringBuffer string = new StringBuffer();
    Object testArgs1[] = {new Integer(0), "MyDisk"};
    form.format(testArgs1, string, ignore);
    assertEquals("format#1",
                 "The disk \"MyDisk\" contains no files.",
                 string.toString());

    string.setLength(0);
    Object testArgs2[] = {new Integer(1), "MyDisk"};
    form.format(testArgs2, string, ignore);
    assertEquals("format#2",
                 "The disk \"MyDisk\" contains one file.",
                 string.toString());

    string.setLength(0);
    Object testArgs3[] = {new Integer(1273), "MyDisk"};
    form.format(testArgs3, string, ignore);
    assertEquals("format#3",
                 "The disk \"MyDisk\" contains 1,273 files.",
                 string.toString());
}
 
Example 36
Source Project: j2objc   Source File: NumberFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_setRoundingMode_NullRoundingMode() {
	try {
		// Create a subclass ChoiceFormat which doesn't support
		// RoundingMode
		ChoiceFormat choiceFormat = new ChoiceFormat(
				"0#Less than one|1#one|1<Between one and two|2<Greater than two");
		((NumberFormat) choiceFormat).setRoundingMode(null);
		// Follow the behavior of RI
		fail("UnsupportedOperationException expected");
	} catch (UnsupportedOperationException e) {
		// expected
	}
}
 
Example 37
Source Project: j2objc   Source File: NumberFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_setRoundingMode_Normal() {
	try {
		// Create a subclass ChoiceFormat which doesn't support
		// RoundingMode
		ChoiceFormat choiceFormat = new ChoiceFormat(
				"0#Less than one|1#one|1<Between one and two|2<Greater than two");
		((NumberFormat) choiceFormat).setRoundingMode(RoundingMode.CEILING);
		fail("UnsupportedOperationException expected");
	} catch (UnsupportedOperationException e) {
		// expected
	}
}
 
Example 38
Source Project: j2objc   Source File: MessageFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_setFormats$Ljava_text_Format() throws Exception {
  MessageFormat f1 = (MessageFormat) format1.clone();

  // case 1: Test with repeating formats and max argument index < max
  // offset
  // compare getFormats() results after calls to setFormats(Format[])
  Format[] correctFormats = new Format[] {
    DateFormat.getTimeInstance(),
    new ChoiceFormat("0#off|1#on"),
    DateFormat.getTimeInstance(),
    NumberFormat.getCurrencyInstance(),
    new ChoiceFormat("1#few|2#ok|3#a lot")
  };

  f1.setFormats(correctFormats);
  Format[] formats = f1.getFormats();

  assertTrue("Test1A:Returned wrong number of formats:", correctFormats.length <= formats.length);
  for (int i = 0; i < correctFormats.length; i++) {
    assertEquals("Test1B:wrong format for argument index " + i + ":", correctFormats[i], formats[i]);
  }

  // case 2: Try to pass null argument to setFormats().
  try {
    f1.setFormats(null);
    fail();
  } catch (NullPointerException expected) {
  }
}
 
Example 39
Source Project: j2objc   Source File: MessageFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_getFormats() {
  // test with repeating formats and max argument index < max offset
  Format[] formats = format1.getFormats();
  Format[] correctFormats = new Format[] {
    NumberFormat.getCurrencyInstance(),
    DateFormat.getTimeInstance(),
    NumberFormat.getPercentInstance(), null,
    new ChoiceFormat("0#off|1#on"), DateFormat.getDateInstance(), };

  assertEquals("Test1:Returned wrong number of formats:",
               correctFormats.length, formats.length);
  for (int i = 0; i < correctFormats.length; i++) {
    assertEquals("Test1:wrong format for pattern index " + i + ":",
                 correctFormats[i], formats[i]);
  }

  // test with max argument index > max offset
  formats = format2.getFormats();
  correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
      DateFormat.getTimeInstance(),
      NumberFormat.getPercentInstance(), null,
      new ChoiceFormat("0#off|1#on"), DateFormat.getDateInstance() };

  assertEquals("Test2:Returned wrong number of formats:",
               correctFormats.length, formats.length);
  for (int i = 0; i < correctFormats.length; i++) {
    assertEquals("Test2:wrong format for pattern index " + i + ":",
                 correctFormats[i], formats[i]);
  }

  // test with argument number being zero
  formats = format3.getFormats();
  assertEquals("Test3: Returned wrong number of formats:", 0,
               formats.length);
}
 
Example 40
Source Project: j2objc   Source File: MessageFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_getFormatsByArgumentIndex() {
    // test with repeating formats and max argument index < max offset
    Format[] formats = format1.getFormatsByArgumentIndex();
    Format[] correctFormats = new Format[] { DateFormat.getDateInstance(),
            new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(),
            NumberFormat.getCurrencyInstance(), null };

    assertEquals("Test1:Returned wrong number of formats:",
            correctFormats.length, formats.length);
    for (int i = 0; i < correctFormats.length; i++) {
        assertEquals("Test1:wrong format for argument index " + i + ":",
                correctFormats[i], formats[i]);
    }

    // test with max argument index > max offset
    formats = format2.getFormatsByArgumentIndex();
    correctFormats = new Format[] { DateFormat.getDateInstance(),
            new ChoiceFormat("0#off|1#on"), null,
            NumberFormat.getCurrencyInstance(), null, null, null, null,
            DateFormat.getTimeInstance() };

    assertEquals("Test2:Returned wrong number of formats:",
            correctFormats.length, formats.length);
    for (int i = 0; i < correctFormats.length; i++) {
        assertEquals("Test2:wrong format for argument index " + i + ":",
                correctFormats[i], formats[i]);
    }

    // test with argument number being zero
    formats = format3.getFormatsByArgumentIndex();
    assertEquals("Test3: Returned wrong number of formats:", 0,
            formats.length);
}