ICU-5323 check-in all eclipse icu plug-in project and source files

X-SVN-Rev: 20080
This commit is contained in:
Yoshito Umaoka 2006-08-17 20:32:32 +00:00
parent cd1a997369
commit 72184a0b2c
57 changed files with 16888 additions and 18 deletions

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.ibm.icu-feature</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.pde.FeatureBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.FeatureNature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,20 @@
###############################################################################
# Copyright (c) 2000, 2005 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
bin.includes =\
epl-v10.html,\
eclipse_update_120.jpg,\
feature.xml,\
feature.properties,\
license.html
outputUpdateJars = true
generate.plugin@com.ibm.icu.source=com.ibm.icu

View file

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="com.ibm.icu"
label="com.ibm.icu"
version="3.4.5">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<plugin
id="com.ibm.icu"
download-size="0"
install-size="0"
version="3.4.5"
unpack="false"/>
<plugin
id="com.ibm.icu.source"
download-size="0"
install-size="0"
version="3.4.5"/>
</feature>

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
bin.includes = about.html, plugin.properties, plugin.xml, src/**,META-INF/
sourcePlugin = true

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
pluginName = International Components for Unicode for Java (ICU4J) source plug-in
providerName = IBM Corporation

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.ibm.icu.base-feature</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.pde.FeatureBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.FeatureNature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,9 @@
bin.includes =\
epl-v10.html,\
eclipse_update_120.jpg,\
feature.xml,\
feature.properties,\
license.html
outputUpdateJars = true
generate.plugin@com.ibm.icu.base.source=com.ibm.icu.base

View file

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
id="com.ibm.icu.base"
label="com.ibm.icu.base"
version="3.4.5"
provider-name="IBM">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<plugin
id="com.ibm.icu.base"
download-size="0"
install-size="0"
version="3.4.5"
unpack="false"/>
<plugin
id="com.ibm.icu.base.source"
download-size="0"
install-size="0"
version="3.4.5"/>
</feature>

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
bin.includes = about.html, plugin.properties, plugin.xml, src/**,META-INF/
sourcePlugin = true

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
pluginName = International Components for Unicode for Java (ICU4J) Replacement source plug-in
providerName = IBM Corporation

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.ibm.icu.base.tests</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,14 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: ICU4J Base test fragment
Bundle-SymbolicName: com.ibm.icu.base.tests
Bundle-Version: 1.0.0
Bundle-Vendor: IBM
Bundle-Copyright: Licensed Materials - Property of IBM
(C) Copyright IBM Corp. 2006. All Rights Reserved.
IBM is a registered trademark of IBM Corp.
Fragment-Host: com.ibm.icu.base;bundle-version="[3.4.3,3.5.0)"
Bundle-Localization: plugin
Bundle-RequiredExecutionEnvironment: J2SE-1.3,
CDC-1.0/Foundation-1.0
Require-Bundle: org.junit

View file

@ -0,0 +1,4 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.

View file

@ -0,0 +1,359 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Locale;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.util.ULocale;
public class BreakIteratorTest extends ICUTestCase {
// ICU behaves a bit differently with this text, but the tested values aren't
// affected. If Java changes behavior they might need to change.
private static final String text = "Mr. and Mrs. Mumblety-Peg paid $35.97 for a new 12\" cockatoo. " +
"When they got home they both cooed \"Isn't it lovely?\" and sighed softly. " +
"\"Let's name it u\u0308\u5098!\" they said with glee.";
private static int pos = text.indexOf("sn't");
private static BreakIterator cbr;
private static BreakIterator wbr;
private static BreakIterator lbr;
private static BreakIterator sbr;
static {
cbr = BreakIterator.getCharacterInstance();
cbr.setText(text);
wbr = BreakIterator.getWordInstance();
wbr.setText(text);
lbr = BreakIterator.getLineInstance();
lbr.setText(text);
sbr = BreakIterator.getSentenceInstance();
sbr.setText(text);
// diagnostic
// dump(cbr);
// dump(wbr);
// dump(lbr);
// dump(sbr);
}
// private static void dump(BreakIterator bi) {
// for (int ix = bi.first(), lim = text.length(); ix != lim;) {
// int nx = bi.next();
// if (nx < 0) nx = lim;
// System.out.println(Integer.toString(ix) + ": " + text.substring(ix, nx));
// ix = nx;
// }
// }
/*
* Test method for 'com.ibm.icu.text.BreakIterator.hashCode()'
*/
public void testHashCode() {
BreakIterator br = BreakIterator.getWordInstance();
br.setText(text);
BreakIterator brne = BreakIterator.getWordInstance();
brne.setText(text + "X");
wbr.first();
testEHCS(br, wbr, brne);
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.BreakIterator(BreakIterator)'
*/
public void testBreakIterator() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.first()'
*/
public void testFirst() {
assertEquals(0, cbr.first());
assertEquals(0, wbr.first());
assertEquals(0, lbr.first());
assertEquals(0, sbr.first());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.last()'
*/
public void testLast() {
assertEquals(text.length(), cbr.last());
assertEquals(text.length(), wbr.last());
assertEquals(text.length(), lbr.last());
assertEquals(text.length(), sbr.last());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.next(int)'
*/
public void testNextInt() {
cbr.first();
wbr.first();
lbr.first();
sbr.first();
assertEquals(2, cbr.next(2));
assertEquals(3, wbr.next(2));
assertEquals(8, lbr.next(2));
assertEquals(62, sbr.next(2));
cbr.last();
wbr.last();
lbr.last();
sbr.last();
assertEquals(174, cbr.next(-2));
assertEquals(171, wbr.next(-2));
assertEquals(166, lbr.next(-2));
assertEquals(135, sbr.next(-2));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.next()'
*/
public void testNext() {
cbr.first();
wbr.first();
lbr.first();
sbr.first();
assertEquals(1, cbr.next());
assertEquals(2, wbr.next());
assertEquals(4, lbr.next());
assertEquals(13, sbr.next());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.previous()'
*/
public void testPrevious() {
cbr.last();
wbr.last();
lbr.last();
sbr.last();
assertEquals(175, cbr.previous());
assertEquals(175, wbr.previous());
assertEquals(171, lbr.previous());
assertEquals(156, sbr.previous());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.following(int)'
*/
public void testFollowing() {
assertEquals(100, cbr.following(pos));
assertEquals(103, wbr.following(pos));
assertEquals(104, lbr.following(pos));
assertEquals(116, sbr.following(pos));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.preceding(int)'
*/
public void testPreceding() {
assertEquals(98, cbr.preceding(pos));
assertEquals(98, wbr.preceding(pos));
assertEquals(97, lbr.preceding(pos));
assertEquals(62, sbr.preceding(pos));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.isBoundary(int)'
*/
public void testIsBoundary() {
assertTrue(cbr.isBoundary(pos));
assertFalse(wbr.isBoundary(pos));
assertFalse(lbr.isBoundary(pos));
assertFalse(sbr.isBoundary(pos));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.current()'
*/
public void testCurrent() {
cbr.following(pos);
wbr.following(pos);
lbr.following(pos);
sbr.following(pos);
assertEquals(100, cbr.current());
assertEquals(103, wbr.current());
assertEquals(104, lbr.current());
assertEquals(116, sbr.current());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getText()'
*/
public void testGetText() {
CharacterIterator ci = cbr.getText();
StringBuffer buf = new StringBuffer(ci.getEndIndex() - ci.getBeginIndex());
for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
buf.append(c);
}
String result = buf.toString();
assertEquals(text, result);
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.setText(String)'
*/
public void testSetTextString() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.setText(CharacterIterator)'
*/
public void testSetTextCharacterIterator() {
CharacterIterator ci = new StringCharacterIterator(text, pos);
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(ci);
assertEquals(2, bi.next());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getWordInstance()'
*/
public void testGetWordInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getWordInstance(Locale)'
*/
public void testGetWordInstanceLocale() {
assertNotNull(BreakIterator.getWordInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getWordInstance(ULocale)'
*/
public void testGetWordInstanceULocale() {
assertNotNull(BreakIterator.getWordInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getLineInstance()'
*/
public void testGetLineInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getLineInstance(Locale)'
*/
public void testGetLineInstanceLocale() {
assertNotNull(BreakIterator.getLineInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getLineInstance(ULocale)'
*/
public void testGetLineInstanceULocale() {
assertNotNull(BreakIterator.getLineInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getCharacterInstance()'
*/
public void testGetCharacterInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getCharacterInstance(Locale)'
*/
public void testGetCharacterInstanceLocale() {
assertNotNull(BreakIterator.getCharacterInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getCharacterInstance(ULocale)'
*/
public void testGetCharacterInstanceULocale() {
assertNotNull(BreakIterator.getCharacterInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getSentenceInstance()'
*/
public void testGetSentenceInstance() {
// implicitly tested
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getSentenceInstance(Locale)'
*/
public void testGetSentenceInstanceLocale() {
assertNotNull(BreakIterator.getSentenceInstance(Locale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getSentenceInstance(ULocale)'
*/
public void testGetSentenceInstanceULocale() {
assertNotNull(BreakIterator.getSentenceInstance(ULocale.JAPAN));
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getTitleInstance()'
*/
public void testGetTitleInstance() {
// not implemented
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getTitleInstance(Locale)'
*/
public void testGetTitleInstanceLocale() {
// not implemented
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getTitleInstance(ULocale)'
*/
public void testGetTitleInstanceULocale() {
// not implemented
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getAvailableLocales()'
*/
public void testGetAvailableLocales() {
assertNotNull(BreakIterator.getAvailableLocales());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.getAvailableULocales()'
*/
public void testGetAvailableULocales() {
assertNotNull(BreakIterator.getAvailableULocales());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.toString()'
*/
public void testToString() {
assertNotNull(cbr.toString());
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.clone()'
*/
public void testClone() {
// see testHashCode
}
/*
* Test method for 'com.ibm.icu.text.BreakIterator.equals(Object)'
*/
public void testEqualsObject() {
// see testHashCode
}
}

View file

@ -0,0 +1,559 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;
public class CalendarTest extends ICUTestCase {
/*
* Test method for 'com.ibm.icu.util.Calendar.hashCode()'
*/
public void testHashCode() {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
Calendar cal3 = Calendar.getInstance();
cal3.setMinimalDaysInFirstWeek(cal3.getMinimalDaysInFirstWeek()+1);
testEHCS(cal1, cal2, cal3);
}
/*
* Test method for 'com.ibm.icu.util.Calendar.Calendar(Calendar)'
*/
public void testCalendar() {
// tested implicitly everywhere
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getInstance()'
*/
public void testGetInstance() {
// tested by testEHCS
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getInstance(TimeZone)'
*/
public void testGetInstanceTimeZone() {
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
Calendar cal = Calendar.getInstance(tz);
assertNotNull(cal);
assertNotNull(cal.getTime());
assertEquals(tz, cal.getTimeZone());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getInstance(Locale)'
*/
public void testGetInstanceLocale() {
Calendar cal = Calendar.getInstance(Locale.US);
assertNotNull(cal);
assertNotNull(cal.getTime());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getInstance(ULocale)'
*/
public void testGetInstanceULocale() {
Calendar cal = Calendar.getInstance(ULocale.US);
assertNotNull(cal);
assertNotNull(cal.getTime());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getInstance(TimeZone, Locale)'
*/
public void testGetInstanceTimeZoneLocale() {
TimeZone tz = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(tz, Locale.US);
assertNotNull(cal);
assertNotNull(cal.getTime());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getInstance(TimeZone, ULocale)'
*/
public void testGetInstanceTimeZoneULocale() {
TimeZone tz = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(tz, ULocale.US);
assertNotNull(cal);
assertNotNull(cal.getTime());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getAvailableLocales()'
*/
public void testGetAvailableLocales() {
assertNotNull(Calendar.getAvailableLocales());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getAvailableULocales()'
*/
public void testGetAvailableULocales() {
assertNotNull(Calendar.getAvailableULocales());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getTime()'
*/
public void testGetTime() {
Calendar cal = Calendar.getInstance();
assertNotNull(cal.getTime());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.setTime(Date)'
*/
public void testSetTime() {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2006, 0, 20, 9, 30, 0);
Date date = cal.getTime();
cal = Calendar.getInstance();
cal.setTime(date);
assertEquals(date, cal.getTime());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getTimeInMillis()'
*/
public void testGetTimeInMillis() {
Calendar cal = Calendar.getInstance();
assertTrue(0 != cal.getTimeInMillis());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.setTimeInMillis(long)'
*/
public void testSetTimeInMillis() {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2006, 0, 20, 9, 30, 0);
long millis = cal.getTimeInMillis();
Date date = cal.getTime();
cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
assertEquals(date, cal.getTime());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.get(int)'
*/
public void testGet() {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2006, 0, 20, 9, 30, 0);
assertEquals(0, cal.get(Calendar.MONTH));
assertEquals(20, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(30, cal.get(Calendar.MINUTE));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.set(int, int)'
*/
public void testSetIntInt() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1977);
assertEquals(1977, cal.get(Calendar.YEAR));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.set(int, int, int)'
*/
public void testSetIntIntInt() {
Calendar cal = Calendar.getInstance();
cal.set(1997, 9, 15);
assertEquals(15, cal.get(Calendar.DATE));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.set(int, int, int, int, int)'
*/
public void testSetIntIntIntIntInt() {
Calendar cal = Calendar.getInstance();
cal.set(1997, 9, 15, 14, 25);
assertEquals(25, cal.get(Calendar.MINUTE));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.set(int, int, int, int, int, int)'
*/
public void testSetIntIntIntIntIntInt() {
Calendar cal = Calendar.getInstance();
cal.set(1997, 9, 15, 14, 25, 51);
assertEquals(51, cal.get(Calendar.SECOND));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.clear()'
*/
public void testClear() {
Calendar cal = Calendar.getInstance();
cal.set(1997, 9, 15, 14, 25, 51);
cal.clear();
assertEquals(0, cal.get(Calendar.MONTH));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.clear(int)'
*/
public void testClearInt() {
Calendar cal = Calendar.getInstance();
cal.set(1997, 9, 15, 14, 25, 51);
assertTrue(cal.isSet(Calendar.DAY_OF_MONTH));
cal.clear(Calendar.DAY_OF_MONTH);
assertFalse(cal.isSet(Calendar.DAY_OF_MONTH));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.isSet(int)'
*/
public void testIsSet() {
// see testClearInt
}
/*
* Test method for 'com.ibm.icu.util.Calendar.equals(Object)'
*/
public void testEqualsObject() {
// tested by testHashCode
}
/*
* Test method for 'com.ibm.icu.util.Calendar.isEquivalentTo(Calendar)'
*/
public void testIsEquivalentTo() {
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal2.set(1994, 6, 21, 8, 7);
assertTrue(cal.isEquivalentTo(cal2));
cal.setTimeZone(TimeZone.getTimeZone("CST"));
cal2.setTimeZone(TimeZone.getTimeZone("PDT"));
assertFalse(cal.isEquivalentTo(cal2));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.before(Object)'
*/
public void testBefore() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1990);
assertTrue(cal.before(new Date()));
assertTrue(cal.before(Calendar.getInstance()));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.after(Object)'
*/
public void testAfter() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 3058);
assertTrue(cal.after(new Date()));
assertTrue(cal.after(Calendar.getInstance()));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getActualMaximum(int)'
*/
public void testGetActualMaximum() {
Calendar cal = Calendar.getInstance(Locale.US);
assertEquals(11, cal.getActualMaximum(Calendar.MONTH));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getActualMinimum(int)'
*/
public void testGetActualMinimum() {
Calendar cal = Calendar.getInstance(Locale.US);
assertEquals(0, cal.getActualMinimum(Calendar.MONTH));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.roll(int, boolean)'
*/
public void testRollIntBoolean() {
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(1997, 1, 27);
cal.roll(Calendar.DATE, true);
assertEquals(28, cal.get(Calendar.DATE));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.roll(int, int)'
*/
public void testRollIntInt() {
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(1997, 1, 27);
cal.roll(Calendar.DATE, 3);
assertEquals(2, cal.get(Calendar.DATE));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.add(int, int)'
*/
public void testAdd() {
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(1997, 1, 27);
cal.add(Calendar.DATE, 3);
assertEquals(2, cal.get(Calendar.DATE));
assertEquals(2, cal.get(Calendar.MONTH));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getDisplayName(Locale)'
*/
public void testGetDisplayNameLocale() {
Calendar cal = Calendar.getInstance();
assertEquals("Calendar", cal.getDisplayName(Locale.US));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getDisplayName(ULocale)'
*/
public void testGetDisplayNameULocale() {
Calendar cal = Calendar.getInstance();
assertEquals("Calendar", cal.getDisplayName(ULocale.US));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.compareTo(Calendar)'
*/
public void testCompareToCalendar() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1990);
assertTrue(0 > cal.compareTo(Calendar.getInstance()));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.compareTo(Object)'
*/
public void testCompareToObject() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1990);
assertTrue(0 > cal.compareTo((Object)Calendar.getInstance()));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getDateTimeFormat(int, int, Locale)'
*/
public void testGetDateTimeFormatIntIntLocale() {
Calendar cal = Calendar.getInstance();
cal.set(1990, 8, 16, 20, 3);
DateFormat df = cal.getDateTimeFormat(DateFormat.LONG, DateFormat.SHORT, Locale.US);
assertEquals("September 16, 1990 8:03 PM", df.format(cal));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getDateTimeFormat(int, int, ULocale)'
*/
public void testGetDateTimeFormatIntIntULocale() {
Calendar cal = Calendar.getInstance();
cal.set(1990, 8, 16, 20, 3);
DateFormat df = cal.getDateTimeFormat(DateFormat.LONG, DateFormat.SHORT, ULocale.US);
assertEquals("September 16, 1990 8:03 PM", df.format(cal));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.fieldDifference(Date, int)'
*/
public void testFieldDifference() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 0);
Date date = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, 5);
assertEquals(-5, cal.fieldDifference(date, Calendar.DAY_OF_MONTH));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getTimeZone()'
*/
public void testGetTimeZone() {
Calendar cal = Calendar.getInstance();
assertNotNull(cal.getTimeZone());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.setTimeZone(TimeZone)'
*/
public void testSetTimeZone() {
Calendar cal = Calendar.getInstance();
TimeZone value1 = cal.getTimeZone();
String tzn = "PDT".equals(value1.getID()) ? "CST" : "PDT";
TimeZone value2 = TimeZone.getTimeZone(tzn);
cal.setTimeZone(value2);
TimeZone result = cal.getTimeZone();
assertNotEqual(value1, result);
assertEquals(value2, result);
}
/*
* Test method for 'com.ibm.icu.util.Calendar.setLenient(boolean)'
*/
public void testSetLenient() {
Calendar cal = Calendar.getInstance();
boolean lenient = cal.isLenient();
cal.setLenient(!lenient);
assertFalse(lenient == cal.isLenient());
// not testing if it has the expected effect
}
/*
* Test method for 'com.ibm.icu.util.Calendar.isLenient()'
*/
public void testIsLenient() {
// tested by testSetLenient
}
/*
* Test method for 'com.ibm.icu.util.Calendar.setFirstDayOfWeek(int)'
*/
public void testSetFirstDayOfWeek() {
Calendar cal = Calendar.getInstance();
int firstDay = cal.getFirstDayOfWeek();
cal.setFirstDayOfWeek(firstDay+1);
assertEquals(firstDay+1, cal.getFirstDayOfWeek());
// don't test functionality
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getFirstDayOfWeek()'
*/
public void testGetFirstDayOfWeek() {
// tested by testSetFirstDayOfWeek
}
/*
* Test method for 'com.ibm.icu.util.Calendar.setMinimalDaysInFirstWeek(int)'
*/
public void testSetMinimalDaysInFirstWeek() {
Calendar cal = Calendar.getInstance();
int firstDay = cal.getMinimalDaysInFirstWeek();
cal.setMinimalDaysInFirstWeek(firstDay+1);
assertEquals(firstDay+1, cal.getMinimalDaysInFirstWeek());
// don't test functionality
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getMinimalDaysInFirstWeek()'
*/
public void testGetMinimalDaysInFirstWeek() {
// tested by testSetMinimalDaysInFirstWeek
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getMinimum(int)'
*/
public void testGetMinimum() {
Calendar cal = Calendar.getInstance();
assertEquals(1, cal.getMinimum(Calendar.DAY_OF_WEEK));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getMaximum(int)'
*/
public void testGetMaximum() {
Calendar cal = Calendar.getInstance();
assertEquals(7, cal.getMaximum(Calendar.DAY_OF_WEEK));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getGreatestMinimum(int)'
*/
public void testGetGreatestMinimum() {
Calendar cal = Calendar.getInstance();
assertEquals(1, cal.getGreatestMinimum(Calendar.DATE));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getLeastMaximum(int)'
*/
public void testGetLeastMaximum() {
Calendar cal = Calendar.getInstance();
assertEquals(28, cal.getLeastMaximum(Calendar.DATE));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getDayOfWeekType(int)'
*/
public void testGetDayOfWeekType() {
Calendar cal = Calendar.getInstance(Locale.US);
assertEquals(Calendar.WEEKDAY, cal.getDayOfWeekType(Calendar.FRIDAY));
assertEquals(Calendar.WEEKEND, cal.getDayOfWeekType(Calendar.SATURDAY));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getWeekendTransition(int)'
*/
public void testGetWeekendTransition() {
Calendar cal = Calendar.getInstance(Locale.US);
try {
cal.getWeekendTransition(Calendar.WEEKEND_ONSET);
fail("expected IllegalArgumentException from getWeekendTransition");
}
catch (IllegalArgumentException e) {
// ok
}
}
/*
* Test method for 'com.ibm.icu.util.Calendar.isWeekend(Date)'
*/
public void testIsWeekendDate() {
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
assertTrue(cal.isWeekend(cal.getTime()));
cal.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
assertFalse(cal.isWeekend(cal.getTime()));
}
/*
* Test method for 'com.ibm.icu.util.Calendar.isWeekend()'
*/
public void testIsWeekend() {
Calendar cal = Calendar.getInstance(Locale.US);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
assertTrue(cal.isWeekend());
cal.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
assertFalse(cal.isWeekend());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.clone()'
*/
public void testClone() {
// tested by testHashCode
}
/*
* Test method for 'com.ibm.icu.util.Calendar.toString()'
*/
public void testToString() {
Calendar cal = Calendar.getInstance();
assertNotNull(cal.toString());
}
/*
* Test method for 'com.ibm.icu.util.Calendar.getType()'
*/
public void testGetType() {
Calendar cal = Calendar.getInstance(Locale.US);
assertEquals("gregorian", cal.getType());
}
}

View file

@ -0,0 +1,102 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import com.ibm.icu.text.CollationKey;
import com.ibm.icu.text.Collator;
public class CollationKeyTest extends ICUTestCase {
/*
* Test method for 'com.ibm.icu.text.CollationKey.hashCode()'
*/
public void testHashCode() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey("This");
CollationKey k2 = c.getCollationKey("this");
c.setStrength(Collator.TERTIARY);
CollationKey kn = c.getCollationKey("this");
testEHCS(k1, k2, kn);
}
/*
* Test method for 'com.ibm.icu.text.CollationKey.CollationKey(CollationKey)'
*/
public void testCollationKey() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.CollationKey.compareTo(CollationKey)'
*/
public void testCompareToCollationKey() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey("This");
CollationKey k2 = c.getCollationKey("this");
c.setStrength(Collator.TERTIARY);
CollationKey k3 = c.getCollationKey("this");
assertTrue(0 == k1.compareTo(k2));
assertFalse(0 == k1.compareTo(k3));
}
/*
* Test method for 'com.ibm.icu.text.CollationKey.compareTo(Object)'
*/
public void testCompareToObject() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey("This");
CollationKey k2 = c.getCollationKey("this");
assertTrue(0 == k1.compareTo((Object)k2));
}
/*
* Test method for 'com.ibm.icu.text.CollationKey.equals(Object)'
*/
public void testEqualsObject() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey("This");
CollationKey k2 = c.getCollationKey("this");
assertTrue(k1.equals((Object)k2));
}
/*
* Test method for 'com.ibm.icu.text.CollationKey.toString()'
*/
public void testToString() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey("This");
assertNotNull(k1.toString());
}
/*
* Test method for 'com.ibm.icu.text.CollationKey.getSourceString()'
*/
public void testGetSourceString() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey("This");
assertEquals("This", k1.getSourceString());
}
/*
* Test method for 'com.ibm.icu.text.CollationKey.toByteArray()'
*/
public void testToByteArray() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey("This");
byte[] key = k1.toByteArray();
assertNotNull(key);
assertTrue(0 < key.length);
}
}

View file

@ -0,0 +1,205 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.util.Locale;
import com.ibm.icu.text.CollationKey;
import com.ibm.icu.text.Collator;
import com.ibm.icu.util.ULocale;
public class CollatorTest extends ICUTestCase {
private static final String s1 = "Fu\u0308nf"; // capital F + u + diaresis
private static final String s2 = "fu\u0308nf"; // u + diaresis
private static final String s3 = "f\u00fcnf"; // u-umlaut
private static final String s4 = "fu\u0308\u0316nf"; // u + diaresis above + grave below
private static final String s5 = "fu\u0316\u0308nf"; // u + grave below + diaresis above
/*
* Test method for 'com.ibm.icu.text.Collator.hashCode()'
*/
public void testHashCode() {
Collator c = Collator.getInstance();
c.setStrength(Collator.SECONDARY);
Collator c2 = Collator.getInstance();
c2.setStrength(Collator.SECONDARY);
Collator cn = Collator.getInstance();
cn.setStrength(Collator.TERTIARY);
testEHCS(c, c2, cn);
}
/*
* Test method for 'com.ibm.icu.text.Collator.Collator(Collator)'
*/
public void testCollator() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.Collator.setStrength(int)'
*/
public void testSetStrength() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
assertTrue(0 == c.compare(s1, s2));
c.setStrength(Collator.SECONDARY);
assertTrue(0 == c.compare(s1, s2));
c.setStrength(Collator.TERTIARY);
assertTrue(0 < c.compare(s1, s2));
assertTrue(0 == c.compare(s2, s3));
c.setStrength(Collator.QUATERNARY);
assertTrue(0 > c.compare(s2, s3));
}
/*
* Test method for 'com.ibm.icu.text.Collator.setDecomposition(int)'
*/
public void testSetDecomposition() {
Collator c = Collator.getInstance();
c.setStrength(Collator.TERTIARY);
assertTrue(0 != c.compare(s4, s5));
c.setDecomposition(Collator.IDENTICAL);
assertTrue(0 == c.compare(s4, s5));
}
/*
* Test method for 'com.ibm.icu.text.Collator.getInstance()'
*/
public void testGetInstance() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.Collator.getInstance(ULocale)'
*/
public void testGetInstanceULocale() {
Collator c = Collator.getInstance(ULocale.GERMANY);
assertNotNull(c);
}
/*
* Test method for 'com.ibm.icu.text.Collator.getInstance(Locale)'
*/
public void testGetInstanceLocale() {
Collator c = Collator.getInstance(Locale.GERMANY);
assertNotNull(c);
}
/*
* Test method for 'com.ibm.icu.text.Collator.getAvailableLocales()'
*/
public void testGetAvailableLocales() {
assertNotNull(Collator.getAvailableLocales());
}
/*
* Test method for 'com.ibm.icu.text.Collator.getAvailableULocales()'
*/
public void testGetAvailableULocales() {
assertNotNull(Collator.getAvailableULocales());
}
/*
* Test method for 'com.ibm.icu.text.Collator.getKeywords()'
*/
public void testGetKeywords() {
assertEquals(0, Collator.getKeywords().length);
}
/*
* Test method for 'com.ibm.icu.text.Collator.getKeywordValues(String)'
*/
public void testGetKeywordValues() {
assertEquals(0, Collator.getKeywordValues("").length);
}
/*
* Test method for 'com.ibm.icu.text.Collator.getStrength()'
*/
public void testGetStrength() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
assertEquals(Collator.PRIMARY, c.getStrength());
c.setStrength(Collator.SECONDARY);
assertEquals(Collator.SECONDARY, c.getStrength());
}
/*
* Test method for 'com.ibm.icu.text.Collator.getDecomposition()'
*/
public void testGetDecomposition() {
Collator c = Collator.getInstance();
c.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
assertEquals(Collator.CANONICAL_DECOMPOSITION, c.getDecomposition());
c.setDecomposition(Collator.NO_DECOMPOSITION);
assertEquals(Collator.NO_DECOMPOSITION, c.getDecomposition());
}
/*
* Test method for 'com.ibm.icu.text.Collator.compare(Object, Object)'
*/
public void testCompareObjectObject() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
assertTrue(0 == c.compare((Object)s1, (Object)s2));
}
/*
* Test method for 'com.ibm.icu.text.Collator.equals(String, String)'
*/
public void testEqualsStringString() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
assertTrue(c.equals(s1, s2));
}
/*
* Test method for 'com.ibm.icu.text.Collator.compare(String, String)'
*/
public void testCompareStringString() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
assertTrue(0 == c.compare(s1, s2));
}
/*
* Test method for 'com.ibm.icu.text.Collator.getCollationKey(String)'
*/
public void testGetCollationKey() {
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
CollationKey k1 = c.getCollationKey(s1);
CollationKey k2 = c.getCollationKey(s2);
assertTrue(k1.equals(k2));
c.setStrength(Collator.TERTIARY);
k1 = c.getCollationKey(s1);
k2 = c.getCollationKey(s2);
assertFalse(k1.equals(k2));
}
/*
* Test method for 'com.ibm.icu.text.Collator.toString()'
*/
public void testToString() {
assertNotNull(Collator.getInstance().toString());
}
/*
* Test method for 'com.ibm.icu.text.Collator.clone()'
*/
public void testClone() {
// tested above
}
/*
* Test method for 'com.ibm.icu.text.Collator.equals(Object)'
*/
public void testEqualsObject() {
// tested above
}
}

View file

@ -0,0 +1,257 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.util.Locale;
import com.ibm.icu.text.DateFormatSymbols;
import com.ibm.icu.util.ULocale;
public class DateFormatSymbolsTest extends ICUTestCase {
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.hashCode()'
*/
public void testHashCode() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
DateFormatSymbols dfs2 = new DateFormatSymbols(ULocale.US);
DateFormatSymbols dfsn = new DateFormatSymbols(Locale.US);
dfsn.setAmPmStrings(new String[] { "sw", "xw" });
testEHCS(dfs, dfs2, dfsn);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.DateFormatSymbols(DateFormatSymbols)'
*/
public void testDateFormatSymbolsDateFormatSymbols() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.DateFormatSymbols()'
*/
public void testDateFormatSymbols() {
DateFormatSymbols dfs = new DateFormatSymbols();
assertNotNull(dfs.getWeekdays());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.DateFormatSymbols(Locale)'
*/
public void testDateFormatSymbolsLocale() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getWeekdays());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.DateFormatSymbols(ULocale)'
*/
public void testDateFormatSymbolsULocale() {
DateFormatSymbols dfs = new DateFormatSymbols(ULocale.US);
assertNotNull(dfs.getWeekdays());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getEras()'
*/
public void testGetEras() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getEras());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setEras(String[])'
*/
public void testSetEras() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[] oldvalue = dfs.getEras();
String[] newvalue = (String[])oldvalue.clone();
newvalue[0] = newvalue[0] + "!";
dfs.setEras(newvalue);
String[] result = dfs.getEras();
assertArraysNotEqual(oldvalue, result);
assertArraysEqual(newvalue, result);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getMonths()'
*/
public void testGetMonths() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getMonths());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setMonths(String[])'
*/
public void testSetMonths() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[] oldvalue = dfs.getMonths();
String[] newvalue = (String[])oldvalue.clone();
newvalue[0] = newvalue[0] + "!";
dfs.setMonths(newvalue);
String[] result = dfs.getMonths();
assertArraysNotEqual(oldvalue, result);
assertArraysEqual(newvalue, result);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getShortMonths()'
*/
public void testGetShortMonths() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getShortMonths());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setShortMonths(String[])'
*/
public void testSetShortMonths() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[] oldvalue = dfs.getShortMonths();
String[] newvalue = (String[])oldvalue.clone();
newvalue[0] = newvalue[0] + "!";
dfs.setShortMonths(newvalue);
String[] result = dfs.getShortMonths();
assertArraysNotEqual(oldvalue, result);
assertArraysEqual(newvalue, result);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getWeekdays()'
*/
public void testGetWeekdays() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getShortMonths());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setWeekdays(String[])'
*/
public void testSetWeekdays() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[] oldvalue = dfs.getWeekdays();
String[] newvalue = (String[])oldvalue.clone();
newvalue[0] = newvalue[0] + "!";
dfs.setWeekdays(newvalue);
String[] result = dfs.getWeekdays();
assertArraysNotEqual(oldvalue, result);
assertArraysEqual(newvalue, result);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getShortWeekdays()'
*/
public void testGetShortWeekdays() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getShortWeekdays());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setShortWeekdays(String[])'
*/
public void testSetShortWeekdays() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[] oldvalue = dfs.getShortWeekdays();
String[] newvalue = (String[])oldvalue.clone();
newvalue[0] = newvalue[0] + "!";
dfs.setShortWeekdays(newvalue);
String[] result = dfs.getShortWeekdays();
assertArraysNotEqual(oldvalue, result);
assertArraysEqual(newvalue, result);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getAmPmStrings()'
*/
public void testGetAmPmStrings() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getAmPmStrings());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setAmPmStrings(String[])'
*/
public void testSetAmPmStrings() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[] oldvalue = dfs.getAmPmStrings();
String[] newvalue = (String[])oldvalue.clone();
newvalue[0] = newvalue[0] + "!";
dfs.setAmPmStrings(newvalue);
String[] result = dfs.getAmPmStrings();
assertArraysNotEqual(oldvalue, result);
assertArraysEqual(newvalue, result);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getZoneStrings()'
*/
public void testGetZoneStrings() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getZoneStrings());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setZoneStrings(String[][])'
*/
public void testSetZoneStrings() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[][] oldvalue = dfs.getZoneStrings();
String[][] newvalue = (String[][])cloneComplex(oldvalue);
newvalue[0][0] = newvalue[0][0] + "!";
dfs.setZoneStrings(newvalue);
String[][] result = dfs.getZoneStrings();
assertArraysNotEqual(oldvalue, result);
assertArraysEqual(newvalue, result);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.getLocalPatternChars()'
*/
public void testGetLocalPatternChars() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.getLocalPatternChars());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.setLocalPatternChars(String)'
*/
public void testSetLocalPatternChars() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String pat = dfs.getLocalPatternChars();
StringBuffer buf = new StringBuffer(pat);
buf.setCharAt(0, (char)(pat.charAt(0) + 1));
String pat2 = buf.toString();
dfs.setLocalPatternChars(pat2);
String pat3 = dfs.getLocalPatternChars();
assertNotEqual(pat, pat2);
assertEquals(pat2, pat3);
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.toString()'
*/
public void testToString() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
assertNotNull(dfs.toString());
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.clone()'
*/
public void testClone() {
// tested by testHashCode
}
/*
* Test method for 'com.ibm.icu.text.DateFormatSymbols.equals(Object)'
*/
public void testEqualsObject() {
// tested by testHashCode
}
}

View file

@ -0,0 +1,443 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;
public class DateFormatTest extends ICUTestCase {
private Calendar aCal;
private Calendar anESTCal;
private Date aDate;
private String aDateString;
private String aTimeString;
private String anESTTimeString;
private String aDateTimeString;
private String aShortDateTimeString;
private String aDefaultESTDateTimeString;
private DateFormat aDF;
private StringBuffer aBuf;
private FieldPosition anFP;
protected void setUp() throws Exception {
super.setUp();
java.util.GregorianCalendar gcal = new java.util.GregorianCalendar();
gcal.clear();
gcal.set(java.util.GregorianCalendar.YEAR, 1990);
gcal.set(java.util.GregorianCalendar.MONTH, java.util.GregorianCalendar.DECEMBER);
gcal.set(java.util.GregorianCalendar.DATE, 17);
gcal.set(java.util.GregorianCalendar.HOUR, 5);
gcal.set(java.util.GregorianCalendar.MINUTE, 17);
aCal = new Calendar(gcal);
anESTCal = Calendar.getInstance();
anESTCal.setTimeZone(TimeZone.getTimeZone("EST"));
aDate = gcal.getTime();
aDateString = "Dec 17, 1990"; // medium -- the default
aTimeString = "5:17:00 AM"; // medium
anESTTimeString = "8:17:00 AM";
aDateTimeString = "Dec 17, 1990 5:17:00 AM"; // medium, medium
aDefaultESTDateTimeString = "Dec 17, 1990 8:17 AM"; // medium, short -- the default
aShortDateTimeString = "12/17/90 5:17 AM"; // short, short
aDF = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US);
aBuf = new StringBuffer();
anFP = new FieldPosition(0);
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.hashCode()'
*/
public final void testHashCode() {
DateFormat df = DateFormat.getInstance();
DateFormat eq = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
testEHCS(df, eq, aDF);
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.DateFormat(DateFormat)'
*/
public final void testDateFormat() {
DateFormat df = new DateFormat(java.text.DateFormat.getInstance());
assertEquals(DateFormat.getInstance(), df);
}
private void assertEqualDateString(StringBuffer buf) {
assertEquals(aDateTimeString, buf.toString());
}
private void assertEqualDateString(String str) {
assertEquals(aDateTimeString, str);
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.format(Object, StringBuffer, FieldPosition)'
*/
public final void testFormatObjectStringBufferFieldPosition() {
assertEqualDateString(aDF.format(aDate, aBuf, anFP));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.format(Calendar, StringBuffer, FieldPosition)'
*/
public final void testFormatCalendarStringBufferFieldPosition() {
assertEqualDateString(aDF.format(aCal, aBuf, anFP));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.format(Date, StringBuffer, FieldPosition)'
*/
public final void testFormatDateStringBufferFieldPosition() {
assertEqualDateString(aDF.format(aDate, aBuf, anFP));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.format(Date)'
*/
public final void testFormatDate() {
assertEqualDateString(aDF.format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.parse(String)'
*/
public final void testParseString() throws Exception {
assertEquals(aDate, aDF.parse(aDateTimeString));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.parse(String, Calendar, ParsePosition)'
*/
public final void testParseStringCalendarParsePosition() {
aDF.parse(aDateTimeString, aCal, new ParsePosition(0));
assertEquals(aDate, aCal.getTime());
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.parse(String, ParsePosition)'
*/
public final void testParseStringParsePosition() {
assertEquals(aDate, aDF.parse(aDateTimeString, new ParsePosition(0)));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.parseObject(String, ParsePosition)'
*/
public final void testParseObjectStringParsePosition() {
assertEquals(aDate, aDF.parseObject(aDateTimeString, new ParsePosition(0)));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeInstance()'
*/
public final void testGetTimeInstance() {
assertEquals(aTimeString, DateFormat.getTimeInstance().format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeInstance(int)'
*/
public final void testGetTimeInstanceInt() {
assertEquals(aTimeString, DateFormat.getTimeInstance(DateFormat.MEDIUM).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeInstance(int, Locale)'
*/
public final void testGetTimeInstanceIntLocale() {
assertEquals(aTimeString, DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeInstance(int, ULocale)'
*/
public final void testGetTimeInstanceIntULocale() {
assertEquals(aTimeString, DateFormat.getTimeInstance(DateFormat.MEDIUM, ULocale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateInstance()'
*/
public final void testGetDateInstance() {
assertEquals(aDateString, DateFormat.getDateInstance().format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateInstance(int)'
*/
public final void testGetDateInstanceInt() {
assertEquals(aDateString, DateFormat.getDateInstance(DateFormat.MEDIUM).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateInstance(int, Locale)'
*/
public final void testGetDateInstanceIntLocale() {
assertEquals(aDateString, DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateInstance(int, ULocale)'
*/
public final void testGetDateInstanceIntULocale() {
assertEquals(aDateString, DateFormat.getDateInstance(DateFormat.MEDIUM, ULocale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateTimeInstance()'
*/
public final void testGetDateTimeInstance() {
assertEquals(aDateTimeString, DateFormat.getDateTimeInstance().format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateTimeInstance(int, int)'
*/
public final void testGetDateTimeInstanceIntInt() {
assertEquals(aDateTimeString,
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.MEDIUM).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateTimeInstance(int, int, Locale)'
*/
public final void testGetDateTimeInstanceIntIntLocale() {
assertEquals(aDateTimeString,
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateTimeInstance(int, int, ULocale)'
*/
public final void testGetDateTimeInstanceIntIntULocale() {
assertEquals(aDateTimeString,
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.MEDIUM, ULocale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getInstance()'
*/
public final void testGetInstance() {
assertEquals(aShortDateTimeString, DateFormat.getInstance().format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getAvailableLocales()'
*/
public final void testGetAvailableLocales() {
Locale[] locales = DateFormat.getAvailableLocales();
if (ICUTestCase.testingWrapper) {
ICUTestCase.assertArraysEqual(java.text.DateFormat.getAvailableLocales(), locales);
} else {
assertNotNull(locales);
}
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.setCalendar(Calendar)'
*/
public final void testSetCalendar() {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("EST"));
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
df.setCalendar(cal);
assertEquals("8:17 AM", df.format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getCalendar()'
*/
public final void testGetCalendar() {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("EST"));
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
df.setCalendar(cal);
assertEquals(cal, df.getCalendar());
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.setNumberFormat(NumberFormat)'
*/
public final void testSetNumberFormat() {
// no easy way to test effect of setting the number format
NumberFormat nf = NumberFormat.getInstance();
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
df.setNumberFormat(nf);
// note, can't actually USE the dateformat since it changes the calendar
assertEquals(nf, df.getNumberFormat());
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getNumberFormat()'
*/
public final void testGetNumberFormat() {
// see testSetNumberFormat
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.setTimeZone(TimeZone)'
*/
public final void testSetTimeZone() {
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
TimeZone tz = TimeZone.getTimeZone("EST");
df.setTimeZone(tz);
assertEquals("8:17 AM", df.format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeZone()'
*/
public final void testGetTimeZone() {
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
TimeZone tz = TimeZone.getTimeZone("EST");
df.setTimeZone(tz);
assertEquals(tz, df.getTimeZone());
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.setLenient(boolean)'
*/
public final void testSetLenient() throws Exception {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
df.parse("2/31/90"); // succeeds, default is lenient
df.setLenient(false);
try {
df.parse("2/31/90");
throw new Exception("strict parse should have failed");
}
catch (ParseException e) {
// ok, this is what we expect
}
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.isLenient()'
*/
public final void testIsLenient() {
DateFormat df = DateFormat.getInstance();
assertTrue(df.isLenient());
df.setLenient(false);
assertFalse(df.isLenient());
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateInstance(Calendar, int, Locale)'
*/
public final void testGetDateInstanceCalendarIntLocale() {
assertEquals(aDateString, DateFormat.getDateInstance(aCal, DateFormat.MEDIUM, Locale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateInstance(Calendar, int, ULocale)'
*/
public final void testGetDateInstanceCalendarIntULocale() {
assertEquals(aDateString, DateFormat.getDateInstance(aCal, DateFormat.MEDIUM, ULocale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeInstance(Calendar, int, Locale)'
*/
public final void testGetTimeInstanceCalendarIntLocale() {
assertEquals(anESTTimeString, DateFormat.getTimeInstance(anESTCal, DateFormat.MEDIUM, Locale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeInstance(Calendar, int, ULocale)'
*/
public final void testGetTimeInstanceCalendarIntULocale() {
assertEquals(anESTTimeString, DateFormat.getTimeInstance(anESTCal, DateFormat.MEDIUM, ULocale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateTimeInstance(Calendar, int, int, Locale)'
*/
public final void testGetDateTimeInstanceCalendarIntIntLocale() {
assertEquals(aDefaultESTDateTimeString, DateFormat.getDateTimeInstance(anESTCal, DateFormat.MEDIUM, DateFormat.SHORT, Locale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateTimeInstance(Calendar, int, int, ULocale)'
*/
public final void testGetDateTimeInstanceCalendarIntIntULocale() {
assertEquals(aDefaultESTDateTimeString, DateFormat.getDateTimeInstance(anESTCal, DateFormat.MEDIUM, DateFormat.SHORT, ULocale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getInstance(Calendar, Locale)'
*/
public final void testGetInstanceCalendarLocale() {
assertEquals(aDefaultESTDateTimeString, DateFormat.getInstance(anESTCal, Locale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getInstance(Calendar, ULocale)'
*/
public final void testGetInstanceCalendarULocale() {
assertEquals(aDefaultESTDateTimeString, DateFormat.getInstance(anESTCal, ULocale.US).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getInstance(Calendar)'
*/
public final void testGetInstanceCalendar() {
assertEquals(aDefaultESTDateTimeString, DateFormat.getInstance(anESTCal).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateInstance(Calendar, int)'
*/
public final void testGetDateInstanceCalendarInt() {
assertEquals(aDateString, DateFormat.getDateInstance(aCal, DateFormat.MEDIUM).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getTimeInstance(Calendar, int)'
*/
public final void testGetTimeInstanceCalendarInt() {
assertEquals(anESTTimeString, DateFormat.getTimeInstance(anESTCal, DateFormat.MEDIUM).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.getDateTimeInstance(Calendar, int, int)'
*/
public final void testGetDateTimeInstanceCalendarIntInt() {
assertEquals(aDefaultESTDateTimeString, DateFormat.getDateTimeInstance(anESTCal, DateFormat.MEDIUM, DateFormat.SHORT).format(aDate));
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.toString()'
*/
public final void testToString() {
assertNotNull(aDF.toString());
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.clone()'
*/
public final void testClone() {
// see testHashCode
}
/*
* Test method for 'com.ibm.icu.text.DateFormat.equals(Object)'
*/
public final void testEqualsObject() {
// see testHashCode
}
}

View file

@ -0,0 +1,344 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.util.Locale;
import com.ibm.icu.text.DecimalFormatSymbols;
import com.ibm.icu.util.ULocale;
public class DecimalFormatSymbolsTest extends ICUTestCase {
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.hashCode()'
*/
public void testHashCode() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
DecimalFormatSymbols dfs2 = new DecimalFormatSymbols(ULocale.US);
DecimalFormatSymbols dfsn = new DecimalFormatSymbols(Locale.FRANCE);
testEHCS(dfs, dfs2, dfsn);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.DecimalFormatSymbols(DecimalFormatSymbols)'
*/
public void testDecimalFormatSymbolsDecimalFormatSymbols() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.DecimalFormatSymbols()'
*/
public void testDecimalFormatSymbols() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
assertTrue(-1 != dfs.getDecimalSeparator());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.DecimalFormatSymbols(Locale)'
*/
public void testDecimalFormatSymbolsLocale() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
assertTrue(-1 != dfs.getDecimalSeparator());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.DecimalFormatSymbols(ULocale)'
*/
public void testDecimalFormatSymbolsULocale() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertTrue(-1 != dfs.getDecimalSeparator());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getZeroDigit()'
*/
public void testGetZeroDigit() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals('0', dfs.getZeroDigit());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setZeroDigit(char)'
*/
public void testSetZeroDigit() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getZeroDigit();
char value1 = (char)(value + 1);
dfs.setZeroDigit(value1);
char result = dfs.getZeroDigit();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getGroupingSeparator()'
*/
public void testGetGroupingSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals(',', dfs.getGroupingSeparator());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setGroupingSeparator(char)'
*/
public void testSetGroupingSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getGroupingSeparator();
char value1 = (char)(value + 1);
dfs.setGroupingSeparator(value1);
char result = dfs.getGroupingSeparator();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getDecimalSeparator()'
*/
public void testGetDecimalSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals('.', dfs.getDecimalSeparator());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setDecimalSeparator(char)'
*/
public void testSetDecimalSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getDecimalSeparator();
char value1 = (char)(value + 1);
dfs.setDecimalSeparator(value1);
char result = dfs.getDecimalSeparator();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getPerMill()'
*/
public void testGetPerMill() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals('\u2030', dfs.getPerMill());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setPerMill(char)'
*/
public void testSetPerMill() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getPerMill();
char value1 = (char)(value + 1);
dfs.setPerMill(value1);
char result = dfs.getPerMill();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getPercent()'
*/
public void testGetPercent() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals('%', dfs.getPercent());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setPercent(char)'
*/
public void testSetPercent() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getPercent();
char value1 = (char)(value + 1);
dfs.setPercent(value1);
char result = dfs.getPercent();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getDigit()'
*/
public void testGetDigit() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals('#', dfs.getDigit());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setDigit(char)'
*/
public void testSetDigit() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getDigit();
char value1 = (char)(value + 1);
dfs.setDigit(value1);
char result = dfs.getDigit();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getPatternSeparator()'
*/
public void testGetPatternSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals(';', dfs.getPatternSeparator());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setPatternSeparator(char)'
*/
public void testSetPatternSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getPatternSeparator();
char value1 = (char)(value + 1);
dfs.setPatternSeparator(value1);
char result = dfs.getPatternSeparator();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getInfinity()'
*/
public void testGetInfinity() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals("\u221e", dfs.getInfinity());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setInfinity(String)'
*/
public void testSetInfinity() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
String value = dfs.getInfinity();
String value1 = value + "!";
dfs.setInfinity(value1);
String result = dfs.getInfinity();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getNaN()'
*/
public void testGetNaN() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertNotNull(dfs.getNaN()); // java returns missing character???
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setNaN(String)'
*/
public void testSetNaN() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
String value = dfs.getNaN();
String value1 = value + "!";
dfs.setNaN(value1);
String result = dfs.getNaN();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getMinusSign()'
*/
public void testGetMinusSign() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals('-', dfs.getMinusSign());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setMinusSign(char)'
*/
public void testSetMinusSign() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getMinusSign();
char value1 = (char)(value + 1);
dfs.setMinusSign(value1);
char result = dfs.getMinusSign();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getCurrencySymbol()'
*/
public void testGetCurrencySymbol() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals("$", dfs.getCurrencySymbol());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setCurrencySymbol(String)'
*/
public void testSetCurrencySymbol() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
String value = dfs.getCurrencySymbol();
String value1 = value + "!";
dfs.setCurrencySymbol(value1);
String result = dfs.getCurrencySymbol();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getInternationalCurrencySymbol()'
*/
public void testGetInternationalCurrencySymbol() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals("USD", dfs.getInternationalCurrencySymbol());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setInternationalCurrencySymbol(String)'
*/
public void testSetInternationalCurrencySymbol() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
String value = dfs.getInternationalCurrencySymbol();
String value1 = value + "!";
dfs.setInternationalCurrencySymbol(value1);
String result = dfs.getInternationalCurrencySymbol();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.getMonetaryDecimalSeparator()'
*/
public void testGetMonetaryDecimalSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
assertEquals('.', dfs.getMonetaryDecimalSeparator());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.setMonetaryDecimalSeparator(char)'
*/
public void testSetMonetaryDecimalSeparator() {
DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.US);
char value = dfs.getMonetaryDecimalSeparator();
char value1 = (char)(value + 1);
dfs.setMonetaryDecimalSeparator(value1);
char result = dfs.getMonetaryDecimalSeparator();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.clone()'
*/
public void testClone() {
// tested in testHashcode
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormatSymbols.equals(Object)'
*/
public void testEqualsObject() {
// tested in testHashcode
}
}

View file

@ -0,0 +1,242 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.util.Locale;
import com.ibm.icu.text.DecimalFormat;
import com.ibm.icu.text.DecimalFormatSymbols;
public class DecimalFormatTest extends ICUTestCase {
private static final long lmax = Long.MAX_VALUE;
private static final double dsmall = 23.33;
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.clone()'
*/
public void testClone() {
DecimalFormat df = new DecimalFormat("#,#0.00");
DecimalFormat df2 = new DecimalFormat("#,#0.00");
DecimalFormat dfn = new DecimalFormat("#,#0.00");
dfn.setNegativePrefix(dfn.getNegativePrefix() + '!');
testEHCS(df, df2, dfn);
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.DecimalFormat(DecimalFormat)'
*/
public void testDecimalFormatDecimalFormat() {
// tested implicitly
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.DecimalFormat()'
*/
public void testDecimalFormat() {
DecimalFormat df = new DecimalFormat();
assertEquals("9,223,372,036,854,775,807", df.format(lmax));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.DecimalFormat(String)'
*/
public void testDecimalFormatString() {
DecimalFormat df = new DecimalFormat("#,##0.000");
assertEquals("23.330", df.format(dsmall));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.DecimalFormat(String, DecimalFormatSymbols)'
*/
public void testDecimalFormatStringDecimalFormatSymbols() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.FRANCE);
DecimalFormat df = new DecimalFormat("#,##0.000", sym);
assertEquals("23,330", df.format(dsmall));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.getDecimalFormatSymbols()'
*/
public void testGetDecimalFormatSymbols() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.FRANCE);
DecimalFormat df = new DecimalFormat("#,##0.000", sym);
assertEquals(sym, df.getDecimalFormatSymbols());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setDecimalFormatSymbols(DecimalFormatSymbols)'
*/
public void testSetDecimalFormatSymbols() {
DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.FRANCE));
assertEquals("23,33", df.format(dsmall));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.getPositivePrefix()'
*/
public void testGetPositivePrefix() {
DecimalFormat df = new DecimalFormat("+#,##0.#;-#,##0.#");
assertEquals("+", df.getPositivePrefix());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setPositivePrefix(String)'
*/
public void testSetPositivePrefix() {
DecimalFormat df = new DecimalFormat("+#,##0.#;-#,##0.#");
df.setPositivePrefix("?");
assertEquals("?23.3", df.format(dsmall));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.getNegativePrefix()'
*/
public void testGetNegativePrefix() {
DecimalFormat df = new DecimalFormat("+#,##0.#;-#,##0.#");
assertEquals("-", df.getNegativePrefix());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setNegativePrefix(String)'
*/
public void testSetNegativePrefix() {
DecimalFormat df = new DecimalFormat("+#,##0.#;-#,##0.#");
df.setNegativePrefix("~");
assertEquals("~23.3", df.format(-dsmall));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.getPositiveSuffix()'
*/
public void testGetPositiveSuffix() {
DecimalFormat df = new DecimalFormat("+#,##0.#**;-#,##0.#~~");
assertEquals("**", df.getPositiveSuffix());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setPositiveSuffix(String)'
*/
public void testSetPositiveSuffix() {
DecimalFormat df = new DecimalFormat("+#,##0.#;-#,##0.#");
df.setPositiveSuffix("**");
assertEquals("+23.3**", df.format(dsmall));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.getNegativeSuffix()'
*/
public void testGetNegativeSuffix() {
DecimalFormat df = new DecimalFormat("+#,##0.#**;-#,##0.#~~");
assertEquals("~~", df.getNegativeSuffix());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setNegativeSuffix(String)'
*/
public void testSetNegativeSuffix() {
DecimalFormat df = new DecimalFormat("+#,##0.#;-#,##0.#");
df.setNegativeSuffix("~~");
assertEquals("-23.3~~", df.format(-dsmall));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.getMultiplier()'
*/
public void testGetMultiplier() {
DecimalFormat df = new DecimalFormat("%000");
df.setMultiplier(1000);
assertEquals(1000, df.getMultiplier());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setMultiplier(int)'
*/
public void testSetMultiplier() {
DecimalFormat df = new DecimalFormat("%000");
assertEquals("%012", df.format(.123));
df.setMultiplier(1000);
assertEquals("%123", df.format(.123));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.getGroupingSize()'
*/
public void testGetGroupingSize() {
DecimalFormat df = new DecimalFormat("#,#0.#");
assertEquals(2, df.getGroupingSize());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setGroupingSize(int)'
*/
public void testSetGroupingSize() {
DecimalFormat df = new DecimalFormat("#,##0.##");
assertEquals("1,234,567.89", df.format(1234567.89));
df.setGroupingSize(2);
assertEquals("1,23,45,67.89", df.format(1234567.89));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.isDecimalSeparatorAlwaysShown()'
*/
public void testIsDecimalSeparatorAlwaysShown() {
DecimalFormat df = new DecimalFormat("#.#");
df.setDecimalSeparatorAlwaysShown(false);
assertEquals("1", df.format(1));
assertEquals("1.2", df.format(1.2));
df.setDecimalSeparatorAlwaysShown(true);
assertEquals("1.", df.format(1));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.setDecimalSeparatorAlwaysShown(boolean)'
*/
public void testSetDecimalSeparatorAlwaysShown() {
DecimalFormat df = new DecimalFormat("#.#");
df.setDecimalSeparatorAlwaysShown(false);
assertFalse(df.isDecimalSeparatorAlwaysShown());
df.setDecimalSeparatorAlwaysShown(true);
assertTrue(df.isDecimalSeparatorAlwaysShown());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.toPattern()'
*/
public void testToPattern() {
DecimalFormat df = new DecimalFormat("#,##0.##");
assertEquals("#,##0.##", df.toPattern());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.toLocalizedPattern()'
*/
public void testToLocalizedPattern() {
DecimalFormat df = new DecimalFormat("#,##0.##", new DecimalFormatSymbols(Locale.FRANCE));
assertEquals("#,##0.##", df.toPattern());
assertEquals("#\u00a0##0,##", df.toLocalizedPattern());
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.applyPattern(String)'
*/
public void testApplyPattern() {
DecimalFormat df = new DecimalFormat("#,##0.##");
df.applyPattern("#,0.#");
assertEquals("1,2,3.4", df.format(123.4));
}
/*
* Test method for 'com.ibm.icu.text.DecimalFormat.applyLocalizedPattern(String)'
*/
public void testApplyLocalizedPattern() {
DecimalFormat df = new DecimalFormat("#,##0.##", new DecimalFormatSymbols(Locale.FRANCE));
df.applyLocalizedPattern("#\u00a00,#");
assertEquals("1\u00a02\u00a03,4", df.format(123.4));
}
}

View file

@ -0,0 +1,286 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;
import junit.framework.TestCase;
/**
* Implement boilerplate tests.
* Currently there is only one method, testEHCS, which tests equals, hashCode,
* clone, and serialization.
*/
public abstract class ICUTestCase extends TestCase {
private static final Object[] EMPTY_ARGS = {};
private static final Class[] EMPTY_CLASSES = {};
private static final Locale oldLocale = Locale.getDefault();
private static final ULocale oldULocale = ULocale.getDefault();
private static final java.util.TimeZone oldJTimeZone = java.util.TimeZone.getDefault();
private static final TimeZone oldITimeZone = TimeZone.getDefault();
// TODO: what's the best way to check this?
public static final boolean testingWrapper = true;
protected void setUp() throws Exception {
super.setUp();
Locale.setDefault(Locale.US);
ULocale.setDefault(ULocale.US);
java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("PST"));
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
}
protected void tearDown() throws Exception {
ULocale.setDefault(oldULocale);
Locale.setDefault(oldLocale);
TimeZone.setDefault(oldITimeZone);
java.util.TimeZone.setDefault(oldJTimeZone);
super.tearDown();
}
private static final Object test = new Object();
/**
* Assert that two objects are _not_ equal. Curiously missing from Assert.
* @param lhs an object to test, may be null
* @param rhs an object to test, may be null
*/
public static void assertNotEqual(Object lhs, Object rhs) {
if (lhs == null) {
if (rhs == null) fail("null equals null");
} else {
if (lhs.equals(rhs)) {
fail(lhs.toString() + " equals " + rhs);
}
}
}
public static void assertNotEqual(long lhs, long rhs) {
if (lhs == rhs) {
fail("values are equal: " + lhs);
}
}
/**
* Test whether equality, hashCode, clone, and serialization work as expected.
* Equals(Object) is assumed to return false (not throw an exception) if passed
* null or an object of an incompatible class.
* Hashcodes must be equal iff the two objects compare equal. No attempt is made to
* evaluate the quality of the hashcode distribution, so (in particular) degenerate
* hashcode implementations will pass this test.
* Clone will be tested if the method "clone" is public on the class of obj.
* It is assumed to return an object that compares equal to obj.
* Serialization will be tested if object implements Serializable or Externalizable.
* It is assumed the serialized/deserialized object compares equal to obj.
* @param obj the object to test
* @param eq an object that should compare equal to, but is not the same as, obj.
* it should be assignable to the class of obj.
* @param neq a non-null object that should not compare equal to obj.
* it should be assignable to the class of obj.
*/
public static void testEHCS(Object obj, Object eq, Object neq) {
if (obj == null || eq == null || neq == null) {
throw new NullPointerException();
}
Class cls = obj.getClass();
if (!(cls.isAssignableFrom(eq.getClass()) && cls.isAssignableFrom(neq.getClass()))) {
throw new IllegalArgumentException("unassignable classes");
}
// reflexive
assertEquals(obj, obj);
// should return false, not throw exception
assertNotEqual(obj, test);
assertNotEqual(obj, null);
// commutative
assertEquals(obj, eq);
assertEquals(eq, obj);
assertNotEqual(obj, neq);
assertNotEqual(neq, obj);
// equal objects MUST have equal hashes, unequal objects MAY have equal hashes
assertEquals(obj.hashCode(), eq.hashCode());
Object clone = null;
try {
// look for public clone method and call it if available
Method method_clone = cls.getMethod("clone", EMPTY_CLASSES);
clone = method_clone.invoke(obj, EMPTY_ARGS);
assertNotNull(clone);
}
catch(NoSuchMethodException e) {
// ok
}
catch(InvocationTargetException e) {
// ok
}
catch(IllegalAccessException e) {
// ok
}
if (clone != null) {
assertEquals(obj, clone);
assertEquals(clone, obj);
}
if (obj instanceof Serializable || obj instanceof Externalizable) {
Object ser = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(clone);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
ser = ois.readObject();
ois.close();
}
catch(IOException e) {
System.err.println(e.getMessage());
throw new RuntimeException(e);
}
catch(ClassNotFoundException e) {
System.err.println(e.getMessage());
throw new RuntimeException(e);
}
if (ser != null) {
assertEquals(obj, ser);
assertEquals(ser, obj);
assertEquals(obj.hashCode(), ser.hashCode());
}
}
}
/**
* Fail if the arrays are not equal. To be equal, the arrays must
* be the same length, and each element in the left array must compare
* equal to the corresponding element of the right array.
* Also fails if one of the objects is not an array.
* @param lhs the left array
* @param rhs the right array
*/
public static void assertArraysEqual(Object lhs, Object rhs) {
Class lcls = lhs.getClass();
Class rcls = rhs.getClass();
if (!(lcls.isArray() && rcls.isArray())) {
fail("objects are not arrays");
}
String result = arraysAreEqual(lhs, rhs);
if (result != null) {
fail(result);
}
}
/**
* Fail if the arrays are equal. Also fails if one or the other
* argument is not an array.
* @param lhs the left array
* @param rhs the right array
*/
public static void assertArraysNotEqual(Object lhs, Object rhs) {
Class lcls = lhs.getClass();
Class rcls = rhs.getClass();
if (!(lcls.isArray() && rcls.isArray())) {
fail("objects are not arrays");
}
String result = arraysAreEqual(lhs, rhs);
if (result == null) {
fail("arrays are equal");
}
}
// slow but general
private static String arraysAreEqual(Object lhsa, Object rhsa) {
int lhsl = Array.getLength(lhsa);
int rhsl = Array.getLength(rhsa);
if (lhsl != rhsl) {
return "length " + lhsl + " != " + rhsl;
}
boolean lhsaA = lhsa.getClass().getComponentType().isArray();
boolean rhsaA = rhsa.getClass().getComponentType().isArray();
if (lhsaA != rhsaA) {
return (lhsaA ? "" : "non-") + "array != " + (rhsaA ? "" : "non-") + "array";
}
for (int i = 0; i < lhsl; ++i) {
Object lhse = Array.get(lhsa, i);
Object rhse = Array.get(rhsa, i);
if (lhse == null) {
if (rhse != null) {
return "null != " + rhse;
}
} else {
if (lhsaA) {
String result = arraysAreEqual(lhse, rhse);
if (result != null) {
if (result.charAt(0) != '[') {
result = " " + result;
}
return "[" + i + "]" + result;
}
} else {
if (!lhse.equals(rhse)) {
return lhse.toString() + " != " + rhse;
}
}
}
}
return null;
}
// much more painful and slow than it should be... partly because of the
// oddness of clone, partly because arrays don't provide a Method for
// 'clone' despite the fact that they implement it and make it public.
public static Object cloneComplex(Object obj) {
Object result = null;
if (obj != null) {
Class cls = obj.getClass();
if (cls.isArray()) {
int len = Array.getLength(obj);
Class typ = cls.getComponentType();
result = Array.newInstance(typ, len);
boolean prim = typ.isPrimitive();
for (int i = 0; i < len; ++i) {
Object elem = Array.get(obj, i);
Array.set(result, i, prim ? elem : cloneComplex(elem));
}
} else {
result = obj; // default
try {
Method cloneM = cls.getMethod("clone", null);
result = cloneM.invoke(obj, null);
}
catch (NoSuchMethodException e) {
}
catch (IllegalAccessException e) {
}
catch (InvocationTargetException e) {
}
}
}
return result;
}
}

View file

@ -0,0 +1,307 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.MessageFormat;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.util.ULocale;
public class MessageFormatTest extends ICUTestCase {
private final String pattern = "Deleted {0,number} files at {1,time,short} on {1,date}.";
private final String altPattern = "Deleted {0, number } files at {1, time, short} on {1, date}.";
private final Date date = new Date(716698890835L);
private final Number num = new Long(3456);
private final Object[] args = { num, date };
private final Date dateOnly = new Date(716626800000L);
private final String englishTarget = "Deleted 3,456 files at 8:01 PM on Sep 16, 1992.";
private final String germanTarget = "Deleted 3.456 files at 20:01 on 16.09.1992.";
private final String modifiedTarget = "Deleted 3,456 files at 8:01:30 PM PDT on Sep 16, 1992.";
/*
* Test method for 'com.ibm.icu.text.MessageFormat.hashCode()'
*/
public void testHashCode() {
MessageFormat mf = new MessageFormat(pattern);
MessageFormat eq = new MessageFormat(altPattern);
MessageFormat ne = new MessageFormat("Deleted (0, number, currency} files at {1, time} on {1, date}.");
testEHCS(mf, eq, ne);
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.MessageFormat(MessageFormat)'
*/
public void testMessageFormatMessageFormat() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.MessageFormat(String)'
*/
public void testMessageFormatString() {
MessageFormat mf = new MessageFormat(pattern);
assertEquals(englishTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.MessageFormat(String, Locale)'
*/
public void testMessageFormatStringLocale() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
assertEquals(englishTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.MessageFormat(String, ULocale)'
*/
public void testMessageFormatStringULocale() {
MessageFormat mf = new MessageFormat(pattern, ULocale.US);
assertEquals(englishTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.setLocale(Locale)'
*/
public void testSetLocaleLocale() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
mf.setLocale(Locale.GERMANY);
mf.applyPattern(pattern);
assertEquals(germanTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.setLocale(ULocale)'
*/
public void testSetLocaleULocale() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
mf.setLocale(ULocale.GERMANY);
mf.applyPattern(pattern);
assertEquals(germanTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.getLocale()'
*/
public void testGetLocale() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
mf.setLocale(Locale.GERMANY);
assertEquals(Locale.GERMANY, mf.getLocale());
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.getULocale()'
*/
public void testGetULocale() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
mf.setLocale(ULocale.GERMANY);
assertEquals(ULocale.GERMANY, mf.getULocale());
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.applyPattern(String)'
*/
public void testApplyPattern() {
MessageFormat mf = new MessageFormat("foo");
mf.applyPattern(pattern);
assertEquals(englishTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.toPattern()'
*/
public void testToPattern() {
MessageFormat mf = new MessageFormat(altPattern);
assertEquals(pattern, mf.toPattern());
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.setFormatsByArgumentIndex(Format[])'
public void testSetFormatsByArgumentIndex() {
// this api is broken. if the same argument is used twice with two different
// formats, this can't be used, since it sets only one format per argument.
MessageFormat mf = new MessageFormat(pattern, Locale.US);
Format[] formats = {
NumberFormat.getIntegerInstance(),
DateFormat.getTimeInstance(DateFormat.SHORT),
DateFormat.getDateInstance(),
};
mf.setFormatsByArgumentIndex(formats);
assertEquals(brokenButConformantTarget, mf.format(args));
}
*/
/*
* Test method for 'com.ibm.icu.text.MessageFormat.setFormats(Format[])'
*/
public void testSetFormats() {
// this api, while it has the problem that the order of formats depends
// on the order in the string, at least lets you set all the formats.
MessageFormat mf = new MessageFormat(pattern, Locale.US);
Format[] formats = {
NumberFormat.getIntegerInstance(),
DateFormat.getTimeInstance(DateFormat.SHORT),
DateFormat.getDateInstance(),
};
mf.setFormats(formats);
assertEquals(englishTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.setFormatByArgumentIndex(int, Format)'
public void testSetFormatByArgumentIndex() {
// same problem, once you set a format for an argument, you've set all of them
MessageFormat mf = new MessageFormat(pattern, Locale.US);
mf.setFormatByArgumentIndex(1, DateFormat.getTimeInstance(DateFormat.SHORT));
assertEquals(brokenButConformantTarget, mf.format(args));
}
*/
/*
* Test method for 'com.ibm.icu.text.MessageFormat.setFormat(int, Format)'
*/
public void testSetFormat() {
// and ok again
MessageFormat mf = new MessageFormat(pattern, Locale.US);
mf.setFormat(1, DateFormat.getTimeInstance(DateFormat.LONG));
assertEquals(modifiedTarget, mf.format(args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.getFormatsByArgumentIndex()'
public void testGetFormatsByArgumentIndex() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
Format[] formats = mf.getFormatsByArgumentIndex();
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
assertEquals(formats[0], nf);
DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
assertEquals(formats[1], df);
}
*/
/*
* Test method for 'com.ibm.icu.text.MessageFormat.getFormats()'
*/
public void testGetFormats() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
Format[] formats = mf.getFormats();
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
assertEquals(formats[0], nf);
DateFormat tf = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US);
assertEquals(formats[1], tf);
DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
assertEquals(formats[2], df);
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.format(Object[], StringBuffer, FieldPosition)'
*/
public void testFormatObjectArrayStringBufferFieldPosition() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
StringBuffer buf = new StringBuffer();
FieldPosition fp = new FieldPosition(0);
mf.format(args, buf, fp);
assertEquals(englishTarget, buf.toString());
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.format(String, Object[])'
*/
public void testFormatStringObjectArray() {
assertEquals(englishTarget, MessageFormat.format(pattern, args));
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.format(Object, StringBuffer, FieldPosition)'
*/
public void testFormatObjectStringBufferFieldPosition() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
StringBuffer buf = new StringBuffer();
FieldPosition fp = new FieldPosition(0);
mf.format((Object)args, buf, fp);
assertEquals(englishTarget, buf.toString());
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.parse(String, ParsePosition)'
*/
public void testParseStringParsePosition() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
ParsePosition pp = new ParsePosition(1);
Object[] result = mf.parse("!" + englishTarget, pp);
assertEquals(num, result[0]);
assertEquals(dateOnly, result[1]);
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.parse(String)'
*/
public void testParseString() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
try {
Object[] result = mf.parse(englishTarget);
assertEquals(num, result[0]);
assertEquals(dateOnly, result[1]);
}
catch (ParseException e) {
fail(e.getMessage());
}
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.parseObject(String, ParsePosition)'
*/
public void testParseObjectStringParsePosition() {
MessageFormat mf = new MessageFormat(pattern, Locale.US);
ParsePosition pp = new ParsePosition(0);
Object result = mf.parseObject(englishTarget, pp);
assertEquals(num, ((Object[])result)[0]);
assertEquals(dateOnly, ((Object[])result)[1]);
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.autoQuoteApostrophe(String)'
*/
public void testAutoQuoteApostrophe() {
String str = "Let's meet at {1,time,h 'o'' clock'} at l'Orange Bleue";
String pat = MessageFormat.autoQuoteApostrophe(str);
MessageFormat mf = new MessageFormat(pat, Locale.US);
String result = mf.format(args);
assertEquals("Let's meet at 8 o' clock at l'Orange Bleue", result);
assertEquals("Let''s meet at {1,time,h 'o'' clock'} at l''Orange Bleue", pat);
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.clone()'
*/
public void testClone() {
// tested already in testHashcode
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.equals(Object)'
*/
public void testEqualsObject() {
// tested already in testHashcode
}
/*
* Test method for 'com.ibm.icu.text.MessageFormat.toString()'
*/
public void testToString() {
// no need to test
}
}

View file

@ -0,0 +1,441 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.math.BigInteger;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.util.ULocale;
public class NumberFormatTest extends ICUTestCase {
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.NumberFormat(NumberFormat)'
*/
public void testNumberFormat() {
NumberFormat nf = new NumberFormat(java.text.NumberFormat.getInstance());
assertEquals(nf, NumberFormat.getInstance());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.format(Object, StringBuffer, FieldPosition)'
*/
public void testFormatObjectStringBufferFieldPosition() {
Number num = new Long(1234L);
StringBuffer buf = new StringBuffer();
FieldPosition fp = new FieldPosition(0);
NumberFormat.getInstance().format(num, buf, fp);
assertEquals("1,234", buf.toString());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.parseObject(String, ParsePosition)'
*/
public void testParseObjectStringParsePosition() {
ParsePosition pp = new ParsePosition(0);
Object result = NumberFormat.getInstance().parse("1,234", pp);
assertEquals(result, new Long(1234));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.format(double)'
*/
public void testFormatDouble() {
assertEquals("1,234.567", NumberFormat.getInstance().format(1234.567));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.format(long)'
*/
public void testFormatLong() {
assertEquals("1,234", NumberFormat.getInstance().format(1234L));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.format(BigInteger)'
*/
public void testFormatBigInteger() {
// note, java doesn't handle biginteger with full precision.
BigInteger bi = new BigInteger("123456");
assertEquals("123,456", java.text.NumberFormat.getInstance().format(bi));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.format(double, StringBuffer, FieldPosition)'
*/
public void testFormatDoubleStringBufferFieldPosition() {
StringBuffer buf = new StringBuffer();
FieldPosition fp = new FieldPosition(0);
assertEquals("123,456.789", NumberFormat.getInstance().format(123456.789, buf, fp).toString());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.format(long, StringBuffer, FieldPosition)'
*/
public void testFormatLongStringBufferFieldPosition() {
StringBuffer buf = new StringBuffer();
FieldPosition fp = new FieldPosition(0);
assertEquals("123,456", NumberFormat.getInstance().format(123456L, buf, fp).toString());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.format(BigInteger, StringBuffer, FieldPosition)'
*/
public void testFormatBigIntegerStringBufferFieldPosition() {
// note, java doesn't handle biginteger with full precision.
StringBuffer buf = new StringBuffer();
FieldPosition fp = new FieldPosition(0);
BigInteger bi = new BigInteger("123456");
assertEquals("123,456", java.text.NumberFormat.getInstance().format(bi, buf, fp).toString());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.parse(String, ParsePosition)'
*/
public void testParseStringParsePosition() {
ParsePosition pp = new ParsePosition(3);
assertEquals(new Long(123456), NumberFormat.getInstance().parse("xxx123,456yyy", pp));
assertEquals(10, pp.getIndex());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.parse(String)'
*/
public void testParseString() throws ParseException {
Number result = NumberFormat.getInstance().parse("123,456,yyy");
assertEquals(new Long(123456), result);
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.isParseIntegerOnly()'
*/
public void testIsParseIntegerOnly() {
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
assertTrue(nf.isParseIntegerOnly());
nf.setParseIntegerOnly(false);
assertFalse(nf.isParseIntegerOnly());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.setParseIntegerOnly(boolean)'
*/
public void testSetParseIntegerOnly() throws ParseException {
String str = "123.456,yyy";
NumberFormat nf = NumberFormat.getInstance();
assertEquals(new Double(123.456), nf.parse(str));
nf.setParseIntegerOnly(true);
assertEquals(new Long(123), nf.parse(str));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getInstance()'
*/
public void testGetInstance() {
// used everywhere, no need to test
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getInstance(Locale)'
*/
public void testGetInstanceLocale() {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
assertEquals("123,456", nf.format(123.456));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getInstance(ULocale)'
*/
public void testGetInstanceULocale() {
NumberFormat nf = NumberFormat.getInstance(ULocale.GERMANY);
assertEquals("123,456", nf.format(123.456));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getNumberInstance()'
*/
public void testGetNumberInstance() {
NumberFormat nf = NumberFormat.getNumberInstance();
assertEquals("123,456.789", nf.format(123456.789));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getNumberInstance(Locale)'
*/
public void testGetNumberInstanceLocale() {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMANY);
assertEquals("123.456,789", nf.format(123456.789));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getNumberInstance(ULocale)'
*/
public void testGetNumberInstanceULocale() {
NumberFormat nf = NumberFormat.getNumberInstance(ULocale.GERMANY);
assertEquals("123.456,789", nf.format(123456.789));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getIntegerInstance()'
*/
public void testGetIntegerInstance() {
NumberFormat nf = NumberFormat.getIntegerInstance();
assertEquals("123,457", nf.format(123456.789)); // rounds
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getIntegerInstance(Locale)'
*/
public void testGetIntegerInstanceLocale() {
NumberFormat nf = NumberFormat.getIntegerInstance(Locale.GERMANY);
assertEquals("123.457", nf.format(123456.789)); // rounds
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getIntegerInstance(ULocale)'
*/
public void testGetIntegerInstanceULocale() {
NumberFormat nf = NumberFormat.getIntegerInstance(ULocale.GERMANY);
assertEquals("123.457", nf.format(123456.789)); // rounds
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getCurrencyInstance()'
*/
public void testGetCurrencyInstance() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
assertEquals("$123,456.99", nf.format(123456.99));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getCurrencyInstance(Locale)'
*/
public void testGetCurrencyInstanceLocale() {
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.GERMANY);
assertEquals("123.456,99 €", nf.format(123456.99));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getCurrencyInstance(ULocale)'
*/
public void testGetCurrencyInstanceULocale() {
NumberFormat nf = NumberFormat.getCurrencyInstance(ULocale.GERMANY);
assertEquals("123.456,99 €", nf.format(123456.99));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getPercentInstance()'
*/
public void testGetPercentInstance() {
NumberFormat nf = NumberFormat.getPercentInstance();
assertEquals("123,456%", nf.format(1234.56));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getPercentInstance(Locale)'
*/
public void testGetPercentInstanceLocale() {
NumberFormat nf = NumberFormat.getPercentInstance(Locale.GERMANY);
assertEquals("123.456%", nf.format(1234.56));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getPercentInstance(ULocale)'
*/
public void testGetPercentInstanceULocale() {
NumberFormat nf = NumberFormat.getPercentInstance(ULocale.GERMANY);
assertEquals("123.456%", nf.format(1234.56));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getScientificInstance()'
*/
public void testGetScientificInstance() {
NumberFormat nf = NumberFormat.getScientificInstance();
assertEquals(".123456E4", nf.format(1234.56));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getScientificInstance(Locale)'
*/
public void testGetScientificInstanceLocale() {
NumberFormat nf = NumberFormat.getScientificInstance(Locale.GERMANY);
assertEquals(",123456E4", nf.format(1234.56));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getScientificInstance(ULocale)'
*/
public void testGetScientificInstanceULocale() {
NumberFormat nf = NumberFormat.getScientificInstance(ULocale.GERMANY);
assertEquals(",123456E4", nf.format(1234.56));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getAvailableLocales()'
*/
public void testGetAvailableLocales() {
Locale[] ilocales = NumberFormat.getAvailableLocales();
if (ICUTestCase.testingWrapper) {
Locale[] jlocales = java.text.NumberFormat.getAvailableLocales();
for (int i = 0; i < ilocales.length; ++i) {
assertEquals(jlocales[i], ilocales[i]);
}
}
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getAvailableULocales()'
*/
public void testGetAvailableULocales() {
ULocale[] ulocales = NumberFormat.getAvailableULocales();
if (ICUTestCase.testingWrapper) {
Locale[] jlocales = java.text.NumberFormat.getAvailableLocales();
for (int i = 0; i < ulocales.length; ++i) {
assertEquals(jlocales[i], ulocales[i].toLocale());
}
}
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.isGroupingUsed()'
*/
public void testIsGroupingUsed() {
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(true);
assertTrue(nf.isGroupingUsed());
nf.setGroupingUsed(false);
assertFalse(nf.isGroupingUsed());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.setGroupingUsed(boolean)'
*/
public void testSetGroupingUsed() {
NumberFormat nf = NumberFormat.getInstance();
assertEquals("123,456,789", nf.format(123456789));
nf.setGroupingUsed(false);
assertEquals("123456789", nf.format(123456789));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getMaximumIntegerDigits()'
*/
public void testGetMaximumIntegerDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
assertEquals(4, nf.getMaximumIntegerDigits());
nf.setMaximumIntegerDigits(6);
assertEquals(6, nf.getMaximumIntegerDigits());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.setMaximumIntegerDigits(int)'
*/
public void testSetMaximumIntegerDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
assertEquals("3,456", nf.format(123456)); // high digits truncated
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getMinimumIntegerDigits()'
*/
public void testGetMinimumIntegerDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumIntegerDigits(4);
assertEquals(4, nf.getMinimumIntegerDigits());
nf.setMinimumIntegerDigits(6);
assertEquals(6, nf.getMinimumIntegerDigits());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.setMinimumIntegerDigits(int)'
*/
public void testSetMinimumIntegerDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumIntegerDigits(4);
assertEquals("0,012", nf.format(12)); // pad out with zero, grouping still used
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getMaximumFractionDigits()'
*/
public void testGetMaximumFractionDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(4);
assertEquals(4, nf.getMaximumFractionDigits());
nf.setMaximumFractionDigits(6);
assertEquals(6, nf.getMaximumFractionDigits());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.setMaximumFractionDigits(int)'
*/
public void testSetMaximumFractionDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(4);
assertEquals("1.2346", nf.format(1.2345678)); // low digits rounded
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.getMinimumFractionDigits()'
*/
public void testGetMinimumFractionDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(4);
assertEquals(4, nf.getMinimumFractionDigits());
nf.setMinimumFractionDigits(6);
assertEquals(6, nf.getMinimumFractionDigits());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.setMinimumFractionDigits(int)'
*/
public void testSetMinimumFractionDigits() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(4);
assertEquals("1.2000", nf.format(1.2));
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.toString()'
*/
public void testToString() {
assertNotNull(NumberFormat.getInstance().toString());
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.hashCode()'
*/
public void testHashCode() {
NumberFormat nf = NumberFormat.getInstance();
NumberFormat eq = NumberFormat.getInstance(Locale.US);
NumberFormat neq = NumberFormat.getInstance(Locale.GERMANY);
ICUTestCase.testEHCS(nf, eq, neq);
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.clone()'
*/
public void testClone() {
// see testHashCode
}
/*
* Test method for 'com.ibm.icu.x.text.NumberFormat.equals(Object)'
*/
public void testEqualsObject() {
// see testHashCode
}
}

View file

@ -0,0 +1,202 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.text.DateFormatSymbols;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;
public class SimpleDateFormatTest extends ICUTestCase {
private static final String mdy = "MMM dd yyyy";
private static final String md2 = "MMM dd yy";
private static final String hmz = "'The time is' HH:mm:ss zzz";
private static final String hmzmdy = hmz + " 'on' " + mdy;
private static final String hmzmdyStr = "The time is 15:05:20 CST on Jan 10 2006";
private static final TimeZone tzc = TimeZone.getTimeZone("CST");
private static final TimeZone tzp = TimeZone.getTimeZone("PST");
private static final Calendar cal = Calendar.getInstance(tzc);
private static final Date date;
static {
cal.clear();
cal.set(2006, 0, 10, 15, 5, 20); // arrgh, doesn't clear millis
date = cal.getTime();
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.format(Calendar, StringBuffer, FieldPosition)'
*/
public void testFormatCalendarStringBufferFieldPosition() {
StringBuffer buf = new StringBuffer();
FieldPosition fp = new FieldPosition(0);
SimpleDateFormat sdf = new SimpleDateFormat(hmzmdy);
sdf.format(cal, buf, fp);
assertEquals(hmzmdyStr, buf.toString());
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.parse(String, Calendar, ParsePosition)'
*/
public void testParseStringCalendarParsePosition() {
Calendar cal = Calendar.getInstance(tzp);
cal.clear();
ParsePosition pp = new ParsePosition(0);
SimpleDateFormat sdf = new SimpleDateFormat(hmzmdy);
sdf.parse(hmzmdyStr, cal, pp);
assertEquals(date, cal.getTime());
// note: java doesn't return the parsed time zone
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.clone()'
*/
public void testClone() {
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.SimpleDateFormat()'
*/
public void testSimpleDateFormat() {
SimpleDateFormat sdf = new SimpleDateFormat();
java.text.SimpleDateFormat jsdf = new java.text.SimpleDateFormat();
assertEquals(jsdf.format(date), sdf.format(date));
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.SimpleDateFormat(String)'
*/
public void testSimpleDateFormatString() {
SimpleDateFormat sdf = new SimpleDateFormat(mdy);
java.text.SimpleDateFormat jsdf = new java.text.SimpleDateFormat(mdy);
assertEquals(jsdf.format(date), sdf.format(date));
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.SimpleDateFormat(String, Locale)'
*/
public void testSimpleDateFormatStringLocale() {
Locale l = Locale.JAPAN;
SimpleDateFormat sdf = new SimpleDateFormat(mdy, l);
java.text.SimpleDateFormat jsdf = new java.text.SimpleDateFormat(mdy, l);
assertEquals(jsdf.format(date), sdf.format(date));
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.SimpleDateFormat(String, ULocale)'
*/
public void testSimpleDateFormatStringULocale() {
ULocale l = ULocale.JAPAN;
SimpleDateFormat sdf = new SimpleDateFormat(mdy, l);
java.text.SimpleDateFormat jsdf = new java.text.SimpleDateFormat(mdy, l.toLocale());
assertEquals(jsdf.format(date), sdf.format(date));
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.SimpleDateFormat(String, DateFormatSymbols)'
*/
public void testSimpleDateFormatStringDateFormatSymbols() {
Locale l = Locale.US;
DateFormatSymbols dfs = new DateFormatSymbols(l);
java.text.DateFormatSymbols jdfs = new java.text.DateFormatSymbols(l);
SimpleDateFormat sdf = new SimpleDateFormat(mdy, dfs);
java.text.SimpleDateFormat jsdf = new java.text.SimpleDateFormat(mdy, jdfs);
assertEquals(jsdf.format(date), sdf.format(date));
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.set2DigitYearStart(Date)'
*/
public void testSet2DigitYearStart() {
SimpleDateFormat sdf = new SimpleDateFormat(md2);
sdf.set2DigitYearStart(date);
try {
Date d = sdf.parse("Jan 15 04");
assertNotEqual(-1, d.toString().indexOf("2104"));
}
catch (ParseException pe) {
fail(pe.getMessage());
}
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.get2DigitYearStart()'
*/
public void testGet2DigitYearStart() {
SimpleDateFormat sdf = new SimpleDateFormat(md2);
sdf.set2DigitYearStart(date);
assertEquals(date, sdf.get2DigitYearStart());
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.toPattern()'
*/
public void testToPattern() {
SimpleDateFormat sdf = new SimpleDateFormat(mdy);
assertEquals(mdy, sdf.toPattern());
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.toLocalizedPattern()'
*/
public void testToLocalizedPattern() {
Locale l = Locale.getDefault();
Locale.setDefault(Locale.US);
SimpleDateFormat sdf = new SimpleDateFormat(mdy);
assertEquals(mdy, sdf.toLocalizedPattern());
Locale.setDefault(l);
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.applyPattern(String)'
*/
public void testApplyPattern() {
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(tzc);
sdf.applyPattern(hmzmdy);
assertEquals(hmzmdyStr, sdf.format(date));
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.applyLocalizedPattern(String)'
*/
public void testApplyLocalizedPattern() {
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(tzc);
sdf.applyLocalizedPattern(hmzmdy);
assertEquals(hmzmdyStr, sdf.format(date));
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.getDateFormatSymbols()'
*/
public void testGetDateFormatSymbols() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
SimpleDateFormat sdf = new SimpleDateFormat(mdy, dfs);
assertEquals(dfs, sdf.getDateFormatSymbols());
}
/*
* Test method for 'com.ibm.icu.text.SimpleDateFormat.setDateFormatSymbols(DateFormatSymbols)'
*/
public void testSetDateFormatSymbols() {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.JAPAN);
SimpleDateFormat sdf = new SimpleDateFormat(hmzmdy);
sdf.setDateFormatSymbols(dfs);
// assumes Japanese symbols do not have gregorian month names
assertEquals(-1, sdf.format(date).indexOf("Jan"));
}
}

View file

@ -0,0 +1,235 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;
public class TimeZoneTest extends ICUTestCase {
/*
* Test method for 'com.ibm.icu.util.TimeZone.hashCode()'
*/
public void testHashCode() {
TimeZone tz1 = TimeZone.getTimeZone("PST");
TimeZone tz2 = TimeZone.getTimeZone("PST");
TimeZone tzn = TimeZone.getTimeZone("CST");
testEHCS(tz1, tz2, tzn);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.TimeZone(TimeZone)'
*/
public void testTimeZone() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getOffset(int, int, int, int, int, int)'
*/
public void testGetOffset() {
TimeZone tz = TimeZone.getTimeZone("PST");
int offset = tz.getOffset(1, 2004, 0, 01, 1, 0);
assertEquals(-28800000, offset);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.setRawOffset(int)'
*/
public void testSetRawOffset() {
TimeZone tz = TimeZone.getTimeZone("PST");
int value = tz.getRawOffset();
int value1 = value + 100000;
tz.setRawOffset(value1);
int result = tz.getRawOffset();
assertNotEqual(value, result);
assertEquals(value1, result);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getRawOffset()'
*/
public void testGetRawOffset() {
TimeZone tz = TimeZone.getTimeZone("PST");
int offset = tz.getRawOffset();
assertEquals(-28800000, offset);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getID()'
*/
public void testGetID() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals("PST", tz.getID());
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.setID(String)'
*/
public void testSetID() {
TimeZone tz = TimeZone.getTimeZone("PST");
String value1 = tz.getID();
String value2 = value1 + "!";
tz.setID(value2);
String result = tz.getID();
assertNotEqual(value1, result);
assertEquals(value2, result);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDisplayName()'
*/
public void testGetDisplayName() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals("Pacific Standard Time", tz.getDisplayName());
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDisplayName(Locale)'
*/
public void testGetDisplayNameLocale() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals("Pacific Standard Time", tz.getDisplayName(Locale.US));
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDisplayName(ULocale)'
*/
public void testGetDisplayNameULocale() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals("Pacific Standard Time", tz.getDisplayName(ULocale.US));
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDisplayName(boolean, int)'
*/
public void testGetDisplayNameBooleanInt() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals("PDT", tz.getDisplayName(true, TimeZone.SHORT));
assertEquals("Pacific Daylight Time", tz.getDisplayName(true, TimeZone.LONG));
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDisplayName(boolean, int, Locale)'
*/
public void testGetDisplayNameBooleanIntLocale() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals("PDT", tz.getDisplayName(true, TimeZone.SHORT, Locale.US));
assertEquals("Pacific Daylight Time", tz.getDisplayName(true, TimeZone.LONG, Locale.US));
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDisplayName(boolean, int, ULocale)'
*/
public void testGetDisplayNameBooleanIntULocale() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals("PDT", tz.getDisplayName(true, TimeZone.SHORT, ULocale.US));
assertEquals("Pacific Daylight Time", tz.getDisplayName(true, TimeZone.LONG, ULocale.US));
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDSTSavings()'
*/
public void testGetDSTSavings() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals(3600000, tz.getDSTSavings());
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.useDaylightTime()'
*/
public void testUseDaylightTime() {
TimeZone tz = TimeZone.getTimeZone("PST");
assertTrue(tz.useDaylightTime());
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.inDaylightTime(Date)'
*/
public void testInDaylightTime() {
TimeZone tz = TimeZone.getTimeZone("PST");
Calendar cal = Calendar.getInstance();
cal.set(2005, 0, 17);
Date date = cal.getTime();
assertFalse(tz.inDaylightTime(date));
cal.set(2005, 6, 17);
date = cal.getTime();
assertTrue(tz.inDaylightTime(date));
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getTimeZone(String)'
*/
public void testGetTimeZone() {
// implicitly tested everywhere
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getAvailableIDs(int)'
*/
public void testGetAvailableIDsInt() {
String[] ids = TimeZone.getAvailableIDs(-28800000);
assertNotNull(ids);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getAvailableIDs()'
*/
public void testGetAvailableIDs() {
String[] ids = TimeZone.getAvailableIDs();
assertNotNull(ids);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.getDefault()'
*/
public void testGetDefault() {
TimeZone tz = TimeZone.getDefault();
assertNotNull(tz);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.setDefault(TimeZone)'
*/
public void testSetDefault() {
TimeZone tz1 = TimeZone.getDefault();
String newCode = "PDT".equals(tz1.getID()) ? "CST" : "PDT";
TimeZone tz2 = TimeZone.getTimeZone(newCode);
TimeZone.setDefault(tz2);
TimeZone result = TimeZone.getDefault();
assertNotEqual(tz1, result);
assertEquals(tz2, result);
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.hasSameRules(TimeZone)'
*/
public void testHasSameRules() {
TimeZone tz1 = TimeZone.getTimeZone("PST");
TimeZone tz2 = TimeZone.getTimeZone("America/Los_Angeles");
assertTrue(tz1.hasSameRules(tz2));
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.clone()'
*/
public void testClone() {
// tested by testHashCode
}
/*
* Test method for 'com.ibm.icu.util.TimeZone.equals(Object)'
*/
public void testEqualsObject() {
// tested by testHashCode
}
}

View file

@ -0,0 +1,748 @@
/*
*******************************************************************************
* Copyright (C) 2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.tests;
import java.util.Iterator;
import java.util.Locale;
import com.ibm.icu.util.ULocale;
public class ULocaleTest extends ICUTestCase {
private String sampleName;
private String longULocaleName;
private String longULocaleBasename;
private String nonNormalizedName;
private ULocale longULocale;
private Locale sampleLocale;
/**
* @Override
*/
protected void setUp() throws Exception {
super.setUp();
sampleName = "ll_CC_VVVV";
longULocaleName = "ll_Ssss_CC_VVVV@collation=phonebook;key=value";
longULocaleBasename = longULocaleName.substring(0, longULocaleName.indexOf('@'));
nonNormalizedName = "LL_ssss_cc_VVVV@ Key = value ; Collation = phonebook ; ";
longULocale = new ULocale(longULocaleName);
sampleLocale = new ULocale(sampleName).toLocale();
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.hashCode()'
*/
public void testHashCode() {
ULocale obj = ULocale.GERMANY;
ULocale eq = new ULocale("de_DE");
ULocale neq = new ULocale("de_DE_FRENCH");
ICUTestCase.testEHCS(obj, eq, neq);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.forLocale(Locale)'
*/
public void testForLocale() {
assertEquals(ULocale.GERMANY, ULocale.forLocale(Locale.GERMANY));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.ULocale(String)'
*/
public void testULocaleString() {
assertEquals(ULocale.GERMAN, new ULocale("de"));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.ULocale(String, String)'
*/
public void testULocaleStringString() {
assertEquals(ULocale.GERMANY, new ULocale("de", "DE"));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.ULocale(String, String, String)'
*/
public void testULocaleStringStringString() {
assertEquals(sampleLocale, new ULocale("ll", "cc", "VVVV").toLocale());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.createCanonical(String)'
*/
public void testCreateCanonical() {
ULocale result = ULocale.createCanonical("de__PHONEBOOK");
assertEquals(new ULocale("de@collation=phonebook"), result);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.toLocale()'
*/
public void testToLocale() {
assertEquals(sampleLocale, new ULocale("ll", "cc", "VVVV").toLocale());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDefault()'
*/
public void testGetDefault() {
assertEquals(Locale.getDefault(), ULocale.getDefault().toLocale());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.setDefault(ULocale)'
*/
public void testSetDefault() {
Locale oldLocale = Locale.getDefault();
ULocale oldULocale = ULocale.getDefault();
try {
ULocale.setDefault(longULocale);
ICUTestCase.assertNotEqual(Locale.getDefault(), oldLocale);
ICUTestCase.assertNotEqual(ULocale.getDefault(), oldULocale);
assertEquals(longULocale, ULocale.getDefault());
assertEquals(sampleLocale, Locale.getDefault());
}
finally {
ULocale.setDefault(oldULocale);
Locale.setDefault(oldLocale); // in case of some error
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.clone()'
*/
public void testClone() {
// see testHashcode
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.equals(Object)'
*/
public void testEqualsObject() {
// see testHashcode
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getAvailableLocales()'
*/
public void testGetAvailableLocales() {
ULocale[] ulocales = ULocale.getAvailableLocales();
if (ICUTestCase.testingWrapper) {
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < ulocales.length; ++i) {
assertEquals(ulocales[i].toLocale(), locales[i]);
}
}
// else nothing to test except that the function returned.
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getISOCountries()'
*/
public void testGetISOCountries() {
String[] ucountries = ULocale.getISOCountries();
assertNotNull(ucountries);
if (ICUTestCase.testingWrapper) {
// keep our own data for now
// our data doesn't match java's so this test would fail
// TODO: enable if we decide to use java's data
// String[] countries = Locale.getISOCountries();
// TestBoilerplate.assertArraysEqual(ucountries, countries);
}
// else nothing to test except that the function returned.
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getISOLanguages()'
*/
public void testGetISOLanguages() {
String[] ulanguages = ULocale.getISOLanguages();
assertNotNull(ulanguages);
if (ICUTestCase.testingWrapper) {
// keep our own data for now
// our data doesn't match java's so this test would fail
// TODO: enable if we decide to use java's data
// String[] languages = Locale.getISOLanguages();
// TestBoilerplate.assertArraysEqual(ulanguages, languages);
}
// else nothing to test except that the function returned.
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getLanguage()'
*/
public void testGetLanguage() {
assertEquals("ll", longULocale.getLanguage());
assertEquals("ll", longULocale.toLocale().getLanguage());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getLanguage(String)'
*/
public void testGetLanguageString() {
assertEquals("ll", ULocale.getLanguage(longULocale.getName()));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getScript()'
*/
public void testGetScript() {
assertEquals("Ssss", longULocale.getScript());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getScript(String)'
*/
public void testGetScriptString() {
assertEquals("Ssss", ULocale.getScript(longULocale.getName()));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getCountry()'
*/
public void testGetCountry() {
assertEquals("CC", longULocale.getCountry());
assertEquals("CC", longULocale.toLocale().getCountry());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getCountry(String)'
*/
public void testGetCountryString() {
assertEquals("CC", ULocale.getCountry(longULocale.getName()));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getVariant()'
*/
public void testGetVariant() {
assertEquals("VVVV", longULocale.getVariant());
assertEquals("VVVV", longULocale.toLocale().getVariant());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getVariant(String)'
*/
public void testGetVariantString() {
assertEquals("VVVV", ULocale.getVariant(longULocale.getName()));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getFallback(String)'
*/
public void testGetFallbackString() {
assertEquals(ULocale.GERMAN, ULocale.getFallback(ULocale.GERMANY.getName()));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getFallback()'
*/
public void testGetFallback() {
assertEquals(ULocale.GERMAN, ULocale.GERMANY.getFallback());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getBaseName()'
*/
public void testGetBaseName() {
assertEquals(longULocaleBasename, longULocale.getBaseName());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getBaseName(String)'
*/
public void testGetBaseNameString() {
assertEquals(longULocaleBasename, longULocale.getBaseName());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getName()'
*/
public void testGetName() {
assertEquals(longULocaleName, longULocale.getName());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getName(String)'
*/
public void testGetNameString() {
assertEquals(longULocaleName, ULocale.getName(nonNormalizedName));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.toString()'
*/
public void testToString() {
assertEquals(longULocaleName, longULocale.toString());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getKeywords()'
*/
public void testGetKeywords() {
Iterator iter = longULocale.getKeywords();
assertEquals(iter.next(), "collation");
assertEquals(iter.next(), "key");
assertFalse(iter.hasNext());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getKeywords(String)'
*/
public void testGetKeywordsString() {
Iterator iter = ULocale.getKeywords(nonNormalizedName);
assertEquals(iter.next(), "collation");
assertEquals(iter.next(), "key");
assertFalse(iter.hasNext());
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getKeywordValue(String)'
*/
public void testGetKeywordValueString() {
assertEquals("value", longULocale.getKeywordValue("key"));
assertEquals("phonebook", longULocale.getKeywordValue("collation"));
assertNull(longULocale.getKeywordValue("zzyzx"));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getKeywordValue(String, String)'
*/
public void testGetKeywordValueStringString() {
assertEquals("value", ULocale.getKeywordValue(longULocaleName, "key"));
assertEquals("phonebook", ULocale.getKeywordValue(longULocaleName, "collation"));
assertNull(ULocale.getKeywordValue(longULocaleName, "zzyzx"));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.canonicalize(String)'
*/
public void testCanonicalize() {
assertEquals("de@collation=phonebook", ULocale.canonicalize("de__PHONEBOOK"));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.setKeywordValue(String, String)'
*/
public void testSetKeywordValueStringString() {
ULocale munged = longULocale.setKeywordValue("key", "C#");
assertEquals("C#", munged.getKeywordValue("key"));
munged = munged.setKeywordValue("zzyzx", "grue");
assertEquals("grue", munged.getKeywordValue("zzyzx"));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.setKeywordValue(String, String, String)'
*/
public void testSetKeywordValueStringStringString() {
String munged = ULocale.setKeywordValue(longULocaleName, "key", "C#");
assertEquals("C#", ULocale.getKeywordValue(munged, "key"));
munged = ULocale.setKeywordValue(munged, "zzyzx", "grue");
assertEquals("grue", ULocale.getKeywordValue(munged, "zzyzx"));
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getISO3Language()'
*/
public void testGetISO3Language() {
String il = ULocale.GERMANY.getISO3Language();
String jl = Locale.GERMANY.getISO3Language();
assertEquals(il, jl);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getISO3Language(String)'
*/
public void testGetISO3LanguageString() {
String il = ULocale.getISO3Language(ULocale.GERMANY.getName());
String jl = Locale.GERMANY.getISO3Language();
assertEquals(il, jl);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getISO3Country()'
*/
public void testGetISO3Country() {
String ic = ULocale.GERMANY.getISO3Country();
String jc = Locale.GERMANY.getISO3Country();
assertEquals(ic, jc);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getISO3Country(String)'
*/
public void testGetISO3CountryString() {
String ic = ULocale.getISO3Country(ULocale.GERMANY.getName());
String jc = Locale.GERMANY.getISO3Country();
assertEquals(ic, jc);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayLanguage()'
*/
public void testGetDisplayLanguage() {
String idl = ULocale.GERMANY.getDisplayLanguage();
String jdl = Locale.GERMANY.getDisplayLanguage();
assertEquals(idl, jdl);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayLanguage(ULocale)'
*/
public void testGetDisplayLanguageULocale() {
String idl = ULocale.GERMANY.getDisplayLanguage(ULocale.GERMANY);
String jdl = Locale.GERMANY.getDisplayLanguage(Locale.GERMANY);
assertEquals(idl, jdl);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayLanguage(String, String)'
*/
public void testGetDisplayLanguageStringString() {
String idl = ULocale.getDisplayLanguage(ULocale.GERMANY.getName(), "de_DE");
String jdl = Locale.GERMANY.getDisplayLanguage(Locale.GERMANY);
assertEquals(idl, jdl);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayLanguage(String, ULocale)'
*/
public void testGetDisplayLanguageStringULocale() {
String idl = ULocale.getDisplayLanguage(ULocale.GERMANY.getName(), ULocale.GERMANY);
String jdl = Locale.GERMANY.getDisplayLanguage(Locale.GERMANY);
assertEquals(idl, jdl);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayScript()'
*/
public void testGetDisplayScript() {
String is = ULocale.TRADITIONAL_CHINESE.getDisplayScript();
if (ICUTestCase.testingWrapper) {
assertEquals("Hant", is);
} else {
assertEquals("Traditional Chinese", is);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayScript(ULocale)'
*/
public void testGetDisplayScriptULocale() {
String is = ULocale.TRADITIONAL_CHINESE.getDisplayScript(ULocale.GERMANY);
if (ICUTestCase.testingWrapper) {
assertEquals("Hant", is);
} else {
// TODO: look up expected value
assertEquals("Hant", is);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayScript(String, String)'
*/
public void testGetDisplayScriptStringString() {
String is = ULocale.getDisplayScript("zh_Hant", "de_DE");
if (ICUTestCase.testingWrapper) {
assertEquals("Hant", is);
} else {
// TODO: look up expected value
assertEquals("Hant", is);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayScript(String, ULocale)'
*/
public void testGetDisplayScriptStringULocale() {
String is = ULocale.getDisplayScript("zh_Hant", ULocale.GERMANY);
if (ICUTestCase.testingWrapper) {
assertEquals("Hant", is);
} else {
// TODO: look up expected value
assertEquals("Hant", is);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayCountry()'
*/
public void testGetDisplayCountry() {
String idc = ULocale.GERMANY.getDisplayCountry();
String jdc = Locale.GERMANY.getDisplayCountry();
assertEquals(idc, jdc);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayCountry(ULocale)'
*/
public void testGetDisplayCountryULocale() {
String idc = ULocale.GERMANY.getDisplayCountry(ULocale.GERMANY);
String jdc = Locale.GERMANY.getDisplayCountry(Locale.GERMANY);
assertEquals(idc, jdc);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayCountry(String, String)'
*/
public void testGetDisplayCountryStringString() {
String idc = ULocale.getDisplayCountry("de_DE", "de_DE");
String jdc = Locale.GERMANY.getDisplayCountry(Locale.GERMANY);
assertEquals(idc, jdc);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayCountry(String, ULocale)'
*/
public void testGetDisplayCountryStringULocale() {
String idc = ULocale.getDisplayCountry("de_DE", ULocale.GERMANY);
String jdc = Locale.GERMANY.getDisplayCountry(Locale.GERMANY);
assertEquals(idc, jdc);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayVariant()'
*/
public void testGetDisplayVariant() {
String idv = new ULocale("de_DE_PHONEBOOK").getDisplayVariant();
String jdv = new Locale("de", "DE", "PHONEBOOK").getDisplayVariant();
assertEquals(jdv, idv);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayVariant(ULocale)'
*/
public void testGetDisplayVariantULocale() {
String idv = new ULocale("de_DE_PHONEBOOK").getDisplayVariant(ULocale.GERMANY);
String jdv = new Locale("de", "DE", "PHONEBOOK").getDisplayVariant(Locale.GERMANY);
assertEquals(jdv, idv);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayVariant(String, String)'
*/
public void testGetDisplayVariantStringString() {
String idv = ULocale.getDisplayVariant("de_DE_PHONEBOOK", "de_DE");
String jdv = new Locale("de", "DE", "PHONEBOOK").getDisplayVariant(Locale.GERMANY);
assertEquals(jdv, idv);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayVariant(String, ULocale)'
*/
public void testGetDisplayVariantStringULocale() {
String idv = ULocale.getDisplayVariant("de_DE_PHONEBOOK", ULocale.GERMANY);
String jdv = new Locale("de", "DE", "PHONEBOOK").getDisplayVariant(Locale.GERMANY);
assertEquals(jdv, idv);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayKeyword(String)'
*/
public void testGetDisplayKeywordString() {
String idk = ULocale.getDisplayKeyword("collation");
assertEquals("collation", idk);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayKeyword(String, String)'
*/
public void testGetDisplayKeywordStringString() {
String idk = ULocale.getDisplayKeyword("collation", "de_DE");
if (ICUTestCase.testingWrapper) {
assertEquals("collation", idk);
} else {
// TODO: find real value
assertEquals("collation", idk);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayKeyword(String, ULocale)'
*/
public void testGetDisplayKeywordStringULocale() {
String idk = ULocale.getDisplayKeyword("collation", ULocale.GERMANY);
if (ICUTestCase.testingWrapper) {
assertEquals("collation", idk);
} else {
// TODO: find real value
assertEquals("collation", idk);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayKeywordValue(String)'
*/
public void testGetDisplayKeywordValueString() {
ULocale ul = new ULocale("de_DE@collation=phonebook");
String idk = ul.getDisplayKeywordValue("collation");
if (ICUTestCase.testingWrapper) {
assertEquals("phonebook", idk);
} else {
// TODO: find real value
assertEquals("phonebook", idk);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayKeywordValue(String, ULocale)'
*/
public void testGetDisplayKeywordValueStringULocale() {
ULocale ul = new ULocale("de_DE@collation=phonebook");
String idk = ul.getDisplayKeywordValue("collation", ULocale.GERMANY);
if (ICUTestCase.testingWrapper) {
assertEquals("phonebook", idk);
} else {
// TODO: find real value
assertEquals("phonebook", idk);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayKeywordValue(String, String, String)'
*/
public void testGetDisplayKeywordValueStringStringString() {
String idk = ULocale.getDisplayKeywordValue("de_DE@collation=phonebook", "collation", "de_DE");
if (ICUTestCase.testingWrapper) {
assertEquals("phonebook", idk);
} else {
// TODO: find real value
assertEquals("phonebook", idk);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayKeywordValue(String, String, ULocale)'
*/
public void testGetDisplayKeywordValueStringStringULocale() {
String idk = ULocale.getDisplayKeywordValue("de_DE@collation=phonebook", "collation", ULocale.GERMANY);
if (ICUTestCase.testingWrapper) {
assertEquals("phonebook", idk);
} else {
// TODO: find real value
assertEquals("phonebook", idk);
}
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayName()'
*/
public void testGetDisplayName() {
String idn = ULocale.GERMANY.getDisplayName();
String jdn = Locale.GERMANY.getDisplayName();
assertEquals(idn, jdn);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayName(ULocale)'
*/
public void testGetDisplayNameULocale() {
String idn = ULocale.GERMANY.getDisplayName(ULocale.GERMANY);
String jdn = Locale.GERMANY.getDisplayName(Locale.GERMANY);
assertEquals(idn, jdn);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayName(String, String)'
*/
public void testGetDisplayNameStringString() {
String idn = ULocale.getDisplayName("de_DE", "de_DE");
String jdn = Locale.GERMANY.getDisplayName(Locale.GERMANY);
assertEquals(idn, jdn);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.getDisplayName(String, ULocale)'
*/
public void testGetDisplayNameStringULocale() {
String idn = ULocale.getDisplayName("de_DE", ULocale.GERMANY);
String jdn = Locale.GERMANY.getDisplayName(Locale.GERMANY);
assertEquals(idn, jdn);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.acceptLanguage(String, ULocale[], boolean[])'
*/
public void testAcceptLanguageStringULocaleArrayBooleanArray() {
boolean[] fallback = new boolean[1];
ULocale[] locales = {
new ULocale("en_CA"),
new ULocale("es_US"),
};
ULocale result = ULocale.acceptLanguage("en-US, en-GB, en-CA, es-US", locales, fallback);
assertEquals(new ULocale("en_CA"), result);
assertFalse(fallback[0]);
result = ULocale.acceptLanguage("en-US, en-GB, es-US-NEWMEXICO", locales, fallback);
assertEquals(new ULocale("es_US"), result);
assertTrue(fallback[0]);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.acceptLanguage(ULocale[], ULocale[], boolean[])'
*/
public void testAcceptLanguageULocaleArrayULocaleArrayBooleanArray() {
boolean[] fallback = new boolean[1];
ULocale[] locales = {
new ULocale("en_CA"),
new ULocale("es_US"),
};
ULocale[] accept_locales = {
new ULocale("en_US"),
new ULocale("en_GB"),
new ULocale("en_CA"),
new ULocale("es_US"),
};
ULocale[] accept_locales2 = {
new ULocale("en_US"),
new ULocale("en_GB"),
new ULocale("es_US_NEWMEXICO"),
};
ULocale result = ULocale.acceptLanguage(accept_locales, locales, fallback);
assertEquals(new ULocale("en_CA"), result);
assertFalse(fallback[0]);
result = ULocale.acceptLanguage(accept_locales2, locales, fallback);
assertEquals(new ULocale("es_US"), result);
assertTrue(fallback[0]);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.acceptLanguage(String, boolean[])'
*/
public void testAcceptLanguageStringBooleanArray() {
boolean[] fallback = new boolean[1];
ULocale result = ULocale.acceptLanguage("en-CA, en-GB, es-US", fallback);
assertEquals(new ULocale("en_CA"), result);
assertFalse(fallback[0]);
result = ULocale.acceptLanguage("es-US-NEWMEXICO", fallback);
assertNotNull(result); // actual result depends on jdk
assertTrue(fallback[0]);
}
/*
* Test method for 'com.ibm.icu.x.util.ULocale.acceptLanguage(ULocale[], boolean[])'
*/
public void testAcceptLanguageULocaleArrayBooleanArray() {
boolean[] fallback = new boolean[1];
ULocale[] accept_locales = {
new ULocale("en_CA"),
new ULocale("en_GB"),
new ULocale("es_US"),
};
ULocale[] accept_locales2 = {
new ULocale("es_US_NEWMEXICO"),
};
ULocale result = ULocale.acceptLanguage(accept_locales, fallback);
assertEquals(new ULocale("en_CA"), result);
assertFalse(fallback[0]);
result = ULocale.acceptLanguage(accept_locales2, fallback);
assertNotNull(result); // actual result depends on jdk
assertTrue(fallback[0]);
}
}

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.ibm.icu.base</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View file

@ -0,0 +1,15 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %pluginName
Bundle-SymbolicName: com.ibm.icu.base
Bundle-Version: 3.4.5
Bundle-Vendor: %providerName
Bundle-Localization: plugin
Bundle-Copyright: Licensed Materials - Property of IBM
(C) Copyright IBM Corp. 2006. All Rights Reserved.
IBM is a registered trademark of IBM Corp.
Export-Package: com.ibm.icu.text,
com.ibm.icu.util
Eclipse-LazyStart: true
Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0,
J2SE-1.3

View file

@ -0,0 +1,9 @@
source.. = src/
output.. = bin/
src.includes = about.html,\
about_files/
bin.includes = about_files/,\
.,\
about.html,\
plugin.properties,\
META-INF/

View file

@ -0,0 +1,171 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="com.ibm.icu.base" default="build.jars" basedir=".">
<property name="basews" value="${ws}"/>
<property name="baseos" value="${os}"/>
<property name="basearch" value="${arch}"/>
<property name="basenl" value="${nl}"/>
<!-- Compiler settings. -->
<property name="javacFailOnError" value="false"/>
<property name="javacDebugInfo" value="on"/>
<property name="javacVerbose" value="false"/>
<property name="logExtension" value=".log"/>
<property name="compilerArg" value=""/>
<property name="javacSource" value="1.3"/>
<property name="javacTarget" value="1.2"/>
<path id="path_bootclasspath">
<fileset dir="${java.home}/lib">
<include name="*.jar"/>
</fileset>
</path>
<property name="bootclasspath" refid="path_bootclasspath"/>
<condition property="bundleBootClasspath" value="${CDC-1.0/Foundation-1.0}">
<isset property="CDC-1.0/Foundation-1.0"/>
</condition>
<condition property="bundleJavacSource" value="1.3">
<isset property="CDC-1.0/Foundation-1.0"/>
</condition>
<condition property="bundleJavacTarget" value="1.1">
<isset property="CDC-1.0/Foundation-1.0"/>
</condition>
<condition property="bundleBootClasspath" value="${J2SE-1.3}">
<isset property="J2SE-1.3"/>
</condition>
<condition property="bundleJavacSource" value="1.3">
<isset property="J2SE-1.3"/>
</condition>
<condition property="bundleJavacTarget" value="1.1">
<isset property="J2SE-1.3"/>
</condition>
<property name="bundleJavacSource" value="${javacSource}"/>
<property name="bundleJavacTarget" value="${javacTarget}"/>
<property name="bundleBootClasspath" value="${bootclasspath}"/>
<target name="init" depends="properties">
<condition property="pluginTemp" value="${buildTempFolder}/plugins">
<isset property="buildTempFolder"/>
</condition>
<property name="pluginTemp" value="${basedir}"/>
<condition property="build.result.folder" value="${pluginTemp}/com.ibm.icu.base">
<isset property="buildTempFolder"/>
</condition>
<property name="build.result.folder" value="${basedir}"/>
<property name="temp.folder" value="${basedir}/temp.folder"/>
<property name="plugin.destination" value="${basedir}"/>
</target>
<target name="properties" if="eclipse.running">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</target>
<target name="build.update.jar" depends="init" description="Build the plug-in: com.ibm.icu.base for an update site.">
<delete dir="${temp.folder}"/>
<mkdir dir="${temp.folder}"/>
<antcall target="build.jars"/>
<antcall target="gather.bin.parts">
<param name="destination.temp.folder" value="${temp.folder}/"/>
</antcall>
<zip destfile="${plugin.destination}/com.ibm.icu.base_3.4.5.jar" basedir="${temp.folder}/com.ibm.icu.base_3.4.5" filesonly="false" whenempty="skip" update="false"/>
<delete dir="${temp.folder}"/>
</target>
<target name="@dot" depends="init" unless="@dot" description="Create jar: com.ibm.icu.base @dot.">
<delete dir="${temp.folder}/@dot.bin"/>
<mkdir dir="${temp.folder}/@dot.bin"/>
<path id="@dot.classpath">
</path>
<!-- compile the source code -->
<javac destdir="${temp.folder}/@dot.bin" failonerror="${javacFailOnError}" verbose="${javacVerbose}" debug="${javacDebugInfo}" includeAntRuntime="no" bootclasspath="${bundleBootClasspath}" source="${bundleJavacSource}" target="${bundleJavacTarget}" >
<compilerarg line="${compilerArg}" compiler="${build.compiler}"/>
<classpath refid="@dot.classpath" />
<src path="src/" />
<compilerarg line="-log '${temp.folder}/@dot.bin${logExtension}'" compiler="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</javac>
<!-- Copy necessary resources -->
<copy todir="${temp.folder}/@dot.bin" failonerror="true" overwrite="false">
<fileset dir="src/" excludes="**/*.java, **/package.htm*" />
</copy>
<mkdir dir="${build.result.folder}"/>
<copy todir="${build.result.folder}/@dot" failonerror="true" overwrite="false">
<fileset dir="${temp.folder}/@dot.bin" />
</copy>
<delete dir="${temp.folder}/@dot.bin"/>
</target>
<target name="src.zip" depends="init" unless="src.zip">
<mkdir dir="${build.result.folder}"/>
<zip destfile="${build.result.folder}/src.zip" filesonly="false" whenempty="skip" update="false">
<fileset dir="src/" includes="**/*.java" />
</zip>
</target>
<target name="build.jars" depends="init" description="Build all the jars for the plug-in: com.ibm.icu.base.">
<available property="@dot" file="${build.result.folder}/@dot"/>
<antcall target="@dot"/>
</target>
<target name="build.sources" depends="init">
<available property="src.zip" file="${build.result.folder}/src.zip"/>
<antcall target="src.zip"/>
</target>
<target name="gather.bin.parts" depends="init" if="destination.temp.folder">
<mkdir dir="${destination.temp.folder}/com.ibm.icu.base_3.4.5"/>
<copy todir="${destination.temp.folder}/com.ibm.icu.base_3.4.5" failonerror="true" overwrite="false">
<fileset dir="${build.result.folder}/@dot" includes="**" />
</copy>
<copy todir="${destination.temp.folder}/com.ibm.icu.base_3.4.5" failonerror="true" overwrite="false">
<fileset dir="${basedir}" includes="META-INF/,about.html,about_files/" />
</copy>
</target>
<target name="build.zips" depends="init">
</target>
<target name="gather.sources" depends="init" if="destination.temp.folder">
<mkdir dir="${destination.temp.folder}/com.ibm.icu.base_3.4.5"/>
<copy file="${build.result.folder}/src.zip" todir="${destination.temp.folder}/com.ibm.icu.base_3.4.5" failonerror="false" overwrite="false"/>
<copy todir="${destination.temp.folder}/com.ibm.icu.base_3.4.5" failonerror="false" overwrite="false">
<fileset dir="${basedir}" includes="about.html, about_files/" />
</copy>
</target>
<target name="gather.logs" depends="init" if="destination.temp.folder">
<mkdir dir="${destination.temp.folder}/com.ibm.icu.base_3.4.5"/>
<copy file="${temp.folder}/@dot.bin${logExtension}" todir="${destination.temp.folder}/com.ibm.icu.base_3.4.5" failonerror="false" overwrite="false"/>
</target>
<target name="clean" depends="init" description="Clean the plug-in: com.ibm.icu.base of all the zips, jars and logs created.">
<delete dir="${build.result.folder}/@dot"/>
<delete file="${build.result.folder}/src.zip"/>
<delete file="${plugin.destination}/com.ibm.icu.base_3.4.5.jar"/>
<delete file="${plugin.destination}/com.ibm.icu.base_3.4.5.zip"/>
<delete dir="${temp.folder}"/>
</target>
<target name="refresh" depends="init" if="eclipse.running" description="Refresh this folder.">
<eclipse.convertPath fileSystemPath="F:/eclipse_icu345/eclipseICU/com.ibm.icu.base" property="resourcePath"/>
<eclipse.refreshLocal resource="${resourcePath}" depth="infinite"/>
</target>
<target name="zip.plugin" depends="init" description="Create a zip containing all the elements for the plug-in: com.ibm.icu.base.">
<delete dir="${temp.folder}"/>
<mkdir dir="${temp.folder}"/>
<antcall target="build.jars"/>
<antcall target="build.sources"/>
<antcall target="gather.bin.parts">
<param name="destination.temp.folder" value="${temp.folder}/"/>
</antcall>
<antcall target="gather.sources">
<param name="destination.temp.folder" value="${temp.folder}/"/>
</antcall>
<delete>
<fileset dir="${temp.folder}" includes="**/*.bin${logExtension}" />
</delete>
<zip destfile="${plugin.destination}/com.ibm.icu.base_3.4.5.zip" basedir="${temp.folder}" filesonly="true" whenempty="skip" update="false"/>
<delete dir="${temp.folder}"/>
</target>
</project>

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
pluginName = International Components for Unicode for Java (ICU4J) Replacement plug-in
providerName = IBM Corporation

View file

@ -0,0 +1,661 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Locale;
import com.ibm.icu.util.ULocale;
/**
* A class that locates boundaries in text. This class defines a protocol for
* objects that break up a piece of natural-language text according to a set
* of criteria. Instances or subclasses of BreakIterator can be provided, for
* example, to break a piece of text into words, sentences, or logical characters
* according to the conventions of some language or group of languages.
*
* We provide five built-in types of BreakIterator:
* <ul><li>getTitleInstance() returns a BreakIterator that locates boundaries
* between title breaks.
* <li>getSentenceInstance() returns a BreakIterator that locates boundaries
* between sentences. This is useful for triple-click selection, for example.
* <li>getWordInstance() returns a BreakIterator that locates boundaries between
* words. This is useful for double-click selection or "find whole words" searches.
* This type of BreakIterator makes sure there is a boundary position at the
* beginning and end of each legal word. (Numbers count as words, too.) Whitespace
* and punctuation are kept separate from real words.
* <li>getLineInstance() returns a BreakIterator that locates positions where it is
* legal for a text editor to wrap lines. This is similar to word breaking, but
* not the same: punctuation and whitespace are generally kept with words (you don't
* want a line to start with whitespace, for example), and some special characters
* can force a position to be considered a line-break position or prevent a position
* from being a line-break position.
* <li>getCharacterInstance() returns a BreakIterator that locates boundaries between
* logical characters. Because of the structure of the Unicode encoding, a logical
* character may be stored internally as more than one Unicode code point. (A with an
* umlaut may be stored as an a followed by a separate combining umlaut character,
* for example, but the user still thinks of it as one character.) This iterator allows
* various processes (especially text editors) to treat as characters the units of text
* that a user would think of as characters, rather than the units of text that the
* computer sees as "characters".</ul>
*
* BreakIterator's interface follows an "iterator" model (hence the name), meaning it
* has a concept of a "current position" and methods like first(), last(), next(),
* and previous() that update the current position. All BreakIterators uphold the
* following invariants:
* <ul><li>The beginning and end of the text are always treated as boundary positions.
* <li>The current position of the iterator is always a boundary position (random-
* access methods move the iterator to the nearest boundary position before or
* after the specified position, not _to_ the specified position).
* <li>DONE is used as a flag to indicate when iteration has stopped. DONE is only
* returned when the current position is the end of the text and the user calls next(),
* or when the current position is the beginning of the text and the user calls
* previous().
* <li>Break positions are numbered by the positions of the characters that follow
* them. Thus, under normal circumstances, the position before the first character
* is 0, the position after the first character is 1, and the position after the
* last character is 1 plus the length of the string.
* <li>The client can change the position of an iterator, or the text it analyzes,
* at will, but cannot change the behavior. If the user wants different behavior, he
* must instantiate a new iterator.</ul>
*
* BreakIterator accesses the text it analyzes through a CharacterIterator, which makes
* it possible to use BreakIterator to analyze text in any text-storage vehicle that
* provides a CharacterIterator interface.
*
* <b>NOTE:</b> Some types of BreakIterator can take a long time to create, and
* instances of BreakIterator are not currently cached by the system. For
* optimal performance, keep instances of BreakIterator around as long as makes
* sense. For example, when word-wrapping a document, don't create and destroy a
* new BreakIterator for each line. Create one break iterator for the whole document
* (or whatever stretch of text you're wrapping) and use it to do the whole job of
* wrapping the text.
*
* <P>
* <strong>Examples</strong>:<P>
* Creating and using text boundaries
* <blockquote>
* <pre>
* public static void main(String args[]) {
* if (args.length == 1) {
* String stringToExamine = args[0];
* //print each word in order
* BreakIterator boundary = BreakIterator.getWordInstance();
* boundary.setText(stringToExamine);
* printEachForward(boundary, stringToExamine);
* //print each sentence in reverse order
* boundary = BreakIterator.getSentenceInstance(Locale.US);
* boundary.setText(stringToExamine);
* printEachBackward(boundary, stringToExamine);
* printFirst(boundary, stringToExamine);
* printLast(boundary, stringToExamine);
* }
* }
* </pre>
* </blockquote>
*
* Print each element in order
* <blockquote>
* <pre>
* public static void printEachForward(BreakIterator boundary, String source) {
* int start = boundary.first();
* for (int end = boundary.next();
* end != BreakIterator.DONE;
* start = end, end = boundary.next()) {
* System.out.println(source.substring(start,end));
* }
* }
* </pre>
* </blockquote>
*
* Print each element in reverse order
* <blockquote>
* <pre>
* public static void printEachBackward(BreakIterator boundary, String source) {
* int end = boundary.last();
* for (int start = boundary.previous();
* start != BreakIterator.DONE;
* end = start, start = boundary.previous()) {
* System.out.println(source.substring(start,end));
* }
* }
* </pre>
* </blockquote>
*
* Print first element
* <blockquote>
* <pre>
* public static void printFirst(BreakIterator boundary, String source) {
* int start = boundary.first();
* int end = boundary.next();
* System.out.println(source.substring(start,end));
* }
* </pre>
* </blockquote>
*
* Print last element
* <blockquote>
* <pre>
* public static void printLast(BreakIterator boundary, String source) {
* int end = boundary.last();
* int start = boundary.previous();
* System.out.println(source.substring(start,end));
* }
* </pre>
* </blockquote>
*
* Print the element at a specified position
* <blockquote>
* <pre>
* public static void printAt(BreakIterator boundary, int pos, String source) {
* int end = boundary.following(pos);
* int start = boundary.previous();
* System.out.println(source.substring(start,end));
* }
* </pre>
* </blockquote>
*
* Find the next word
* <blockquote>
* <pre>
* public static int nextWordStartAfter(int pos, String text) {
* BreakIterator wb = BreakIterator.getWordInstance();
* wb.setText(text);
* int last = wb.following(pos);
* int current = wb.next();
* while (current != BreakIterator.DONE) {
* for (int p = last; p < current; p++) {
* if (Character.isLetter(text.charAt(p))
* return last;
* }
* last = current;
* current = wb.next();
* }
* return BreakIterator.DONE;
* }
* </pre>
* (The iterator returned by BreakIterator.getWordInstance() is unique in that
* the break positions it returns don't represent both the start and end of the
* thing being iterated over. That is, a sentence-break iterator returns breaks
* that each represent the end of one sentence and the beginning of the next.
* With the word-break iterator, the characters between two boundaries might be a
* word, or they might be the punctuation or whitespace between two words. The
* above code uses a simple heuristic to determine which boundary is the beginning
* of a word: If the characters between this boundary and the next boundary
* include at least one letter (this can be an alphabetical letter, a CJK ideograph,
* a Hangul syllable, a Kana character, etc.), then the text between this boundary
* and the next is a word; otherwise, it's the material between words.)
* </blockquote>
*
* @see CharacterIterator
* @stable ICU 2.0
*
*/
public abstract class BreakIterator implements Cloneable {
protected BreakIterator() {
}
/**
* Create a copy of this iterator
* @return A copy of this
*/
public Object clone() {
// this is here for subclass use. we must override it ourselves, though.
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/**
* DONE is returned by previous() and next() after all valid
* boundaries have been returned.
* @stable ICU 2.0
*/
public static final int DONE = -1;
/**
* Return the first boundary position. This is always the beginning
* index of the text this iterator iterates over. For example, if
* the iterator iterates over a whole string, this function will
* always return 0. This function also updates the iteration position
* to point to the beginning of the text.
* @return The character offset of the beginning of the stretch of text
* being broken.
* @stable ICU 2.0
*/
public abstract int first();
/**
* Return the last boundary position. This is always the "past-the-end"
* index of the text this iterator iterates over. For example, if the
* iterator iterates over a whole string (call it "text"), this function
* will always return text.length(). This function also updated the
* iteration position to point to the end of the text.
* @return The character offset of the end of the stretch of text
* being broken.
* @stable ICU 2.0
*/
public abstract int last();
/**
* Advances the specified number of steps forward in the text (a negative
* number, therefore, advances backwards). If this causes the iterator
* to advance off either end of the text, this function returns DONE;
* otherwise, this function returns the position of the appropriate
* boundary. Calling this function is equivalent to calling next() or
* previous() n times.
* @param n The number of boundaries to advance over (if positive, moves
* forward; if negative, moves backwards).
* @return The position of the boundary n boundaries from the current
* iteration position, or DONE if moving n boundaries causes the iterator
* to advance off either end of the text.
* @stable ICU 2.0
*/
public abstract int next(int n);
/**
* Advances the iterator forward one boundary. The current iteration
* position is updated to point to the next boundary position after the
* current position, and this is also the value that is returned. If
* the current position is equal to the value returned by last(), or to
* DONE, this function returns DONE and sets the current position to
* DONE.
* @return The position of the first boundary position following the
* iteration position.
* @stable ICU 2.0
*/
public abstract int next();
/**
* Advances the iterator backward one boundary. The current iteration
* position is updated to point to the last boundary position before
* the current position, and this is also the value that is returned. If
* the current position is equal to the value returned by first(), or to
* DONE, this function returns DONE and sets the current position to
* DONE.
* @return The position of the last boundary position preceding the
* iteration position.
* @stable ICU 2.0
*/
public abstract int previous();
/**
* Sets the iterator's current iteration position to be the first
* boundary position following the specified position. (Whether the
* specified position is itself a boundary position or not doesn't
* matter-- this function always moves the iteration position to the
* first boundary after the specified position.) If the specified
* position is the past-the-end position, returns DONE.
* @param offset The character position to start searching from.
* @return The position of the first boundary position following
* "offset" (whether or not "offset" itself is a boundary position),
* or DONE if "offset" is the past-the-end offset.
* @stable ICU 2.0
*/
public abstract int following(int offset);
/**
* Sets the iterator's current iteration position to be the last
* boundary position preceding the specified position. (Whether the
* specified position is itself a boundary position or not doesn't
* matter-- this function always moves the iteration position to the
* last boundary before the specified position.) If the specified
* position is the starting position, returns DONE.
* @param offset The character position to start searching from.
* @return The position of the last boundary position preceding
* "offset" (whether of not "offset" itself is a boundary position),
* or DONE if "offset" is the starting offset of the iterator.
* @stable ICU 2.0
*/
public int preceding(int offset) {
int pos = following(offset);
while (pos >= offset && pos != DONE) {
pos = previous();
}
return pos;
}
/**
* Return true if the specfied position is a boundary position. If the
* function returns true, the current iteration position is set to the
* specified position; if the function returns false, the current
* iteration position is set as though following() had been called.
* @param offset the offset to check.
* @return True if "offset" is a boundary position.
* @stable ICU 2.0
*/
public boolean isBoundary(int offset) {
return offset == 0 || following(offset - 1) == offset;
}
/**
* Return the iterator's current position.
* @return The iterator's current position.
* @stable ICU 2.0
*/
public abstract int current();
/**
* Returns a CharacterIterator over the text being analyzed.
* For at least some subclasses of BreakIterator, this is a reference
* to the <b>actual iterator being used</b> by the BreakIterator,
* and therefore, this function's return value should be treated as
* <tt>const</tt>. No guarantees are made about the current position
* of this iterator when it is returned. If you need to move that
* position to examine the text, clone this function's return value first.
* @return A CharacterIterator over the text being analyzed.
* @stable ICU 2.0
*/
public abstract CharacterIterator getText();
/**
* Sets the iterator to analyze a new piece of text. The new
* piece of text is passed in as a String, and the current
* iteration position is reset to the beginning of the string.
* (The old text is dropped.)
* @param newText A String containing the text to analyze with
* this BreakIterator.
* @stable ICU 2.0
*/
public void setText(String newText) {
setText(new StringCharacterIterator(newText));
}
/**
* Sets the iterator to analyze a new piece of text. The
* BreakIterator is passed a CharacterIterator through which
* it will access the text itself. The current iteration
* position is reset to the CharacterIterator's start index.
* (The old iterator is dropped.)
* @param newText A CharacterIterator referring to the text
* to analyze with this BreakIterator (the iterator's current
* position is ignored, but its other state is significant).
* @stable ICU 2.0
*/
public abstract void setText(CharacterIterator newText);
/** @stable ICU 2.4 */
public static final int KIND_CHARACTER = 0;
/** @stable ICU 2.4 */
public static final int KIND_WORD = 1;
/** @stable ICU 2.4 */
public static final int KIND_LINE = 2;
/** @stable ICU 2.4 */
public static final int KIND_SENTENCE = 3;
/** @stable ICU 2.4 */
public static final int KIND_TITLE = 4;
/**
* Returns a new instance of BreakIterator that locates word boundaries.
* This function assumes that the text being analyzed is in the default
* locale's language.
* @return An instance of BreakIterator that locates word boundaries.
* @stable ICU 2.0
*/
public static BreakIterator getWordInstance() {
return getWordInstance(Locale.getDefault());
}
/**
* Returns a new instance of BreakIterator that locates word boundaries.
* @param where A locale specifying the language of the text to be
* analyzed.
* @return An instance of BreakIterator that locates word boundaries.
* @stable ICU 2.0
*/
public static BreakIterator getWordInstance(Locale where) {
return getBreakInstance(where, KIND_WORD);
}
/**
* Returns a new instance of BreakIterator that locates word boundaries.
* @param where A locale specifying the language of the text to be
* analyzed.
* @return An instance of BreakIterator that locates word boundaries.
* @stable ICU 3.4.3
*/
public static BreakIterator getWordInstance(ULocale where) {
return getBreakInstance(where.toLocale(), KIND_WORD);
}
/**
* Returns a new instance of BreakIterator that locates legal line-
* wrapping positions. This function assumes the text being broken
* is in the default locale's language.
* @return A new instance of BreakIterator that locates legal
* line-wrapping positions.
* @stable ICU 2.0
*/
public static BreakIterator getLineInstance() {
return getLineInstance(Locale.getDefault());
}
/**
* Returns a new instance of BreakIterator that locates legal line-
* wrapping positions.
* @param where A Locale specifying the language of the text being broken.
* @return A new instance of BreakIterator that locates legal
* line-wrapping positions.
* @stable ICU 2.0
*/
public static BreakIterator getLineInstance(Locale where) {
return getBreakInstance(where, KIND_LINE);
}
/**
* Returns a new instance of BreakIterator that locates legal line-
* wrapping positions.
* @param where A Locale specifying the language of the text being broken.
* @return A new instance of BreakIterator that locates legal
* line-wrapping positions.
* @stable ICU 3.4.3
*/
public static BreakIterator getLineInstance(ULocale where) {
return getBreakInstance(where.toLocale(), KIND_LINE);
}
/**
* Returns a new instance of BreakIterator that locates logical-character
* boundaries. This function assumes that the text being analyzed is
* in the default locale's language.
* @return A new instance of BreakIterator that locates logical-character
* boundaries.
* @stable ICU 2.0
*/
public static BreakIterator getCharacterInstance() {
return getCharacterInstance(Locale.getDefault());
}
/**
* Returns a new instance of BreakIterator that locates logical-character
* boundaries.
* @param where A Locale specifying the language of the text being analyzed.
* @return A new instance of BreakIterator that locates logical-character
* boundaries.
* @stable ICU 2.0
*/
public static BreakIterator getCharacterInstance(Locale where) {
return getBreakInstance(where, KIND_CHARACTER);
}
/**
* Returns a new instance of BreakIterator that locates logical-character
* boundaries.
* @param where A Locale specifying the language of the text being analyzed.
* @return A new instance of BreakIterator that locates logical-character
* boundaries.
* @draft ICU 3.2
*/
public static BreakIterator getCharacterInstance(ULocale where) {
return getBreakInstance(where.toLocale(), KIND_CHARACTER);
}
/**
* Returns a new instance of BreakIterator that locates sentence boundaries.
* This function assumes the text being analyzed is in the default locale's
* language.
* @return A new instance of BreakIterator that locates sentence boundaries.
* @stable ICU 2.0
*/
public static BreakIterator getSentenceInstance() {
return getSentenceInstance(Locale.getDefault());
}
/**
* Returns a new instance of BreakIterator that locates sentence boundaries.
* @param where A Locale specifying the language of the text being analyzed.
* @return A new instance of BreakIterator that locates sentence boundaries.
* @stable ICU 2.0
*/
public static BreakIterator getSentenceInstance(Locale where) {
return getBreakInstance(where, KIND_SENTENCE);
}
/**
* Returns a new instance of BreakIterator that locates sentence boundaries.
* @param where A Locale specifying the language of the text being analyzed.
* @return A new instance of BreakIterator that locates sentence boundaries.
* @stable ICU 3.4.3
*/
public static BreakIterator getSentenceInstance(ULocale where) {
return getBreakInstance(where.toLocale(), KIND_SENTENCE);
}
private static BreakIterator getBreakInstance(Locale where, int kind) {
java.text.BreakIterator br = null;
switch(kind) {
case KIND_CHARACTER: br = java.text.BreakIterator.getCharacterInstance(where); break;
case KIND_WORD: br = java.text.BreakIterator.getWordInstance(where); break;
case KIND_LINE: br = java.text.BreakIterator.getLineInstance(where); break;
case KIND_SENTENCE: br = java.text.BreakIterator.getSentenceInstance(where); break;
case KIND_TITLE: throw new UnsupportedOperationException();
}
return new BreakIteratorHandle(br);
}
/**
* Returns a list of locales for which BreakIterators can be used.
* @return An array of Locales. All of the locales in the array can
* be used when creating a BreakIterator.
* @stable ICU 3.4.3
*/
public static synchronized Locale[] getAvailableLocales() {
return java.text.BreakIterator.getAvailableLocales();
}
/**
* Returns a list of locales for which BreakIterators can be used.
* @return An array of ULocales. All of the locales in the array can
* be used when creating a BreakIterator.
* @stable ICU 3.4.3
*/
public static synchronized ULocale[] getAvailableULocales() {
Locale[] locales = java.text.BreakIterator.getAvailableLocales();
ULocale[] ulocales = new ULocale[locales.length];
for (int i = 0; i < locales.length; ++i) {
ulocales[i] = ULocale.forLocale(locales[i]);
}
return ulocales;
}
// forwarding implementation class
static final class BreakIteratorHandle extends BreakIterator {
/**
* @internal
*/
public final java.text.BreakIterator breakIterator;
/**
* @internal
* @param delegate the BreakIterator to which to delegate
*/
public BreakIteratorHandle(java.text.BreakIterator delegate) {
this.breakIterator = delegate;
}
public int first() {
return breakIterator.first();
}
public int last() {
return breakIterator.last();
}
public int next(int n) {
return breakIterator.next(n);
}
public int next() {
return breakIterator.next();
}
public int previous() {
return breakIterator.previous();
}
public int following(int offset) {
return breakIterator.following(offset);
}
public int preceding(int offset) {
return breakIterator.preceding(offset);
}
public boolean isBoundary(int offset) {
return breakIterator.isBoundary(offset);
}
public int current() {
return breakIterator.current();
}
public CharacterIterator getText() {
return breakIterator.getText();
}
public void setText(CharacterIterator newText) {
breakIterator.setText(newText);
}
/**
* Return a string suitable for debugging.
* @return a string suitable for debugging
* @stable ICU 3.4.3
*/
public String toString() {
return breakIterator.toString();
}
/**
* Return a clone of this BreakIterator.
* @return a clone of this BreakIterator
* @stable ICU 3.4.3
*/
public Object clone() {
return new BreakIteratorHandle((java.text.BreakIterator)breakIterator.clone());
}
/**
* Return true if rhs is a BreakIterator with the same break behavior as this.
* @return true if rhs equals this
* @stable ICU 3.4.3
*/
public boolean equals(Object rhs) {
try {
return breakIterator.equals(((BreakIteratorHandle)rhs).breakIterator);
}
catch (Exception e) {
return false;
}
}
/**
* Return a hashCode.
* @return a hashCode
* @stable ICU 3.4.3
*/
public int hashCode() {
return breakIterator.hashCode();
}
}
}

View file

@ -0,0 +1,250 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
/**
* <p>A <code>CollationKey</code> represents a <code>String</code>
* under the rules of a specific <code>Collator</code>
* object. Comparing two <code>CollationKey</code>s returns the
* relative order of the <code>String</code>s they represent.</p>
*
* <p>Since the rule set of <code>Collator</code>s can differ, the
* sort orders of the same string under two different
* <code>Collator</code>s might differ. Hence comparing
* <code>CollationKey</code>s generated from different
* <code>Collator</code>s can give incorrect results.</p>
* <p>Both the method
* <code>CollationKey.compareTo(CollationKey)</code> and the method
* <code>Collator.compare(String, String)</code> compare two strings
* and returns their relative order. The performance characterictics
* of these two approaches can differ.</p>
*
* <p>During the construction of a <code>CollationKey</code>, the
* entire source string is examined and processed into a series of
* bits terminated by a null, that are stored in the <code>CollationKey</code>.
* When <code>CollationKey.compareTo(CollationKey)</code> executes, it
* performs bitwise comparison on the bit sequences. This can incurs
* startup cost when creating the <code>CollationKey</code>, but once
* the key is created, binary comparisons are fast. This approach is
* recommended when the same strings are to be compared over and over
* again.</p>
*
* <p>On the other hand, implementations of
* <code>Collator.compare(String, String)</code> can examine and
* process the strings only until the first characters differing in
* order. This approach is recommended if the strings are to be
* compared only once.</p>
*
* <p>More information about the composition of the bit sequence can
* be found in the
* <a href="http://icu.sourceforge.net/userguide/Collate_ServiceArchitecture.html">
* user guide</a>.</p>
*
* <p>The following example shows how <code>CollationKey</code>s can be used
* to sort a list of <code>String</code>s.</p>
* <blockquote>
* <pre>
* // Create an array of CollationKeys for the Strings to be sorted.
* Collator myCollator = Collator.getInstance();
* CollationKey[] keys = new CollationKey[3];
* keys[0] = myCollator.getCollationKey("Tom");
* keys[1] = myCollator.getCollationKey("Dick");
* keys[2] = myCollator.getCollationKey("Harry");
* sort( keys );
* <br>
* //...
* <br>
* // Inside body of sort routine, compare keys this way
* if( keys[i].compareTo( keys[j] ) > 0 )
* // swap keys[i] and keys[j]
* <br>
* //...
* <br>
* // Finally, when we've returned from sort.
* System.out.println( keys[0].getSourceString() );
* System.out.println( keys[1].getSourceString() );
* System.out.println( keys[2].getSourceString() );
* </pre>
* </blockquote>
* </p>
* <p>
* This class is not subclassable
* </p>
* @see Collator
* @see RuleBasedCollator
* @stable ICU 2.8
*/
public final class CollationKey implements Comparable {
/**
* @internal
*/
final java.text.CollationKey key;
/**
* @internal
*/
CollationKey(java.text.CollationKey delegate) {
this.key = delegate;
}
/**
* Return the source string that this CollationKey represents.
* @return source string that this CollationKey represents
* @stable ICU 2.8
*/
public String getSourceString() {
return key.getSourceString();
}
/**
* <p>Duplicates and returns the value of this CollationKey as a sequence
* of big-endian bytes terminated by a null.</p>
*
* <p>If two CollationKeys can be legitimately compared, then one can
* compare the byte arrays of each to obtain the same result, e.g.
* <pre>
* byte key1[] = collationkey1.toByteArray();
* byte key2[] = collationkey2.toByteArray();
* int key, targetkey;
* int i = 0;
* do {
* key = key1[i] & 0xFF;
* targetkey = key2[i] & 0xFF;
* if (key &lt; targetkey) {
* System.out.println("String 1 is less than string 2");
* return;
* }
* if (targetkey &lt; key) {
* System.out.println("String 1 is more than string 2");
* }
* i ++;
* } while (key != 0 && targetKey != 0);
*
* System.out.println("Strings are equal.");
* </pre>
* </p>
* @return CollationKey value in a sequence of big-endian byte bytes
* terminated by a null.
* @stable ICU 2.8
*/
public byte[] toByteArray() {
return key.toByteArray();
}
/**
* <p>Compare this CollationKey to another CollationKey. The
* collation rules of the Collator that created this key are
* applied.</p>
*
* <p><strong>Note:</strong> Comparison between CollationKeys
* created by different Collators might return incorrect
* results. See class documentation.</p>
*
* @param target target CollationKey
* @return an integer value. If the value is less than zero this CollationKey
* is less than than target, if the value is zero they are equal, and
* if the value is greater than zero this CollationKey is greater
* than target.
* @exception NullPointerException is thrown if argument is null.
* @see Collator#compare(String, String)
* @stable ICU 2.8
*/
public int compareTo(CollationKey target) {
return key.compareTo(target.key);
}
/**
* <p>Compare this CollationKey with the specified Object. The
* collation rules of the Collator that created this key are
* applied.</p>
*
* <p>See note in compareTo(CollationKey) for warnings about possible
* incorrect results.</p>
*
* @param obj the Object to be compared to.
* @return Returns a negative integer, zero, or a positive integer
* respectively if this CollationKey is less than, equal to, or
* greater than the given Object.
* @exception ClassCastException is thrown when the argument is not
* a CollationKey. NullPointerException is thrown when the argument
* is null.
* @see #compareTo(CollationKey)
* @stable ICU 2.8
*/
public int compareTo(Object o) {
return compareTo((CollationKey)o);
}
/**
* <p>Compare this CollationKey and the specified Object for
* equality. The collation rules of the Collator that created
* this key are applied.</p>
*
* <p>See note in compareTo(CollationKey) for warnings about
* possible incorrect results.</p>
*
* @param target the object to compare to.
* @return true if the two keys compare as equal, false otherwise.
* @see #compareTo(CollationKey)
* @exception ClassCastException is thrown when the argument is not
* a CollationKey. NullPointerException is thrown when the argument
* is null.
* @stable ICU 2.8
*/
public boolean equals(Object target) {
try {
return key.equals(((CollationKey)target).key);
}
catch (Exception e) {
return false;
}
}
/**
* <p>
* Compare this CollationKey and the argument target CollationKey for
* equality.
* The collation
* rules of the Collator object which created these objects are applied.
* </p>
* <p>
* See note in compareTo(CollationKey) for warnings of incorrect results
* </p>
* @param target the CollationKey to compare to.
* @return true if two objects are equal, false otherwise.
* @exception NullPointerException is thrown when the argument is null.
* @stable ICU 2.8
*/
public boolean equals(CollationKey target) {
return key.equals(target.key);
}
/**
* <p>Returns a hash code for this CollationKey. The hash value is calculated
* on the key itself, not the String from which the key was created. Thus
* if x and y are CollationKeys, then x.hashCode(x) == y.hashCode()
* if x.equals(y) is true. This allows language-sensitive comparison in a
* hash table.
* </p>
* @return the hash value.
* @stable ICU 2.8
*/
public int hashCode() {
return key.hashCode();
}
/**
* Return a description of the CollationKey.
* @return a description of the CollationKey, used for debugging
* @stable ICU 3.4.2
*/
public String toString() {
return key.toString();
}
}

View file

@ -0,0 +1,567 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import java.util.Comparator;
import java.util.Locale;
import com.ibm.icu.util.ULocale;
/**
* <p>Collator performs locale-sensitive string comparison.</p>
*
* <p>Following the <a href=http://www.unicode.org>Unicode
* Consortium</a>'s specifications for the
* <a href="http://www.unicode.org/unicode/reports/tr10/"> Unicode Collation
* Algorithm (UCA)</a>, there are 5 different levels of strength used
* in comparisons:
*
* <ul>
* <li>PRIMARY strength: Typically, this is used to denote differences between
* base characters (for example, "a" &lt; "b").
* It is the strongest difference. For example, dictionaries are divided
* into different sections by base character.
* <li>SECONDARY strength: Accents in the characters are considered secondary
* differences (for example, "as" &lt; "&agrave;s" &lt; "at"). Other
* differences
* between letters can also be considered secondary differences, depending
* on the language. A secondary difference is ignored when there is a
* primary difference anywhere in the strings.
* <li>TERTIARY strength: Upper and lower case differences in characters are
* distinguished at tertiary strength (for example, "ao" &lt; "Ao" &lt;
* "a&ograve;"). In addition, a variant of a letter differs from the base
* form on the tertiary strength (such as "A" and "&#9398;"). Another
* example is the
* difference between large and small Kana. A tertiary difference is ignored
* when there is a primary or secondary difference anywhere in the strings.
* <li>QUATERNARY strength: When punctuation is ignored
* <a href="http://icu.sourceforge.net/userguide/Collate_Concepts.html#Ignoring_Punctuation">
* (see Ignoring Punctuations in the user guide)</a> at PRIMARY to TERTIARY
* strength, an additional strength level can
* be used to distinguish words with and without punctuation (for example,
* "ab" &lt; "a-b" &lt; "aB").
* This difference is ignored when there is a PRIMARY, SECONDARY or TERTIARY
* difference. The QUATERNARY strength should only be used if ignoring
* punctuation is required.
* <li>IDENTICAL strength:
* When all other strengths are equal, the IDENTICAL strength is used as a
* tiebreaker. The Unicode code point values of the NFD form of each string
* are compared, just in case there is no difference.
* For example, Hebrew cantellation marks are only distinguished at this
* strength. This strength should be used sparingly, as only code point
* value differences between two strings is an extremely rare occurrence.
* Using this strength substantially decreases the performance for both
* comparison and collation key generation APIs. This strength also
* increases the size of the collation key.
* </ul>
*
* Unlike the JDK, ICU4J's Collator deals only with 2 decomposition modes,
* the canonical decomposition mode and one that does not use any decomposition.
* The compatibility decomposition mode, java.text.Collator.FULL_DECOMPOSITION
* is not supported here. If the canonical
* decomposition mode is set, the Collator handles un-normalized text properly,
* producing the same results as if the text were normalized in NFD. If
* canonical decomposition is turned off, it is the user's responsibility to
* ensure that all text is already in the appropriate form before performing
* a comparison or before getting a CollationKey.</p>
*
* <p>For more information about the collation service see the
* <a href="http://icu.sourceforge.net/userguide/Collate_Intro.html">users
* guide</a>.</p>
*
* <p>Examples of use
* <pre>
* // Get the Collator for US English and set its strength to PRIMARY
* Collator usCollator = Collator.getInstance(Locale.US);
* usCollator.setStrength(Collator.PRIMARY);
* if (usCollator.compare("abc", "ABC") == 0) {
* System.out.println("Strings are equivalent");
* }
*
* The following example shows how to compare two strings using the
* Collator for the default locale.
*
* // Compare two strings in the default locale
* Collator myCollator = Collator.getInstance();
* myCollator.setDecomposition(NO_DECOMPOSITION);
* if (myCollator.compare("&agrave;&#92;u0325", "a&#92;u0325&#768;") != 0) {
* System.out.println("&agrave;&#92;u0325 is not equals to a&#92;u0325&#768; without decomposition");
* myCollator.setDecomposition(CANONICAL_DECOMPOSITION);
* if (myCollator.compare("&agrave;&#92;u0325", "a&#92;u0325&#768;") != 0) {
* System.out.println("Error: &agrave;&#92;u0325 should be equals to a&#92;u0325&#768; with decomposition");
* }
* else {
* System.out.println("&agrave;&#92;u0325 is equals to a&#92;u0325&#768; with decomposition");
* }
* }
* else {
* System.out.println("Error: &agrave;&#92;u0325 should be not equals to a&#92;u0325&#768; without decomposition");
* }
* </pre>
* </p>
* @see CollationKey
* @author Syn Wee Quek
* @stable ICU 2.8
*/
public class Collator implements Comparator, Cloneable
{
/**
* @internal
*/
private final java.text.Collator collator;
/**
* @internal
*/
private Collator(java.text.Collator delegate) {
this.collator = delegate;
}
/**
* Create a collator with a null delegate.
* For use by possible subclassers. This is present since
* the original Collator is abstract, and so, in theory
* subclassable. All member APIs must be overridden.
*/
protected Collator() {
this.collator = null;
}
// public data members ---------------------------------------------------
/**
* Strongest collator strength value. Typically used to denote differences
* between base characters. See class documentation for more explanation.
* @see #setStrength
* @see #getStrength
* @stable ICU 2.8
*/
public final static int PRIMARY = java.text.Collator.PRIMARY;
/**
* Second level collator strength value.
* Accents in the characters are considered secondary differences.
* Other differences between letters can also be considered secondary
* differences, depending on the language.
* See class documentation for more explanation.
* @see #setStrength
* @see #getStrength
* @stable ICU 2.8
*/
public final static int SECONDARY = java.text.Collator.SECONDARY;
/**
* Third level collator strength value.
* Upper and lower case differences in characters are distinguished at this
* strength level. In addition, a variant of a letter differs from the base
* form on the tertiary level.
* See class documentation for more explanation.
* @see #setStrength
* @see #getStrength
* @stable ICU 2.8
*/
public final static int TERTIARY = java.text.Collator.TERTIARY;
/**
* Fourth level collator strength value.
* When punctuation is ignored
* <a href="http://icu.sourceforge.net/userguide/Collate_Concepts.html#Ignoring_Punctuation">
* (see Ignoring Punctuations in the user guide)</a> at PRIMARY to TERTIARY
* strength, an additional strength level can
* be used to distinguish words with and without punctuation.
* See class documentation for more explanation.
* @see #setStrength
* @see #getStrength
* @stable ICU 2.8
*/
public final static int QUATERNARY = java.text.Collator.IDENTICAL;
/**
* <p>
* Smallest Collator strength value. When all other strengths are equal,
* the IDENTICAL strength is used as a tiebreaker. The Unicode code point
* values of the NFD form of each string are compared, just in case there
* is no difference.
* See class documentation for more explanation.
* </p>
* <p>
* Note this value is different from JDK's
* </p>
* @stable ICU 2.8
*/
public final static int IDENTICAL = java.text.Collator.FULL_DECOMPOSITION;
/**
* This is for backwards compatibility with Java APIs only. It
* should not be used, IDENTICAL should be used instead. ICU's
* collation does not support Java's FULL_DECOMPOSITION mode.
* @draft ICU 3.4
* @deprecated Backwards compatibility with Java only.
*/
public final static int FULL_DECOMPOSITION = java.text.Collator.FULL_DECOMPOSITION;
/**
* <p>Decomposition mode value. With NO_DECOMPOSITION set, Strings
* will not be decomposed for collation. This is the default
* decomposition setting unless otherwise specified by the locale
* used to create the Collator.</p>
*
* <p><strong>Note</strong> this value is different from the JDK's.</p>
* @see #CANONICAL_DECOMPOSITION
* @see #getDecomposition
* @see #setDecomposition
* @stable ICU 2.8
*/
public final static int NO_DECOMPOSITION = java.text.Collator.NO_DECOMPOSITION;
/**
* <p>Decomposition mode value. With CANONICAL_DECOMPOSITION set,
* characters that are canonical variants according to the Unicode standard
* will be decomposed for collation.</p>
*
* <p>CANONICAL_DECOMPOSITION corresponds to Normalization Form D as
* described in <a href="http://www.unicode.org/unicode/reports/tr15/">
* Unicode Technical Report #15</a>.
* </p>
* @see #NO_DECOMPOSITION
* @see #getDecomposition
* @see #setDecomposition
* @stable ICU 2.8
*/
public final static int CANONICAL_DECOMPOSITION = java.text.Collator.CANONICAL_DECOMPOSITION;
// public methods --------------------------------------------------------
// public setters --------------------------------------------------------
/**
* <p>Sets this Collator's strength property. The strength property
* determines the minimum level of difference considered significant
* during comparison.</p>
*
* <p>The default strength for the Collator is TERTIARY, unless specified
* otherwise by the locale used to create the Collator.</p>
*
* <p>See the Collator class description for an example of use.</p>
* @param newStrength the new strength value.
* @see #getStrength
* @see #PRIMARY
* @see #SECONDARY
* @see #TERTIARY
* @see #QUATERNARY
* @see #IDENTICAL
* @exception IllegalArgumentException if the new strength value is not one
* of PRIMARY, SECONDARY, TERTIARY, QUATERNARY or IDENTICAL.
* @stable ICU 2.8
*/
public void setStrength(int newStrength) {
collator.setStrength(newStrength);
}
/**
* <p>Set the decomposition mode of this Collator. Setting this
* decomposition property with CANONICAL_DECOMPOSITION allows the
* Collator to handle un-normalized text properly, producing the
* same results as if the text were normalized. If
* NO_DECOMPOSITION is set, it is the user's responsibility to
* insure that all text is already in the appropriate form before
* a comparison or before getting a CollationKey. Adjusting
* decomposition mode allows the user to select between faster and
* more complete collation behavior.</p>
*
* <p>Since a great many of the world's languages do not require
* text normalization, most locales set NO_DECOMPOSITION as the
* default decomposition mode.</p>
*
* The default decompositon mode for the Collator is
* NO_DECOMPOSITON, unless specified otherwise by the locale used
* to create the Collator.</p>
*
* <p>See getDecomposition for a description of decomposition
* mode.</p>
*
* @param decomposition the new decomposition mode
* @see #getDecomposition
* @see #NO_DECOMPOSITION
* @see #CANONICAL_DECOMPOSITION
* @exception IllegalArgumentException If the given value is not a valid
* decomposition mode.
* @stable ICU 2.8
*/
public void setDecomposition(int decomposition) {
collator.setDecomposition(decomposition);
}
// public getters --------------------------------------------------------
/**
* Gets the Collator for the current default locale.
* The default locale is determined by java.util.Locale.getDefault().
* @return the Collator for the default locale (for example, en_US) if it
* is created successfully. Otherwise if there is no Collator
* associated with the current locale, the default UCA collator
* will be returned.
* @see java.util.Locale#getDefault()
* @see #getInstance(Locale)
* @stable ICU 2.8
*/
public static final Collator getInstance() {
return new Collator(java.text.Collator.getInstance());
}
/**
* Gets the Collator for the desired locale.
* @param locale the desired locale.
* @return Collator for the desired locale if it is created successfully.
* Otherwise if there is no Collator
* associated with the current locale, a default UCA collator will
* be returned.
* @see java.util.Locale
* @see java.util.ResourceBundle
* @see #getInstance(Locale)
* @see #getInstance()
* @stable ICU 3.4.3
*/
public static final Collator getInstance(ULocale locale) {
return getInstance(locale.toLocale());
}
/**
* Gets the Collator for the desired locale.
* @param locale the desired locale.
* @return Collator for the desired locale if it is created successfully.
* Otherwise if there is no Collator
* associated with the current locale, a default UCA collator will
* be returned.
* @see java.util.Locale
* @see java.util.ResourceBundle
* @see #getInstance(ULocale)
* @see #getInstance()
* @stable ICU 2.8
*/
public static final Collator getInstance(Locale locale) {
return new Collator(java.text.Collator.getInstance(locale));
}
/**
* Get the set of locales, as Locale objects, for which collators
* are installed. Note that Locale objects do not support RFC 3066.
* @return the list of locales in which collators are installed.
* This list includes any that have been registered, in addition to
* those that are installed with ICU4J.
* @stable ICU 2.4
*/
public static Locale[] getAvailableLocales() {
return java.text.Collator.getAvailableLocales();
}
/**
* Get the set of locales, as ULocale objects, for which collators
* are installed. ULocale objects support RFC 3066.
* @return the list of locales in which collators are installed.
* This list includes any that have been registered, in addition to
* those that are installed with ICU4J.
* @stable ICU 3.4.3
*/
public static final ULocale[] getAvailableULocales() {
Locale[] locales = java.text.Collator.getAvailableLocales();
ULocale[] ulocales = new ULocale[locales.length];
for (int i = 0; i < locales.length; ++i) {
ulocales[i] = ULocale.forLocale(locales[i]);
}
return ulocales;
}
/**
* Return an array of all possible keywords that are relevant to
* collation. At this point, the only recognized keyword for this
* service is "collation".
* @return an array of valid collation keywords.
* @see #getKeywordValues
* @draft ICU 3.0
* @provisional
*/
public static final String[] getKeywords() {
return new String[0];
}
/**
* Given a keyword, return an array of all values for
* that keyword that are currently in use.
* @param keyword one of the keywords returned by getKeywords.
* @see #getKeywords
* @draft ICU 3.0
* @provisional
*/
public static final String[] getKeywordValues(String keyword) {
return new String[0];
}
/**
* <p>Returns this Collator's strength property. The strength property
* determines the minimum level of difference considered significant.
* </p>
* <p>
* See the Collator class description for more details.
* </p>
* @return this Collator's current strength property.
* @see #setStrength
* @see #PRIMARY
* @see #SECONDARY
* @see #TERTIARY
* @see #QUATERNARY
* @see #IDENTICAL
* @stable ICU 2.8
*/
public int getStrength() {
return collator.getStrength();
}
/**
* <p>
* Get the decomposition mode of this Collator. Decomposition mode
* determines how Unicode composed characters are handled.
* </p>
* <p>
* See the Collator class description for more details.
* </p>
* @return the decomposition mode
* @see #setDecomposition
* @see #NO_DECOMPOSITION
* @see #CANONICAL_DECOMPOSITION
* @stable ICU 2.8
*/
public int getDecomposition() {
return collator.getDecomposition();
}
/**
* <p>
* Compares the source text String to the target text String according to
* this Collator's rules, strength and decomposition mode.
* Returns an integer less than,
* equal to or greater than zero depending on whether the source String is
* less than, equal to or greater than the target String. See the Collator
* class description for an example of use.
* </p>
* @param source the source String.
* @param target the target String.
* @return Returns an integer value. Value is less than zero if source is
* less than target, value is zero if source and target are equal,
* value is greater than zero if source is greater than target.
* @see CollationKey
* @see #getCollationKey
* @exception NullPointerException thrown if either arguments is null.
* IllegalArgumentException thrown if either source or target is
* not of the class String.
* @stable ICU 2.8
*/
public int compare(Object source, Object target) {
return collator.compare(source, target);
}
// public other methods -------------------------------------------------
/**
* Convenience method for comparing the equality of two text Strings using
* this Collator's rules, strength and decomposition mode.
* @param source the source string to be compared.
* @param target the target string to be compared.
* @return true if the strings are equal according to the collation
* rules, otherwise false.
* @see #compare
* @exception NullPointerException thrown if either arguments is null.
* @stable ICU 2.8
*/
public boolean equals(String source, String target) {
return (compare(source, target) == 0);
}
/**
* <p>
* Compares the source text String to the target text String according to
* this Collator's rules, strength and decomposition mode.
* Returns an integer less than,
* equal to or greater than zero depending on whether the source String is
* less than, equal to or greater than the target String. See the Collator
* class description for an example of use.
* </p>
* @param source the source String.
* @param target the target String.
* @return Returns an integer value. Value is less than zero if source is
* less than target, value is zero if source and target are equal,
* value is greater than zero if source is greater than target.
* @see CollationKey
* @see #getCollationKey
* @exception NullPointerException thrown if either arguments is null.
* @stable ICU 2.8
*/
public int compare(String source, String target) {
return collator.compare(source, target);
}
/**
* <p>
* Transforms the String into a CollationKey suitable for efficient
* repeated comparison. The resulting key depends on the collator's
* rules, strength and decomposition mode.
* </p>
* <p>See the CollationKey class documentation for more information.</p>
* @param source the string to be transformed into a CollationKey.
* @return the CollationKey for the given String based on this Collator's
* collation rules. If the source String is null, a null
* CollationKey is returned.
* @see CollationKey
* @see #compare(String, String)
* @stable ICU 2.8
*/
public CollationKey getCollationKey(String source) {
return new CollationKey(collator.getCollationKey(source));
}
/**
* Return a string suitable for debugging.
* @return a string suitable for debugging
* @stable ICU 3.4.3
*/
public String toString() {
return collator.toString();
}
/**
* Clone the collator.
* @return a clone of this collator.
* @stable ICU 2.6
*/
public Object clone() throws CloneNotSupportedException {
return new Collator((java.text.Collator)collator.clone());
}
/**
* Return true if rhs is a Collator and compares the same as this.
* @return true if rhs equals this
* @stable ICU 3.4.3
*/
public boolean equals(Object rhs) {
try {
return collator.equals(((Collator)rhs).collator);
}
catch (Exception e) {
return false;
}
}
/**
* Return a hashCode.
* @return a hashCode
* @stable ICU 3.4.3
*/
public int hashCode() {
return collator.hashCode();
}
}

View file

@ -0,0 +1,988 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;
/**
* DateFormat is an abstract class for date/time formatting subclasses which
* formats and parses dates or time in a language-independent manner.
* The date/time formatting subclass, such as SimpleDateFormat, allows for
* formatting (i.e., date -> text), parsing (text -> date), and
* normalization. The date is represented as a <code>Date</code> object or
* as the milliseconds since January 1, 1970, 00:00:00 GMT.
*
* <p>DateFormat provides many class methods for obtaining default date/time
* formatters based on the default or a given loacle and a number of formatting
* styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More
* detail and examples of using these styles are provided in the method
* descriptions.
*
* <p>DateFormat helps you to format and parse dates for any locale.
* Your code can be completely independent of the locale conventions for
* months, days of the week, or even the calendar format: lunar vs. solar.
*
* <p>To format a date for the current Locale, use one of the
* static factory methods:
* <pre>
* myString = DateFormat.getDateInstance().format(myDate);
* </pre>
* <p>If you are formatting multiple numbers, it is
* more efficient to get the format and use it multiple times so that
* the system doesn't have to fetch the information about the local
* language and country conventions multiple times.
* <pre>
* DateFormat df = DateFormat.getDateInstance();
* for (int i = 0; i < a.length; ++i) {
* output.println(df.format(myDate[i]) + "; ");
* }
* </pre>
* <p>To format a number for a different Locale, specify it in the
* call to getDateInstance().
* <pre>
* DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
* </pre>
* <p>You can use a DateFormat to parse also.
* <pre>
* myDate = df.parse(myString);
* </pre>
* <p>Use getDateInstance to get the normal date format for that country.
* There are other static factory methods available.
* Use getTimeInstance to get the time format for that country.
* Use getDateTimeInstance to get a date and time format. You can pass in
* different options to these factory methods to control the length of the
* result; from SHORT to MEDIUM to LONG to FULL. The exact result depends
* on the locale, but generally:
* <ul><li>SHORT is completely numeric, such as 12.13.52 or 3:30pm
* <li>MEDIUM is longer, such as Jan 12, 1952
* <li>LONG is longer, such as January 12, 1952 or 3:30:32pm
* <li>FULL is pretty completely specified, such as
* Tuesday, April 12, 1952 AD or 3:30:42pm PST.
* </ul>
*
* <p>You can also set the time zone on the format if you wish.
* If you want even more control over the format or parsing,
* (or want to give your users more control),
* you can try casting the DateFormat you get from the factory methods
* to a SimpleDateFormat. This will work for the majority
* of countries; just remember to put it in a try block in case you
* encounter an unusual one.
*
* <p>You can also use forms of the parse and format methods with
* ParsePosition and FieldPosition to
* allow you to
* <ul><li>progressively parse through pieces of a string.
* <li>align any particular field, or find out where it is for selection
* on the screen.
* </ul>
*
* <h4>Synchronization</h4>
*
* Date formats are not synchronized. It is recommended to create separate
* format instances for each thread. If multiple threads access a format
* concurrently, it must be synchronized externally.
*
* @see UFormat
* @see NumberFormat
* @see SimpleDateFormat
* @see com.ibm.icu.util.Calendar
* @see com.ibm.icu.util.GregorianCalendar
* @see com.ibm.icu.util.TimeZone
* @author Mark Davis, Chen-Lieh Huang, Alan Liu
* @stable ICU 2.0
*/
public class DateFormat extends Format {
private static final long serialVersionUID = 1;
/**
* @internal
*/
public final java.text.DateFormat dateFormat;
/**
* @internal
* @param delegate the DateFormat to which to delegate
*/
public DateFormat(java.text.DateFormat delegate) {
this.dateFormat = delegate;
}
/**
* For subclass use. Subclasses will generally not
* work correctly unless they manipulate the delegate.
*/
protected DateFormat() {
this.dateFormat = java.text.DateFormat.getInstance();
}
/**
* FieldPosition selector for 'G' field alignment,
* corresponding to the {@link Calendar#ERA} field.
* @stable ICU 2.0
*/
public final static int ERA_FIELD = 0;
/**
* FieldPosition selector for 'y' field alignment,
* corresponding to the {@link Calendar#YEAR} field.
* @stable ICU 2.0
*/
public final static int YEAR_FIELD = 1;
/**
* FieldPosition selector for 'M' field alignment,
* corresponding to the {@link Calendar#MONTH} field.
* @stable ICU 2.0
*/
public final static int MONTH_FIELD = 2;
/**
* FieldPosition selector for 'd' field alignment,
* corresponding to the {@link Calendar#DATE} field.
* @stable ICU 2.0
*/
public final static int DATE_FIELD = 3;
/**
* FieldPosition selector for 'k' field alignment,
* corresponding to the {@link Calendar#HOUR_OF_DAY} field.
* HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
* For example, 23:59 + 01:00 results in 24:59.
* @stable ICU 2.0
*/
public final static int HOUR_OF_DAY1_FIELD = 4;
/**
* FieldPosition selector for 'H' field alignment,
* corresponding to the {@link Calendar#HOUR_OF_DAY} field.
* HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
* For example, 23:59 + 01:00 results in 00:59.
* @stable ICU 2.0
*/
public final static int HOUR_OF_DAY0_FIELD = 5;
/**
* FieldPosition selector for 'm' field alignment,
* corresponding to the {@link Calendar#MINUTE} field.
* @stable ICU 2.0
*/
public final static int MINUTE_FIELD = 6;
/**
* FieldPosition selector for 's' field alignment,
* corresponding to the {@link Calendar#SECOND} field.
* @stable ICU 2.0
*/
public final static int SECOND_FIELD = 7;
/**
* FieldPosition selector for 'S' field alignment,
* corresponding to the {@link Calendar#MILLISECOND} field.
* @draft ICU 3.0
* @provisional
*/
public final static int FRACTIONAL_SECOND_FIELD = 8;
/**
* Alias for FRACTIONAL_SECOND_FIELD.
* @stable ICU 3.4.3
*/
public final static int MILLISECOND_FIELD = FRACTIONAL_SECOND_FIELD;
/**
* FieldPosition selector for 'E' field alignment,
* corresponding to the {@link Calendar#DAY_OF_WEEK} field.
* @stable ICU 2.0
*/
public final static int DAY_OF_WEEK_FIELD = 9;
/**
* FieldPosition selector for 'D' field alignment,
* corresponding to the {@link Calendar#DAY_OF_YEAR} field.
* @stable ICU 2.0
*/
public final static int DAY_OF_YEAR_FIELD = 10;
/**
* FieldPosition selector for 'F' field alignment,
* corresponding to the {@link Calendar#DAY_OF_WEEK_IN_MONTH} field.
* @stable ICU 2.0
*/
public final static int DAY_OF_WEEK_IN_MONTH_FIELD = 11;
/**
* FieldPosition selector for 'w' field alignment,
* corresponding to the {@link Calendar#WEEK_OF_YEAR} field.
* @stable ICU 2.0
*/
public final static int WEEK_OF_YEAR_FIELD = 12;
/**
* FieldPosition selector for 'W' field alignment,
* corresponding to the {@link Calendar#WEEK_OF_MONTH} field.
* @stable ICU 2.0
*/
public final static int WEEK_OF_MONTH_FIELD = 13;
/**
* FieldPosition selector for 'a' field alignment,
* corresponding to the {@link Calendar#AM_PM} field.
* @stable ICU 2.0
*/
public final static int AM_PM_FIELD = 14;
/**
* FieldPosition selector for 'h' field alignment,
* corresponding to the {@link Calendar#HOUR} field.
* HOUR1_FIELD is used for the one-based 12-hour clock.
* For example, 11:30 PM + 1 hour results in 12:30 AM.
* @stable ICU 2.0
*/
public final static int HOUR1_FIELD = 15;
/**
* FieldPosition selector for 'K' field alignment,
* corresponding to the {@link Calendar#HOUR} field.
* HOUR0_FIELD is used for the zero-based 12-hour clock.
* For example, 11:30 PM + 1 hour results in 00:30 AM.
* @stable ICU 2.0
*/
public final static int HOUR0_FIELD = 16;
/**
* FieldPosition selector for 'z' field alignment,
* corresponding to the {@link Calendar#ZONE_OFFSET} and
* {@link Calendar#DST_OFFSET} fields.
* @stable ICU 2.0
*/
public final static int TIMEZONE_FIELD = 17;
/**
* Overrides Format.
* Formats a time object into a time string. Examples of time objects
* are a time value expressed in milliseconds and a Date object.
* @param obj must be a Number or a Date or a Calendar.
* @param toAppendTo the string buffer for the returning time string.
* @return the formatted time string.
* @param fieldPosition keeps track of the position of the field
* within the returned string.
* On input: an alignment field,
* if desired. On output: the offsets of the alignment field. For
* example, given a time text "1996.07.10 AD at 15:08:56 PDT",
* if the given fieldPosition is DateFormat.YEAR_FIELD, the
* begin index and end index of fieldPosition will be set to
* 0 and 4, respectively.
* Notice that if the same time field appears
* more than once in a pattern, the fieldPosition will be set for the first
* occurence of that time field. For instance, formatting a Date to
* the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
* "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
* the begin index and end index of fieldPosition will be set to
* 5 and 8, respectively, for the first occurence of the timezone
* pattern character 'z'.
* @see java.text.Format
* @stable ICU 2.0
*/
public final StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition) {
if (obj instanceof Calendar) {
return format((Calendar)obj, toAppendTo, fieldPosition);
} else if (obj instanceof Date) {
return format((Date)obj, toAppendTo, fieldPosition);
} else if (obj instanceof Number) {
return format(new Date(((Number)obj).longValue()), toAppendTo, fieldPosition );
} else {
throw new IllegalArgumentException("Cannot format given Object as a Date");
}
}
/**
* Formats a date into a date/time string.
* @param cal a Calendar set to the date and time to be formatted
* into a date/time string.
* @param toAppendTo the string buffer for the returning date/time string.
* @param fieldPosition keeps track of the position of the field
* within the returned string.
* On input: an alignment field,
* if desired. On output: the offsets of the alignment field. For
* example, given a time text "1996.07.10 AD at 15:08:56 PDT",
* if the given fieldPosition is DateFormat.YEAR_FIELD, the
* begin index and end index of fieldPosition will be set to
* 0 and 4, respectively.
* Notice that if the same time field appears
* more than once in a pattern, the fieldPosition will be set for the first
* occurence of that time field. For instance, formatting a Date to
* the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
* "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
* the begin index and end index of fieldPosition will be set to
* 5 and 8, respectively, for the first occurence of the timezone
* pattern character 'z'.
* @return the formatted date/time string.
* @stable ICU 2.0
*/
public StringBuffer format(Calendar cal, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return format(cal.getTime(), toAppendTo, fieldPosition);
}
/**
* Formats a Date into a date/time string.
* @param date a Date to be formatted into a date/time string.
* @param toAppendTo the string buffer for the returning date/time string.
* @param fieldPosition keeps track of the position of the field
* within the returned string.
* On input: an alignment field,
* if desired. On output: the offsets of the alignment field. For
* example, given a time text "1996.07.10 AD at 15:08:56 PDT",
* if the given fieldPosition is DateFormat.YEAR_FIELD, the
* begin index and end index of fieldPosition will be set to
* 0 and 4, respectively.
* Notice that if the same time field appears
* more than once in a pattern, the fieldPosition will be set for the first
* occurence of that time field. For instance, formatting a Date to
* the time string "1 PM PDT (Pacific Daylight Time)" using the pattern
* "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD,
* the begin index and end index of fieldPosition will be set to
* 5 and 8, respectively, for the first occurence of the timezone
* pattern character 'z'.
* @return the formatted date/time string.
* @stable ICU 2.0
*/
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return dateFormat.format(date, toAppendTo, fieldPosition);
}
/**
* Formats a Date into a date/time string.
* @param date the time value to be formatted into a time string.
* @return the formatted time string.
* @stable ICU 2.0
*/
public final String format(Date date) {
return dateFormat.format(date);
}
/**
* Parse a date/time string.
*
* @param text The date/time string to be parsed
*
* @return A Date, or null if the input could not be parsed
*
* @exception ParseException If the given string cannot be parsed as a date.
*
* @see #parse(String, ParsePosition)
* @stable ICU 2.0
*/
public Date parse(String text) throws ParseException {
return dateFormat.parse(text);
}
/**
* Parse a date/time string according to the given parse position.
* For example, a time text "07/10/96 4:5 PM, PDT" will be parsed
* into a Calendar that is equivalent to Date(837039928046). The
* caller should clear the calendar before calling this method,
* unless existing field information is to be kept.
*
* <p> By default, parsing is lenient: If the input is not in the form used
* by this object's format method but can still be parsed as a date, then
* the parse succeeds. Clients may insist on strict adherence to the
* format by calling setLenient(false).
*
* @see #setLenient(boolean)
*
* @param text The date/time string to be parsed
*
* @param cal The calendar into which parsed data will be stored.
* In general, this should be cleared before calling this
* method. If this parse fails, the calendar may still
* have been modified.
*
* @param pos On input, the position at which to start parsing; on
* output, the position at which parsing terminated, or the
* start position if the parse failed.
* @stable ICU 2.0
*/
public void parse(String text, Calendar cal, ParsePosition pos) {
Date result = dateFormat.parse(text, pos);
cal.setTime(result);
}
/**
* Parse a date/time string according to the given parse position. For
* example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
* that is equivalent to Date(837039928046).
*
* <p> By default, parsing is lenient: If the input is not in the form used
* by this object's format method but can still be parsed as a date, then
* the parse succeeds. Clients may insist on strict adherence to the
* format by calling setLenient(false).
*
* @see #setLenient(boolean)
*
* @param text The date/time string to be parsed
*
* @param pos On input, the position at which to start parsing; on
* output, the position at which parsing terminated, or the
* start position if the parse failed.
*
* @return A Date, or null if the input could not be parsed
* @stable ICU 2.0
*/
public Date parse(String text, ParsePosition pos) {
return dateFormat.parse(text, pos);
}
/**
* Parse a date/time string into an Object. This convenience method simply
* calls parse(String, ParsePosition).
*
* @see #parse(String, ParsePosition)
* @stable ICU 2.0
*/
public Object parseObject(String source, ParsePosition pos) {
return parse(source, pos);
}
/**
* Constant for full style pattern.
* @stable ICU 2.0
*/
public static final int FULL = 0;
/**
* Constant for long style pattern.
* @stable ICU 2.0
*/
public static final int LONG = 1;
/**
* Constant for medium style pattern.
* @stable ICU 2.0
*/
public static final int MEDIUM = 2;
/**
* Constant for short style pattern.
* @stable ICU 2.0
*/
public static final int SHORT = 3;
/**
* Constant for default style pattern. Its value is MEDIUM.
* @stable ICU 2.0
*/
public static final int DEFAULT = MEDIUM;
/**
* Gets the time formatter with the default formatting style
* for the default locale.
* @return a time formatter.
* @stable ICU 2.0
*/
public final static DateFormat getTimeInstance() {
return new DateFormat(java.text.DateFormat.getTimeInstance());
}
/**
* Gets the time formatter with the given formatting style
* for the default locale.
* @param style the given formatting style. For example,
* SHORT for "h:mm a" in the US locale.
* @return a time formatter.
* @stable ICU 2.0
*/
public final static DateFormat getTimeInstance(int style) {
return new DateFormat(java.text.DateFormat.getTimeInstance(style));
}
/**
* Gets the time formatter with the given formatting style
* for the given locale.
* @param style the given formatting style. For example,
* SHORT for "h:mm a" in the US locale.
* @param aLocale the given locale.
* @return a time formatter.
* @stable ICU 2.0
*/
public final static DateFormat getTimeInstance(int style, Locale aLocale) {
return new DateFormat(java.text.DateFormat.getTimeInstance(style, aLocale));
}
/**
* Gets the time formatter with the given formatting style
* for the given locale.
* @param style the given formatting style. For example,
* SHORT for "h:mm a" in the US locale.
* @param aLocale the given locale.
* @return a time formatter.
* @draft ICU 3.2
*/
public final static DateFormat getTimeInstance(int style, ULocale aLocale) {
return new DateFormat(java.text.DateFormat.getTimeInstance(style, aLocale.toLocale()));
}
/**
* Gets the date formatter with the default formatting style
* for the default locale.
* @return a date formatter.
* @stable ICU 2.0
*/
public final static DateFormat getDateInstance() {
return new DateFormat(java.text.DateFormat.getDateInstance());
}
/**
* Gets the date formatter with the given formatting style
* for the default locale.
* @param style the given formatting style. For example,
* SHORT for "M/d/yy" in the US locale.
* @return a date formatter.
* @stable ICU 2.0
*/
public final static DateFormat getDateInstance(int style) {
return new DateFormat(java.text.DateFormat.getDateInstance(style));
}
/**
* Gets the date formatter with the given formatting style
* for the given locale.
* @param style the given formatting style. For example,
* SHORT for "M/d/yy" in the US locale.
* @param aLocale the given locale.
* @return a date formatter.
* @stable ICU 2.0
*/
public final static DateFormat getDateInstance(int style, Locale aLocale) {
return new DateFormat(java.text.DateFormat.getDateInstance(style, aLocale));
}
/**
* Gets the date formatter with the given formatting style
* for the given locale.
* @param style the given formatting style. For example,
* SHORT for "M/d/yy" in the US locale.
* @param aLocale the given locale.
* @return a date formatter.
* @stable ICU 3.4.3
*/
public final static DateFormat getDateInstance(int style, ULocale aLocale) {
return new DateFormat(java.text.DateFormat.getDateInstance(style, aLocale.toLocale()));
}
/**
* Gets the date/time formatter with the default formatting style
* for the default locale.
* @return a date/time formatter.
* @stable ICU 2.0
*/
public final static DateFormat getDateTimeInstance() {
return new DateFormat(java.text.DateFormat.getDateTimeInstance());
}
/**
* Gets the date/time formatter with the given date and time
* formatting styles for the default locale.
* @param dateStyle the given date formatting style. For example,
* SHORT for "M/d/yy" in the US locale.
* @param timeStyle the given time formatting style. For example,
* SHORT for "h:mm a" in the US locale.
* @return a date/time formatter.
* @stable ICU 2.0
*/
public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle) {
return new DateFormat(java.text.DateFormat.getDateTimeInstance(dateStyle, timeStyle));
}
/**
* Gets the date/time formatter with the given formatting styles
* for the given locale.
* @param dateStyle the given date formatting style.
* @param timeStyle the given time formatting style.
* @param aLocale the given locale.
* @return a date/time formatter.
* @stable ICU 2.0
*/
public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale) {
return new DateFormat(java.text.DateFormat.getDateTimeInstance(dateStyle, timeStyle, aLocale));
}
/**
* Gets the date/time formatter with the given formatting styles
* for the given locale.
* @param dateStyle the given date formatting style.
* @param timeStyle the given time formatting style.
* @param aLocale the given locale.
* @return a date/time formatter.
* @stable ICU 3.4.3
*/
public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, ULocale aLocale) {
return new DateFormat(java.text.DateFormat.getDateTimeInstance(dateStyle, timeStyle, aLocale.toLocale()));
}
/**
* Get a default date/time formatter that uses the SHORT style for both the
* date and the time.
* @stable ICU 2.0
*/
public final static DateFormat getInstance() {
return new DateFormat(java.text.DateFormat.getInstance());
}
/**
* Gets the set of locales for which DateFormats are installed.
* @return the set of locales for which DateFormats are installed.
* @stable ICU 2.0
*/
public static Locale[] getAvailableLocales() {
return java.text.DateFormat.getAvailableLocales();
}
/**
* Gets the set of locales for which DateFormats are installed.
* @return the set of locales for which DateFormats are installed.
* @stable ICU 3.4.3
*/
public static ULocale[] getAvailableULocales() {
Locale[] locales = java.text.DateFormat.getAvailableLocales();
ULocale[] ulocales = new ULocale[locales.length];
for (int i = 0; i < locales.length; ++i) {
ulocales[i] = ULocale.forLocale(locales[i]);
}
return ulocales;
}
/**
* Set the calendar to be used by this date format. Initially, the default
* calendar for the specified or default locale is used.
* @param newCalendar the new Calendar to be used by the date format
* @stable ICU 2.0
*/
public void setCalendar(Calendar newCalendar) {
dateFormat.setCalendar(newCalendar.calendar);
}
/**
* Gets the calendar associated with this date/time formatter.
* @return the calendar associated with this date/time formatter.
* @stable ICU 2.0
*/
public Calendar getCalendar() {
return new Calendar(dateFormat.getCalendar());
}
/**
* Allows you to set the number formatter.
* @param newNumberFormat the given new NumberFormat.
* @stable ICU 2.0
*/
public void setNumberFormat(NumberFormat newNumberFormat) {
dateFormat.setNumberFormat(newNumberFormat.numberFormat);
}
/**
* Gets the number formatter which this date/time formatter uses to
* format and parse a time.
* @return the number formatter which this date/time formatter uses.
* @stable ICU 2.0
*/
public NumberFormat getNumberFormat() {
return new NumberFormat(dateFormat.getNumberFormat());
}
/**
* Sets the time zone for the calendar of this DateFormat object.
* @param zone the given new time zone.
* @stable ICU 2.0
*/
public void setTimeZone(TimeZone zone) {
dateFormat.setTimeZone(zone.timeZone);
}
/**
* Gets the time zone.
* @return the time zone associated with the calendar of DateFormat.
* @stable ICU 2.0
*/
public TimeZone getTimeZone() {
return new TimeZone(dateFormat.getTimeZone());
}
/**
* Specify whether or not date/time parsing is to be lenient. With
* lenient parsing, the parser may use heuristics to interpret inputs that
* do not precisely match this object's format. With strict parsing,
* inputs must match this object's format.
* @param lenient when true, parsing is lenient
* @see com.ibm.icu.util.Calendar#setLenient
* @stable ICU 2.0
*/
public void setLenient(boolean lenient) {
dateFormat.setLenient(lenient);
}
/**
* Tell whether date/time parsing is to be lenient.
* @stable ICU 2.0
*/
public boolean isLenient() {
return dateFormat.isLenient();
}
/**
* Create a {@link DateFormat} object that can be used to format dates in
* the calendar system specified by <code>cal</code>.
* <p>
* @param cal The calendar system for which a date format is desired.
*
* @param dateStyle The type of date format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param locale The locale for which the date format is desired.
* @stable ICU 2.0
*/
static final public DateFormat getDateInstance(Calendar cal, int dateStyle, Locale locale) {
DateFormat df = getDateInstance(dateStyle, locale);
df.setCalendar(cal);
return df;
}
/**
* Create a {@link DateFormat} object that can be used to format dates in
* the calendar system specified by <code>cal</code>.
* <p>
* @param cal The calendar system for which a date format is desired.
*
* @param dateStyle The type of date format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param locale The locale for which the date format is desired.
* @draft ICU 3.2
* @provisional
*/
static final public DateFormat getDateInstance(Calendar cal, int dateStyle, ULocale locale) {
DateFormat df = getDateInstance(dateStyle, locale);
df.setCalendar(cal);
return df;
}
/**
* Create a {@link DateFormat} object that can be used to format times in
* the calendar system specified by <code>cal</code>.
* <p>
* <b>Note:</b> When this functionality is moved into the core JDK, this method
* will probably be replaced by a new overload of {@link DateFormat#getInstance}.
* <p>
* @param cal The calendar system for which a time format is desired.
*
* @param timeStyle The type of time format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param locale The locale for which the time format is desired.
*
* @see DateFormat#getTimeInstance
* @stable ICU 2.0
*/
static final public DateFormat getTimeInstance(Calendar cal, int timeStyle, Locale locale) {
DateFormat df = getTimeInstance(timeStyle, locale);
df.setCalendar(cal);
return df;
}
/**
* Create a {@link DateFormat} object that can be used to format times in
* the calendar system specified by <code>cal</code>.
* <p>
* <b>Note:</b> When this functionality is moved into the core JDK, this method
* will probably be replaced by a new overload of {@link DateFormat#getInstance}.
* <p>
* @param cal The calendar system for which a time format is desired.
*
* @param timeStyle The type of time format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param locale The locale for which the time format is desired.
*
* @see DateFormat#getTimeInstance
* @draft ICU 3.2
* @provisional
*/
static final public DateFormat getTimeInstance(Calendar cal, int timeStyle, ULocale locale) {
DateFormat df = getTimeInstance(timeStyle, locale);
df.setCalendar(cal);
return df;
}
/**
* Create a {@link DateFormat} object that can be used to format dates and times in
* the calendar system specified by <code>cal</code>.
* <p>
* <b>Note:</b> When this functionality is moved into the core JDK, this method
* will probably be replaced by a new overload of {@link DateFormat#getInstance}.
* <p>
* @param cal The calendar system for which a date/time format is desired.
*
* @param dateStyle The type of date format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param timeStyle The type of time format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param locale The locale for which the date/time format is desired.
*
* @see DateFormat#getDateTimeInstance
* @stable ICU 2.0
*/
static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle,
int timeStyle, Locale locale) {
DateFormat df = getDateTimeInstance(dateStyle, timeStyle, locale);
df.setCalendar(cal);
return df;
}
/**
* Create a {@link DateFormat} object that can be used to format dates and times in
* the calendar system specified by <code>cal</code>.
* <p>
* <b>Note:</b> When this functionality is moved into the core JDK, this method
* will probably be replaced by a new overload of {@link DateFormat#getInstance}.
* <p>
* @param cal The calendar system for which a date/time format is desired.
*
* @param dateStyle The type of date format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param timeStyle The type of time format desired. This can be
* {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM},
* etc.
*
* @param locale The locale for which the date/time format is desired.
*
* @see DateFormat#getDateTimeInstance
* @draft ICU 3.2
* @provisional
*/
static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle,
int timeStyle, ULocale locale) {
DateFormat df = getDateTimeInstance(dateStyle, timeStyle, locale);
df.setCalendar(cal);
return df;
}
/**
* Convenience overload
* @stable ICU 2.0
*/
static final public DateFormat getInstance(Calendar cal, Locale locale) {
return getDateTimeInstance(cal, MEDIUM, SHORT, locale);
}
/**
* Convenience overload
* @draft ICU 3.2
* @provisional
*/
public static final DateFormat getInstance(Calendar cal, ULocale locale) {
return getDateTimeInstance(cal, MEDIUM, SHORT, locale);
}
/**
* Convenience overload
* @stable ICU 2.0
*/
public static final DateFormat getInstance(Calendar cal) {
return getDateTimeInstance(cal, MEDIUM, SHORT, ULocale.getDefault());
}
/**
* Convenience overload
* @stable ICU 2.0
*/
public static final DateFormat getDateInstance(Calendar cal, int dateStyle) {
DateFormat df = getDateInstance(dateStyle);
df.setCalendar(cal);
return df;
}
/**
* Convenience overload
* @stable ICU 2.0
*/
static final public DateFormat getTimeInstance(Calendar cal, int timeStyle) {
DateFormat df = getTimeInstance(timeStyle);
df.setCalendar(cal);
return df;
}
/**
* Convenience overload
* @stable ICU 2.0
*/
static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle, int timeStyle) {
DateFormat df = getDateTimeInstance(dateStyle, timeStyle);
df.setCalendar(cal);
return df;
}
/**
* Return a string suitable for debugging.
* @return a string suitable for debugging
* @stable ICU 3.4.3
*/
public String toString() {
return dateFormat.toString();
}
/**
* Return a clone of this DateFormat.
* @return a clone of this DateFormat
* @stable ICU 3.4.3
*/
public Object clone() {
return new DateFormat((java.text.DateFormat)dateFormat.clone());
}
/**
* Return true if rhs is a DateFormatSymbols and has the same symbols as this.
* @return true if rhs equals this
* @stable ICU 3.4.3
*/
public boolean equals(Object arg0) {
try {
return dateFormat.equals(((DateFormat)arg0).dateFormat);
}
catch (Exception e) {
return false;
}
}
/**
* Return a hashCode.
* @return a hashCode
* @stable ICU 3.4.3
*/
public int hashCode() {
return dateFormat.hashCode();
}
}

View file

@ -0,0 +1,302 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import java.io.Serializable;
import java.util.Locale;
import com.ibm.icu.util.ULocale;
/**
* <code>DateFormatSymbols</code> is a public class for encapsulating
* localizable date-time formatting data, such as the names of the
* months, the names of the days of the week, and the time zone data.
* <code>DateFormat</code> and <code>SimpleDateFormat</code> both use
* <code>DateFormatSymbols</code> to encapsulate this information.
*
* <p>
* Typically you shouldn't use <code>DateFormatSymbols</code> directly.
* Rather, you are encouraged to create a date-time formatter with the
* <code>DateFormat</code> class's factory methods: <code>getTimeInstance</code>,
* <code>getDateInstance</code>, or <code>getDateTimeInstance</code>.
* These methods automatically create a <code>DateFormatSymbols</code> for
* the formatter so that you don't have to. After the
* formatter is created, you may modify its format pattern using the
* <code>setPattern</code> method. For more information about
* creating formatters using <code>DateFormat</code>'s factory methods,
* see {@link DateFormat}.
*
* <p>
* If you decide to create a date-time formatter with a specific
* format pattern for a specific locale, you can do so with:
* <blockquote>
* <pre>
* new SimpleDateFormat(aPattern, new DateFormatSymbols(aLocale)).
* </pre>
* </blockquote>
*
* <p>
* <code>DateFormatSymbols</code> objects are clonable. When you obtain
* a <code>DateFormatSymbols</code> object, feel free to modify the
* date-time formatting data. For instance, you can replace the localized
* date-time format pattern characters with the ones that you feel easy
* to remember. Or you can change the representative cities
* to your favorite ones.
*
* <p>
* New <code>DateFormatSymbols</code> subclasses may be added to support
* <code>SimpleDateFormat</code> for date-time formatting for additional locales.
* @see DateFormat
* @see SimpleDateFormat
* @see com.ibm.icu.util.SimpleTimeZone
* @author Chen-Lieh Huang
* @stable ICU 2.0
*/
public class DateFormatSymbols implements Serializable, Cloneable {
private static final long serialVersionUID = 1;
/** @internal */
public java.text.DateFormatSymbols dfs;
/** @internal */
public DateFormatSymbols(java.text.DateFormatSymbols delegate) {
this.dfs = delegate;
}
/**
* Construct a DateFormatSymbols object by loading format data from
* resources for the default locale.
*
* @throws java.util.MissingResourceException
* if the resources for the default locale cannot be
* found or cannot be loaded.
* @stable ICU 2.0
*/
public DateFormatSymbols() {
this(new java.text.DateFormatSymbols());
}
/**
* Construct a DateFormatSymbols object by loading format data from
* resources for the given locale.
*
* @throws java.util.MissingResourceException
* if the resources for the specified locale cannot be
* found or cannot be loaded.
* @stable ICU 2.0
*/
public DateFormatSymbols(Locale locale) {
this(new java.text.DateFormatSymbols(locale));
}
/**
* Construct a DateFormatSymbols object by loading format data from
* resources for the given ulocale.
*
* @throws java.util.MissingResourceException
* if the resources for the specified locale cannot be
* found or cannot be loaded.
* @draft ICU 3.2
*/
public DateFormatSymbols(ULocale locale) {
this(new java.text.DateFormatSymbols(locale.toLocale()));
}
/**
* Gets era strings. For example: "AD" and "BC".
* @return the era strings.
* @stable ICU 2.0
*/
public String[] getEras() {
return dfs.getEras();
}
/**
* Sets era strings. For example: "AD" and "BC".
* @param newEras the new era strings.
* @stable ICU 2.0
*/
public void setEras(String[] newEras) {
dfs.setEras(newEras);
}
/**
* Gets month strings. For example: "January", "February", etc.
* @return the month strings.
* @stable ICU 2.0
*/
public String[] getMonths() {
return dfs.getMonths();
}
/**
* Sets month strings. For example: "January", "February", etc.
* @param newMonths the new month strings.
* @stable ICU 2.0
*/
public void setMonths(String[] newMonths) {
dfs.setMonths(newMonths);
}
/**
* Gets short month strings. For example: "Jan", "Feb", etc.
* @return the short month strings.
* @stable ICU 2.0
*/
public String[] getShortMonths() {
return dfs.getShortMonths();
}
/**
* Sets short month strings. For example: "Jan", "Feb", etc.
* @param newShortMonths the new short month strings.
* @stable ICU 2.0
*/
public void setShortMonths(String[] newShortMonths) {
dfs.setShortMonths(newShortMonths);
}
/**
* Gets weekday strings. For example: "Sunday", "Monday", etc.
* @return the weekday strings. Use <code>Calendar.SUNDAY</code>,
* <code>Calendar.MONDAY</code>, etc. to index the result array.
* @stable ICU 2.0
*/
public String[] getWeekdays() {
return dfs.getWeekdays();
}
/**
* Sets weekday strings. For example: "Sunday", "Monday", etc.
* @param newWeekdays the new weekday strings. The array should
* be indexed by <code>Calendar.SUNDAY</code>,
* <code>Calendar.MONDAY</code>, etc.
* @stable ICU 2.0
*/
public void setWeekdays(String[] newWeekdays) {
dfs.setWeekdays(newWeekdays);
}
/**
* Gets short weekday strings. For example: "Sun", "Mon", etc.
* @return the short weekday strings. Use <code>Calendar.SUNDAY</code>,
* <code>Calendar.MONDAY</code>, etc. to index the result array.
* @stable ICU 2.0
*/
public String[] getShortWeekdays() {
return dfs.getShortWeekdays();
}
/**
* Sets short weekday strings. For example: "Sun", "Mon", etc.
* @param newShortWeekdays the new short weekday strings. The array should
* be indexed by <code>Calendar.SUNDAY</code>,
* <code>Calendar.MONDAY</code>, etc.
* @stable ICU 2.0
*/
public void setShortWeekdays(String[] newShortWeekdays) {
dfs.setShortWeekdays(newShortWeekdays);
}
/**
* Gets ampm strings. For example: "AM" and "PM".
* @return the weekday strings.
* @stable ICU 2.0
*/
public String[] getAmPmStrings() {
return dfs.getAmPmStrings();
}
/**
* Sets ampm strings. For example: "AM" and "PM".
* @param newAmpms the new ampm strings.
* @stable ICU 2.0
*/
public void setAmPmStrings(String[] newAmpms) {
dfs.setAmPmStrings(newAmpms);
}
/**
* Gets timezone strings.
* @return the timezone strings.
* @stable ICU 2.0
*/
public String[][] getZoneStrings() {
return dfs.getZoneStrings();
}
/**
* Sets timezone strings.
* @param newZoneStrings the new timezone strings.
* @stable ICU 2.0
*/
public void setZoneStrings(String[][] newZoneStrings) {
dfs.setZoneStrings(newZoneStrings);
}
/**
* Gets localized date-time pattern characters. For example: 'u', 't', etc.
* @return the localized date-time pattern characters.
* @stable ICU 2.0
*/
public String getLocalPatternChars() {
return dfs.getLocalPatternChars();
}
/**
* Sets localized date-time pattern characters. For example: 'u', 't', etc.
* @param newLocalPatternChars the new localized date-time
* pattern characters.
* @stable ICU 2.0
*/
public void setLocalPatternChars(String newLocalPatternChars) {
dfs.setLocalPatternChars(newLocalPatternChars);
}
/**
* Return a string suitable for debugging.
* @return a string suitable for debugging
* @draft ICU 3.4.2
*/
public String toString() {
return dfs.toString();
}
/**
* Return a clone of this DateFormatSymbols.
* @return a clone of this DateFormatSymbols
* @draft ICU 3.4.2
*/
public Object clone() {
return new DateFormatSymbols((java.text.DateFormatSymbols)dfs.clone());
}
/**
* Return true if rhs is a DateFormatSymbols and has the same symbols as this.
* @return true if rhs equals this
* @draft ICU 3.4.2
*/
public boolean equals(Object rhs) {
try {
return dfs.equals(((DateFormatSymbols)rhs).dfs);
}
catch (Exception e) {
return false;
}
}
/**
* Return a hashCode.
* @return a hashCode
* @draft ICU 3.4.2
*/
public int hashCode() {
return dfs.hashCode();
}
}

View file

@ -0,0 +1,903 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
/**
* <code>DecimalFormat</code> is a concrete subclass of
* {@link NumberFormat} that formats decimal numbers.
*
* <p>To obtain a {@link NumberFormat} for a specific locale (including the
* default locale) call one of <code>NumberFormat</code>'s factory methods such
* as {@link NumberFormat#getInstance}. Do not call the <code>DecimalFormat</code>
* constructors directly, unless you know what you are doing, since the
* {@link NumberFormat} factory methods may return subclasses other than
* <code>DecimalFormat</code>. If you need to customize the format object, do
* something like this:
*
* <blockquote><pre>
* NumberFormat f = NumberFormat.getInstance(loc);
* if (f instanceof DecimalFormat) {
* ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
* }</pre></blockquote>
*
* <p><strong>Example Usage</strong>
*
* <blockquote><pre>
* <strong>// Print out a number using the localized number, currency,
* // and percent format for each locale</strong>
* Locale[] locales = NumberFormat.getAvailableLocales();
* double myNumber = -1234.56;
* NumberFormat format;
* for (int j=0; j<3; ++j) {
* System.out.println("FORMAT");
* for (int i = 0; i < locales.length; ++i) {
* if (locales[i].getCountry().length() == 0) {
* // Skip language-only locales
* continue;
* }
* System.out.print(locales[i].getDisplayName());
* switch (j) {
* case 0:
* format = NumberFormat.getInstance(locales[i]); break;
* case 1:
* format = NumberFormat.getCurrencyInstance(locales[i]); break;
* default:
* format = NumberFormat.getPercentInstance(locales[i]); break;
* }
* try {
* // Assume format is a DecimalFormat
* System.out.print(": " + ((DecimalFormat) format).toPattern()
* + " -> " + form.format(myNumber));
* } catch (Exception e) {}
* try {
* System.out.println(" -> " + format.parse(form.format(myNumber)));
* } catch (ParseException e) {}
* }
* }</pre></blockquote>
*
* <h4>Patterns</h4>
*
* <p>A <code>DecimalFormat</code> consists of a <em>pattern</em> and a set of
* <em>symbols</em>. The pattern may be set directly using
* {@link #applyPattern}, or indirectly using other API methods which
* manipulate aspects of the pattern, such as the minimum number of integer
* digits. The symbols are stored in a {@link DecimalFormatSymbols}
* object. When using the {@link NumberFormat} factory methods, the
* pattern and symbols are read from ICU's locale data.
*
* <h4>Special Pattern Characters</h4>
*
* <p>Many characters in a pattern are taken literally; they are matched during
* parsing and output unchanged during formatting. Special characters, on the
* other hand, stand for other characters, strings, or classes of characters.
* For example, the '#' character is replaced by a localized digit. Often the
* replacement character is the same as the pattern character; in the U.S. locale,
* the ',' grouping character is replaced by ','. However, the replacement is
* still happening, and if the symbols are modified, the grouping character
* changes. Some special characters affect the behavior of the formatter by
* their presence; for example, if the percent character is seen, then the
* value is multiplied by 100 before being displayed.
*
* <p>To insert a special character in a pattern as a literal, that is, without
* any special meaning, the character must be quoted. There are some exceptions to
* this which are noted below.
*
* <p>The characters listed here are used in non-localized patterns. Localized
* patterns use the corresponding characters taken from this formatter's
* {@link DecimalFormatSymbols} object instead, and these characters lose
* their special status. Two exceptions are the currency sign and quote, which
* are not localized.
*
* <blockquote>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing symbol,
* location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>Symbol
* <th align=left>Location
* <th align=left>Localized?
* <th align=left>Meaning
* <tr valign=top>
* <td><code>0</code>
* <td>Number
* <td>Yes
* <td>Digit
* <tr valign=top bgcolor="#eeeeff">
* <td><code>1-9</code>
* <td>Number
* <td>Yes
* <td><strong><font face=helvetica color=red>NEW</font></strong>
* '1' through '9' indicate rounding.
* <tr valign=top>
* <td><code>@</code>
* <td>Number
* <td>No
* <td><strong><font face=helvetica color=red>NEW</font></strong>
* Significant digit
* <tr valign=top bgcolor="#eeeeff">
* <td><code>#</code>
* <td>Number
* <td>Yes
* <td>Digit, zero shows as absent
* <tr valign=top>
* <td><code>.</code>
* <td>Number
* <td>Yes
* <td>Decimal separator or monetary decimal separator
* <tr valign=top bgcolor="#eeeeff">
* <td><code>-</code>
* <td>Number
* <td>Yes
* <td>Minus sign
* <tr valign=top>
* <td><code>,</code>
* <td>Number
* <td>Yes
* <td>Grouping separator
* <tr valign=top bgcolor="#eeeeff">
* <td><code>E</code>
* <td>Number
* <td>Yes
* <td>Separates mantissa and exponent in scientific notation.
* <em>Need not be quoted in prefix or suffix.</em>
* <tr valign=top>
* <td><code>+</code>
* <td>Exponent
* <td>Yes
* <td><strong><font face=helvetica color=red>NEW</font></strong>
* Prefix positive exponents with localized plus sign.
* <em>Need not be quoted in prefix or suffix.</em>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>;</code>
* <td>Subpattern boundary
* <td>Yes
* <td>Separates positive and negative subpatterns
* <tr valign=top>
* <td><code>%</code>
* <td>Prefix or suffix
* <td>Yes
* <td>Multiply by 100 and show as percentage
* <tr valign=top bgcolor="#eeeeff">
* <td><code>&#92;u2030</code>
* <td>Prefix or suffix
* <td>Yes
* <td>Multiply by 1000 and show as per mille
* <tr valign=top>
* <td><code>&#164;</code> (<code>&#92;u00A4</code>)
* <td>Prefix or suffix
* <td>No
* <td>Currency sign, replaced by currency symbol. If
* doubled, replaced by international currency symbol.
* If present in a pattern, the monetary decimal separator
* is used instead of the decimal separator.
* <tr valign=top bgcolor="#eeeeff">
* <td><code>'</code>
* <td>Prefix or suffix
* <td>No
* <td>Used to quote special characters in a prefix or suffix,
* for example, <code>"'#'#"</code> formats 123 to
* <code>"#123"</code>. To create a single quote
* itself, use two in a row: <code>"# o''clock"</code>.
* <tr valign=top>
* <td><code>*</code>
* <td>Prefix or suffix boundary
* <td>Yes
* <td><strong><font face=helvetica color=red>NEW</font></strong>
* Pad escape, precedes pad character
* </table>
* </blockquote>
*
* <p>A <code>DecimalFormat</code> pattern contains a postive and negative
* subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a
* prefix, a numeric part, and a suffix. If there is no explicit negative
* subpattern, the negative subpattern is the localized minus sign prefixed to the
* positive subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00". If there
* is an explicit negative subpattern, it serves only to specify the negative
* prefix and suffix; the number of digits, minimal digits, and other
* characteristics are ignored in the negative subpattern. That means that
* "#,##0.0#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)".
*
* <p>The prefixes, suffixes, and various symbols used for infinity, digits,
* thousands separators, decimal separators, etc. may be set to arbitrary
* values, and they will appear properly during formatting. However, care must
* be taken that the symbols and strings do not conflict, or parsing will be
* unreliable. For example, either the positive and negative prefixes or the
* suffixes must be distinct for {@link #parse} to be able
* to distinguish positive from negative values. Another example is that the
* decimal separator and thousands separator should be distinct characters, or
* parsing will be impossible.
*
* <p>The <em>grouping separator</em> is a character that separates clusters of
* integer digits to make large numbers more legible. It commonly used for
* thousands, but in some locales it separates ten-thousands. The <em>grouping
* size</em> is the number of digits between the grouping separators, such as 3
* for "100,000,000" or 4 for "1 0000 0000". There are actually two different
* grouping sizes: One used for the least significant integer digits, the
* <em>primary grouping size</em>, and one used for all others, the
* <em>secondary grouping size</em>. In most locales these are the same, but
* sometimes they are different. For example, if the primary grouping interval
* is 3, and the secondary is 2, then this corresponds to the pattern
* "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a
* pattern contains multiple grouping separators, the interval between the last
* one and the end of the integer defines the primary grouping size, and the
* interval between the last two defines the secondary grouping size. All others
* are ignored, so "#,##,###,####" == "###,###,####" == "##,#,###,####".
*
* <p>Illegal patterns, such as "#.#.#" or "#.###,###", will cause
* <code>DecimalFormat</code> to throw an {@link IllegalArgumentException}
* with a message that describes the problem.
*
* <h4>Pattern BNF</h4>
*
* <pre>
* pattern := subpattern (';' subpattern)?
* subpattern := prefix? number exponent? suffix?
* number := (integer ('.' fraction)?) | sigDigits
* prefix := '&#92;u0000'..'&#92;uFFFD' - specialCharacters
* suffix := '&#92;u0000'..'&#92;uFFFD' - specialCharacters
* integer := '#'* '0'* '0'
* fraction := '0'* '#'*
* sigDigits := '#'* '@' '@'* '#'*
* exponent := 'E' '+'? '0'* '0'
* padSpec := '*' padChar
* padChar := '&#92;u0000'..'&#92;uFFFD' - quote
* &#32;
* Notation:
* X* 0 or more instances of X
* X? 0 or 1 instances of X
* X|Y either X or Y
* C..D any character from C up to D, inclusive
* S-T characters in S, except those in T
* </pre>
* The first subpattern is for positive numbers. The second (optional)
* subpattern is for negative numbers.
*
* <p>Not indicated in the BNF syntax above:
*
* <ul><li>The grouping separator ',' can occur inside the integer and
* sigDigits elements, between any two pattern characters of that
* element, as long as the integer or sigDigits element is not
* followed by the exponent element.
*
* <li><font color=red face=helvetica><strong>NEW</strong></font>
* Two grouping intervals are recognized: That between the
* decimal point and the first grouping symbol, and that
* between the first and second grouping symbols. These
* intervals are identical in most locales, but in some
* locales they differ. For example, the pattern
* &quot;#,##,###&quot; formats the number 123456789 as
* &quot;12,34,56,789&quot;.</li>
*
* <li>
* <strong><font face=helvetica color=red>NEW</font></strong>
* The pad specifier <code>padSpec</code> may appear before the prefix,
* after the prefix, before the suffix, after the suffix, or not at all.
*
* <li>
* <strong><font face=helvetica color=red>NEW</font></strong>
* In place of '0', the digits '1' through '9' may be used to
* indicate a rounding increment.
* </ul>
*
* <h4>Parsing</h4>
*
* <p><code>DecimalFormat</code> parses all Unicode characters that represent
* decimal digits, as defined by {@link UCharacter#digit}. In addition,
* <code>DecimalFormat</code> also recognizes as digits the ten consecutive
* characters starting with the localized zero digit defined in the
* {@link DecimalFormatSymbols} object. During formatting, the
* {@link DecimalFormatSymbols}-based digits are output.
*
* <p>During parsing, grouping separators are ignored.
*
* <p>If {@link #parse(String, ParsePosition)} fails to parse
* a string, it returns <code>null</code> and leaves the parse position
* unchanged. The convenience method {@link #parse(String)}
* indicates parse failure by throwing a {@link java.text.ParseException}.
*
* <h4>Formatting</h4>
*
* <p>Formatting is guided by several parameters, all of which can be
* specified either using a pattern or using the API. The following
* description applies to formats that do not use <a href="#sci">scientific
* notation</a> or <a href="#sigdig">significant digits</a>.
*
* <ul><li>If the number of actual integer digits exceeds the
* <em>maximum integer digits</em>, then only the least significant
* digits are shown. For example, 1997 is formatted as "97" if the
* maximum integer digits is set to 2.
*
* <li>If the number of actual integer digits is less than the
* <em>minimum integer digits</em>, then leading zeros are added. For
* example, 1997 is formatted as "01997" if the minimum integer digits
* is set to 5.
*
* <li>If the number of actual fraction digits exceeds the <em>maximum
* fraction digits</em>, then half-even rounding it performed to the
* maximum fraction digits. For example, 0.125 is formatted as "0.12"
* if the maximum fraction digits is 2. This behavior can be changed
* by specifying a rounding increment and a rounding mode.
*
* <li>If the number of actual fraction digits is less than the
* <em>minimum fraction digits</em>, then trailing zeros are added.
* For example, 0.125 is formatted as "0.1250" if the mimimum fraction
* digits is set to 4.
*
* <li>Trailing fractional zeros are not displayed if they occur
* <em>j</em> positions after the decimal, where <em>j</em> is less
* than the maximum fraction digits. For example, 0.10004 is
* formatted as "0.1" if the maximum fraction digits is four or less.
* </ul>
*
* <p><strong>Special Values</strong>
*
* <p><code>NaN</code> is represented as a single character, typically
* <code>&#92;uFFFD</code>. This character is determined by the
* {@link DecimalFormatSymbols} object. This is the only value for which
* the prefixes and suffixes are not used.
*
* <p>Infinity is represented as a single character, typically
* <code>&#92;u221E</code>, with the positive or negative prefixes and suffixes
* applied. The infinity character is determined by the
* {@link DecimalFormatSymbols} object.
*
* <a name="sci"><h4>Scientific Notation</h4></a>
*
* <p>Numbers in scientific notation are expressed as the product of a mantissa
* and a power of ten, for example, 1234 can be expressed as 1.234 x 10<sup>3</sup>. The
* mantissa is typically in the half-open interval [1.0, 10.0) or sometimes [0.0, 1.0),
* but it need not be. <code>DecimalFormat</code> supports arbitrary mantissas.
* <code>DecimalFormat</code> can be instructed to use scientific
* notation through the API or through the pattern. In a pattern, the exponent
* character immediately followed by one or more digit characters indicates
* scientific notation. Example: "0.###E0" formats the number 1234 as
* "1.234E3".
*
* <ul>
* <li>The number of digit characters after the exponent character gives the
* minimum exponent digit count. There is no maximum. Negative exponents are
* formatted using the localized minus sign, <em>not</em> the prefix and suffix
* from the pattern. This allows patterns such as "0.###E0 m/s". To prefix
* positive exponents with a localized plus sign, specify '+' between the
* exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0",
* "1E-1", etc. (In localized patterns, use the localized plus sign rather than
* '+'.)
*
* <li>The minimum number of integer digits is achieved by adjusting the
* exponent. Example: 0.00123 formatted with "00.###E0" yields "12.3E-4". This
* only happens if there is no maximum number of integer digits. If there is a
* maximum, then the minimum number of integer digits is fixed at one.
*
* <li>The maximum number of integer digits, if present, specifies the exponent
* grouping. The most common use of this is to generate <em>engineering
* notation</em>, in which the exponent is a multiple of three, e.g.,
* "##0.###E0". The number 12345 is formatted using "##0.####E0" as "12.345E3".
*
* <li>When using scientific notation, the formatter controls the
* digit counts using significant digits logic. The maximum number of
* significant digits limits the total number of integer and fraction
* digits that will be shown in the mantissa; it does not affect
* parsing. For example, 12345 formatted with "##0.##E0" is "12.3E3".
* See the section on significant digits for more details.
*
* <li>The number of significant digits shown is determined as
* follows: If areSignificantDigitsUsed() returns false, then the
* minimum number of significant digits shown is one, and the maximum
* number of significant digits shown is the sum of the <em>minimum
* integer</em> and <em>maximum fraction</em> digits, and is
* unaffected by the maximum integer digits. If this sum is zero,
* then all significant digits are shown. If
* areSignificantDigitsUsed() returns true, then the significant digit
* counts are specified by getMinimumSignificantDigits() and
* getMaximumSignificantDigits(). In this case, the number of
* integer digits is fixed at one, and there is no exponent grouping.
*
* <li>Exponential patterns may not contain grouping separators.
* </ul>
*
* <a name="sigdig"><h4>
* <strong><font face=helvetica color=red>NEW</font></strong>
* Significant Digits</h4></a>
*
* <code>DecimalFormat</code> has two ways of controlling how many
* digits are shows: (a) significant digits counts, or (b) integer and
* fraction digit counts. Integer and fraction digit counts are
* described above. When a formatter is using significant digits
* counts, the number of integer and fraction digits is not specified
* directly, and the formatter settings for these counts are ignored.
* Instead, the formatter uses however many integer and fraction
* digits are required to display the specified number of significant
* digits. Examples:
*
* <blockquote>
* <table border=0 cellspacing=3 cellpadding=0>
* <tr bgcolor="#ccccff">
* <th align=left>Pattern
* <th align=left>Minimum significant digits
* <th align=left>Maximum significant digits
* <th align=left>Number
* <th align=left>Output of format()
* <tr valign=top>
* <td><code>@@@</code>
* <td>3
* <td>3
* <td>12345
* <td><code>12300</code>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>@@@</code>
* <td>3
* <td>3
* <td>0.12345
* <td><code>0.123</code>
* <tr valign=top>
* <td><code>@@##</code>
* <td>2
* <td>4
* <td>3.14159
* <td><code>3.142</code>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>@@##</code>
* <td>2
* <td>4
* <td>1.23004
* <td><code>1.23</code>
* </table>
* </blockquote>
*
* <ul>
* <li>Significant digit counts may be expressed using patterns that
* specify a minimum and maximum number of significant digits. These
* are indicated by the <code>'@'</code> and <code>'#'</code>
* characters. The minimum number of significant digits is the number
* of <code>'@'</code> characters. The maximum number of significant
* digits is the number of <code>'@'</code> characters plus the number
* of <code>'#'</code> characters following on the right. For
* example, the pattern <code>"@@@"</code> indicates exactly 3
* significant digits. The pattern <code>"@##"</code> indicates from
* 1 to 3 significant digits. Trailing zero digits to the right of
* the decimal separator are suppressed after the minimum number of
* significant digits have been shown. For example, the pattern
* <code>"@##"</code> formats the number 0.1203 as
* <code>"0.12"</code>.
*
* <li>If a pattern uses significant digits, it may not contain a
* decimal separator, nor the <code>'0'</code> pattern character.
* Patterns such as <code>"@00"</code> or <code>"@.###"</code> are
* disallowed.
*
* <li>Any number of <code>'#'</code> characters may be prepended to
* the left of the leftmost <code>'@'</code> character. These have no
* effect on the minimum and maximum significant digits counts, but
* may be used to position grouping separators. For example,
* <code>"#,#@#"</code> indicates a minimum of one significant digits,
* a maximum of two significant digits, and a grouping size of three.
*
* <li>In order to enable significant digits formatting, use a pattern
* containing the <code>'@'</code> pattern character. Alternatively,
* call {@link #setSignificantDigitsUsed setSignificantDigitsUsed(true)}.
*
* <li>In order to disable significant digits formatting, use a
* pattern that does not contain the <code>'@'</code> pattern
* character. Alternatively, call {@link #setSignificantDigitsUsed
* setSignificantDigitsUsed(false)}.
*
* <li>The number of significant digits has no effect on parsing.
*
* <li>Significant digits may be used together with exponential notation. Such
* patterns are equivalent to a normal exponential pattern with a minimum and
* maximum integer digit count of one, a minimum fraction digit count of
* <code>getMinimumSignificantDigits() - 1</code>, and a maximum fraction digit
* count of <code>getMaximumSignificantDigits() - 1</code>. For example, the
* pattern <code>"@@###E0"</code> is equivalent to <code>"0.0###E0"</code>.
*
* <li>If signficant digits are in use, then the integer and fraction
* digit counts, as set via the API, are ignored. If significant
* digits are not in use, then the signficant digit counts, as set via
* the API, are ignored.
*
* </ul>
*
* <h4>
* <strong><font face=helvetica color=red>NEW</font></strong>
* Padding</h4>
*
* <p><code>DecimalFormat</code> supports padding the result of
* {@link #format} to a specific width. Padding may be specified either
* through the API or through the pattern syntax. In a pattern the pad escape
* character, followed by a single pad character, causes padding to be parsed
* and formatted. The pad escape character is '*' in unlocalized patterns, and
* can be localized using {@link DecimalFormatSymbols#setPadEscape}. For
* example, <code>"$*x#,##0.00"</code> formats 123 to <code>"$xx123.00"</code>,
* and 1234 to <code>"$1,234.00"</code>.
*
* <ul>
* <li>When padding is in effect, the width of the positive subpattern,
* including prefix and suffix, determines the format width. For example, in
* the pattern <code>"* #0 o''clock"</code>, the format width is 10.
*
* <li>The width is counted in 16-bit code units (Java <code>char</code>s).
*
* <li>Some parameters which usually do not matter have meaning when padding is
* used, because the pattern width is significant with padding. In the pattern
* "* ##,##,#,##0.##", the format width is 14. The initial characters "##,##,"
* do not affect the grouping size or maximum integer digits, but they do affect
* the format width.
*
* <li>Padding may be inserted at one of four locations: before the prefix,
* after the prefix, before the suffix, or after the suffix. If padding is
* specified in any other location, {@link #applyPattern} throws an {@link
* IllegalArgumentException}. If there is no prefix, before the
* prefix and after the prefix are equivalent, likewise for the suffix.
*
* <li>When specified in a pattern, the 16-bit <code>char</code> immediately
* following the pad escape is the pad character. This may be any character,
* including a special pattern character. That is, the pad escape
* <em>escapes</em> the following character. If there is no character after
* the pad escape, then the pattern is illegal.
*
* </ul>
*
* <p>
* <strong><font face=helvetica color=red>NEW</font></strong>
* <strong>Rounding</strong>
*
* <p><code>DecimalFormat</code> supports rounding to a specific increment. For
* example, 1230 rounded to the nearest 50 is 1250. 1.234 rounded to the
* nearest 0.65 is 1.3. The rounding increment may be specified through the API
* or in a pattern. To specify a rounding increment in a pattern, include the
* increment in the pattern itself. "#,#50" specifies a rounding increment of
* 50. "#,##0.05" specifies a rounding increment of 0.05.
*
* <ul>
* <li>Rounding only affects the string produced by formatting. It does
* not affect parsing or change any numerical values.
*
* <li>A <em>rounding mode</em> determines how values are rounded; see the
* {@link com.ibm.icu.math.BigDecimal} documentation for a description of the
* modes. Rounding increments specified in patterns use the default mode,
* {@link com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN}.
*
* <li>Some locales use rounding in their currency formats to reflect the
* smallest currency denomination.
*
* <li>In a pattern, digits '1' through '9' specify rounding, but otherwise
* behave identically to digit '0'.
* </ul>
*
* <h4>Synchronization</h4>
*
* <p><code>DecimalFormat</code> objects are not synchronized. Multiple
* threads should not access one formatter concurrently.
*
* @see java.text.Format
* @see NumberFormat
* @author Mark Davis
* @author Alan Liu
* @stable ICU 2.0
*/
public class DecimalFormat extends NumberFormat {
private static final long serialVersionUID = 1L;
/**
* @internal
* @param delegate the NumberFormat to which to delegate
*/
public DecimalFormat(java.text.DecimalFormat delegate) {
super(delegate);
}
/**
* Create a DecimalFormat using the default pattern and symbols
* for the default locale. This is a convenient way to obtain a
* DecimalFormat when internationalization is not the main concern.
* <p>
* To obtain standard formats for a given locale, use the factory methods
* on NumberFormat such as getNumberInstance. These factories will
* return the most appropriate sub-class of NumberFormat for a given
* locale.
* @see NumberFormat#getInstance
* @see NumberFormat#getNumberInstance
* @see NumberFormat#getCurrencyInstance
* @see NumberFormat#getPercentInstance
* @stable ICU 2.0
*/
public DecimalFormat() {
this(new java.text.DecimalFormat());
}
/**
* Create a DecimalFormat from the given pattern and the symbols
* for the default locale. This is a convenient way to obtain a
* DecimalFormat when internationalization is not the main concern.
* <p>
* To obtain standard formats for a given locale, use the factory methods
* on NumberFormat such as getNumberInstance. These factories will
* return the most appropriate sub-class of NumberFormat for a given
* locale.
* @param pattern A non-localized pattern string.
* @exception IllegalArgumentException if the given pattern is invalid.
* @see NumberFormat#getInstance
* @see NumberFormat#getNumberInstance
* @see NumberFormat#getCurrencyInstance
* @see NumberFormat#getPercentInstance
* @stable ICU 2.0
*/
public DecimalFormat(String pattern) {
this(new java.text.DecimalFormat(pattern));
}
/**
* Create a DecimalFormat from the given pattern and symbols.
* Use this constructor when you need to completely customize the
* behavior of the format.
* <p>
* To obtain standard formats for a given
* locale, use the factory methods on NumberFormat such as
* getInstance or getCurrencyInstance. If you need only minor adjustments
* to a standard format, you can modify the format returned by
* a NumberFormat factory method.
* @param pattern a non-localized pattern string
* @param symbols the set of symbols to be used
* @exception IllegalArgumentException if the given pattern is invalid
* @see NumberFormat#getInstance
* @see NumberFormat#getNumberInstance
* @see NumberFormat#getCurrencyInstance
* @see NumberFormat#getPercentInstance
* @see DecimalFormatSymbols
* @stable ICU 2.0
*/
public DecimalFormat(String pattern, DecimalFormatSymbols symbols) {
this(new java.text.DecimalFormat(pattern, symbols.dfs));
}
/**
* Returns a copy of the decimal format symbols used by this format.
* @return desired DecimalFormatSymbols
* @see DecimalFormatSymbols
* @stable ICU 2.0
*/
public DecimalFormatSymbols getDecimalFormatSymbols() {
return new DecimalFormatSymbols(((java.text.DecimalFormat)numberFormat).getDecimalFormatSymbols());
}
/**
* Sets the decimal format symbols used by this format. The
* format uses a copy of the provided symbols.
* @param newSymbols desired DecimalFormatSymbols
* @see DecimalFormatSymbols
* @stable ICU 2.0
*/
public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) {
((java.text.DecimalFormat)numberFormat).setDecimalFormatSymbols(newSymbols.dfs);
}
/**
* Get the positive prefix.
* <P>Examples: +123, $123, sFr123
* @stable ICU 2.0
*/
public String getPositivePrefix() {
return ((java.text.DecimalFormat)numberFormat).getPositivePrefix();
}
/**
* Set the positive prefix.
* <P>Examples: +123, $123, sFr123
* @stable ICU 2.0
*/
public void setPositivePrefix(String newValue) {
((java.text.DecimalFormat)numberFormat).setPositivePrefix(newValue);
}
/**
* Get the negative prefix.
* <P>Examples: -123, ($123) (with negative suffix), sFr-123
* @stable ICU 2.0
*/
public String getNegativePrefix () {
return ((java.text.DecimalFormat)numberFormat).getNegativePrefix();
}
/**
* Set the negative prefix.
* <P>Examples: -123, ($123) (with negative suffix), sFr-123
* @stable ICU 2.0
*/
public void setNegativePrefix (String newValue) {
((java.text.DecimalFormat)numberFormat).setNegativePrefix(newValue);
}
/**
* Get the positive suffix.
* <P>Example: 123%
* @stable ICU 2.0
*/
public String getPositiveSuffix () {
return ((java.text.DecimalFormat)numberFormat).getPositiveSuffix();
}
/**
* Set the positive suffix.
* <P>Example: 123%
* @stable ICU 2.0
*/
public void setPositiveSuffix (String newValue) {
((java.text.DecimalFormat)numberFormat).setPositiveSuffix(newValue);
}
/**
* Get the negative suffix.
* <P>Examples: -123%, ($123) (with positive suffixes)
* @stable ICU 2.0
*/
public String getNegativeSuffix () {
return ((java.text.DecimalFormat)numberFormat).getNegativeSuffix();
}
/**
* Set the positive suffix.
* <P>Examples: 123%
* @stable ICU 2.0
*/
public void setNegativeSuffix (String newValue) {
((java.text.DecimalFormat)numberFormat).setNegativeSuffix(newValue);
}
/**
* Get the multiplier for use in percent, permill, etc.
* For a percentage, set the suffixes to have "%" and the multiplier to be 100.
* (For Arabic, use arabic percent symbol).
* For a permill, set the suffixes to have "\u2031" and the multiplier to be 1000.
* <P>Examples: with 100, 1.23 -> "123", and "123" -> 1.23
* @stable ICU 2.0
*/
public int getMultiplier () {
return ((java.text.DecimalFormat)numberFormat).getMultiplier();
}
/**
* Set the multiplier for use in percent, permill, etc.
* For a percentage, set the suffixes to have "%" and the multiplier to be 100.
* (For Arabic, use arabic percent symbol).
* For a permill, set the suffixes to have "\u2031" and the multiplier to be 1000.
* <P>Examples: with 100, 1.23 -> "123", and "123" -> 1.23
* @stable ICU 2.0
*/
public void setMultiplier (int newValue) {
((java.text.DecimalFormat)numberFormat).setMultiplier(newValue);
}
/**
* Return the grouping size. Grouping size is the number of digits between
* grouping separators in the integer portion of a number. For example,
* in the number "123,456.78", the grouping size is 3.
* @see #setGroupingSize
* @see NumberFormat#isGroupingUsed
* @see DecimalFormatSymbols#getGroupingSeparator
* @stable ICU 2.0
*/
public int getGroupingSize () {
return ((java.text.DecimalFormat)numberFormat).getGroupingSize();
}
/**
* Set the grouping size. Grouping size is the number of digits between
* grouping separators in the integer portion of a number. For example,
* in the number "123,456.78", the grouping size is 3.
* @see #getGroupingSize
* @see NumberFormat#setGroupingUsed
* @see DecimalFormatSymbols#setGroupingSeparator
* @stable ICU 2.0
*/
public void setGroupingSize (int newValue) {
((java.text.DecimalFormat)numberFormat).setGroupingSize(newValue);
}
/**
* Allows you to get the behavior of the decimal separator with integers.
* (The decimal separator will always appear with decimals.)
* <P>Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345
* @stable ICU 2.0
*/
public boolean isDecimalSeparatorAlwaysShown() {
return ((java.text.DecimalFormat)numberFormat).isDecimalSeparatorAlwaysShown();
}
/**
* Allows you to set the behavior of the decimal separator with integers.
* (The decimal separator will always appear with decimals.)
*
* <p>This only affects formatting, and only where
* there might be no digits after the decimal point, e.g.,
* if true, 3456.00 -> "3,456."
* if false, 3456.00 -> "3456"
* This is independent of parsing. If you want parsing to stop at the decimal
* point, use setParseIntegerOnly.
*
* <P>Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345
* @stable ICU 2.0
*/
public void setDecimalSeparatorAlwaysShown(boolean newValue) {
((java.text.DecimalFormat)numberFormat).setDecimalSeparatorAlwaysShown(newValue);
}
/**
* Standard override; no change in semantics.
* @stable ICU 2.0
*/
public Object clone() {
return new DecimalFormatSymbols((java.text.DecimalFormatSymbols)numberFormat.clone());
}
/**
* Synthesizes a pattern string that represents the current state
* of this Format object.
* @see #applyPattern
* @stable ICU 2.0
*/
public String toPattern() {
return ((java.text.DecimalFormat)numberFormat).toPattern();
}
/**
* Synthesizes a localized pattern string that represents the current
* state of this Format object.
* @see #applyPattern
* @stable ICU 2.0
*/
public String toLocalizedPattern() {
return ((java.text.DecimalFormat)numberFormat).toLocalizedPattern();
}
/**
* Apply the given pattern to this Format object. A pattern is a
* short-hand specification for the various formatting properties.
* These properties can also be changed individually through the
* various setter methods.
* <p>
* There is no limit to integer digits are set
* by this routine, since that is the typical end-user desire;
* use setMaximumInteger if you want to set a real value.
* For negative numbers, use a second pattern, separated by a semicolon
* <P>Example "#,#00.0#" -> 1,234.56
* <P>This means a minimum of 2 integer digits, 1 fraction digit, and
* a maximum of 2 fraction digits.
* <p>Example: "#,#00.0#;(#,#00.0#)" for negatives in parentheses.
* <p>In negative patterns, the minimum and maximum counts are ignored;
* these are presumed to be set in the positive pattern.
* @stable ICU 2.0
*/
public void applyPattern(String pattern) {
((java.text.DecimalFormat)numberFormat).applyPattern(pattern);
}
/**
* Apply the given pattern to this Format object. The pattern
* is assumed to be in a localized notation. A pattern is a
* short-hand specification for the various formatting properties.
* These properties can also be changed individually through the
* various setter methods.
* <p>
* There is no limit to integer digits are set
* by this routine, since that is the typical end-user desire;
* use setMaximumInteger if you want to set a real value.
* For negative numbers, use a second pattern, separated by a semicolon
* <P>Example "#,#00.0#" -> 1,234.56
* <P>This means a minimum of 2 integer digits, 1 fraction digit, and
* a maximum of 2 fraction digits.
* <p>Example: "#,#00.0#;(#,#00.0#)" for negatives in parentheses.
* <p>In negative patterns, the minimum and maximum counts are ignored;
* these are presumed to be set in the positive pattern.
* @stable ICU 2.0
*/
public void applyLocalizedPattern(String pattern) {
((java.text.DecimalFormat)numberFormat).applyLocalizedPattern(pattern);
}
}

View file

@ -0,0 +1,349 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import java.io.Serializable;
import java.util.Locale;
import com.ibm.icu.util.ULocale;
/**
* This class represents the set of symbols (such as the decimal separator, the
* grouping separator, and so on) needed by <code>DecimalFormat</code> to format
* numbers. <code>DecimalFormat</code> creates for itself an instance of
* <code>DecimalFormatSymbols</code> from its locale data. If you need to
* change any of these symbols, you can get the
* <code>DecimalFormatSymbols</code> object from your <code>DecimalFormat</code>
* and modify it.
*
* <p><strong>This is an enhanced version of <code>DecimalFormatSymbols</code> that
* is based on the standard version in the JDK. New or changed functionality
* is labeled
* <strong><font face=helvetica color=red>NEW</font></strong>.</strong>
*
* @see java.util.Locale
* @see DecimalFormat
* @author Mark Davis
* @author Alan Liu
* @stable ICU 2.0
*/
final public class DecimalFormatSymbols implements Cloneable, Serializable {
private static final long serialVersionUID =1L;
/**
* @internal
*/
public final java.text.DecimalFormatSymbols dfs;
/**
* @internal
*/
public DecimalFormatSymbols(java.text.DecimalFormatSymbols delegate) {
this.dfs = delegate;
}
/**
* Create a DecimalFormatSymbols object for the default locale.
* @stable ICU 2.0
*/
public DecimalFormatSymbols() {
this(new java.text.DecimalFormatSymbols());
}
/**
* Create a DecimalFormatSymbols object for the given locale.
* @param locale the locale
* @stable ICU 2.0
*/
public DecimalFormatSymbols(Locale locale) {
this(new java.text.DecimalFormatSymbols(locale));
}
/**
* Create a DecimalFormatSymbols object for the given locale.
* @param locale the locale
* @draft ICU 3.2
*/
public DecimalFormatSymbols(ULocale locale) {
this(new java.text.DecimalFormatSymbols(locale.toLocale()));
}
/**
* Return the character used for zero. Different for Arabic, etc.
* @return the character
* @stable ICU 2.0
*/
public char getZeroDigit() {
return dfs.getZeroDigit();
}
/**
* Set the character used for zero.
* @param zeroDigit the zero character.
* @stable ICU 2.0
*/
public void setZeroDigit(char zeroDigit) {
dfs.setZeroDigit(zeroDigit);
}
/**
* Return the character used for thousands separator. Different for French, etc.
* @return the thousands character
* @stable ICU 2.0
*/
public char getGroupingSeparator() {
return dfs.getGroupingSeparator();
}
/**
* Set the character used for thousands separator. Different for French, etc.
* @param groupingSeparator the thousands character
* @stable ICU 2.0
*/
public void setGroupingSeparator(char groupingSeparator) {
dfs.setGroupingSeparator(groupingSeparator);
}
/**
* Return the character used for decimal sign. Different for French, etc.
* @return the decimal character
* @stable ICU 2.0
*/
public char getDecimalSeparator() {
return dfs.getDecimalSeparator();
}
/**
* Set the character used for decimal sign. Different for French, etc.
* @param decimalSeparator the decimal character
* @stable ICU 2.0
*/
public void setDecimalSeparator(char decimalSeparator) {
dfs.setDecimalSeparator(decimalSeparator);
}
/**
* Return the character used for mille percent sign. Different for Arabic, etc.
* @return the mille percent character
* @stable ICU 2.0
*/
public char getPerMill() {
return dfs.getPerMill();
}
/**
* Set the character used for mille percent sign. Different for Arabic, etc.
* @param perMill the mille percent character
* @stable ICU 2.0
*/
public void setPerMill(char perMill) {
dfs.setPerMill(perMill);
}
/**
* Return the character used for percent sign. Different for Arabic, etc.
* @return the percent character
* @stable ICU 2.0
*/
public char getPercent() {
return dfs.getPercent();
}
/**
* Set the character used for percent sign. Different for Arabic, etc.
* @param percent the percent character
* @stable ICU 2.0
*/
public void setPercent(char percent) {
dfs.setPercent(percent);
}
/**
* Return the character used for a digit in a pattern.
* @return the digit pattern character
* @stable ICU 2.0
*/
public char getDigit() {
return dfs.getDigit();
}
/**
* Set the character used for a digit in a pattern.
* @param digit the digit pattern character
* @stable ICU 2.0
*/
public void setDigit(char digit) {
dfs.setDigit(digit);
}
/**
* Return the character used to separate positive and negative subpatterns
* in a pattern.
* @return the pattern separator character
* @stable ICU 2.0
*/
public char getPatternSeparator() {
return dfs.getPatternSeparator();
}
/**
* Set the character used to separate positive and negative subpatterns
* in a pattern.
* @param patternSeparator the pattern separator character
* @stable ICU 2.0
*/
public void setPatternSeparator(char patternSeparator) {
dfs.setPatternSeparator(patternSeparator);
}
/**
* Return the String used to represent infinity. Almost always left
* unchanged.
* @return the Infinity string
* @stable ICU 2.0
*/
public String getInfinity() {
return dfs.getInfinity();
}
/**
* Set the String used to represent infinity. Almost always left
* unchanged.
* @param infinity the Infinity String
* @stable ICU 2.0
*/
public void setInfinity(String infinity) {
dfs.setInfinity(infinity);
}
/**
* Return the String used to represent NaN. Almost always left
* unchanged.
* @return the NaN String
* @stable ICU 2.0
*/
public String getNaN() {
return dfs.getNaN();
}
/**
* Set the String used to represent NaN. Almost always left
* unchanged.
* @param NaN the NaN String
* @stable ICU 2.0
*/
public void setNaN(String NaN) {
dfs.setNaN(NaN);
}
/**
* Return the character used to represent minus sign. If no explicit
* negative format is specified, one is formed by prefixing
* minusSign to the positive format.
* @return the minus sign character
* @stable ICU 2.0
*/
public char getMinusSign() {
return dfs.getMinusSign();
}
/**
* Set the character used to represent minus sign. If no explicit
* negative format is specified, one is formed by prefixing
* minusSign to the positive format.
* @param minusSign the minus sign character
* @stable ICU 2.0
*/
public void setMinusSign(char minusSign) {
dfs.setMinusSign(minusSign);
}
/**
* Return the string denoting the local currency.
* @return the local currency String.
* @stable ICU 2.0
*/
public String getCurrencySymbol() {
return dfs.getCurrencySymbol();
}
/**
* Set the string denoting the local currency.
* @param currency the local currency String.
* @stable ICU 2.0
*/
public void setCurrencySymbol(String currency) {
dfs.setCurrencySymbol(currency);
}
/**
* Return the international string denoting the local currency.
* @return the international string denoting the local currency
* @stable ICU 2.0
*/
public String getInternationalCurrencySymbol() {
return dfs.getInternationalCurrencySymbol();
}
/**
* Set the international string denoting the local currency.
* @param currency the international string denoting the local currency.
* @stable ICU 2.0
*/
public void setInternationalCurrencySymbol(String currency) {
dfs.setInternationalCurrencySymbol(currency);
}
/**
* Return the monetary decimal separator.
* @return the monetary decimal separator character
* @stable ICU 2.0
*/
public char getMonetaryDecimalSeparator() {
return dfs.getMonetaryDecimalSeparator();
}
/**
* Set the monetary decimal separator.
* @param sep the monetary decimal separator character
* @stable ICU 2.0
*/
public void setMonetaryDecimalSeparator(char sep) {
dfs.setMonetaryDecimalSeparator(sep);
}
/**
* Standard override.
* @stable ICU 2.0
*/
public Object clone() {
return new DecimalFormatSymbols((java.text.DecimalFormatSymbols)dfs.clone());
}
/**
* Override equals.
* @stable ICU 2.0
*/
public boolean equals(Object obj) {
try {
return dfs.equals(((DecimalFormatSymbols)obj).dfs);
}
catch (Exception e) {
return false;
}
}
/**
* Override hashCode
* @stable ICU 2.0
*/
public int hashCode() {
return dfs.hashCode();
}
}

View file

@ -0,0 +1,778 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.text.DecimalFormatSymbols;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
import com.ibm.icu.util.ULocale;
/**
* <code>NumberFormat</code> is the abstract base class for all number
* formats. This class provides the interface for formatting and parsing
* numbers. <code>NumberFormat</code> also provides methods for determining
* which locales have number formats, and what their names are.
*
* <p><strong>This is an enhanced version of <code>NumberFormat</code> that
* is based on the standard version in the JDK. New or changed functionality
* is labeled
* <strong><font face=helvetica color=red>NEW</font></strong> or
* <strong><font face=helvetica color=red>CHANGED</font></strong>.</strong>
*
* <p>
* <code>NumberFormat</code> helps you to format and parse numbers for any locale.
* Your code can be completely independent of the locale conventions for
* decimal points, thousands-separators, or even the particular decimal
* digits used, or whether the number format is even decimal.
*
* <p>
* To format a number for the current Locale, use one of the factory
* class methods:
* <blockquote>
* <pre>
* myString = NumberFormat.getInstance().format(myNumber);
* </pre>
* </blockquote>
* If you are formatting multiple numbers, it is
* more efficient to get the format and use it multiple times so that
* the system doesn't have to fetch the information about the local
* language and country conventions multiple times.
* <blockquote>
* <pre>
* NumberFormat nf = NumberFormat.getInstance();
* for (int i = 0; i < a.length; ++i) {
* output.println(nf.format(myNumber[i]) + "; ");
* }
* </pre>
* </blockquote>
* To format a number for a different Locale, specify it in the
* call to <code>getInstance</code>.
* <blockquote>
* <pre>
* NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
* </pre>
* </blockquote>
* You can also use a <code>NumberFormat</code> to parse numbers:
* <blockquote>
* <pre>
* myNumber = nf.parse(myString);
* </pre>
* </blockquote>
* Use <code>getInstance</code> or <code>getNumberInstance</code> to get the
* normal number format. Use <code>getIntegerInstance</code> to get an
* integer number format. Use <code>getCurrencyInstance</code> to get the
* currency number format. And use <code>getPercentInstance</code> to get a
* format for displaying percentages. With this format, a fraction like
* 0.53 is displayed as 53%.
*
* <p>
* You can also control the display of numbers with such methods as
* <code>setMinimumFractionDigits</code>.
* If you want even more control over the format or parsing,
* or want to give your users more control,
* you can try casting the <code>NumberFormat</code> you get from the factory methods
* to a <code>DecimalFormat</code>. This will work for the vast majority
* of locales; just remember to put it in a <code>try</code> block in case you
* encounter an unusual one.
*
* <p>
* NumberFormat is designed such that some controls
* work for formatting and others work for parsing. The following is
* the detailed description for each these control methods,
* <p>
* setParseIntegerOnly : only affects parsing, e.g.
* if true, "3456.78" -> 3456 (and leaves the parse position just after '6')
* if false, "3456.78" -> 3456.78 (and leaves the parse position just after '8')
* This is independent of formatting. If you want to not show a decimal point
* where there might be no digits after the decimal point, use
* setDecimalSeparatorAlwaysShown on DecimalFormat.
* <p>
* You can also use forms of the <code>parse</code> and <code>format</code>
* methods with <code>ParsePosition</code> and <code>FieldPosition</code> to
* allow you to:
* <ul>
* <li> progressively parse through pieces of a string
* <li> align the decimal point and other areas
* </ul>
* For example, you can align numbers in two ways:
* <ol>
* <li> If you are using a monospaced font with spacing for alignment,
* you can pass the <code>FieldPosition</code> in your format call, with
* <code>field</code> = <code>INTEGER_FIELD</code>. On output,
* <code>getEndIndex</code> will be set to the offset between the
* last character of the integer and the decimal. Add
* (desiredSpaceCount - getEndIndex) spaces at the front of the string.
*
* <li> If you are using proportional fonts,
* instead of padding with spaces, measure the width
* of the string in pixels from the start to <code>getEndIndex</code>.
* Then move the pen by
* (desiredPixelWidth - widthToAlignmentPoint) before drawing the text.
* It also works where there is no decimal, but possibly additional
* characters at the end, e.g., with parentheses in negative
* numbers: "(12)" for -12.
* </ol>
*
* <h4>Synchronization</h4>
* <p>
* Number formats are generally not synchronized. It is recommended to create
* separate format instances for each thread. If multiple threads access a format
* concurrently, it must be synchronized externally.
* <p>
*
* <h4>DecimalFormat</h4>
* <p>DecimalFormat is the concrete implementation of NumberFormat, and the
* NumberFormat API is essentially an abstraction from DecimalFormat's API.
* Refer to DecimalFormat for more information about this API.</p>
*
* see DecimalFormat
* see java.text.ChoiceFormat
* @author Mark Davis
* @author Helena Shih
* @author Alan Liu
* @stable ICU 2.0
*/
public class NumberFormat extends Format {
private static final long serialVersionUID = 1;
/**
* @internal
*/
public final java.text.NumberFormat numberFormat;
/**
* @internal
* @param delegate the NumberFormat to which to delegate
*/
public NumberFormat(java.text.NumberFormat delegate) {
this.numberFormat = delegate;
}
/**
* Default constructor to mirror Java's default public
* constructor. Java's is not callable as a public API, since
* their NumberFormat is abstract, so this is only useful to
* subclasses. In general, subclasses will not work unless
* they manipulate the delegate.
*/
public NumberFormat() {
this.numberFormat = java.text.NumberFormat.getInstance();
}
/**
* Field constant used to construct a FieldPosition object. Signifies that
* the position of the integer part of a formatted number should be returned.
* @see java.text.FieldPosition
* @stable ICU 2.0
*/
public static final int INTEGER_FIELD = 0;
/**
* Field constant used to construct a FieldPosition object. Signifies that
* the position of the fraction part of a formatted number should be returned.
* @see java.text.FieldPosition
* @stable ICU 2.0
*/
public static final int FRACTION_FIELD = 1;
/**
* <strong><font face=helvetica color=red>CHANGED</font></strong>
* Format an object. Change: recognizes <code>BigInteger</code>
* and <code>BigDecimal</code> objects.
* @stable ICU 2.0
*/
public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) {
return numberFormat.format(number, toAppendTo, pos);
}
/**
* @stable ICU 2.0
*/
public final Object parseObject(String source, ParsePosition parsePosition) {
return numberFormat.parse(source, parsePosition);
}
/**
* Specialization of format.
* @see java.text.Format#format(Object)
* @stable ICU 2.0
*/
public final String format(double number) {
return numberFormat.format(number);
}
/**
* Specialization of format.
* @see java.text.Format#format(Object)
* @stable ICU 2.0
*/
public final String format(long number) {
return numberFormat.format(number);
}
/**
* <strong><font face=helvetica color=red>NEW</font></strong>
* Convenience method to format a BigInteger.
* @stable ICU 2.0
*/
public final String format(BigInteger number) {
return numberFormat.format(number);
}
/**
* Specialization of format.
* @see java.text.Format#format(Object, StringBuffer, FieldPosition)
* @stable ICU 2.0
*/
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
return numberFormat.format(number, toAppendTo, pos);
}
/**
* Specialization of format.
* @see java.text.Format#format(Object, StringBuffer, FieldPosition)
* @stable ICU 2.0
*/
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
return numberFormat.format(number, toAppendTo, pos);
}
/**
* <strong><font face=helvetica color=red>NEW</font></strong>
* Format a BigInteger.
* @see java.text.Format#format(Object, StringBuffer, FieldPosition)
* @stable ICU 2.0
*/
public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) {
return numberFormat.format(number, toAppendTo, pos);
}
/**
* Returns a Long if possible (e.g., within the range [Long.MIN_VALUE,
* Long.MAX_VALUE] and with no decimals), otherwise a Double.
* If IntegerOnly is set, will stop at a decimal
* point (or equivalent; e.g., for rational numbers "1 2/3", will stop
* after the 1).
* Does not throw an exception; if no object can be parsed, index is
* unchanged!
* @see #isParseIntegerOnly
* @see java.text.Format#parseObject(String, ParsePosition)
* @stable ICU 2.0
*/
public Number parse(String text, ParsePosition parsePosition) {
return numberFormat.parse(text, parsePosition);
}
/**
* Parses text from the beginning of the given string to produce a number.
* The method might not use the entire text of the given string.
*
* @param text A String whose beginning should be parsed.
* @return A Number parsed from the string.
* @exception ParseException if the beginning of the specified string
* cannot be parsed.
* @see #format
* @stable ICU 2.0
*/
public Number parse(String text) throws ParseException {
return numberFormat.parse(text);
}
/**
* Returns true if this format will parse numbers as integers only.
* For example in the English locale, with ParseIntegerOnly true, the
* string "1234." would be parsed as the integer value 1234 and parsing
* would stop at the "." character. The decimal separator accepted
* by the parse operation is locale-dependent and determined by the
* subclass.
* @return true if this will parse integers only
* @stable ICU 2.0
*/
public boolean isParseIntegerOnly() {
return numberFormat.isParseIntegerOnly();
}
/**
* Sets whether or not numbers should be parsed as integers only.
* @param value true if this should parse integers only
* @see #isParseIntegerOnly
* @stable ICU 2.0
*/
public void setParseIntegerOnly(boolean value) {
numberFormat.setParseIntegerOnly(value);
}
//============== Locale Stuff =====================
/**
* Returns the default number format for the current default locale.
* The default format is one of the styles provided by the other
* factory methods: getNumberInstance, getIntegerInstance,
* getCurrencyInstance or getPercentInstance.
* Exactly which one is locale-dependent.
* @stable ICU 2.0
*/
public final static NumberFormat getInstance() {
return getInstance(ULocale.getDefault(), NUMBERSTYLE);
}
/**
* Returns the default number format for the specified locale.
* The default format is one of the styles provided by the other
* factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance.
* Exactly which one is locale-dependent.
* @stable ICU 2.0
*/
public static NumberFormat getInstance(Locale inLocale) {
return getInstance(ULocale.forLocale(inLocale), NUMBERSTYLE);
}
/**
* Returns the default number format for the specified locale.
* The default format is one of the styles provided by the other
* factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance.
* Exactly which one is locale-dependent.
* @draft ICU 3.2
*/
public static NumberFormat getInstance(ULocale inLocale) {
return getInstance(inLocale, NUMBERSTYLE);
}
/**
* Returns a general-purpose number format for the current default locale.
* @stable ICU 2.0
*/
public final static NumberFormat getNumberInstance() {
return getInstance(ULocale.getDefault(), NUMBERSTYLE);
}
/**
* Returns a general-purpose number format for the specified locale.
* @stable ICU 2.0
*/
public static NumberFormat getNumberInstance(Locale inLocale) {
return getInstance(ULocale.forLocale(inLocale), NUMBERSTYLE);
}
/**
* Returns a general-purpose number format for the specified locale.
* @draft ICU 3.2
*/
public static NumberFormat getNumberInstance(ULocale inLocale) {
return getInstance(inLocale, NUMBERSTYLE);
}
/**
* Returns an integer number format for the current default locale. The
* returned number format is configured to round floating point numbers
* to the nearest integer using IEEE half-even rounding (see {@link
* com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
* and to parse only the integer part of an input string (see {@link
* #isParseIntegerOnly isParseIntegerOnly}).
*
* @return a number format for integer values
* @stable ICU 2.0
*/
public final static NumberFormat getIntegerInstance() {
return getInstance(ULocale.getDefault(), INTEGERSTYLE);
}
/**
* Returns an integer number format for the specified locale. The
* returned number format is configured to round floating point numbers
* to the nearest integer using IEEE half-even rounding (see {@link
* com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
* and to parse only the integer part of an input string (see {@link
* #isParseIntegerOnly isParseIntegerOnly}).
*
* @param inLocale the locale for which a number format is needed
* @return a number format for integer values
* @stable ICU 2.0
*/
public static NumberFormat getIntegerInstance(Locale inLocale) {
return getInstance(ULocale.forLocale(inLocale), INTEGERSTYLE);
}
/**
* Returns an integer number format for the specified locale. The
* returned number format is configured to round floating point numbers
* to the nearest integer using IEEE half-even rounding (see {@link
* com.ibm.icu.math.BigDecimal#ROUND_HALF_EVEN ROUND_HALF_EVEN}) for formatting,
* and to parse only the integer part of an input string (see {@link
* #isParseIntegerOnly isParseIntegerOnly}).
*
* @param inLocale the locale for which a number format is needed
* @return a number format for integer values
* @draft ICU 3.2
*/
public static NumberFormat getIntegerInstance(ULocale inLocale) {
return getInstance(inLocale, INTEGERSTYLE);
}
/**
* Returns a currency format for the current default locale.
* @return a number format for currency
* @stable ICU 2.0
*/
public final static NumberFormat getCurrencyInstance() {
return getInstance(ULocale.getDefault(), CURRENCYSTYLE);
}
/**
* Returns a currency format for the specified locale.
* @return a number format for currency
* @stable ICU 2.0
*/
public static NumberFormat getCurrencyInstance(Locale inLocale) {
return getInstance(ULocale.forLocale(inLocale), CURRENCYSTYLE);
}
/**
* Returns a currency format for the specified locale.
* @return a number format for currency
* @draft ICU 3.2
*/
public static NumberFormat getCurrencyInstance(ULocale inLocale) {
return getInstance(inLocale, CURRENCYSTYLE);
}
/**
* Returns a percentage format for the current default locale.
* @return a number format for percents
* @stable ICU 2.0
*/
public final static NumberFormat getPercentInstance() {
return getInstance(ULocale.getDefault(), PERCENTSTYLE);
}
/**
* Returns a percentage format for the specified locale.
* @return a number format for percents
* @stable ICU 2.0
*/
public static NumberFormat getPercentInstance(Locale inLocale) {
return getInstance(ULocale.forLocale(inLocale), PERCENTSTYLE);
}
/**
* Returns a percentage format for the specified locale.
* @return a number format for percents
* @draft ICU 3.2
*/
public static NumberFormat getPercentInstance(ULocale inLocale) {
return getInstance(inLocale, PERCENTSTYLE);
}
/**
* <strong><font face=helvetica color=red>NEW</font></strong>
* Returns a scientific format for the current default locale.
* @return a scientific number format
* @stable ICU 2.0
*/
public final static NumberFormat getScientificInstance() {
return getInstance(ULocale.getDefault(), SCIENTIFICSTYLE);
}
/**
* <strong><font face=helvetica color=red>NEW</font></strong>
* Returns a scientific format for the specified locale.
* @return a scientific number format
* @stable ICU 2.0
*/
public static NumberFormat getScientificInstance(Locale inLocale) {
return getInstance(ULocale.forLocale(inLocale), SCIENTIFICSTYLE);
}
/**
* <strong><font face=helvetica color=red>NEW</font></strong>
* Returns a scientific format for the specified locale.
* @return a scientific number format
* @draft ICU 3.2
*/
public static NumberFormat getScientificInstance(ULocale inLocale) {
return getInstance(inLocale, SCIENTIFICSTYLE);
}
/**
* Get the list of Locales for which NumberFormats are available.
* @return the available locales
* @stable ICU 2.0
*/
public static Locale[] getAvailableLocales() {
return java.text.NumberFormat.getAvailableLocales();
}
/**
* Get the list of Locales for which NumberFormats are available.
* @return the available locales
* @draft ICU 3.2
*/
public static ULocale[] getAvailableULocales() {
if (availableULocales == null) {
Locale[] locales = java.text.NumberFormat.getAvailableLocales();
ULocale[] ulocales = new ULocale[locales.length];
for (int i = 0; i < locales.length; ++i) {
ulocales[i] = ULocale.forLocale(locales[i]);
}
availableULocales = ulocales;
}
return (ULocale[])availableULocales.clone();
}
private static ULocale[] availableULocales;
/**
* Returns true if grouping is used in this format. For example, in the
* en_US locale, with grouping on, the number 1234567 will be formatted
* as "1,234,567". The grouping separator as well as the size of each group
* is locale-dependent and is determined by subclasses of NumberFormat.
* Grouping affects both parsing and formatting.
* @return true if grouping is used
* @see #setGroupingUsed
* @stable ICU 2.0
*/
public boolean isGroupingUsed() {
return numberFormat.isGroupingUsed();
}
/**
* Sets whether or not grouping will be used in this format. Grouping
* affects both parsing and formatting.
* @see #isGroupingUsed
* @param newValue true to use grouping.
* @stable ICU 2.0
*/
public void setGroupingUsed(boolean newValue) {
numberFormat.setGroupingUsed(newValue);
}
/**
* Returns the maximum number of digits allowed in the integer portion of a
* number. The default value is 40, which subclasses can override.
* When formatting, the exact behavior when this value is exceeded is
* subclass-specific. When parsing, this has no effect.
* @return the maximum number of integer digits
* @see #setMaximumIntegerDigits
* @stable ICU 2.0
*/
public int getMaximumIntegerDigits() {
return numberFormat.getMaximumIntegerDigits();
}
/**
* Sets the maximum number of digits allowed in the integer portion of a
* number. This must be >= minimumIntegerDigits. If the
* new value for maximumIntegerDigits is less than the current value
* of minimumIntegerDigits, then minimumIntegerDigits will also be set to
* the new value.
* @param newValue the maximum number of integer digits to be shown; if
* less than zero, then zero is used. Subclasses might enforce an
* upper limit to this value appropriate to the numeric type being formatted.
* @see #getMaximumIntegerDigits
* @stable ICU 2.0
*/
public void setMaximumIntegerDigits(int newValue) {
numberFormat.setMaximumIntegerDigits(newValue);
}
/**
* Returns the minimum number of digits allowed in the integer portion of a
* number. The default value is 1, which subclasses can override.
* When formatting, if this value is not reached, numbers are padded on the
* left with the locale-specific '0' character to ensure at least this
* number of integer digits. When parsing, this has no effect.
* @return the minimum number of integer digits
* @see #setMinimumIntegerDigits
* @stable ICU 2.0
*/
public int getMinimumIntegerDigits() {
return numberFormat.getMinimumIntegerDigits();
}
/**
* Sets the minimum number of digits allowed in the integer portion of a
* number. This must be <= maximumIntegerDigits. If the
* new value for minimumIntegerDigits is more than the current value
* of maximumIntegerDigits, then maximumIntegerDigits will also be set to
* the new value.
* @param newValue the minimum number of integer digits to be shown; if
* less than zero, then zero is used. Subclasses might enforce an
* upper limit to this value appropriate to the numeric type being formatted.
* @see #getMinimumIntegerDigits
* @stable ICU 2.0
*/
public void setMinimumIntegerDigits(int newValue) {
numberFormat.setMinimumIntegerDigits(newValue);
}
/**
* Returns the maximum number of digits allowed in the fraction
* portion of a number. The default value is 3, which subclasses
* can override. When formatting, the exact behavior when this
* value is exceeded is subclass-specific. When parsing, this has
* no effect.
* @return the maximum number of fraction digits
* @see #setMaximumFractionDigits
* @stable ICU 2.0
*/
public int getMaximumFractionDigits() {
return numberFormat.getMaximumFractionDigits();
}
/**
* Sets the maximum number of digits allowed in the fraction portion of a
* number. This must be >= minimumFractionDigits. If the
* new value for maximumFractionDigits is less than the current value
* of minimumFractionDigits, then minimumFractionDigits will also be set to
* the new value.
* @param newValue the maximum number of fraction digits to be shown; if
* less than zero, then zero is used. The concrete subclass may enforce an
* upper limit to this value appropriate to the numeric type being formatted.
* @see #getMaximumFractionDigits
* @stable ICU 2.0
*/
public void setMaximumFractionDigits(int newValue) {
numberFormat.setMaximumFractionDigits(newValue);
}
/**
* Returns the minimum number of digits allowed in the fraction portion of a
* number. The default value is 0, which subclasses can override.
* When formatting, if this value is not reached, numbers are padded on
* the right with the locale-specific '0' character to ensure at least
* this number of fraction digits. When parsing, this has no effect.
* @return the minimum number of fraction digits
* @see #setMinimumFractionDigits
* @stable ICU 2.0
*/
public int getMinimumFractionDigits() {
return numberFormat.getMinimumFractionDigits();
}
/**
* Sets the minimum number of digits allowed in the fraction portion of a
* number. This must be <= maximumFractionDigits. If the
* new value for minimumFractionDigits exceeds the current value
* of maximumFractionDigits, then maximumFractionDigits will also be set to
* the new value.
* @param newValue the minimum number of fraction digits to be shown; if
* less than zero, then zero is used. Subclasses might enforce an
* upper limit to this value appropriate to the numeric type being formatted.
* @see #getMinimumFractionDigits
* @stable ICU 2.0
*/
public void setMinimumFractionDigits(int newValue) {
numberFormat.setMinimumFractionDigits(newValue);
}
/**
* Return a string suitable for debugging.
* @return a string suitable for debugging
* @draft ICU 3.4.2
*/
public String toString() {
return numberFormat.toString();
}
/**
* Overrides Cloneable.
* @stable ICU 2.0
*/
public Object clone() {
return new NumberFormat((java.text.NumberFormat)numberFormat.clone());
}
/**
* Overrides equals. Two NumberFormats are equal if they are of the same class
* and the settings (groupingUsed, parseIntegerOnly, maximumIntegerDigits, etc.
* are equal.
* @param obj the object to compare against
* @return true if the object is equal to this.
* @stable ICU 2.0
*/
public boolean equals(Object obj) {
try {
return numberFormat.equals(((NumberFormat)obj).numberFormat);
}
catch (Exception e) {
return false;
}
}
/**
* Overrides hashCode
* @stable ICU 2.0
*/
public int hashCode() {
return numberFormat.hashCode();
}
// =======================privates===============================
private static NumberFormat getInstance(ULocale desiredLocale, int choice) {
Locale locale = desiredLocale.toLocale();
java.text.NumberFormat nf = null;
switch (choice) {
case NUMBERSTYLE: nf = java.text.NumberFormat.getInstance(locale); break;
case CURRENCYSTYLE: nf = java.text.NumberFormat.getCurrencyInstance(locale); break;
case PERCENTSTYLE: nf = java.text.NumberFormat.getPercentInstance(locale); break;
case SCIENTIFICSTYLE: nf = new java.text.DecimalFormat("#E0", new DecimalFormatSymbols(locale));
nf.setMaximumFractionDigits(10);
break;
case INTEGERSTYLE:
if (unchecked) {
unchecked = false;
try {
Class[] args = { java.util.Locale.class };
integer14API = java.text.NumberFormat.class.getMethod("getIntegerInstance", args);
}
catch (Exception e) {
}
}
if (integer14API != null) {
try {
Object[] args = { locale };
nf = (java.text.NumberFormat)integer14API.invoke(null, args);
}
catch (IllegalAccessException e) {
integer14API = null;
}
catch (InvocationTargetException e) {
integer14API = null;
}
catch (Exception e) {
// shouldn't happen, but locale might be null, for example
// and we don't want to throw away our method because someone
// called us with a bad parameter
}
}
if (nf == null) {
nf = java.text.NumberFormat.getNumberInstance(locale);
nf.setMaximumFractionDigits(0);
nf.setParseIntegerOnly(true);
}
break;
}
return new NumberFormat(nf);
}
private static boolean unchecked = true;
private static Method integer14API;
private static final int NUMBERSTYLE = 0;
private static final int CURRENCYSTYLE = 1;
private static final int PERCENTSTYLE = 2;
private static final int SCIENTIFICSTYLE = 3;
private static final int INTEGERSTYLE = 4;
}

View file

@ -0,0 +1,382 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Locale;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.ULocale;
/**
* <code>SimpleDateFormat</code> is a concrete class for formatting and
* parsing dates in a locale-sensitive manner. It allows for formatting
* (date -> text), parsing (text -> date), and normalization.
*
* <p>
* <code>SimpleDateFormat</code> allows you to start by choosing
* any user-defined patterns for date-time formatting. However, you
* are encouraged to create a date-time formatter with either
* <code>getTimeInstance</code>, <code>getDateInstance</code>, or
* <code>getDateTimeInstance</code> in <code>DateFormat</code>. Each
* of these class methods can return a date/time formatter initialized
* with a default format pattern. You may modify the format pattern
* using the <code>applyPattern</code> methods as desired.
* For more information on using these methods, see
* {@link DateFormat}.
*
* <p>
* <strong>Time Format Syntax:</strong>
* <p>
* To specify the time format use a <em>time pattern</em> string.
* In this pattern, all ASCII letters are reserved as pattern letters,
* which are defined as the following:
* <blockquote>
* <pre>
* Symbol Meaning Presentation Example
* ------ ------- ------------ -------
* G era designator (Text) AD
* y&#x2020; year (Number) 1996
* Y* year (week of year) (Number) 1997
* u* extended year (Number) 4601
* M month in year (Text & Number) July & 07
* d day in month (Number) 10
* h hour in am/pm (1~12) (Number) 12
* H hour in day (0~23) (Number) 0
* m minute in hour (Number) 30
* s second in minute (Number) 55
* S fractional second (Number) 978
* E day of week (Text) Tuesday
* e* day of week (local 1~7) (Number) 2
* D day in year (Number) 189
* F day of week in month (Number) 2 (2nd Wed in July)
* w week in year (Number) 27
* W week in month (Number) 2
* a am/pm marker (Text) PM
* k hour in day (1~24) (Number) 24
* K hour in am/pm (0~11) (Number) 0
* z time zone (Text) Pacific Standard Time
* Z time zone (RFC 822) (Number) -0800
* v time zone (generic) (Text) Pacific Time
* g* Julian day (Number) 2451334
* A* milliseconds in day (Number) 69540000
* ' escape for text (Delimiter) 'Date='
* '' single quote (Literal) 'o''clock'
* </pre>
* </blockquote>
* <tt><b>*</b></tt> These items are not supported by Java's SimpleDateFormat.<br>
* <tt><b>&#x2020;</b></tt> ICU interprets a single 'y' differently than Java.</p>
* <p>
* The count of pattern letters determine the format.
* <p>
* <strong>(Text)</strong>: 4 or more pattern letters--use full form,
* &lt; 4--use short or abbreviated form if one exists.
* <p>
* <strong>(Number)</strong>: the minimum number of digits. Shorter
* numbers are zero-padded to this amount. Year is handled specially;
* that is, if the count of 'y' is 2, the Year will be truncated to 2 digits.
* (e.g., if "yyyy" produces "1997", "yy" produces "97".)
* Unlike other fields, fractional seconds are padded on the right with zero.
* <p>
* <strong>(Text & Number)</strong>: 3 or over, use text, otherwise use number.
* <p>
* Any characters in the pattern that are not in the ranges of ['a'..'z']
* and ['A'..'Z'] will be treated as quoted text. For instance, characters
* like ':', '.', ' ', '#' and '@' will appear in the resulting time text
* even they are not embraced within single quotes.
* <p>
* A pattern containing any invalid pattern letter will result in a thrown
* exception during formatting or parsing.
*
* <p>
* <strong>Examples Using the US Locale:</strong>
* <blockquote>
* <pre>
* Format Pattern Result
* -------------- -------
* "yyyy.MM.dd G 'at' HH:mm:ss vvvv" ->> 1996.07.10 AD at 15:08:56 Pacific Time
* "EEE, MMM d, ''yy" ->> Wed, July 10, '96
* "h:mm a" ->> 12:08 PM
* "hh 'o''clock' a, zzzz" ->> 12 o'clock PM, Pacific Daylight Time
* "K:mm a, vvv" ->> 0:00 PM, PT
* "yyyyy.MMMMM.dd GGG hh:mm aaa" ->> 01996.July.10 AD 12:08 PM
* </pre>
* </blockquote>
* <strong>Code Sample:</strong>
* <blockquote>
* <pre>
* SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
* pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);
* pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);
* <br>
* // Format the current time.
* SimpleDateFormat formatter
* = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss a zzz");
* Date currentTime_1 = new Date();
* String dateString = formatter.format(currentTime_1);
* <br>
* // Parse the previous string back into a Date.
* ParsePosition pos = new ParsePosition(0);
* Date currentTime_2 = formatter.parse(dateString, pos);
* </pre>
* </blockquote>
* In the example, the time value <code>currentTime_2</code> obtained from
* parsing will be equal to <code>currentTime_1</code>. However, they may not be
* equal if the am/pm marker 'a' is left out from the format pattern while
* the "hour in am/pm" pattern symbol is used. This information loss can
* happen when formatting the time in PM.
*
* <p>
* When parsing a date string using the abbreviated year pattern ("yy"),
* SimpleDateFormat must interpret the abbreviated year
* relative to some century. It does this by adjusting dates to be
* within 80 years before and 20 years after the time the SimpleDateFormat
* instance is created. For example, using a pattern of "MM/dd/yy" and a
* SimpleDateFormat instance created on Jan 1, 1997, the string
* "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
* would be interpreted as May 4, 1964.
* During parsing, only strings consisting of exactly two digits, as defined by
* {@link java.lang.Character#isDigit(char)}, will be parsed into the default
* century.
* Any other numeric string, such as a one digit string, a three or more digit
* string, or a two digit string that isn't all digits (for example, "-1"), is
* interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the
* same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
*
* <p>
* If the year pattern does not have exactly two 'y' characters, the year is
* interpreted literally, regardless of the number of digits. So using the
* pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
*
* <p>
* When numeric fields abut one another directly, with no intervening delimiter
* characters, they constitute a run of abutting numeric fields. Such runs are
* parsed specially. For example, the format "HHmmss" parses the input text
* "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to
* parse "1234". In other words, the leftmost field of the run is flexible,
* while the others keep a fixed width. If the parse fails anywhere in the run,
* then the leftmost field is shortened by one character, and the entire run is
* parsed again. This is repeated until either the parse succeeds or the
* leftmost field is one character in length. If the parse still fails at that
* point, the parse of the run fails.
*
* <p>
* For time zones that have no names, use strings GMT+hours:minutes or
* GMT-hours:minutes.
*
* <p>
* The calendar defines what is the first day of the week, the first week
* of the year, whether hours are zero based or not (0 vs 12 or 24), and the
* time zone. There is one common decimal format to handle all the numbers;
* the digit count is handled programmatically according to the pattern.
*
* <h4>Synchronization</h4>
*
* Date formats are not synchronized. It is recommended to create separate
* format instances for each thread. If multiple threads access a format
* concurrently, it must be synchronized externally.
*
* @see com.ibm.icu.util.Calendar
* @see com.ibm.icu.util.GregorianCalendar
* @see com.ibm.icu.util.TimeZone
* @see DateFormat
* @see DateFormatSymbols
* @see DecimalFormat
* @author Mark Davis, Chen-Lieh Huang, Alan Liu
* @stable ICU 2.0
*/
public class SimpleDateFormat extends DateFormat {
private static final long serialVersionUID = 1;
/**
* Construct a SimpleDateFormat using the default pattern for the default
* locale. <b>Note:</b> Not all locales support SimpleDateFormat; for full
* generality, use the factory methods in the DateFormat class.
*
* @see DateFormat
* @stable ICU 2.0
*/
public SimpleDateFormat() {
super(new java.text.SimpleDateFormat());
}
/**
* Construct a SimpleDateFormat using the given pattern in the default
* locale. <b>Note:</b> Not all locales support SimpleDateFormat; for full
* generality, use the factory methods in the DateFormat class.
* @param pattern the pattern to use
* @stable ICU 2.0
*/
public SimpleDateFormat(String pattern) {
super(new java.text.SimpleDateFormat(pattern));
}
/**
* Construct a SimpleDateFormat using the given pattern and locale.
* <b>Note:</b> Not all locales support SimpleDateFormat; for full
* generality, use the factory methods in the DateFormat class.
* @param pattern the pattern to use
* @param loc the locale to use for localization
* @stable ICU 2.0
*/
public SimpleDateFormat(String pattern, Locale loc) {
super(new java.text.SimpleDateFormat(pattern, loc));
}
/**
* Construct a SimpleDateFormat using the given pattern and locale.
* <b>Note:</b> Not all locales support SimpleDateFormat; for full
* generality, use the factory methods in the DateFormat class.
* @param pattern the pattern to use
* @param loc the ulocale to use for localization
* @draft ICU 3.2
*/
public SimpleDateFormat(String pattern, ULocale loc) {
this(pattern, loc.toLocale());
}
/**
* Construct a SimpleDateFormat using the given pattern and
* locale-specific symbol data.
* Warning: uses default locale for digits!
* @param pattern the pattern to use
* @param formatData the symbols to use for localization
* @stable ICU 2.0
*/
public SimpleDateFormat(String pattern, DateFormatSymbols formatData) {
super(new java.text.SimpleDateFormat(pattern, formatData.dfs));
}
/**
* Sets the 100-year period 2-digit years will be interpreted as being in
* to begin on the date the user specifies.
* @param startDate During parsing, two digit years will be placed in the range
* <code>startDate</code> to <code>startDate + 100 years</code>.
* @stable ICU 2.0
*/
public void set2DigitYearStart(Date startDate) {
((java.text.SimpleDateFormat)dateFormat).set2DigitYearStart(startDate);
}
/**
* Returns the beginning date of the 100-year period 2-digit years are interpreted
* as being within.
* @return the start of the 100-year period into which two digit years are
* parsed
* @stable ICU 2.0
*/
public Date get2DigitYearStart() {
return ((java.text.SimpleDateFormat)dateFormat).get2DigitYearStart();
}
/**
* Overrides DateFormat.
* <p>Formats a date or time, which is the standard millis
* since January 1, 1970, 00:00:00 GMT.
* <p>Example: using the US locale:
* "yyyy.MM.dd G 'at' HH:mm:ss zzz" ->> 1996.07.10 AD at 15:08:56 PDT
* @param cal the calendar whose date-time value is to be formatted into a date-time string
* @param toAppendTo where the new date-time text is to be appended
* @param pos the formatting position. On input: an alignment field,
* if desired. On output: the offsets of the alignment field.
* @return the formatted date-time string.
* @see DateFormat
* @stable ICU 2.0
*/
public StringBuffer format(Calendar cal, StringBuffer toAppendTo, FieldPosition pos) {
StringBuffer result;
synchronized(dateFormat) {
java.util.Calendar oldCal = dateFormat.getCalendar();
dateFormat.setCalendar(cal.calendar);
result = dateFormat.format(cal.getTime(), toAppendTo, pos);
dateFormat.setCalendar(oldCal);
}
return result;
}
/**
* Overrides DateFormat
* @see DateFormat
* @stable ICU 2.0
*/
public void parse(String text, Calendar cal, ParsePosition parsePos) {
// TODO: cannot set the parsed timezone, document?
cal.setTime(dateFormat.parse(text, parsePos));
}
/**
* Return a pattern string describing this date format.
* @stable ICU 2.0
*/
public String toPattern() {
return ((java.text.SimpleDateFormat)dateFormat).toPattern();
}
/**
* Return a localized pattern string describing this date format.
* @stable ICU 2.0
*/
public String toLocalizedPattern() {
return ((java.text.SimpleDateFormat)dateFormat).toLocalizedPattern();
}
/**
* Apply the given unlocalized pattern string to this date format.
* @stable ICU 2.0
*/
public void applyPattern(String pattern) {
((java.text.SimpleDateFormat)dateFormat).applyPattern(pattern);
}
/**
* Apply the given localized pattern string to this date format.
* @stable ICU 2.0
*/
public void applyLocalizedPattern(String pattern) {
((java.text.SimpleDateFormat)dateFormat).applyLocalizedPattern(pattern);
}
/**
* Gets the date/time formatting data.
* @return a copy of the date-time formatting data associated
* with this date-time formatter.
* @stable ICU 2.0
*/
public DateFormatSymbols getDateFormatSymbols() {
return new DateFormatSymbols(((java.text.SimpleDateFormat)dateFormat).getDateFormatSymbols());
}
/**
* Allows you to set the date/time formatting data.
* @param newFormatSymbols the new symbols
* @stable ICU 2.0
*/
public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) {
((java.text.SimpleDateFormat)dateFormat).setDateFormatSymbols(newFormatSymbols.dfs);
}
/**
* Overrides Cloneable
* @stable ICU 2.0
*/
public Object clone() {
return new SimpleDateFormat((java.text.SimpleDateFormat)dateFormat.clone());
}
/**
* For clone to use
* @param sdf
*/
private SimpleDateFormat(java.text.SimpleDateFormat sdf) {
super(sdf);
}
// hashCode, equals, clone use DateFormat implementation.
}

View file

@ -0,0 +1,432 @@
/*
*******************************************************************************
* Copyright (C) 1996-2006, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.util;
import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
/**
* <code>TimeZone</code> represents a time zone offset, and also figures out daylight
* savings.
*
* <p>
* Typically, you get a <code>TimeZone</code> using <code>getDefault</code>
* which creates a <code>TimeZone</code> based on the time zone where the program
* is running. For example, for a program running in Japan, <code>getDefault</code>
* creates a <code>TimeZone</code> object based on Japanese Standard Time.
*
* <p>
* You can also get a <code>TimeZone</code> using <code>getTimeZone</code>
* along with a time zone ID. For instance, the time zone ID for the
* U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a
* U.S. Pacific Time <code>TimeZone</code> object with:
* <blockquote>
* <pre>
* TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
* </pre>
* </blockquote>
* You can use <code>getAvailableIDs</code> method to iterate through
* all the supported time zone IDs. You can then choose a
* supported ID to get a <code>TimeZone</code>.
* If the time zone you want is not represented by one of the
* supported IDs, then you can create a custom time zone ID with
* the following syntax:
*
* <blockquote>
* <pre>
* GMT[+|-]hh[[:]mm]
* </pre>
* </blockquote>
*
* For example, you might specify GMT+14:00 as a custom
* time zone ID. The <code>TimeZone</code> that is returned
* when you specify a custom time zone ID does not include
* daylight savings time.
* <p>
* For compatibility with JDK 1.1.x, some other three-letter time zone IDs
* (such as "PST", "CTT", "AST") are also supported. However, <strong>their
* use is deprecated</strong> because the same abbreviation is often used
* for multiple time zones (for example, "CST" could be U.S. "Central Standard
* Time" and "China Standard Time"), and the Java platform can then only
* recognize one of them.
*
* @see Calendar
* @see GregorianCalendar
* @see SimpleTimeZone
* @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
* @stable ICU 2.0
*/
public class TimeZone implements Serializable, Cloneable {
private static final long serialVersionUID = 1;
/**
* @internal
*/
public final java.util.TimeZone timeZone;
/**
* @internal
* @param delegate the TimeZone to which to delegate
*/
public TimeZone(java.util.TimeZone delegate) {
this.timeZone = delegate;
}
/**
* Default constructor to mirror Java's public
* constructor. Java's is not callable as a public API, since
* their TimeZone is abstract, so this is only useful to
* subclasses. In general, subclasses will not work unless
* they manipulate the delegate.
*/
public TimeZone() {
this.timeZone = java.util.TimeZone.getDefault();
}
/**
* A style specifier for <code>getDisplayName()</code> indicating
* a short name, such as "PST."
* @see #LONG
* @stable ICU 2.0
*/
public static final int SHORT = 0;
/**
* A style specifier for <code>getDisplayName()</code> indicating
* a long name, such as "Pacific Standard Time."
* @see #SHORT
* @stable ICU 2.0
*/
public static final int LONG = 1;
/**
* Gets the time zone offset, for current date, modified in case of
* daylight savings. This is the offset to add *to* UTC to get local time.
* @param era the era of the given date.
* @param year the year in the given date.
* @param month the month in the given date.
* Month is 0-based. e.g., 0 for January.
* @param day the day-in-month of the given date.
* @param dayOfWeek the day-of-week of the given date.
* @param milliseconds the millis in day in <em>standard</em> local time.
* @return the offset to add *to* GMT to get local time.
* @stable ICU 2.0
*/
public int getOffset(int era, int year, int month, int day,
int dayOfWeek, int milliseconds) {
return timeZone.getOffset(era, year, month, day, dayOfWeek, milliseconds);
}
/**
* Returns the offset of this time zone from UTC at the specified
* date. If Daylight Saving Time is in effect at the specified
* date, the offset value is adjusted with the amount of daylight
* saving.
*
* @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT
* @return the amount of time in milliseconds to add to UTC to get local time.
*
* @see Calendar#ZONE_OFFSET
* @see Calendar#DST_OFFSET
* @see #getOffset(long, boolean, int[])
* @stable ICU 2.8
*/
public int getOffset(long date) {
if (inDaylightTime(new Date(date))) {
return getRawOffset() + getDSTSavings();
}
return getRawOffset();
}
/**
* Sets the base time zone offset to GMT.
* This is the offset to add *to* UTC to get local time.
* @param offsetMillis the given base time zone offset to GMT.
* @stable ICU 2.0
*/
public void setRawOffset(int offsetMillis) {
timeZone.setRawOffset(offsetMillis);
}
/**
* Gets unmodified offset, NOT modified in case of daylight savings.
* This is the offset to add *to* UTC to get local time.
* @return the unmodified offset to add *to* UTC to get local time.
* @stable ICU 2.0
*/
public int getRawOffset() {
return timeZone.getRawOffset();
}
/**
* Gets the ID of this time zone.
* @return the ID of this time zone.
* @stable ICU 2.0
*/
public String getID() {
return timeZone.getID();
}
/**
* Sets the time zone ID. This does not change any other data in
* the time zone object.
* @param ID the new time zone ID.
* @stable ICU 2.0
*/
public void setID(String ID) {
timeZone.setID(ID);
}
/**
* Returns a name of this time zone suitable for presentation to the user
* in the default locale.
* This method returns the long generic name.
* If the display name is not available for the locale,
* a fallback based on the country, city, or time zone id will be used.
* @return the human-readable name of this time zone in the default locale.
* @stable ICU 2.0
*/
public final String getDisplayName() {
return timeZone.getDisplayName();
}
/**
* Returns a name of this time zone suitable for presentation to the user
* in the specified locale.
* This method returns the long generic name.
* If the display name is not available for the locale,
* a fallback based on the country, city, or time zone id will be used.
* @param locale the locale in which to supply the display name.
* @return the human-readable name of this time zone in the given locale
* or in the default locale if the given locale is not recognized.
* @stable ICU 2.0
*/
public final String getDisplayName(Locale locale) {
return timeZone.getDisplayName(locale);
}
/**
* Returns a name of this time zone suitable for presentation to the user
* in the specified locale.
* This method returns the long name, not including daylight savings.
* If the display name is not available for the locale,
* a fallback based on the country, city, or time zone id will be used.
* @param locale the ulocale in which to supply the display name.
* @return the human-readable name of this time zone in the given locale
* or in the default ulocale if the given ulocale is not recognized.
* @draft ICU 3.2
*/
public final String getDisplayName(ULocale locale) {
return timeZone.getDisplayName(locale.toLocale());
}
/**
* Returns a name of this time zone suitable for presentation to the user
* in the default locale.
* If the display name is not available for the locale,
* then this method returns a string in the format
* <code>GMT[+-]hh:mm</code>.
* @param daylight if true, return the daylight savings name.
* @param style either <code>LONG</code> or <code>SHORT</code>
* @return the human-readable name of this time zone in the default locale.
* @stable ICU 2.0
*/
public final String getDisplayName(boolean daylight, int style) {
return timeZone.getDisplayName(daylight, style);
}
/**
* Returns a name of this time zone suitable for presentation to the user
* in the specified locale.
* If the display name is not available for the locale,
* then this method returns a string in the format
* <code>GMT[+-]hh:mm</code>.
* @param daylight if true, return the daylight savings name.
* @param style either <code>LONG</code> or <code>SHORT</code>
* @param locale the locale in which to supply the display name.
* @return the human-readable name of this time zone in the given locale
* or in the default locale if the given locale is not recognized.
* @exception IllegalArgumentException style is invalid.
* @stable ICU 2.0
*/
public String getDisplayName(boolean daylight, int style, Locale locale) {
return timeZone.getDisplayName(daylight, style, locale);
}
/**
* Returns a name of this time zone suitable for presentation to the user
* in the specified locale.
* If the display name is not available for the locale,
* then this method returns a string in the format
* <code>GMT[+-]hh:mm</code>.
* @param daylight if true, return the daylight savings name.
* @param style either <code>LONG</code> or <code>SHORT</code>
* @param locale the locale in which to supply the display name.
* @return the human-readable name of this time zone in the given locale
* or in the default locale if the given locale is not recognized.
* @exception IllegalArgumentException style is invalid.
* @draft ICU 3.2
*/
public String getDisplayName(boolean daylight, int style, ULocale locale) {
return timeZone.getDisplayName(daylight, style, locale.toLocale());
}
/**
* Returns the amount of time to be added to local standard time
* to get local wall clock time.
* <p>
* The default implementation always returns 3600000 milliseconds
* (i.e., one hour) if this time zone observes Daylight Saving
* Time. Otherwise, 0 (zero) is returned.
* <p>
* If an underlying TimeZone implementation subclass supports
* historical Daylight Saving Time changes, this method returns
* the known latest daylight saving value.
*
* @return the amount of saving time in milliseconds
* @stable ICU 2.8
*/
public int getDSTSavings() {
if (useDaylightTime()) {
return 3600000;
}
return 0;
}
/**
* Queries if this time zone uses daylight savings time.
* @return true if this time zone uses daylight savings time,
* false, otherwise.
* @stable ICU 2.0
*/
public boolean useDaylightTime() {
return timeZone.useDaylightTime();
}
/**
* Queries if the given date is in daylight savings time in
* this time zone.
* @param date the given Date.
* @return true if the given date is in daylight savings time,
* false, otherwise.
* @stable ICU 2.0
*/
public boolean inDaylightTime(Date date) {
return timeZone.inDaylightTime(date);
}
/**
* Gets the <code>TimeZone</code> for the given ID.
*
* @param ID the ID for a <code>TimeZone</code>, either an abbreviation
* such as "PST", a full name such as "America/Los_Angeles", or a custom
* ID such as "GMT-8:00". Note that the support of abbreviations is
* for JDK 1.1.x compatibility only and full names should be used.
*
* @return the specified <code>TimeZone</code>, or the GMT zone if the given ID
* cannot be understood.
* @stable ICU 2.0
*/
public static TimeZone getTimeZone(String ID) {
return new TimeZone(java.util.TimeZone.getTimeZone(ID));
}
/**
* Return a new String array containing all system TimeZone IDs
* with the given raw offset from GMT. These IDs may be passed to
* <code>get()</code> to construct the corresponding TimeZone
* object.
* @param rawOffset the offset in milliseconds from GMT
* @return an array of IDs for system TimeZones with the given
* raw offset. If there are none, return a zero-length array.
* @stable ICU 2.0
*/
public static String[] getAvailableIDs(int rawOffset) {
return java.util.TimeZone.getAvailableIDs(rawOffset);
}
/**
* Return a new String array containing all system TimeZone IDs.
* These IDs (and only these IDs) may be passed to
* <code>get()</code> to construct the corresponding TimeZone
* object.
* @return an array of all system TimeZone IDs
* @stable ICU 2.0
*/
public static String[] getAvailableIDs() {
return java.util.TimeZone.getAvailableIDs();
}
/**
* Gets the default <code>TimeZone</code> for this host.
* The source of the default <code>TimeZone</code>
* may vary with implementation.
* @return a default <code>TimeZone</code>.
* @stable ICU 2.0
*/
public static TimeZone getDefault() {
return new TimeZone(java.util.TimeZone.getDefault());
}
/**
* Sets the <code>TimeZone</code> that is
* returned by the <code>getDefault</code> method. If <code>zone</code>
* is null, reset the default to the value it had originally when the
* VM first started.
* @param tz the new default time zone
* @stable ICU 2.0
*/
public static void setDefault(TimeZone tz) {
java.util.TimeZone.setDefault(tz.timeZone);
}
/**
* Returns true if this zone has the same rule and offset as another zone.
* That is, if this zone differs only in ID, if at all. Returns false
* if the other zone is null.
* @param other the <code>TimeZone</code> object to be compared with
* @return true if the other zone is not null and is the same as this one,
* with the possible exception of the ID
* @stable ICU 2.0
*/
public boolean hasSameRules(TimeZone other) {
return timeZone.hasSameRules(other.timeZone);
}
/**
* Overrides Cloneable
* @stable ICU 2.0
*/
public Object clone() {
return new TimeZone((java.util.TimeZone)timeZone.clone());
}
/**
* Return true if rhs is a TimeZone and has the same time rules as this.
* @return true if rhs equals this
* @draft ICU 3.4.2
*/
public boolean equals(Object rhs){
try {
return timeZone.equals(((TimeZone)rhs).timeZone);
}
catch (Exception e) {
return false;
}
}
/**
* Return a hashCode.
* @return a hashCode
* @draft ICU 3.4.2
*/
public int hashCode(){
return timeZone.hashCode();
}
}

View file

@ -10,4 +10,4 @@ Bundle-Copyright: Licensed Materials - Property of IBM
(C) Copyright IBM Corp. 2000-2006. All Rights Reserved.
IBM is a registered trademark of IBM Corp.
Require-Bundle: org.junit
Bundle-ClassPath: icu4jtests.jar
Bundle-ClassPath: icu4jtests.jar

View file

@ -6,11 +6,9 @@ bin.includes = META-INF/,\
.classpath,\
bin/,\
build.properties,\
.project,\
.settings/
.project
src.includes = src/,\
build.properties,\
.classpath,\
.project,\
.settings/,\
META-INF/

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry exported="true" sourcepath="icu4jcsrc.zip" kind="lib" path="icu4j.jar"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>

View file

@ -5,11 +5,6 @@
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
@ -20,9 +15,14 @@
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.pde.PluginNature</nature>
</natures>
</projectDescription>

View file

@ -6,7 +6,7 @@ Bundle-Version: 3.4.5
Bundle-Vendor: %providerName
Bundle-Localization: plugin
Bundle-Copyright: Licensed Materials - Property of IBM
(C) Copyright IBM Corp. 2000-2006. All Rights Reserved.
(C) Copyright IBM Corp. 2000, 2006. All Rights Reserved.
IBM is a registered trademark of IBM Corp.
Export-Package: com.ibm.icu.lang,
com.ibm.icu.math,

View file

@ -1,6 +1,9 @@
bin.includes = .classpath,\
.project,\
build.properties,\
META-INF/,\
icu4j.jar,
source.. = src/
output.. = bin/
src.includes = about.html,\
about_files/
bin.includes = about_files/,\
.,\
about.html,\
plugin.properties,\
META-INF/

View file

@ -0,0 +1,173 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="com.ibm.icu" default="build.jars" basedir=".">
<property name="basews" value="${ws}"/>
<property name="baseos" value="${os}"/>
<property name="basearch" value="${arch}"/>
<property name="basenl" value="${nl}"/>
<!-- Compiler settings. -->
<property name="javacFailOnError" value="false"/>
<property name="javacDebugInfo" value="on"/>
<property name="javacVerbose" value="false"/>
<property name="logExtension" value=".log"/>
<property name="compilerArg" value=""/>
<property name="javacSource" value="1.3"/>
<property name="javacTarget" value="1.2"/>
<path id="path_bootclasspath">
<fileset dir="${java.home}/lib">
<include name="*.jar"/>
</fileset>
</path>
<property name="bootclasspath" refid="path_bootclasspath"/>
<condition property="bundleBootClasspath" value="${CDC-1.0/Foundation-1.0}">
<isset property="CDC-1.0/Foundation-1.0"/>
</condition>
<condition property="bundleJavacSource" value="1.3">
<isset property="CDC-1.0/Foundation-1.0"/>
</condition>
<condition property="bundleJavacTarget" value="1.1">
<isset property="CDC-1.0/Foundation-1.0"/>
</condition>
<condition property="bundleBootClasspath" value="${J2SE-1.3}">
<isset property="J2SE-1.3"/>
</condition>
<condition property="bundleJavacSource" value="1.3">
<isset property="J2SE-1.3"/>
</condition>
<condition property="bundleJavacTarget" value="1.1">
<isset property="J2SE-1.3"/>
</condition>
<property name="bundleJavacSource" value="${javacSource}"/>
<property name="bundleJavacTarget" value="${javacTarget}"/>
<property name="bundleBootClasspath" value="${bootclasspath}"/>
<target name="init" depends="properties">
<condition property="pluginTemp" value="${buildTempFolder}/plugins">
<isset property="buildTempFolder"/>
</condition>
<property name="pluginTemp" value="${basedir}"/>
<condition property="build.result.folder" value="${pluginTemp}/com.ibm.icu">
<isset property="buildTempFolder"/>
</condition>
<property name="build.result.folder" value="${basedir}"/>
<property name="temp.folder" value="${basedir}/temp.folder"/>
<property name="plugin.destination" value="${basedir}"/>
</target>
<target name="properties" if="eclipse.running">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</target>
<target name="build.update.jar" depends="init" description="Build the plug-in: com.ibm.icu for an update site.">
<delete dir="${temp.folder}"/>
<mkdir dir="${temp.folder}"/>
<antcall target="build.jars"/>
<antcall target="gather.bin.parts">
<param name="destination.temp.folder" value="${temp.folder}/"/>
</antcall>
<zip destfile="${plugin.destination}/com.ibm.icu_3.4.5.jar" basedir="${temp.folder}/com.ibm.icu_3.4.5" filesonly="false" whenempty="skip" update="false"/>
<delete dir="${temp.folder}"/>
</target>
<target name="@dot" depends="init" unless="@dot" description="Create jar: com.ibm.icu @dot.">
<delete dir="${temp.folder}/@dot.bin"/>
<mkdir dir="${temp.folder}/@dot.bin"/>
<path id="@dot.classpath">
<pathelement path="C:/eclipse_3_2/plugins/org.junit_3.8.1/junit.jar"/>
</path>
<!-- compile the source code -->
<javac destdir="${temp.folder}/@dot.bin" failonerror="${javacFailOnError}" verbose="${javacVerbose}" debug="${javacDebugInfo}" includeAntRuntime="no" bootclasspath="${bundleBootClasspath}" source="${bundleJavacSource}" target="${bundleJavacTarget}" >
<compilerarg line="${compilerArg}" compiler="${build.compiler}"/>
<classpath refid="@dot.classpath" />
<src path="src/" />
<compilerarg value="@${basedir}/javaCompiler...args" compiler="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<compilerarg line="-log '${temp.folder}/@dot.bin${logExtension}'" compiler="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</javac>
<!-- Copy necessary resources -->
<copy todir="${temp.folder}/@dot.bin" failonerror="true" overwrite="false">
<fileset dir="src/" excludes="**/*.java, **/package.htm*" />
</copy>
<mkdir dir="${build.result.folder}"/>
<copy todir="${build.result.folder}/@dot" failonerror="true" overwrite="false">
<fileset dir="${temp.folder}/@dot.bin" />
</copy>
<delete dir="${temp.folder}/@dot.bin"/>
</target>
<target name="src.zip" depends="init" unless="src.zip">
<mkdir dir="${build.result.folder}"/>
<zip destfile="${build.result.folder}/src.zip" filesonly="false" whenempty="skip" update="false">
<fileset dir="src/" includes="**/*.java" />
</zip>
</target>
<target name="build.jars" depends="init" description="Build all the jars for the plug-in: com.ibm.icu.">
<available property="@dot" file="${build.result.folder}/@dot"/>
<antcall target="@dot"/>
</target>
<target name="build.sources" depends="init">
<available property="src.zip" file="${build.result.folder}/src.zip"/>
<antcall target="src.zip"/>
</target>
<target name="gather.bin.parts" depends="init" if="destination.temp.folder">
<mkdir dir="${destination.temp.folder}/com.ibm.icu_3.4.5"/>
<copy todir="${destination.temp.folder}/com.ibm.icu_3.4.5" failonerror="true" overwrite="false">
<fileset dir="${build.result.folder}/@dot" includes="**" />
</copy>
<copy todir="${destination.temp.folder}/com.ibm.icu_3.4.5" failonerror="true" overwrite="false">
<fileset dir="${basedir}" includes="about_files/,about.html,plugin.properties,META-INF/" />
</copy>
</target>
<target name="build.zips" depends="init">
</target>
<target name="gather.sources" depends="init" if="destination.temp.folder">
<mkdir dir="${destination.temp.folder}/com.ibm.icu_3.4.5"/>
<copy file="${build.result.folder}/src.zip" todir="${destination.temp.folder}/com.ibm.icu_3.4.5" failonerror="false" overwrite="false"/>
<copy todir="${destination.temp.folder}/com.ibm.icu_3.4.5" failonerror="false" overwrite="false">
<fileset dir="${basedir}" includes="about.html " />
</copy>
</target>
<target name="gather.logs" depends="init" if="destination.temp.folder">
<mkdir dir="${destination.temp.folder}/com.ibm.icu_3.4.5"/>
<copy file="${temp.folder}/@dot.bin${logExtension}" todir="${destination.temp.folder}/com.ibm.icu_3.4.5" failonerror="false" overwrite="false"/>
</target>
<target name="clean" depends="init" description="Clean the plug-in: com.ibm.icu of all the zips, jars and logs created.">
<delete dir="${build.result.folder}/@dot"/>
<delete file="${build.result.folder}/src.zip"/>
<delete file="${plugin.destination}/com.ibm.icu_3.4.5.jar"/>
<delete file="${plugin.destination}/com.ibm.icu_3.4.5.zip"/>
<delete dir="${temp.folder}"/>
</target>
<target name="refresh" depends="init" if="eclipse.running" description="Refresh this folder.">
<eclipse.convertPath fileSystemPath="F:/eclipse_icu345/eclipseICU/com.ibm.icu" property="resourcePath"/>
<eclipse.refreshLocal resource="${resourcePath}" depth="infinite"/>
</target>
<target name="zip.plugin" depends="init" description="Create a zip containing all the elements for the plug-in: com.ibm.icu.">
<delete dir="${temp.folder}"/>
<mkdir dir="${temp.folder}"/>
<antcall target="build.jars"/>
<antcall target="build.sources"/>
<antcall target="gather.bin.parts">
<param name="destination.temp.folder" value="${temp.folder}/"/>
</antcall>
<antcall target="gather.sources">
<param name="destination.temp.folder" value="${temp.folder}/"/>
</antcall>
<delete>
<fileset dir="${temp.folder}" includes="**/*.bin${logExtension}" />
</delete>
<zip destfile="${plugin.destination}/com.ibm.icu_3.4.5.zip" basedir="${temp.folder}" filesonly="true" whenempty="skip" update="false"/>
<delete dir="${temp.folder}"/>
</target>
</project>

View file

@ -0,0 +1,12 @@
###############################################################################
# Copyright (c) 2000, 2006 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
###############################################################################
pluginName = International Components for Unicode for Java (ICU4J)
providerName = IBM Corporation

View file

@ -0,0 +1,33 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>About</title>
</head>
<body lang="EN-US">
<h2>About This Content</h2>
<p>May 10, 2006</p>
<h3>License</h3>
<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise
indicated below, the Content is provided to you under the terms and conditions of the
Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
apply to your use of any object code in the Content. Check the Redistributor's license that was
provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
indicated below, the terms and conditions of the EPL still apply to any source code in the Content
and such source code may be obtained at <a href="http://www.eclipse.org">http://www.eclipse.org</a>.</p>
<h3>Source Code</h3>
<p>This plug-in contains source code zip files (&quot;Source Zips&quot;) that correspond to binary content in other plug-ins. These Source Zips may be distributed under different license
agreements and/or notices. Details about these license agreements and notices are contained in &quot;about.html&quot; files (&quot;Abouts&quot;) located in sub-directories in the
src/ directory of this plug-in. Such Abouts govern your use of the Source Zips in that directory, not the EPL.</p>
</body>
</html>

View file

@ -0,0 +1,48 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>About</title>
</head>
<body lang="EN-US">
<h2>About This Content</h2>
<p>August 25, 2006</p>
<h3>License</h3>
<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise
indicated below, the Content is provided to you under the terms and conditions of the
Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available
at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
For purposes of the EPL, &quot;Program&quot; will mean the Content.</p>
<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may
apply to your use of any object code in the Content. Check the Redistributor's license that was
provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
indicated below, the terms and conditions of the EPL still apply to any source code in the Content
and such source code may be obtained at <a href="http://www.eclipse.org/">http://www.eclipse.org</a>.</p>
<h3>Third Party Content</h3>
<p>The Content includes items that have been sourced from third parties as set out below. If you
did not receive this Content directly from the Eclipse Foundation, the following is provided
for informational purposes only, and you should look to the Redistributor's license for
terms and conditions of use.</p>
<p><strong>ICU4J 3.4.5</strong> <br/><br/>
The plug-in includes software (&quot;ICU4J&quot;) developed by International Business Machines
Corporation and others.
<br/><br/>
ICU4J is:
<blockquote>
Copyright (c) 1995-2006 International Business Machines Corporation and others<br/>
All rights reserved.
</blockquote>
Your use of ICU4J is subject to the terms and conditions of the ICU4J license. A copy of the
license is contained in the file <a href="about_files/license.html" target="_blank">about_files/license.html</a>.
</p>
</body>
</html>