ICU4J reorganizing

X-SVN-Rev: 7681
This commit is contained in:
Mohan 2002-02-15 21:12:29 +00:00
parent abd5f16593
commit 92cf6ca9e6
440 changed files with 0 additions and 265090 deletions

7
.gitattributes vendored
View File

@ -67,7 +67,6 @@ icu4c/source/samples/ucnv/data02.bin -text
icu4c/source/test/testdata/importtest.bin -text
icu4c/source/test/testdata/ja_data.bin -text
icu4c/source/test/testdata/uni-text.bin -text
icu4j/src/com/ibm/data/misc/english.dict -text
icu4j/src/com/ibm/icu/dev/data/holidays_jp.ucs -text
icu4j/src/com/ibm/icu/dev/data/rbbi/english.dict -text
icu4j/src/com/ibm/icu/dev/data/thai6.ucs -text
@ -75,12 +74,6 @@ icu4j/src/com/ibm/icu/dev/data/unicode/Draft-TestSuite.txt -text
icu4j/src/com/ibm/icu/impl/data/thai_dict -text
icu4j/src/com/ibm/icu/impl/data/unames.dat -text
icu4j/src/com/ibm/icu/impl/data/uprops.dat -text
icu4j/src/com/ibm/text/resources/thai_dict -text
icu4j/src/com/ibm/text/resources/unames.dat -text
icu4j/src/com/ibm/text/resources/uprops.dat -text
icu4j/src/data/holidays_jp.ucs -text
icu4j/src/data/thai6.ucs -text
icu4j/src/data/unicode/Draft-TestSuite.txt -text
# The following file types are stored in Git-LFS.
*.jar filter=lfs diff=lfs merge=lfs -text

File diff suppressed because it is too large Load Diff

View File

@ -1,80 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/Attic/DemoApplet.java,v $
* $Date: 2001/10/30 02:42:50 $
* $Revision: 1.4 $
*
*****************************************************************************************
*/
package com.ibm.demo;
import java.applet.Applet;
import java.util.Locale;
import java.awt.*;
import java.awt.event.*;
public abstract class DemoApplet extends java.applet.Applet {
private Button demoButton;
private Frame demoFrame;
private static int demoFrameCount = 0;
protected abstract Frame createDemoFrame(DemoApplet applet);
protected Dimension getDefaultFrameSize(DemoApplet applet, Frame f) {
return new Dimension(700, 550);
}
//Create a button that will display the demo
public void init()
{
setBackground(Color.white);
demoButton = new Button("Demo");
demoButton.setBackground(Color.yellow);
add( demoButton );
demoButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getID() == ActionEvent.ACTION_PERFORMED) {
demoButton.setLabel("loading");
if (demoFrame == null) {
demoFrame = createDemoFrame(DemoApplet.this);
showDemo();
}
demoButton.setLabel("Demo");
}
}
} );
}
public void showDemo()
{
demoFrame = createDemoFrame(this);
demoFrame.doLayout();
Dimension d = getDefaultFrameSize(this, demoFrame);
demoFrame.setSize(d.width, d.height);
demoFrame.show();
demoFrameOpened();
}
public void demoClosed()
{
demoFrame = null;
demoFrameClosed();
}
protected static void demoFrameOpened() {
demoFrameCount++;
}
protected static void demoFrameClosed() {
if (--demoFrameCount == 0) {
System.exit(0);
}
}
}

View File

@ -1,101 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/Attic/DemoTextBox.java,v $
* $Date: 2000/03/10 03:47:42 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
package com.ibm.demo;
import java.text.BreakIterator;
import java.awt.*;
public class DemoTextBox {
public DemoTextBox(Graphics g, String text, int width)
{
this.text = text;
this.chars = new char[text.length()];
text.getChars(0, text.length(), chars, 0);
this.width = width;
this.port = g;
this.metrics = g.getFontMetrics();
breakText();
}
public int getHeight() {
return (nbreaks + 1) * metrics.getHeight();
}
public void draw(Graphics g, int x, int y)
{
int index = 0;
y += metrics.getAscent();
for (int i = 0; i < nbreaks; i++)
{
g.drawChars(chars, index, breakPos[i] - index, x, y);
index = breakPos[i];
y += metrics.getHeight();
}
g.drawChars(chars, index, chars.length - index, x, y);
}
private void breakText()
{
if (metrics.charsWidth(chars, 0, chars.length) > width)
{
BreakIterator iter = BreakIterator.getWordInstance();
iter.setText(text);
int start = iter.first();
int end = start;
int pos;
while ( (pos = iter.next()) != BreakIterator.DONE )
{
int w = metrics.charsWidth(chars, start, pos - start);
if (w > width)
{
// We've gone past the maximum width, so break the line
if (end > start) {
// There was at least one break position before this point
breakPos[nbreaks++] = end;
start = end;
end = pos;
} else {
// There weren't any break positions before this one, so
// let this word overflow the margin (yuck)
breakPos[nbreaks++] = pos;
start = end = pos;
}
} else {
// the current position still fits on the line; it's the best
// tentative break position we have so far.
end = pos;
}
}
}
}
private String text;
private char[] chars;
private Graphics port;
private FontMetrics metrics;
private int width;
private int[] breakPos = new int[10]; // TODO: get real
private int nbreaks = 0;
}

View File

@ -1,136 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/Attic/DemoUtility.java,v $
* $Date: 2001/10/30 02:42:50 $
* $Revision: 1.5 $
*
*****************************************************************************************
*/
package com.ibm.demo;
import java.awt.*;
import java.lang.*;
import java.util.*;
public class DemoUtility
{
public static final Font titleFont = new Font("TimesRoman",Font.BOLD,18);
public static final Font labelFont = new Font("TimesRoman",Font.BOLD,14);
public static final Font choiceFont = new Font("Helvetica",Font.BOLD,12);
public static final Font editFont = new Font("Helvetica",Font.PLAIN,14);
public static final Font creditFont = new Font("Helvetica",Font.PLAIN,10);
public static final Font numberFont = new Font("sansserif", Font.PLAIN, 14);
public static final Color bgColor = Color.lightGray;
public static final Color choiceColor = Color.white;
public static final String copyright1 =
"(C) Copyright Taligent, Inc. 1996-1998. Copyright (C) IBM, Inc. 1998 - All Rights Reserved";
public static final String copyright2 =
"Portions copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved.";
/**
Provides easy way to use basic functions of GridBagLayout, without
the complications. After building a panel, and inserting all the
* subcomponents, call this to lay it out in the desired number of columns.
*/
public static void fixGrid(Container cont, int columns) {
GridBagLayout gridbag = new GridBagLayout();
cont.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
c.weightx = 1.0;
c.insets = new Insets(2,2,2,2);
Component[] components = cont.getComponents();
for (int i = 0; i < components.length; ++i) {
// not used int colNumber = i%columns;
c.gridwidth = 1; // default
if ((i%columns) == columns - 1)
c.gridwidth = GridBagConstraints.REMAINDER; // last in grid
if (components[i] instanceof Label) {
switch (((Label)components[i]).getAlignment()) {
case Label.CENTER: c.anchor = GridBagConstraints.CENTER; break;
case Label.LEFT: c.anchor = GridBagConstraints.WEST; break;
case Label.RIGHT: c.anchor = GridBagConstraints.EAST; break;
}
}
gridbag.setConstraints(components[i], c);
}
}
/**
Provides easy way to change the spacing around an object in a GridBagLayout.
Call AFTER fixGridBag, passing in the container, the component, and the
new insets.
*/
public static void setInsets(Container cont, Component comp, Insets insets) {
GridBagLayout gbl = (GridBagLayout)cont.getLayout();
GridBagConstraints g = gbl.getConstraints(comp);
g.insets = insets;
gbl.setConstraints(comp,g);
}
public static Panel createSpacer() {
Panel spacer = new Panel();
spacer.setLayout(null);
spacer.setSize(1000, 1);
return spacer;
}
// to avoid goofy updates and misplaced cursors
public static void setText(TextComponent area, String newText) {
String foo = area.getText();
if (foo.equals(newText)) return;
area.setText(newText);
}
/**
* Compares two locals. Return value is negative
* if they're different, and more positive the more
* fields that match.
*/
public static int compareLocales(Locale l1, Locale l2)
{
int result = -1;
if (l1.getLanguage().equals(l2.getLanguage())) {
result += 1;
if (l1.getCountry().equals(l2.getCountry())) {
result += 1;
if (l1.getVariant().equals(l2.getVariant())) {
result += 1;
}
}
}
return result;
}
/**
* Get the G7 locale list for demos.
*/
public static Locale[] getG7Locales() {
return localeList;
}
private static Locale[] localeList = {
new Locale("DA", "DK", ""),
new Locale("EN", "US", ""),
new Locale("EN", "GB", ""),
new Locale("EN", "CA", ""),
new Locale("FR", "FR", ""),
new Locale("FR", "CA", ""),
new Locale("DE", "DE", ""),
new Locale("IT", "IT", ""),
//new Locale("JA", "JP", ""),
};
}

View File

@ -1,45 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/calendar/Attic/CalendarApp.java,v $
* $Date: 2000/05/12 23:21:23 $
* $Revision: 1.5 $
*
*****************************************************************************************
*/
package com.ibm.demo.calendar;
import com.ibm.demo.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import com.ibm.util.*;
import com.ibm.text.*;
/**
* CalendarApp demonstrates how Calendar works.
*/
public class CalendarApp extends DemoApplet
{
/**
* The main function which defines the behavior of the CalendarDemo
* applet when an applet is started.
*/
public static void main(String argv[]) {
new CalendarApp().showDemo();
}
/* This creates a CalendarFrame for the demo applet. */
public Frame createDemoFrame(DemoApplet applet) {
return new CalendarFrame(applet);
}
}

View File

@ -1,584 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/calendar/Attic/CalendarCalc.java,v $
* $Date: 2001/10/30 02:42:50 $
* $Revision: 1.9 $
*
*****************************************************************************************
*/
package com.ibm.demo.calendar;
import com.ibm.demo.*;
import java.applet.Applet;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
//import java.text.DateFormat;
import com.ibm.text.DateFormat;
import java.text.ParsePosition;
//import java.util.Calendar;
import com.ibm.util.Calendar;
//import java.util.GregorianCalendar;
import com.ibm.util.GregorianCalendar;
//import java.util.TimeZone;
import com.ibm.util.TimeZone;
import java.util.Locale;
import com.ibm.util.*;
import com.ibm.text.*;
import javax.swing.*;
/**
* CalendarCalc demonstrates how Date/Time formatter works.
*/
public class CalendarCalc extends DemoApplet
{
/**
* The main function which defines the behavior of the MultiCalendarDemo
* applet when an applet is started.
*/
public static void main(String argv[]) {
new CalendarCalc().showDemo();
}
/**
* This creates a CalendarCalcFrame for the demo applet.
*/
public Frame createDemoFrame(DemoApplet applet) {
return new CalendarCalcFrame(applet);
}
}
/**
* A Frame is a top-level window with a title. The default layout for a frame
* is BorderLayout. The CalendarCalcFrame class defines the window layout of
* MultiCalendarDemo.
*/
class CalendarCalcFrame extends Frame implements ActionListener
{
private static final String creditString = "";
static final Locale[] locales = DemoUtility.getG7Locales();
private static final boolean DEBUG = false;
private DemoApplet applet;
private long time = System.currentTimeMillis();
private static final RollAddField kRollAddFields[] = {
new RollAddField(Calendar.YEAR, "Year" ),
new RollAddField(Calendar.MONTH, "Month" ),
new RollAddField(Calendar.WEEK_OF_MONTH, "Week of Month" ),
new RollAddField(Calendar.WEEK_OF_YEAR, "Week of Year" ),
new RollAddField(Calendar.DAY_OF_MONTH, "Day of Month" ),
new RollAddField(Calendar.DAY_OF_WEEK, "Day of Week" ),
new RollAddField(Calendar.DAY_OF_WEEK_IN_MONTH, "Day of Week in Month" ),
new RollAddField(Calendar.DAY_OF_YEAR, "Day of Year" ),
new RollAddField(Calendar.AM_PM, "AM/PM" ),
new RollAddField(Calendar.HOUR_OF_DAY, "Hour of day" ),
new RollAddField(Calendar.HOUR, "Hour" ),
new RollAddField(Calendar.MINUTE, "Minute" ),
new RollAddField(Calendar.SECOND, "Second" ),
};
/**
* Constructs a new CalendarCalcFrame that is initially invisible.
*/
public CalendarCalcFrame(DemoApplet applet)
{
super("Multiple Calendar Demo");
this.applet = applet;
init();
start();
}
/**
* Initializes the applet. You never need to call this directly, it
* is called automatically by the system once the applet is created.
*/
public void init()
{
buildGUI();
patternText.setText( calendars[0].toPattern() );
// Force an update of the display
cityChanged();
millisFormat();
enableEvents(KeyEvent.KEY_RELEASED);
enableEvents(WindowEvent.WINDOW_CLOSING);
}
//------------------------------------------------------------
// package private
//------------------------------------------------------------
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
/**
* Called to start the applet. You never need to call this method
* directly, it is called when the applet's document is visited.
*/
public void start()
{
// do nothing
}
TextField patternText;
Choice dateMenu;
Choice localeMenu;
Button up;
Button down;
Checkbox getRoll;
Checkbox getAdd;
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new FlowLayout()); // shouldn't be necessary, but it is.
// TITLE
Label label1=new Label("Calendar Converter", Label.CENTER);
label1.setFont(DemoUtility.titleFont);
add(label1);
add(DemoUtility.createSpacer());
// IO Panel
Panel topPanel = new Panel();
topPanel.setLayout(new FlowLayout());
CheckboxGroup group1= new CheckboxGroup();
// Set up the controls for each calendar we're demonstrating
for (int i = 0; i < calendars.length; i++)
{
Label label = new Label(calendars[i].name, Label.RIGHT);
label.setFont(DemoUtility.labelFont);
topPanel.add(label);
topPanel.add(calendars[i].text);
final int j = i;
calendars[i].text.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
textChanged(j);
}
} );
calendars[i].rollAdd.setCheckboxGroup(group1);
topPanel.add(calendars[i].rollAdd);
}
calendars[0].rollAdd.setState(true); // Make the first one selected
Label label4=new Label("Pattern", Label.RIGHT);
label4.setFont(DemoUtility.labelFont);
topPanel.add(label4);
patternText=new TextField(FIELD_COLUMNS);
patternText.setFont(DemoUtility.editFont);
topPanel.add(patternText);
topPanel.add(new Label(""));
DemoUtility.fixGrid(topPanel,3);
add(topPanel);
add(DemoUtility.createSpacer());
// ROLL / ADD
Panel rollAddPanel=new Panel();
{
rollAddPanel.setLayout(new FlowLayout());
Panel rollAddBoxes = new Panel();
{
rollAddBoxes.setLayout(new GridLayout(2,1));
CheckboxGroup group2= new CheckboxGroup();
getRoll = new Checkbox("Roll",group2, false);
getAdd = new Checkbox("Add",group2, true);
rollAddBoxes.add(getRoll);
rollAddBoxes.add(getAdd);
}
Label dateLabel=new Label("Date Fields");
dateLabel.setFont(DemoUtility.labelFont);
dateMenu= new Choice();
dateMenu.setBackground(DemoUtility.choiceColor);
for (int i = 0; i < kRollAddFields.length; i++) {
dateMenu.addItem(kRollAddFields[i].name);
if (kRollAddFields[i].field == Calendar.MONTH) {
dateMenu.select(i);
}
}
Panel upDown = new Panel();
{
upDown.setLayout(new GridLayout(2,1));
// *** If the images are not found, we use the label.
up = new Button("^");
down = new Button("v");
up.setBackground(DemoUtility.bgColor);
down.setBackground(DemoUtility.bgColor);
upDown.add(up);
upDown.add(down);
up.addActionListener(this);
down.addActionListener(this);
}
rollAddPanel.add(dateLabel);
rollAddPanel.add(dateMenu);
rollAddPanel.add(rollAddBoxes);
rollAddPanel.add(upDown);
}
Panel localePanel = new Panel();
{
// Make the locale popup menus
localeMenu= new Choice();
Locale defaultLocale = Locale.getDefault();
int bestMatch = -1, thisMatch = -1;
int selectMe = 0;
for (int i = 0; i < locales.length; i++) {
if (i > 0 && locales[i].getLanguage().equals(locales[i-1].getLanguage()) ||
i < locales.length - 1 &&
locales[i].getLanguage().equals(locales[i+1].getLanguage()))
{
localeMenu.addItem( locales[i].getDisplayName() );
} else {
localeMenu.addItem( locales[i].getDisplayLanguage());
}
thisMatch = DemoUtility.compareLocales(locales[i], defaultLocale);
if (thisMatch >= bestMatch) {
bestMatch = thisMatch;
selectMe = i;
}
}
localeMenu.setBackground(DemoUtility.choiceColor);
localeMenu.select(selectMe);
Label localeLabel =new Label("Display Locale");
localeLabel.setFont(DemoUtility.labelFont);
localePanel.add(localeLabel);
localePanel.add(localeMenu);
DemoUtility.fixGrid(localePanel,2);
localeMenu.addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Locale loc = locales[localeMenu.getSelectedIndex()];
System.out.println("Change locale to " + loc.getDisplayName());
for (int i = 0; i < calendars.length; i++) {
calendars[i].setLocale(loc);
}
millisFormat();
}
} );
}
add(rollAddPanel);
add(DemoUtility.createSpacer());
add(localePanel);
add(DemoUtility.createSpacer());
// COPYRIGHT
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,new Label(DemoUtility.copyright1, Label.LEFT),
DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add(copyrightPanel);
}
/**
* This function is called when users change the pattern text.
*/
public void setFormatFromPattern() {
String timePattern = patternText.getText();
for (int i = 0; i < calendars.length; i++) {
calendars[i].applyPattern(timePattern);
}
millisFormat();
}
/**
* This function is called when it is necessary to parse the time
* string in one of the formatted date fields
*/
public void textChanged(int index) {
String rightString = calendars[index].text.getText();
ParsePosition status = new ParsePosition(0);
if (rightString.length() == 0)
{
errorText("Error: no input to parse!");
return;
}
try {
Date date = calendars[index].format.parse(rightString, status);
time = date.getTime();
}
catch (Exception e) {
for (int i = 0; i < calendars.length; i++) {
if (i != index) {
calendars[i].text.setText("ERROR");
}
}
errorText("Exception: " + e.getClass().toString() + " parsing: "+rightString);
return;
}
int start = calendars[index].text.getSelectionStart();
int end = calendars[index].text.getSelectionEnd();
millisFormat();
calendars[index].text.select(start,end);
}
/**
* This function is called when it is necessary to format the time
* in the "Millis" text field.
*/
public void millisFormat() {
String out = "";
for (int i = 0; i < calendars.length; i++) {
try {
out = calendars[i].format.format(new Date(time));
calendars[i].text.setText(out);
}
catch (Exception e) {
calendars[i].text.setText("ERROR");
errorText("Exception: " + e.getClass().toString() + " formatting "
+ calendars[i].name + " " + time);
}
}
}
/**
* This function is called when users change the pattern text.
*/
public void patternTextChanged() {
setFormatFromPattern();
}
/**
* This function is called when users select a new representative city.
*/
public void cityChanged() {
TimeZone timeZone = TimeZone.getDefault();
for (int i = 0; i < calendars.length; i++) {
calendars[i].format.setTimeZone(timeZone);
}
millisFormat();
}
/**
* This function is called when users select a new time field
* to add or roll its value.
*/
public void dateFieldChanged(boolean up) {
int field = kRollAddFields[dateMenu.getSelectedIndex()].field;
for (int i = 0; i < calendars.length; i++)
{
if (calendars[i].rollAdd.getState())
{
Calendar c = calendars[i].calendar;
c.setTime(new Date(time));
if (getAdd.getState()) {
c.add(field, up ? 1 : -1);
} else {
c.roll(field, up);
}
time = c.getTime().getTime();
millisFormat();
break;
}
}
}
/**
* Print out the error message while debugging this program.
*/
public void errorText(String s)
{
if (true) {
System.out.println(s);
}
}
/**
* Called if an action occurs in the CalendarCalcFrame object.
*/
public void actionPerformed(ActionEvent evt)
{
// *** Button events are handled here.
Object obj = evt.getSource();
System.out.println("action " + obj);
if (obj instanceof Button) {
if (evt.getSource() == up) {
dateFieldChanged(false);
} else
if (evt.getSource() == down) {
dateFieldChanged(true);
}
}
}
/**
* Handles the event. Returns true if the event is handled and should not
* be passed to the parent of this component. The default event handler
* calls some helper methods to make life easier on the programmer.
*/
protected void processKeyEvent(KeyEvent evt)
{
System.out.println("key " + evt);
if (evt.getID() == KeyEvent.KEY_RELEASED) {
if (evt.getSource() == patternText) {
patternTextChanged();
}
else {
for (int i = 0; i < calendars.length; i++) {
if (evt.getSource() == calendars[i].text) {
textChanged(i);
}
}
}
}
}
protected void processWindowEvent(WindowEvent evt)
{
System.out.println("window " + evt);
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getSource() == this) {
this.hide();
this.dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
/*
protected void processEvent(AWTEvent evt)
{
if (evt.getID() == AWTEvent. Event.ACTION_EVENT && evt.target == up) {
dateFieldChanged(true);
return true;
}
else if (evt.id == Event.ACTION_EVENT && evt.target == down) {
dateFieldChanged(false);
return true;
}
}
*/
private static final int FIELD_COLUMNS = 35;
private static final String DEFAULT_FORMAT = "EEEE MMMM d, yyyy G";
class CalendarRec {
public CalendarRec(String nameStr, Calendar cal)
{
name = nameStr;
calendar = cal;
rollAdd = new Checkbox();
text = new JTextField("",FIELD_COLUMNS);
text.setFont(DemoUtility.editFont);
format = DateFormat.getDateInstance(cal, DateFormat.FULL,
Locale.getDefault());
//format.applyPattern(DEFAULT_FORMAT);
}
public void setLocale(Locale loc) {
String pattern = toPattern();
format = DateFormat.getDateInstance(calendar, DateFormat.FULL,
loc);
applyPattern(pattern);
}
public void applyPattern(String pattern) {
if (format instanceof SimpleDateFormat) {
((SimpleDateFormat)format).applyPattern(pattern);
//hey {al} -
// } else if (format instanceof java.text.SimpleDateFormat) {
// ((java.text.SimpleDateFormat)format).applyPattern(pattern);
}
}
private String toPattern() {
if (format instanceof SimpleDateFormat) {
return ((SimpleDateFormat)format).toPattern();
//hey {al} -
// } else if (format instanceof java.text.SimpleDateFormat) {
// return ((java.text.SimpleDateFormat)format).toPattern();
} else {
return "";
}
}
Calendar calendar;
DateFormat format;
String name;
JTextField text;
Checkbox rollAdd;
};
private final CalendarRec[] calendars = {
new CalendarRec("Gregorian", new GregorianCalendar()),
new CalendarRec("Hebrew", new HebrewCalendar()),
new CalendarRec("Islamic (civil)", makeIslamic(true)),
new CalendarRec("Islamic (true)", makeIslamic(false)),
new CalendarRec("Buddhist", new BuddhistCalendar()),
new CalendarRec("Japanese", new JapaneseCalendar()),
// new CalendarRec("Chinese", new ChineseCalendar()),
};
static private final Calendar makeIslamic(boolean civil) {
IslamicCalendar cal = new IslamicCalendar();
cal.setCivil(civil);
return cal;
};
};
class RollAddField {
RollAddField(int field, String name) {
this.field = field;
this.name = name;
}
int field;
String name;
};

View File

@ -1,435 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/calendar/Attic/CalendarFrame.java,v $
* $Date: 2000/10/19 00:27:16 $
* $Revision: 1.8 $
*
*****************************************************************************************
*/
package com.ibm.demo.calendar;
import com.ibm.demo.*;
import com.ibm.util.Calendar;
import com.ibm.util.HebrewCalendar;
import com.ibm.util.BuddhistCalendar;
import com.ibm.util.JapaneseCalendar;
import com.ibm.util.IslamicCalendar;
import com.ibm.text.SimpleDateFormat;
//import java.util.SimpleTimeZone;
import com.ibm.util.SimpleTimeZone;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
//import java.text.DateFormat;
import com.ibm.text.DateFormat;
import java.text.MessageFormat;
//import java.util.Calendar;
import com.ibm.util.Calendar;
import java.util.Date;
//import java.util.GregorianCalendar;
import com.ibm.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
//import java.util.TimeZone;
import com.ibm.util.TimeZone;
/**
* A Frame is a top-level window with a title. The default layout for a frame
* is BorderLayout. The CalendarFrame class defines the window layout of
* CalendarDemo.
*/
class CalendarFrame extends Frame
{
private static final boolean DEBUG = false;
private DemoApplet applet;
/**
* Constructs a new CalendarFrame that is initially invisible.
*/
public CalendarFrame(DemoApplet myApplet)
{
super("Calendar Demo");
this.applet = myApplet;
init();
// When the window is closed, we want to shut down the applet or application
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
} );
}
private Choice displayMenu;
private Locale[] locales = DemoUtility.getG7Locales();
private Calendar calendars[] = new Calendar[2];
private Choice calMenu[] = new Choice[2];
private ColoredLabel monthLabel[] = new ColoredLabel[2];
private DateFormat monthFormat[] = new DateFormat[2];
private Button prevYear;
private Button prevMonth;
private Button gotoToday;
private Button nextMonth;
private Button nextYear;
private CalendarPanel calendarPanel;
private static void add(Container container, Component component,
GridBagLayout g, GridBagConstraints c,
int gridwidth, int weightx)
{
c.gridwidth = gridwidth;
c.weightx = weightx;
g.setConstraints(component, c);
container.add(component);
}
/**
* Initializes the applet. You never need to call this directly, it
* is called automatically by the system once the applet is created.
*/
public void init() {
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout(10,10));
Panel topPanel = new Panel();
GridBagLayout g = new GridBagLayout();
topPanel.setLayout(g);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
// Build the two menus for selecting which calendar is displayed,
// plus the month/year label for each calendar
for (int i = 0; i < 2; i++) {
calMenu[i] = new Choice();
for (int j = 0; j < CALENDARS.length; j++) {
calMenu[i].addItem(CALENDARS[j].name);
}
calMenu[i].setBackground(DemoUtility.choiceColor);
calMenu[i].select(i);
calMenu[i].addItemListener(new CalMenuListener());
// Label for the current month name
monthLabel[i] = new ColoredLabel("", COLORS[i]);
monthLabel[i].setFont(DemoUtility.titleFont);
// And the default calendar to use for this slot
calendars[i] = CALENDARS[i].calendar;
add(topPanel, calMenu[i], g, c, 5, 0);
add(topPanel, monthLabel[i], g, c, GridBagConstraints.REMAINDER, 1);
}
// Now add the next/previous year/month buttons:
prevYear = new Button("<<");
prevYear.addActionListener(new AddAction(Calendar.YEAR, -1));
prevMonth = new Button("<");
prevMonth.addActionListener(new AddAction(Calendar.MONTH, -1));
gotoToday = new Button("Today");
gotoToday.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e) {
calendarPanel.setDate( new Date() );
updateMonthName();
}
} );
nextMonth = new Button(">");
nextMonth.addActionListener(new AddAction(Calendar.MONTH, 1));
nextYear = new Button(">>");
nextYear.addActionListener(new AddAction(Calendar.YEAR, 1));
c.fill = GridBagConstraints.NONE;
add(topPanel, prevYear, g, c, 1, 0);
add(topPanel, prevMonth, g, c, 1, 0);
add(topPanel, gotoToday, g, c, 1, 0);
add(topPanel, nextMonth, g, c, 1, 0);
add(topPanel, nextYear, g, c, 1, 0);
// Now add the menu for selecting the display language
Panel displayPanel = new Panel();
{
displayMenu = new Choice();
Locale defaultLocale = Locale.getDefault();
int bestMatch = -1, thisMatch = -1;
int selectMe = 0;
for (int i = 0; i < locales.length; i++) {
if (i > 0 &&
locales[i].getLanguage().equals(locales[i-1].getLanguage()) ||
i < locales.length - 1 &&
locales[i].getLanguage().equals(locales[i+1].getLanguage()))
{
displayMenu.addItem( locales[i].getDisplayName() );
} else {
displayMenu.addItem( locales[i].getDisplayLanguage());
}
thisMatch = DemoUtility.compareLocales(locales[i], defaultLocale);
if (thisMatch >= bestMatch) {
bestMatch = thisMatch;
selectMe = i;
}
}
displayMenu.setBackground(DemoUtility.choiceColor);
displayMenu.select(selectMe);
displayMenu.addItemListener( new ItemListener()
{
public void itemStateChanged(ItemEvent e) {
Locale loc = locales[displayMenu.getSelectedIndex()];
calendarPanel.setLocale( loc );
monthFormat[0] = monthFormat[1] = null;
updateMonthName();
repaint();
}
} );
Label l1 = new Label("Display Language:", Label.RIGHT);
l1.setFont(DemoUtility.labelFont);
displayPanel.setLayout(new FlowLayout());
displayPanel.add(l1);
displayPanel.add(displayMenu);
}
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
add(topPanel, displayPanel, g, c, GridBagConstraints.REMAINDER, 0);
// The title, buttons, etc. go in a panel at the top of the window
add("North", topPanel);
// The copyright notice goes at the bottom of the window
Label copyright = new Label(DemoUtility.copyright1, Label.LEFT);
copyright.setFont(DemoUtility.creditFont);
add("South", copyright);
// Now create the big calendar panel and stick it in the middle
calendarPanel = new CalendarPanel( locales[displayMenu.getSelectedIndex()] );
add("Center", calendarPanel);
for (int i = 0; i < 2; i++) {
calendarPanel.setCalendar(i, calendars[i]);
calendarPanel.setColor(i, COLORS[i]);
}
updateMonthName();
};
private void updateMonthName()
{
for (int i = 0; i < 2; i++) {
try {
if (monthFormat[i] == null) { // TODO: optimize
DateFormat f = DateFormat.getDateTimeInstance(
calendars[i], DateFormat.MEDIUM, -1,
locales[displayMenu.getSelectedIndex()]);
if (f instanceof com.ibm.text.SimpleDateFormat) {
com.ibm.text.SimpleDateFormat f1 = (com.ibm.text.SimpleDateFormat) f;
f1.applyPattern("MMMM, yyyy G");
f1.setTimeZone(new SimpleTimeZone(0, "UTC"));
//hey {al} -
// } else if (f instanceof java.text.SimpleDateFormat) {
// java.text.SimpleDateFormat f1 = (java.text.SimpleDateFormat) f;
// f1.applyPattern("MMMM, yyyy G");
// f1.setTimeZone(new SimpleTimeZone(0, "UTC"));
}
monthFormat[i] = f;
}
} catch (ClassCastException e) {
//hey {lw} - there's something wrong in this routine that cuases exceptions.
System.out.println(e);
}
monthLabel[i].setText( monthFormat[i].format( calendarPanel.firstOfMonth() ));
}
}
/**
* CalMenuListener responds to events in the two popup menus that select
* the calendar systems to be used in the display. It figures out which
* of the two menus the event occurred in and updates the corresponding
* element of the calendars[] array to match the new selection.
*/
private class CalMenuListener implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
for (int i = 0; i < calMenu.length; i++)
{
if (e.getItemSelectable() == calMenu[i])
{
// We found the menu that the event happened in.
// Figure out which new calendar they selected.
Calendar newCal = CALENDARS[ calMenu[i].getSelectedIndex() ].calendar;
if (newCal != calendars[i])
{
// If any of the other menus are set to the same new calendar
// we're about to use for this menu, set them to the current
// calendar from *this* menu so we won't have two the same
for (int j = 0; j < calendars.length; j++) {
if (j != i && calendars[j] == newCal) {
calendars[j] = calendars[i];
calendarPanel.setCalendar(j, calendars[j]);
monthFormat[j] = null;
for (int k = 0; k < CALENDARS.length; k++) {
if (calendars[j] == CALENDARS[k].calendar) {
calMenu[j].select(k);
break;
}
}
}
}
// Now update this menu to use the new calendar the user selected
calendars[i] = newCal;
calendarPanel.setCalendar(i, newCal);
monthFormat[i] = null;
updateMonthName();
}
break;
}
}
}
};
/**
* AddAction handles the next/previous year/month buttons...
*/
private class AddAction implements ActionListener {
AddAction(int field, int amount) {
this.field = field;
this.amount = amount;
}
public void actionPerformed(ActionEvent e) {
calendarPanel.add(field, amount);
updateMonthName();
}
private int field, amount;
}
/**
* ColoredLabel is similar to java.awt.Label, with two differences:
*
* - You can set its text color
*
* - It draws text using drawString rather than using a host-specific
* "Peer" object like AWT does. On 1.2, using drawString gives
* us Bidi reordering for free.
*/
static private class ColoredLabel extends Component {
public ColoredLabel(String label) {
text = label;
}
public ColoredLabel(String label, Color c) {
text = label;
color = c;
}
public void setText(String label) {
text = label;
repaint();
}
public void setFont(Font f) {
font = f;
repaint();
}
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetrics(font);
Rectangle bounds = getBounds();
g.setColor(color);
g.setFont(font);
g.drawString(text, fm.stringWidth("\u00a0"),
bounds.height/2 + fm.getHeight()
- fm.getAscent() + fm.getLeading()/2);
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
public Dimension getMinimumSize() {
FontMetrics fm = getFontMetrics(font);
return new Dimension( fm.stringWidth(text) + 2*fm.stringWidth("\u00a0"),
fm.getHeight() + fm.getLeading()*2);
}
String text;
Color color = Color.black;
Font font = DemoUtility.labelFont;
}
/**
* Print out the error message while debugging this program.
*/
public void errorText(String s)
{
if (DEBUG)
{
System.out.println(s);
}
}
class CalendarRec {
public CalendarRec(String nameStr, Calendar cal)
{
name = nameStr;
calendar = cal;
}
Calendar calendar;
String name;
};
private final CalendarRec[] CALENDARS = {
new CalendarRec("Gregorian Calendar", new GregorianCalendar()),
new CalendarRec("Hebrew Calendar", new HebrewCalendar()),
new CalendarRec("Islamic Calendar", makeIslamic(false)),
new CalendarRec("Islamic Civil Calendar ", makeIslamic(true)),
new CalendarRec("Buddhist Calendar", new BuddhistCalendar()),
new CalendarRec("Japanese Calendar", new JapaneseCalendar()),
};
static private final Calendar makeIslamic(boolean civil) {
IslamicCalendar cal = new IslamicCalendar();
cal.setCivil(civil);
return cal;
};
static final Color[] COLORS = { Color.blue, Color.black };
}

View File

@ -1,369 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/calendar/Attic/CalendarPanel.java,v $
* $Date: 2001/09/08 01:38:55 $
* $Revision: 1.7 $
*
*****************************************************************************************
*/
package com.ibm.demo.calendar;
import com.ibm.demo.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
//import java.util.*;
import java.net.*;
import java.io.*;
//import java.text.DateFormat;
import com.ibm.text.DateFormat;
//import java.util.SimpleTimeZone;
import com.ibm.util.SimpleTimeZone;
//import java.util.*;
import java.util.Date;
import java.util.Locale;
import com.ibm.util.*;
import com.ibm.text.*;
class CalendarPanel extends Canvas {
public CalendarPanel( Locale locale ) {
setLocale(locale);
}
public void setLocale(Locale locale) {
if (fDisplayLocale == null || !fDisplayLocale.equals(locale)) {
fDisplayLocale = locale;
dirty = true;
for (int i = 0; i < fCalendar.length; i++) {
if (fCalendar[i] != null) {
fSymbols[i] = new DateFormatSymbols(fCalendar[i],
fDisplayLocale);
}
}
String lang = locale.getLanguage();
leftToRight = !(lang.equals("iw") || lang.equals("ar"));
repaint();
}
}
public void setDate(Date date) {
fStartOfMonth = date;
dirty = true;
repaint();
}
public void add(int field, int delta)
{
synchronized(fCalendar) {
fCalendar[0].setTime(fStartOfMonth);
fCalendar[0].add(field, delta);
fStartOfMonth = fCalendar[0].getTime();
}
dirty = true;
repaint();
}
public void setColor(int index, Color c) {
fColor[index] = c;
repaint();
}
public void setCalendar(int index, Calendar c) {
Date date = (fCalendar[index] == null) ? new Date()
: fCalendar[index].getTime();
fCalendar[index] = c;
fCalendar[index].setTime(date);
fSymbols[index] = new DateFormatSymbols(c, fDisplayLocale);
dirty = true;
repaint();
}
public Calendar getCalendar(int index) {
return fCalendar[index];
}
public Locale getDisplayLocale() {
return fDisplayLocale;
}
public Date firstOfMonth() {
return fStartOfMonth;
}
private Date startOfMonth(Date dateInMonth)
{
synchronized(fCalendar) {
fCalendar[0].setTime(dateInMonth);
int era = fCalendar[0].get(Calendar.ERA);
int year = fCalendar[0].get(Calendar.YEAR);
int month = fCalendar[0].get(Calendar.MONTH);
fCalendar[0].clear();
fCalendar[0].set(Calendar.ERA, era);
fCalendar[0].set(Calendar.YEAR, year);
fCalendar[0].set(Calendar.MONTH, month);
fCalendar[0].set(Calendar.DATE, 1);
return fCalendar[0].getTime();
}
}
private void calculate()
{
//
// As a workaround for JDK 1.1.3 and below, where Calendars and time
// zones are a bit goofy, always set my calendar's time zone to UTC.
// You would think I would want to do this in the "set" function above,
// but if I do that, the program hangs when this class is loaded,
// perhaps due to some sort of static initialization ordering problem.
// So I do it here instead.
//
fCalendar[0].setTimeZone(new SimpleTimeZone(0, "UTC"));
Calendar c = (Calendar)fCalendar[0].clone(); // Temporary copy
fStartOfMonth = startOfMonth(fStartOfMonth);
// Stash away a few useful constants for this calendar and display
minDay = c.getMinimum(Calendar.DAY_OF_WEEK);
daysInWeek = c.getMaximum(Calendar.DAY_OF_WEEK) - minDay + 1;
firstDayOfWeek = Calendar.getInstance(fDisplayLocale).getFirstDayOfWeek();
// Stash away a Date for the start of this month
// Find the day of week of the first day in this month
c.setTime(fStartOfMonth);
firstDayInMonth = c.get(Calendar.DAY_OF_WEEK);
int firstWeek = c.get(Calendar.WEEK_OF_MONTH);
// Now find the # of days in the month
c.roll(Calendar.DATE, false);
daysInMonth = c.get(Calendar.DATE);
// Finally, find the end of the month, i.e. the start of the next one
c.roll(Calendar.DATE, true);
c.add(Calendar.MONTH, 1);
c.getTime(); // JDK 1.1.2 bug workaround
c.add(Calendar.SECOND, -1);
Date endOfMonth = c.getTime();
endOfMonth = null;
int lastWeek = c.get(Calendar.WEEK_OF_MONTH);
// Calculate the number of full or partial weeks in this month.
numWeeks = lastWeek - firstWeek + 1;
dirty = false;
}
static final int XINSET = 4;
static final int YINSET = 2;
/*
* Convert from the day number within a month (1-based)
* to the cell coordinates on the calendar (0-based)
*/
private void dateToCell(int date, Point pos)
{
int cell = (date + firstDayInMonth - firstDayOfWeek - minDay);
if (firstDayInMonth < firstDayOfWeek) {
cell += daysInWeek;
}
pos.x = cell % daysInWeek;
pos.y = cell / daysInWeek;
}
private Point dateToCell(int date) {
Point p = new Point(0,0);
dateToCell(date, p);
return p;
}
public void paint(Graphics g) {
if (dirty) {
calculate();
}
Point cellPos = new Point(0,0); // Temporary variable
Dimension d = this.getSize();
g.setColor(Color.lightGray);
g.fillRect(0,0,d.width,d.height);
// Draw the day names at the top
g.setColor(Color.black);
g.setFont(DemoUtility.labelFont);
FontMetrics fm = g.getFontMetrics();
int labelHeight = fm.getHeight() + YINSET * 2;
int v = fm.getAscent() + YINSET;
for (int i = 0; i < daysInWeek; i++) {
int dayNum = (i + minDay + firstDayOfWeek - 2) % daysInWeek + 1;
String dayName = fSymbols[0].getWeekdays()[dayNum];
double h;
if (leftToRight) {
h = d.width*(i + 0.5) / daysInWeek;
} else {
h = d.width*(daysInWeek - i - 0.5) / daysInWeek;
}
h -= fm.stringWidth(dayName) / 2;
g.drawString(dayName, (int)h, v);
}
double cellHeight = (d.height - labelHeight - 1) / numWeeks;
double cellWidth = (double)(d.width - 1) / daysInWeek;
// Draw a white background in the part of the calendar
// that displays this month.
// First figure out how much of the first week should be shaded.
{
g.setColor(Color.white);
dateToCell(1, cellPos);
int width = (int)(cellPos.x*cellWidth); // Width of unshaded area
if (leftToRight) {
g.fillRect((int)(width), labelHeight ,
d.width - width, (int)cellHeight);
} else {
g.fillRect(0, labelHeight ,
d.width - width, (int)cellHeight);
}
// All of the intermediate weeks get shaded completely
g.fillRect(0, (int)(labelHeight + cellHeight),
d.width, (int)(cellHeight * (numWeeks - 2)));
// Now figure out the last week.
dateToCell(daysInMonth, cellPos);
width = (int)((cellPos.x+1)*cellWidth); // Width of shaded area
if (leftToRight) {
g.fillRect(0, (int)(labelHeight + (numWeeks-1) * cellHeight),
width, (int)cellHeight);
} else {
g.fillRect(d.width - width, (int)(labelHeight + (numWeeks-1) * cellHeight),
width, (int)cellHeight);
}
}
// Draw the X/Y grid lines
g.setColor(Color.black);
for (int i = 0; i <= numWeeks; i++) {
int y = (int)(labelHeight + i * cellHeight);
g.drawLine(0, y, d.width - 1, y);
}
for (int i = 0; i <= daysInWeek; i++) {
int x = (int)(i * cellWidth);
g.drawLine(x, labelHeight, x, d.height - 1);
}
// Now loop through all of the days in the month, figure out where
// they go in the grid, and draw the day # for each one
// Figure out the date of the first cell in the calendar display
int cell = (1 + firstDayInMonth - firstDayOfWeek - minDay);
if (firstDayInMonth < firstDayOfWeek) {
cell += daysInWeek;
}
Calendar c = (Calendar)fCalendar[0].clone();
c.setTime(fStartOfMonth);
c.add(Calendar.DATE, -cell);
StringBuffer buffer = new StringBuffer();
for (int row = 0; row < numWeeks; row++) {
for (int col = 0; col < daysInWeek; col++) {
g.setFont(DemoUtility.numberFont);
g.setColor(Color.black);
fm = g.getFontMetrics();
int cellx;
if (leftToRight) {
cellx = (int)((col) * cellWidth);
} else {
cellx = (int)((daysInWeek - col - 1) * cellWidth);
}
int celly = (int)(row * cellHeight + labelHeight);
for (int i = 0; i < 2; i++) {
fCalendar[i].setTime(c.getTime());
int date = fCalendar[i].get(Calendar.DATE);
buffer.setLength(0);
buffer.append(date);
String dayNum = buffer.toString();
int x;
if (leftToRight) {
x = cellx + (int)cellWidth - XINSET - fm.stringWidth(dayNum);
} else {
x = cellx + XINSET;
}
int y = celly + + fm.getAscent() + YINSET + i * fm.getHeight();
if (fColor[i] != null) {
g.setColor(fColor[i]);
}
g.drawString(dayNum, x, y);
if (date == 1 || row == 0 && col == 0) {
g.setFont(DemoUtility.numberFont);
String month = fSymbols[i].getMonths()[
fCalendar[i].get(Calendar.MONTH)];
if (leftToRight) {
x = cellx + XINSET;
} else {
x = cellx + (int)cellWidth - XINSET - fm.stringWidth(month);
}
g.drawString(month, x, y);
}
}
c.add(Calendar.DATE, 1);
}
}
}
// Important state variables
private Calendar[] fCalendar = new Calendar[4];
private Color[] fColor = new Color[4];
private Locale fDisplayLocale;
private DateFormatSymbols[] fSymbols = new DateFormatSymbols[4];
private Date fStartOfMonth = new Date(); // 00:00:00 on first day of month
// Cached calculations to make drawing faster.
private transient int minDay; // Minimum legal day #
private transient int daysInWeek; // # of days in a week
private transient int firstDayOfWeek; // First day to display in week
private transient int numWeeks; // # full or partial weeks in month
private transient int daysInMonth; // # days in this month
private transient int firstDayInMonth; // Day of week of first day in month
private transient boolean leftToRight;
private transient boolean dirty = true;
}

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/calendar/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 06:28:48 $
-->
</head>
<body bgcolor="white">
Calendar demo applications including date/time arithmetic.
</body>
</html>

View File

@ -1,551 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1997-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/holiday/Attic/HolidayBorderPanel.java,v $
* $Date: 2001/10/30 02:42:50 $
* $Revision: 1.4 $
*
*****************************************************************************************
*/
package com.ibm.demo.holiday;
import com.ibm.demo.*;
import java.awt.*;
/**
* Various graphical borders. The border itself is a Panel so that it can
* contain other Components (i.e. it borders something). You use the
* HolidayBorderPanel like any other Panel: you set the layout that you prefer and
* add Components to it. Beware that a null layout does not obey the insets
* of the panel so if you use null layouts, adjust your measurements to
* handle the border by calling insets().
*
* @author Andy Clark, Taligent Inc.
* @version 1.0
*/
public class HolidayBorderPanel extends Panel {
// Constants
/** Solid border. */
public final static int SOLID = 0;
/** A raised border. */
public final static int RAISED = 1;
/** A lowered border. */
public final static int LOWERED = 2;
/** An etched in border. */
public final static int IN = 3;
/** An etched out border. */
public final static int OUT = 4;
/** Left alignment. */
public final static int LEFT = 0;
/** Center alignment. */
public final static int CENTER = 1;
/** Right alignment. */
public final static int RIGHT = 2;
/** Default style (IN). */
public final static int DEFAULT_STYLE = IN;
/** Default thickness (10). */
public final static int DEFAULT_THICKNESS = 10;
/** Default thickness for solid borders (4). */
public final static int DEFAULT_SOLID_THICKNESS = 4;
/** Default thickness for raised borders (2). */
public final static int DEFAULT_RAISED_THICKNESS = 2;
/** Default thickness for lowered borders (2). */
public final static int DEFAULT_LOWERED_THICKNESS = 2;
/** Default thickness for etched-in borders (10). */
public final static int DEFAULT_IN_THICKNESS = 10;
/** Default thickness for etched-out borders (10). */
public final static int DEFAULT_OUT_THICKNESS = 10;
/** Default gap between border and contained component (5). */
public final static int DEFAULT_GAP = 5;
/** Default color (black). Applies to SOLID and etched borders. */
public final static Color DEFAULT_COLOR = Color.black;
/** Default font (TimesRoman,PLAIN,14). Only applies to etched borders. */
public final static Font DEFAULT_FONT = new Font("TimesRoman", Font.PLAIN, 14);
/** Default alignment (LEFT). Only applies to etched borders. */
public final static int DEFAULT_ALIGNMENT = LEFT;
// Data
private int style;
private int thickness;
private int gap;
private Color color;
private Font font;
private String text;
private int alignment;
/**
* Constructor. Makes default border.
*/
public HolidayBorderPanel() {
// initialize data
style = DEFAULT_STYLE;
thickness = DEFAULT_THICKNESS;
gap = DEFAULT_GAP;
color = DEFAULT_COLOR;
text = null;
font = DEFAULT_FONT;
alignment = DEFAULT_ALIGNMENT;
}
/**
* Constructor. Makes an etched IN border with given text caption.
*
* @param text Text caption
*/
public HolidayBorderPanel(String text) {
this();
style = IN;
this.text = text;
}
/**
* Constructor. Makes SOLID border with color and thickness given.
*
* @param color The color for the border.
* @param thickness The thickness of the border.
*/
public HolidayBorderPanel(Color color, int thickness) {
this();
style = SOLID;
this.color = color;
this.thickness = thickness;
}
/**
* Constructor. Makes a border of the given style with the default
* thickness for that style.
*
* @param style The style for this border.
*/
public HolidayBorderPanel(int style) {
this();
// set thickness appropriate to this style
int thickness;
switch (style) {
case SOLID: thickness = DEFAULT_SOLID_THICKNESS; break;
case RAISED: thickness = DEFAULT_RAISED_THICKNESS; break;
case LOWERED: thickness = DEFAULT_LOWERED_THICKNESS; break;
case IN: thickness = DEFAULT_IN_THICKNESS; break;
case OUT: thickness = DEFAULT_OUT_THICKNESS; break;
default:
thickness = DEFAULT_THICKNESS;
}
this.style = style;
this.thickness = thickness;
}
/**
* Constructor. Makes border with given style and thickness.
*
* @param style The style for this border.
* @param thickness The thickness for this border.
*/
public HolidayBorderPanel(int style, int thickness) {
this();
this.style = style;
this.thickness = thickness;
}
/**
* Returns the insets of this panel..
*/
public Insets getInsets() {
int adjustment = 0;
// adjust for text string
if (style == IN || style == OUT) {
if (text != null && text.length() > 0) {
try {
// set font and get info
int height = getGraphics().getFontMetrics(font).getHeight();
if (height > thickness)
adjustment = height - thickness;
}
catch (Exception e) {
// nothing: just in case there is no graphics context
// at the beginning.
System.out.print("");
}
}
}
// return appropriate insets
int dist = thickness + gap;
return new Insets(dist + adjustment, dist, dist, dist);
}
/**
* Sets the style of the border
*
* @param style The new style.
*/
public HolidayBorderPanel setStyle(int style) {
// set the style and re-layout the panel
this.style = style;
doLayout();
repaint();
return this;
}
/**
* Gets the style of the border
*/
public int getStyle() {
return style;
}
/**
* Sets the thickness of the border.
*
* @param thickness The new thickness
*/
public HolidayBorderPanel setThickness(int thickness) {
if (thickness > 0) {
this.thickness = thickness;
doLayout();
repaint();
}
return this;
}
/**
* Gets the thickness of the border.
*/
public int getThickness() {
return thickness;
}
/**
* Sets the gap between the border and the contained Component.
*
* @param gap The new gap, in pixels.
*/
public HolidayBorderPanel setGap(int gap) {
if (gap > -1) {
this.gap = gap;
doLayout();
repaint();
}
return this;
}
/**
* Gets the gap between the border and the contained Component.
*/
public int getGap() {
return gap;
}
/**
* Sets the current color for SOLID borders and the caption text
* color for etched borders.
*
* @param color The new color.
*/
public HolidayBorderPanel setColor(Color color) {
this.color = color;
if (style == SOLID || style == IN || style == OUT)
repaint();
return this;
}
/**
* Gets the current color for SOLID borders and the caption
* text color for etched borders.
*/
public Color getColor() {
return color;
}
/**
* Sets the font. Only applies to etched borders.
*/
public HolidayBorderPanel setTextFont(Font font) {
// set font
if (font != null) {
this.font = font;
if (style == IN || style == OUT) {
doLayout();
repaint();
}
}
return this;
}
/**
* Gets the font of the text. Only applies to etched borders.
*/
public Font getTextFont() {
return font;
}
/**
* Sets the text. Only applies to etched borders.
*
* @param text The new text.
*/
public HolidayBorderPanel setText(String text) {
this.text = text;
if (style == IN || style == OUT) {
doLayout();
repaint();
}
return this;
}
/**
* Gets the text. Only applies to etched borders.
*/
public String getText() {
return text;
}
/**
* Sets the text alignment. Only applies to etched borders.
*
* @param alignment The new alignment.
*/
public HolidayBorderPanel setAlignment(int alignment) {
this.alignment = alignment;
if (style == IN || style == OUT) {
doLayout();
repaint();
}
return this;
}
/**
* Gets the text alignment.
*/
public int getAlignment() {
return alignment;
}
/**
* Repaints the border.
*
* @param g The graphics context.
*/
public void paint(Graphics g) {
// get current dimensions
Dimension size = getSize();
int width = size.width;
int height = size.height;
// set colors
Color light = getBackground().brighter().brighter().brighter();
Color dark = getBackground().darker().darker().darker();
// Draw border
switch (style) {
case RAISED: // 3D Border (in or out)
case LOWERED:
Color topleft = null;
Color bottomright = null;
// set colors
if (style == RAISED) {
topleft = light;
bottomright = dark;
}
else {
topleft = dark;
bottomright = light;
}
// draw border
g.setColor(topleft);
for (int i = 0; i < thickness; i++) {
g.drawLine(i, i, width - i - 2, i);
g.drawLine(i, i + 1, i, height - i - 1);
}
g.setColor(bottomright);
for (int i = 0; i < thickness; i++) {
g.drawLine(i + 1, height - i - 1, width - i - 1, height - i - 1);
g.drawLine(width - i - 1, i, width - i - 1, height - i - 2);
}
break;
case IN: // Etched Border (in or out)
case OUT:
int adjust1 = 0;
int adjust2 = 0;
// set font and get info
Font oldfont = g.getFont();
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int ascent = fm.getAscent();
// set adjustment
if (style == IN)
adjust1 = 1;
else
adjust2 = 1;
// Calculate adjustment for text
int adjustment = 0;
if (text != null && text.length() > 0) {
if (ascent > thickness)
adjustment = (ascent - thickness) / 2;
}
// The adjustment is there so that we always draw the
// light rectangle first. Otherwise, your eye picks up
// the discrepancy where the light rect. passes over
// the darker rect.
int x = thickness / 2;
int y = thickness / 2 + adjustment;
int w = width - thickness - 1;
int h = height - thickness - 1 - adjustment;
// draw rectangles
g.setColor(light);
g.drawRect(x + adjust1, y + adjust1, w, h);
g.setColor(dark);
g.drawRect(x + adjust2, y + adjust2, w, h);
// draw text, if applicable
if (text != null && text.length() > 0) {
// calculate drawing area
int fontheight = fm.getHeight();
int strwidth = fm.stringWidth(text);
int textwidth = width - 2 * (thickness + 5);
if (strwidth > textwidth)
strwidth = textwidth;
// calculate offset for alignment
int offset;
switch (alignment) {
case CENTER:
offset = (width - strwidth) / 2;
break;
case RIGHT:
offset = width - strwidth - thickness - 5;
break;
case LEFT:
default: // assume left alignment if invalid
offset = thickness + 5;
break;
}
// clear drawing area and set clipping region
g.clearRect(offset - 5, 0, strwidth + 10, fontheight);
g.clipRect(offset, 0, strwidth, fontheight);
// draw text
g.setColor(color);
g.drawString(text, offset, ascent);
// restore old clipping area
g.clipRect(0, 0, width, height);
}
g.setFont(oldfont);
break;
case SOLID:
default: // assume SOLID
g.setColor(color);
for (int i = 0; i < thickness; i++)
g.drawRect(i, i, width - 2 * i - 1, height - 2 * i - 1);
}
}
/**
* Returns the settings of this HolidayBorderPanel instance as a string.
*/
public String toString() {
StringBuffer str = new StringBuffer("HolidayBorderPanel[");
// style
str.append("style=");
switch (style) {
case SOLID: str.append("SOLID"); break;
case RAISED: str.append("RAISED"); break;
case LOWERED: str.append("LOWERED"); break;
case IN: str.append("IN"); break;
case OUT: str.append("OUT"); break;
default: str.append("unknown");
}
str.append(",");
// thickness
str.append("thickness=");
str.append(thickness);
str.append(",");
// gap
str.append("gap=");
str.append(gap);
str.append(",");
// color
str.append(color);
str.append(",");
// font
str.append(font);
str.append(",");
// text
str.append("text=");
str.append(text);
str.append(",");
// alignment
str.append("alignment=");
switch (alignment) {
case LEFT: str.append("LEFT"); break;
case CENTER: str.append("CENTER"); break;
case RIGHT: str.append("RIGHT"); break;
default: str.append("unknown");
}
str.append("]");
return str.toString();
}
}

View File

@ -1,721 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/holiday/Attic/HolidayCalendarDemo.java,v $
* $Date: 2001/10/30 02:42:49 $
* $Revision: 1.7 $
*
*****************************************************************************************
*/
package com.ibm.demo.holiday;
import com.ibm.demo.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
//import java.util.*;
import java.net.*;
import java.io.*;
//import java.text.SimpleDateFormat;
import com.ibm.text.SimpleDateFormat;
import java.text.DateFormatSymbols;
//import java.util.SimpleTimeZone;
import com.ibm.util.SimpleTimeZone;
import java.util.Locale;
import java.util.Vector;
import java.util.Date;
import com.ibm.util.*;
/**
* CalendarDemo demonstrates how Calendar works.
*/
public class HolidayCalendarDemo extends DemoApplet
{
/**
* The main function which defines the behavior of the CalendarDemo
* applet when an applet is started.
*/
public static void main(String argv[]) {
new HolidayCalendarDemo().showDemo();
}
/* This creates a CalendarFrame for the demo applet. */
public Frame createDemoFrame(DemoApplet applet) {
return new CalendarFrame(applet);
}
/**
* A Frame is a top-level window with a title. The default layout for a frame
* is BorderLayout. The CalendarFrame class defines the window layout of
* CalendarDemo.
*/
private static class CalendarFrame extends Frame implements ActionListener,
ItemListener
{
private static final String creditString = "";
private static final boolean DEBUG = false;
private Locale curLocale = Locale.US;
private DemoApplet applet;
private static final Locale[] calendars = {
//new Locale("de","AT"),
Locale.CANADA,
Locale.CANADA_FRENCH,
Locale.FRANCE,
Locale.GERMANY,
new Locale("iw","IL"),
new Locale("el","GR"),
//new Locale("es","MX"),
Locale.UK,
Locale.US,
};
private static final Locale[] displays = {
Locale.CANADA,
Locale.UK,
Locale.US,
Locale.FRANCE,
Locale.CANADA_FRENCH,
//new Locale("de","AT"),
Locale.GERMAN,
new Locale("el","GR"),
//new Locale("iw","IL"),
new Locale("es","MX"),
};
/**
* Constructs a new CalendarFrame that is initially invisible.
*/
public CalendarFrame(DemoApplet applet)
{
super("Calendar Demo");
this.applet = applet;
init();
start();
enableEvents(WindowEvent.WINDOW_CLOSING);
}
/**
* Initializes the applet. You never need to call this directly, it
* is called automatically by the system once the applet is created.
*/
public void init()
{
// Get G7 locales only for demo purpose. To get all the locales
// supported, switch to calling Calendar.getAvailableLocales().
// commented
locales = displays;
buildGUI();
}
//------------------------------------------------------------
// package private
//------------------------------------------------------------
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
/**
* Called to start the applet. You never need to call this method
* directly, it is called when the applet's document is visited.
*/
public void start()
{
// do nothing
}
private Choice localeMenu;
private Choice displayMenu;
private Locale[] locales;
private Label monthLabel;
private Button prevYear;
private Button prevMonth;
private Button gotoToday;
private Button nextMonth;
private Button nextYear;
private CalendarPanel calendarPanel;
private static final Locale kFirstLocale = Locale.US;
private static void add(Container container, Component component,
GridBagLayout g, GridBagConstraints c)
{
g.setConstraints(component, c);
container.add(component);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout(10,10));
// Label for the demo's title
Label titleLabel = new Label("Calendar Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
// Label for the current month name
monthLabel = new Label("", Label.LEFT);
monthLabel.setFont(new Font(DemoUtility.titleFont.getName(),
DemoUtility.titleFont.getStyle(),
(DemoUtility.titleFont.getSize() * 3)/2));
// Make the locale popup menus
localeMenu= new Choice();
localeMenu.addItemListener(this);
int selectMe = 0;
for (int i = 0; i < calendars.length; i++) {
if (i > 0 &&
calendars[i].getCountry().equals(calendars[i-1].getCountry()) ||
i < calendars.length - 1 &&
calendars[i].getCountry().equals(calendars[i+1].getCountry()))
{
localeMenu.addItem(calendars[i].getDisplayCountry() + " (" +
calendars[i].getDisplayLanguage() + ")");
} else {
localeMenu.addItem( calendars[i].getDisplayCountry() );
}
if (calendars[i].equals(kFirstLocale)) {
selectMe = i;
}
}
localeMenu.setBackground(DemoUtility.choiceColor);
localeMenu.select(selectMe);
displayMenu = new Choice();
displayMenu.addItemListener(this);
selectMe = 0;
for (int i = 0; i < locales.length; i++) {
if (i > 0 &&
locales[i].getLanguage().equals(locales[i-1].getLanguage()) ||
i < locales.length - 1 &&
locales[i].getLanguage().equals(locales[i+1].getLanguage()))
{
displayMenu.addItem( locales[i].getDisplayName() );
} else {
displayMenu.addItem( locales[i].getDisplayLanguage());
}
if (locales[i].equals(kFirstLocale)) {
selectMe = i;
}
}
displayMenu.setBackground(DemoUtility.choiceColor);
displayMenu.select(selectMe);
// Make all the next/previous/today buttons
prevYear = new Button("<<");
prevYear.addActionListener(this);
prevMonth = new Button("<");
prevMonth.addActionListener(this);
gotoToday = new Button("Today");
gotoToday.addActionListener(this);
nextMonth = new Button(">");
nextMonth.addActionListener(this);
nextYear = new Button(">>");
nextYear.addActionListener(this);
// The month name and the control buttons are bunched together
Panel monthPanel = new Panel();
{
GridBagLayout g = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
monthPanel.setLayout(g);
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.REMAINDER;
add(monthPanel, monthLabel, g, c);
c.gridwidth = 1;
add(monthPanel, prevYear, g, c);
add(monthPanel, prevMonth, g, c);
add(monthPanel, gotoToday, g, c);
add(monthPanel, nextMonth, g, c);
c.gridwidth = GridBagConstraints.REMAINDER;
add(monthPanel, nextYear, g, c);
}
// Stick the menu and buttons in a little "control panel"
Panel menuPanel = new Panel();
{
GridBagLayout g = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
menuPanel.setLayout(g);
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.RELATIVE;
Label l1 = new Label("Holidays");
l1.setFont(DemoUtility.labelFont);
add(menuPanel, l1, g, c);
c.gridwidth = GridBagConstraints.REMAINDER;
add(menuPanel, localeMenu, g, c);
c.gridwidth = GridBagConstraints.RELATIVE;
Label l2 = new Label("Display:");
l2.setFont(DemoUtility.labelFont);
add(menuPanel, l2, g, c);
c.gridwidth = GridBagConstraints.REMAINDER;
add(menuPanel, displayMenu, g, c);
}
// The title, buttons, etc. go in a panel at the top of the window
Panel topPanel = new Panel();
{
topPanel.setLayout(new BorderLayout());
//topPanel.add("North", titleLabel);
topPanel.add("Center", monthPanel);
topPanel.add("East", menuPanel);
}
add("North", topPanel);
// The copyright notice goes at the bottom of the window
Label copyright = new Label(DemoUtility.copyright1, Label.LEFT);
copyright.setFont(DemoUtility.creditFont);
add("South", copyright);
// Now create the big calendar panel and stick it in the middle
calendarPanel = new CalendarPanel( kFirstLocale );
add("Center", calendarPanel);
updateMonthName();
}
private void updateMonthName()
{
SimpleDateFormat f = new SimpleDateFormat("MMMM yyyyy",
calendarPanel.getDisplayLocale());
f.setCalendar(calendarPanel.getCalendar());
f.setTimeZone(new SimpleTimeZone(0, "UTC")); // JDK 1.1.2 workaround
monthLabel.setText( f.format( calendarPanel.firstOfMonth() ));
}
/**
* Handles the event. Returns true if the event is handled and should not
* be passed to the parent of this component. The default event handler
* calls some helper methods to make life easier on the programmer.
*/
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
// *** Button events are handled here.
if (obj instanceof Button) {
if (obj == nextMonth) {
calendarPanel.add(Calendar.MONTH, +1);
}
else
if (obj == prevMonth) {
calendarPanel.add(Calendar.MONTH, -1);
}
else
if (obj == prevYear) {
calendarPanel.add(Calendar.YEAR, -1);
}
else
if (obj == nextYear) {
calendarPanel.add(Calendar.YEAR, +1);
}
else
if (obj == gotoToday) {
calendarPanel.set( new Date() );
}
updateMonthName();
}
}
public void itemStateChanged(ItemEvent e)
{
Object obj = e.getSource();
if (obj == localeMenu) {
calendarPanel.setCalendarLocale(calendars[localeMenu.getSelectedIndex()]);
updateMonthName();
}
else
if (obj == displayMenu) {
calendarPanel.setDisplayLocale(locales[displayMenu.getSelectedIndex()]);
updateMonthName();
}
}
/**
* Print out the error message while debugging this program.
*/
public void errorText(String s)
{
if (DEBUG)
{
System.out.println(s);
}
}
protected void processWindowEvent(WindowEvent e)
{
System.out.println("event " + e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
this.hide();
this.dispose();
if (applet != null) {
applet.demoClosed();
} else {
System.exit(0);
}
}
}
}
private static class CalendarPanel extends Canvas {
public CalendarPanel( Locale locale ) {
set(locale, locale, new Date());
}
public void setCalendarLocale(Locale locale) {
set(locale, fDisplayLocale, fCalendar.getTime());
}
public void setDisplayLocale(Locale locale) {
set(fCalendarLocale, locale, fCalendar.getTime());
}
public void set(Date date) {
set(fCalendarLocale, fDisplayLocale, date);
}
public void set(Locale loc, Locale display, Date date)
{
if (fCalendarLocale == null || !loc.equals(fCalendarLocale)) {
fCalendarLocale = loc;
fCalendar = Calendar.getInstance(fCalendarLocale);
fAllHolidays = Holiday.getHolidays(fCalendarLocale);
}
if (fDisplayLocale == null || !display.equals(fDisplayLocale)) {
fDisplayLocale = display;
fSymbols = new DateFormatSymbols(fDisplayLocale);
}
fStartOfMonth = date;
dirty = true;
repaint();
}
public void add(int field, int delta)
{
synchronized(fCalendar) {
fCalendar.setTime(fStartOfMonth);
fCalendar.add(field, delta);
fStartOfMonth = fCalendar.getTime();
}
dirty = true;
repaint();
}
public com.ibm.util.Calendar getCalendar() {
return fCalendar;
}
public Locale getCalendarLocale() {
return fCalendarLocale;
}
public Locale getDisplayLocale() {
return fDisplayLocale;
}
public Date firstOfMonth() {
return fStartOfMonth;
}
private Date startOfMonth(Date dateInMonth)
{
synchronized(fCalendar) {
fCalendar.setTime(dateInMonth); // TODO: synchronization
int era = fCalendar.get(Calendar.ERA);
int year = fCalendar.get(Calendar.YEAR);
int month = fCalendar.get(Calendar.MONTH);
fCalendar.clear();
fCalendar.set(Calendar.ERA, era);
fCalendar.set(Calendar.YEAR, year);
fCalendar.set(Calendar.MONTH, month);
fCalendar.set(Calendar.DATE, 1);
return fCalendar.getTime();
}
}
private void calculate()
{
//
// As a workaround for JDK 1.1.3 and below, where Calendars and time
// zones are a bit goofy, always set my calendar's time zone to UTC.
// You would think I would want to do this in the "set" function above,
// but if I do that, the program hangs when this class is loaded,
// perhaps due to some sort of static initialization ordering problem.
// So I do it here instead.
//
fCalendar.setTimeZone(new SimpleTimeZone(0, "UTC"));
Calendar c = (Calendar)fCalendar.clone(); // Temporary copy
fStartOfMonth = startOfMonth(fStartOfMonth);
// Stash away a few useful constants for this calendar and display
minDay = c.getMinimum(Calendar.DAY_OF_WEEK);
daysInWeek = c.getMaximum(Calendar.DAY_OF_WEEK) - minDay + 1;
firstDayOfWeek = Calendar.getInstance(fDisplayLocale).getFirstDayOfWeek();
// Stash away a Date for the start of this month
// Find the day of week of the first day in this month
c.setTime(fStartOfMonth);
firstDayInMonth = c.get(Calendar.DAY_OF_WEEK);
// Now find the # of days in the month
c.roll(Calendar.DATE, false);
daysInMonth = c.get(Calendar.DATE);
// Finally, find the end of the month, i.e. the start of the next one
c.roll(Calendar.DATE, true);
c.add(Calendar.MONTH, 1);
c.getTime(); // JDK 1.1.2 bug workaround
c.add(Calendar.SECOND, -1);
Date endOfMonth = c.getTime();
//
// Calculate the number of full or partial weeks in this month.
// To do this I can just reuse the code that calculates which
// calendar cell contains a given date.
//
numWeeks = dateToCell(daysInMonth).y - dateToCell(1).y + 1;
// Remember which holidays fall on which days in this month,
// to save the trouble of having to do it later
fHolidays.setSize(0);
for (int h = 0; h < fAllHolidays.length; h++)
{
Date d = fStartOfMonth;
while ( (d = fAllHolidays[h].firstBetween(d, endOfMonth) ) != null)
{
c.setTime(d);
fHolidays.addElement( new HolidayInfo(c.get(Calendar.DATE),
fAllHolidays[h],
fAllHolidays[h].getDisplayName(fDisplayLocale) ));
d.setTime( d.getTime() + 1000 ); // "d++"
}
}
dirty = false;
}
static final int INSET = 2;
/*
* Convert from the day number within a month (1-based)
* to the cell coordinates on the calendar (0-based)
*/
private void dateToCell(int date, Point pos)
{
int cell = (date + firstDayInMonth - firstDayOfWeek - minDay);
if (firstDayInMonth < firstDayOfWeek) {
cell += daysInWeek;
}
pos.x = cell % daysInWeek;
pos.y = cell / daysInWeek;
}
private Point dateToCell(int date) {
Point p = new Point(0,0);
dateToCell(date, p);
return p;
}
public void paint(Graphics g) {
if (dirty) {
calculate();
}
Point cellPos = new Point(0,0); // Temporary variable
Dimension d = getSize();
g.setColor(DemoUtility.bgColor);
g.fillRect(0,0,d.width,d.height);
// Draw the day names at the top
g.setColor(Color.black);
g.setFont(DemoUtility.labelFont);
FontMetrics fm = g.getFontMetrics();
int labelHeight = fm.getHeight() + INSET * 2;
int v = fm.getAscent() + INSET;
for (int i = 0; i < daysInWeek; i++) {
int dayNum = (i + minDay + firstDayOfWeek - 2) % daysInWeek + 1;
String dayName = fSymbols.getWeekdays()[dayNum];
int h = (int) (d.width * (i + 0.5)) / daysInWeek;
h -= fm.stringWidth(dayName) / 2;
g.drawString(dayName, h, v);
}
double cellHeight = (d.height - labelHeight - 1) / numWeeks;
double cellWidth = (double)(d.width - 1) / daysInWeek;
// Draw a white background in the part of the calendar
// that displays this month.
// First figure out how much of the first week should be shaded.
{
g.setColor(Color.white);
dateToCell(1, cellPos);
int width = (int)(cellPos.x*cellWidth); // Width of unshaded area
g.fillRect((int)(width), labelHeight ,
(int)(d.width - width), (int)cellHeight);
// All of the intermediate weeks get shaded completely
g.fillRect(0, (int)(labelHeight + cellHeight),
d.width, (int)(cellHeight * (numWeeks - 2)));
// Now figure out the last week.
dateToCell(daysInMonth, cellPos);
width = (int)((cellPos.x+1)*cellWidth); // Width of shaded area
g.fillRect(0, (int)(labelHeight + (numWeeks-1) * cellHeight),
width, (int)(cellHeight));
}
// Draw the X/Y grid lines
g.setColor(Color.black);
for (int i = 0; i <= numWeeks; i++) {
int y = (int)(labelHeight + i * cellHeight);
g.drawLine(0, y, d.width - 1, y);
}
for (int i = 0; i <= daysInWeek; i++) {
int x = (int)(i * cellWidth);
g.drawLine(x, labelHeight, x, d.height - 1);
}
// Now loop through all of the days in the month, figure out where
// they go in the grid, and draw the day # for each one
Font numberFont = new Font("Helvetica",Font.PLAIN,12);
// not used Font holidayFont = DemoUtility.creditFont;
Calendar c = (Calendar)fCalendar.clone();
c.setTime(fStartOfMonth);
for (int i = 1, h = 0; i <= daysInMonth; i++) {
g.setFont(numberFont);
g.setColor(Color.black);
fm = g.getFontMetrics();
dateToCell(i, cellPos);
int x = (int)((cellPos.x + 1) * cellWidth);
int y = (int)(cellPos.y * cellHeight + labelHeight);
StringBuffer buffer = new StringBuffer();
buffer.append(i);
String dayNum = buffer.toString();
x = x - INSET - fm.stringWidth(dayNum);
y = y + fm.getAscent() + INSET;
g.drawString(dayNum, x, y);
// See if any of the holidays land on this day....
HolidayInfo info = null;
int count = 0;
// Coordinates of lower-left corner of cell.
x = (int)((cellPos.x) * cellWidth);
y = (int)((cellPos.y+1) * cellHeight) + labelHeight;
while (h < fHolidays.size() &&
(info = (HolidayInfo)fHolidays.elementAt(h)).date <= i)
{
if (info.date == i) {
// Draw the holiday here.
g.setFont(numberFont);
g.setColor(Color.red);
DemoTextBox box = new DemoTextBox(g, info.name, (int)(cellWidth - INSET));
box.draw(g, x + INSET, y - INSET - box.getHeight());
y -= (box.getHeight() + INSET);
count++;
}
h++;
}
}
}
// Important state variables
private Locale fCalendarLocale; // Whose calendar
private Calendar fCalendar; // Calendar for calculations
private Locale fDisplayLocale; // How to display it
private DateFormatSymbols fSymbols; // Symbols for drawing
private Date fStartOfMonth; // 00:00:00 on first day of month
// Cached calculations to make drawing faster.
private transient int minDay; // Minimum legal day #
private transient int daysInWeek; // # of days in a week
private transient int firstDayOfWeek; // First day to display in week
private transient int numWeeks; // # full or partial weeks in month
private transient int daysInMonth; // # days in this month
private transient int firstDayInMonth; // Day of week of first day in month
private transient Holiday[] fAllHolidays;
private transient Vector fHolidays = new Vector(5,5);
private transient boolean dirty = true;
}
private static class HolidayInfo {
public HolidayInfo(int date, Holiday holiday, String name) {
this.date = date;
this.holiday = holiday;
this.name = name;
}
public Holiday holiday;
public int date;
public String name;
}
}

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/holiday/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 06:54:50 $
-->
</head>
<body bgcolor="white">
Holiday demo application.
</body>
</html>

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 17:43:40 $
-->
</head>
<body bgcolor="white">
Shared utilities for demo applications and Applets.
</body>
</html>

View File

@ -1,223 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/rbbi/Attic/BreakIteratorRules_en_US_DEMO.java,v $
* $Date: 2001/02/20 22:50:12 $
* $Revision: 1.6 $
*
*****************************************************************************************
*/
package com.ibm.text.resources;
import java.util.ListResourceBundle;
import java.net.URL;
/**
* This resource bundle is included for testing and demonstration purposes only.
* It applies the dictionary-based algorithm to English text that has had all the
* spaces removed. Once we have good test cases for Thai, we will replace this
* with good resource data (and a good dictionary file) for Thai
*/
public class BreakIteratorRules_en_US_DEMO extends ListResourceBundle {
private static final URL url =
BreakIteratorRules_en_US_DEMO.class.getResource("/com/ibm/data/misc/english.dict");
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
// names of classes to instantiate for the different kinds of break
// iterator. Notice we're now using DictionaryBasedBreakIterator
// for word and line breaking.
{ "BreakIteratorClasses",
new String[] { "RuleBasedBreakIterator", // character-break iterator class
"DictionaryBasedBreakIterator", // word-break iterator class
"DictionaryBasedBreakIterator", // line-break iterator class
"RuleBasedBreakIterator" } // sentence-break iterator class
},
// These are the same word-breaking rules as are specified in the default
// resource, except that the Latin letters, apostrophe, and hyphen are
// specified as dictionary characters
{ "WordBreakRules",
// ignore non-spacing marks, enclosing marks, and format characters,
// all of which should not influence the algorithm
"$_ignore_=[[:Mn:][:Me:][:Cf:]];"
// lower and upper case Roman letters, apostrophy and dash are
// in the English dictionary
+ "$_dictionary_=[a-zA-Z\\'\\-];"
// Hindi phrase separator, kanji, katakana, hiragana, CJK diacriticals,
// other letters, and digits
+ "$danda=[\u0964\u0965];"
+ "$kanji=[\u3005\u4e00-\u9fa5\uf900-\ufa2d];"
+ "$kata=[\u3099-\u309c\u30a1-\u30fe];"
+ "$hira=[\u3041-\u309e\u30fc];"
+ "$let=[[[:L:][:Mc:]]-[$kanji$kata$hira]];"
+ "$dgt=[:N:];"
// punctuation that can occur in the middle of a word: currently
// dashes, apostrophes, and quotation marks
+ "$mid_word=[[:Pd:]\u00ad\u2027\\\"\\\'];"
// punctuation that can occur in the middle of a number: currently
// apostrophes, qoutation marks, periods, commas, and the Arabic
// decimal point
+ "$mid_num=[\\\"\\\'\\,\u066b\\.];"
// punctuation that can occur at the beginning of a number: currently
// the period, the number sign, and all currency symbols except the cents sign
+ "$pre_num=[[[:Sc:]-[\u00a2]]\\#\\.];"
// punctuation that can occur at the end of a number: currently
// the percent, per-thousand, per-ten-thousand, and Arabic percent
// signs, the cents sign, and the ampersand
+ "$post_num=[\\%\\&\u00a2\u066a\u2030\u2031];"
// line separators: currently LF, FF, PS, and LS
+ "$ls=[\n\u000c\u2028\u2029];"
// whitespace: all space separators and the tab character
+ "$ws=[[:Zs:]\t];"
// a word is a sequence of letters that may contain internal
// punctuation, as long as it begins and ends with a letter and
// never contains two punctuation marks in a row
+ "$word=($let+($mid_word$let+)*$danda?);"
// a number is a sequence of digits that may contain internal
// punctuation, as long as it begins and ends with a digit and
// never contains two punctuation marks in a row.
+ "$number=($dgt+($mid_num$dgt+)*);"
// break after every character, with the following exceptions
// (this will cause punctuation marks that aren't considered
// part of words or numbers to be treated as words unto themselves)
+ ".;"
// keep together any sequence of contiguous words and numbers
// (including just one of either), plus an optional trailing
// number-suffix character
+ "$word?($number$word)*($number$post_num?)?;"
// keep together and sequence of contiguous words and numbers
// that starts with a number-prefix character and a number,
// and may end with a number-suffix character
+ "$pre_num($number$word)*($number$post_num?)?;"
// keep together runs of whitespace (optionally with a single trailing
// line separator or CRLF sequence)
+ "$ws*\r?$ls?;"
// keep together runs of Katakana
+ "$kata*;"
// keep together runs of Hiragana
+ "$hira*;"
// keep together runs of Kanji
+ "$kanji*;"},
// These are the same line-breaking rules as are specified in the default
// resource, except that the Latin letters, apostrophe, and hyphen are
// specified as dictionary characters
{ "LineBreakRules",
// ignore non-spacing marks, enclosing marks, and format characters
"$_ignore_=[[:Mn:][:Me:][:Cf:]];"
// lower and upper case Roman letters, apostrophy and dash
// are in the English dictionary
+ "$_dictionary_=[a-zA-Z\\'\\-];"
// Hindi phrase separators
+ "$danda=[\u0964\u0965];"
// characters that always cause a break: ETX, tab, LF, FF, LS, and PS
+ "$break=[\u0003\t\n\f\u2028\u2029];"
// characters that always prevent a break: the non-breaking space
// and similar characters
+ "$nbsp=[\u00a0\u2007\u2011\ufeff];"
// whitespace: space separators and control characters, except for
// CR and the other characters mentioned above
+ "$space=[[[:Zs:][:Cc:]]-[$nbsp$break\r]];"
// dashes: dash punctuation and the discretionary hyphen, except for
// non-breaking hyphens
+ "$dash=[[[:Pd:]\u00ad]-[$nbsp]];"
// characters that stick to a word if they precede it: currency symbols
// (except the cents sign) and starting punctuation
+ "$pre_word=[[[:Sc:]-[\u00a2]][:Ps:]\\\"\\\'];"
// characters that stick to a word if they follow it: ending punctuation,
// other punctuation that usually occurs at the end of a sentence,
// small Kana characters, some CJK diacritics, etc.
+ "$post_word=[[:Pe:]\\!\\\"\\\'\\%\\.\\,\\:\\;\\?\u00a2\u00b0\u066a\u2030-\u2034"
+ "\u2103\u2105\u2109\u3001\u3002\u3005\u3041\u3043\u3045\u3047\u3049\u3063"
+ "\u3083\u3085\u3087\u308e\u3099-\u309e\u30a1\u30a3\u30a5\u30a7\u30a9"
+ "\u30c3\u30e3\u30e5\u30e7\u30ee\u30f5\u30f6\u30fc-\u30fe\uff01\uff0c"
+ "\uff0e\uff1f];"
// Kanji: actually includes both Kanji and Kana, except for small Kana and
// CJK diacritics
+ "$kanji=[[\u4e00-\u9fa5\uf900-\ufa2d\u3041-\u3094\u30a1-\u30fa]-[$post_word$_ignore_]];"
// digits
+ "$digit=[[:Nd:][:No:]];"
// punctuation that can occur in the middle of a number: periods and commas
+ "$mid_num=[\\.\\,];"
// everything not mentioned above, plus the quote marks (which are both
// <pre-word>, <post-word>, and <char>)
+ "$char=[^$break$space$dash$kanji$nbsp$_ignore_$pre_word$post_word$mid_num$danda\r\\\"\\\'];"
// a "number" is a run of prefix characters and dashes, followed by one or
// more digits with isolated number-punctuation characters interspersed
+ "$number=([$pre_word$dash]*$digit+($mid_num$digit+)*);"
// the basic core of a word can be either a "number" as defined above, a single
// "Kanji" character, or a run of any number of not-explicitly-mentioned
// characters (this includes Latin letters)
+ "$word_core=([$pre_word$char]*|$kanji|$number);"
// a word may end with an optional suffix that be either a run of one or
// more dashes or a run of word-suffix characters, followed by an optional
// run of whitespace
+ "$word_suffix=(($dash+|$post_word*)$space*);"
// a word, thus, is an optional run of word-prefix characters, followed by
// a word core and a word suffix (the syntax of <word-core> and <word-suffix>
// actually allows either of them to match the empty string, putting a break
// between things like ")(" or "aaa(aaa"
+ "$word=($pre_word*$word_core$word_suffix);"
// finally, the rule that does the work: Keep together any run of words that
// are joined by runs of one of more non-spacing mark. Also keep a trailing
// line-break character or CRLF combination with the word. (line separators
// "win" over nbsp's)
+ "$word($nbsp+$word)*\r?$break?;" },
// these two resources specify the pathnames of the dictionary files to
// use for word breaking and line breaking. Both currently refer to
// a file called english.dict placed in com\ibm\text\resources
// somewhere in the class path. It's important to note that
// english.dict was created for testing purposes only, and doesn't
// come anywhere close to being an exhaustive dictionary of English
// words (basically, it contains all the words in the Declaration of
// Independence, and the Revised Standard Version of the book of Genesis,
// plus a few other words thrown in to show more interesting cases).
// { "WordBreakDictionary", "com\\ibm\\text\\resources\\english.dict" },
// { "LineBreakDictionary", "com\\ibm\\text\\resources\\english.dict" }
{ "WordBreakDictionary", url },
{ "LineBreakDictionary", url }
};
}

View File

@ -1,471 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/rbbi/Attic/DBBIDemo.java,v $
* $Date: 2001/11/12 23:44:44 $
* $Revision: 1.9 $
*
*****************************************************************************************
*/
package com.ibm.demo.rbbi;
import com.ibm.demo.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.KeyEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import java.util.*;
import com.ibm.text.BreakIterator;
public class DBBIDemo extends DemoApplet
{
public static void main(String argv[]) {
Locale.setDefault(new Locale("en", "US", "DEMO"));
new DBBIDemo().showDemo();
}
public Frame createDemoFrame(DemoApplet applet) {
return new DBBIFrame(applet);
}
}
class DBBIFrame extends Frame implements ItemListener
{
private static final String creditString =
"v1.1a9, Demo";
private static final int FIELD_COLUMNS = 45;
private static final Font choiceFont = null;
private static final boolean DEBUG = false;
private DemoApplet applet;
final String right = "-->";
final String left = "<--";
private BreakIterator enum;
private static boolean isctrldown_ = false;
JTextArea text;
// TextArea text;
Choice bound;
public DBBIFrame(DemoApplet applet)
{
this.applet = applet;
init();
start();
}
public void run()
{
/*
while (true) {
try {
checkChange();
Thread.sleep(250);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
catch (Throwable e) {
}
}
*/
}
int s, e;
int ts, te;
public void checkChange()
{
// System.out.println("checkChange...");
if ((text.getSelectionStart() & 0x7FFF) != ts ||
(text.getSelectionEnd() & 0x7FFF) != te) {
// not used int tempS = text.getSelectionStart() & 0x7FFF;
// not used int tempE = text.getSelectionEnd() & 0x7FFF;
// System.out.println(">");
// select(0, 0);
// select(tempS, tempE);
//select(tempS - (ts - s), tempE - (te - e));
// System.out.println("<");
// if (s != ts || e != te) System.out.println(" s("+s+") ts("+ts+") e("+e+") te("+te+")");
// if (tempS != ts || tempE != te) System.out.println(">s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// select(s - (ts - s), e - (te - e));
// if (tempS != ts || tempE != te) System.out.println("s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// System.out.println("lkdslksj");
}
}
public void select(int sIn, int eIn)
{
s = sIn;
e = eIn;
text.select(s, e);
ts = text.getSelectionStart() & 0x7FFF;
te = text.getSelectionEnd() & 0x7FFF;
// if (s != ts || e != te) {
// System.out.println(">s("+s+") ts("+ts+") e("+e+") te("+te+")");
// System.out.println(" "+(ts-s)+","+(te-e));
// }
}
public int getSelectionStart()
{
checkChange();
// return s;
return text.getSelectionStart() & 0x7FFF;
}
public int getSelectionEnd()
{
checkChange();
// return e;
return text.getSelectionEnd() & 0x7FFF;
}
public final synchronized void selectRange(int s, int e)
{
try {
//if (getSelectionStart() != s || getSelectionEnd() != e) {
//text.select(s, e);
select(s,e);
//}
// if (getSelectionStart() != s || getSelectionEnd() != e) {
// System.out.println("AGH! select("+s+","+e+") -> ("+
// getSelectionStart()+","+getSelectionEnd()+")");
// text.select(s - (getSelectionStart() - s), e - (getSelectionEnd() - e));
// }
} catch (Exception exp) {
errorText(exp.toString());
}
}
public void init()
{
buildGUI();
}
public void start()
{
}
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout());
Panel topPanel = new Panel();
Label titleLabel =
new Label("Text Boundary Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
topPanel.add(titleLabel);
//Label demo=new Label(creditString, Label.CENTER);
//demo.setFont(DemoUtility.creditFont);
//topPanel.add(demo);
Panel choicePanel = new Panel();
Label demo1=new Label("Boundaries", Label.LEFT);
demo1.setFont(DemoUtility.labelFont);
choicePanel.add(demo1);
bound = new Choice();
bound.setBackground(DemoUtility.choiceColor);
bound.addItem("Sentence");
bound.addItem("Line Break");
bound.addItem("Word");
bound.addItem("Char");
bound.addItemListener(this);
if (choiceFont != null)
bound.setFont(choiceFont);
choicePanel.add(bound);
topPanel.add(choicePanel);
DemoUtility.fixGrid(topPanel,1);
add("North", topPanel);
int ROWS = 15;
int COLUMNS = 50;
// text = new TextArea(getInitialText(), ROWS, COLUMNS);
text = new JTextArea(getInitialText(), ROWS, COLUMNS);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(true);
text.selectAll();
text.setFont(DemoUtility.editFont);
text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
add("Center", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright1, Label.LEFT),DemoUtility.creditFont);
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright2, Label.LEFT),DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add("South", copyrightPanel);
//layout();
handleEnumChanged();
enableEvents(WindowEvent.WINDOW_CLOSING);
enableEvents(KeyEvent.KEY_PRESSED);
enableEvents(KeyEvent.KEY_RELEASED);
// (new Thread(this)).start();
}
public String getInitialText()
{
return
"When,inthecourseofhumanevents,itbecomesnecessaryforonepeopletodissolvethepoliticalbondswhichhave"
+ "connectedthemwithanother,andtoassumeamongthepowersoftheearth,theseparateandequalstationtowhichthelaws"
+ "ofnatureandofnature'sGodentitlethem,adecentrespecttotheopinionsofmankindrequiresthattheyshoulddeclarethe"
+ "causeswhichimpelthemtotheseparation.\n"
+ "Weholdthesetruthstobeself-evident,thatallmenarecreatedequal,thattheyareendowedbytheirCreatorwithcertain"
+ "unalienablerights,thatamongthesearelife,libertyandthepursuitofhappiness.Thattosecuretheserights,governmentsare"
+ "institutedamongmen,derivingtheirjustpowersfromtheconsentofthegoverned.Thatwheneveranyformofgovernment"
+ "becomesdestructivetotheseends,itistherightofthepeopletoalterortoabolishit,andtoinstitutenewgovernment,laying"
+ "itsfoundationonsuchprinciplesandorganizingitspowersinsuchform,astothemshallseemmostlikelytoeffecttheirsafety"
+ "andhappiness.Prudence,indeed,willdictatethatgovernmentslongestablishedshouldnotbechangedforlightandtransient"
+ "causes;andaccordinglyallexperiencehathshownthatmankindaremoredisposedtosuffer,whileevilsaresufferable,than"
+ "torightthemselvesbyabolishingtheformstowhichtheyareaccustomed.Butwhenalongtrainofabusesandusurpations,"
+ "pursuinginvariablythesameobjectevincesadesigntoreducethemunderabsolutedespotism,itistheirright,itistheirduty,"
+ "tothrowoffsuchgovernment,andtoprovidenewguardsfortheirfuturesecurity.--Suchhasbeenthepatientsufferanceof"
+ "thesecolonies;andsuchisnowthenecessitywhichconstrainsthemtoaltertheirformersystemsofgovernment.Thehistory"
+ "ofthepresentKingofGreatBritainisahistoryofrepeatedinjuriesandusurpations,allhavingindirectobjectthe"
+ "establishmentofanabsolutetyrannyoverthesestates.Toprovethis,letfactsbesubmittedtoacandidworld.\n"
+ "Hehasrefusedhisassenttolaws,themostwholesomeandnecessaryforthepublicgood.\n"
+ "Hehasforbiddenhisgovernorstopasslawsofimmediateandpressingimportance,unlesssuspendedintheiroperationtill"
+ "hisassentshouldbeobtained;andwhensosuspended,hehasutterlyneglectedtoattendtothem.\n"
+ "Hehasrefusedtopassotherlawsfortheaccommodationoflargedistrictsofpeople,unlessthosepeoplewouldrelinquish"
+ "therightofrepresentationinthelegislature,arightinestimabletothemandformidabletotyrantsonly.\n"
+ "Hehascalledtogetherlegislativebodiesatplacesunusual,uncomfortable,anddistantfromthedepositoryoftheirpublic"
+ "records,forthesolepurposeoffatiguingthemintocompliancewithhismeasures.\n"
+ "Hehasdissolvedrepresentativehousesrepeatedly,foropposingwithmanlyfirmnesshisinvasionsontherightsofthepeople.\n"
+ "Hehasrefusedforalongtime,aftersuchdissolutions,tocauseotherstobeelected;wherebythelegislativepowers,"
+ "incapableofannihilation,havereturnedtothepeopleatlargefortheirexercise;thestateremaininginthemeantimeexposed"
+ "toallthedangersofinvasionfromwithout,andconvulsionswithin.\n"
+ "Hehasendeavoredtopreventthepopulationofthesestates;forthatpurposeobstructingthelawsfornaturalizationof"
+ "foreigners;refusingtopassotherstoencouragetheirmigrationhither,andraisingtheconditionsofnewappropriationsof"
+ "lands.\n"
+ "Hehasobstructedtheadministrationofjustice,byrefusinghisassenttolawsforestablishingjudiciarypowers.\n"
+ "Hehasmadejudgesdependentonhiswillalone,forthetenureoftheiroffices,andtheamountandpaymentoftheirsalaries.\n"
+ "Hehaserectedamultitudeofnewoffices,andsenthitherswarmsofofficerstoharassourpeople,andeatouttheir"
+ "substance.\n"
+ "Hehaskeptamongus,intimesofpeace,standingarmieswithouttheconsentofourlegislature.\n"
+ "Hehasaffectedtorenderthemilitaryindependentofandsuperiortocivilpower.\n"
+ "Hehascombinedwithotherstosubjectustoajurisdictionforeigntoourconstitution,andunacknowledgedbyourlaws;"
+ "givinghisassenttotheiractsofpretendedlegislation:\n"
+ "Forquarteringlargebodiesofarmedtroopsamongus:\n"
+ "Forprotectingthem,bymocktrial,frompunishmentforanymurderswhichtheyshouldcommitontheinhabitantsofthese"
+ "states:\n"
+ "Forcuttingoffourtradewithallpartsoftheworld:\n"
+ "Forimposingtaxesonuswithoutourconsent:\n"
+ "Fordeprivingusinmanycases,ofthebenefitsoftrialbyjury:\n"
+ "Fortransportingusbeyondseastobetriedforpretendedoffenses:\n"
+ "ForabolishingthefreesystemofEnglishlawsinaneighboringprovince,establishingthereinanarbitrarygovernment,and"
+ "enlargingitsboundariessoastorenderitatonceanexampleandfitinstrumentforintroducingthesameabsoluteruleinthese"
+ "colonies:\n"
+ "Fortakingawayourcharters,abolishingourmostvaluablelaws,andalteringfundamentallytheformsofourgovernments:\n"
+ "Forsuspendingourownlegislatures,anddeclaringthemselvesinvestedwithpowertolegislateforusinallcaseswhatsoever.\n"
+ "Hehasabdicatedgovernmenthere,bydeclaringusoutofhisprotectionandwagingwaragainstus.\n"
+ "Hehasplunderedourseas,ravagedourcoasts,burnedourtowns,anddestroyedthelivesofourpeople.\n"
+ "Heisatthistimetransportinglargearmiesofforeignmercenariestocompletetheworksofdeath,desolationandtyranny,"
+ "alreadybegunwithcircumstancesofcrueltyandperfidyscarcelyparalleledinthemostbarbarousages,andtotallyunworthy"
+ "theheadofacivilizednation.\n"
+ "Hehasconstrainedourfellowcitizenstakencaptiveonthehighseastobeararmsagainsttheircountry,tobecomethe"
+ "executionersoftheirfriendsandbrethren,ortofallthemselvesbytheirhands.\n"
+ "Hehasexciteddomesticinsurrectionsamongstus,andhasendeavoredtobringontheinhabitantsofourfrontiers,the"
+ "mercilessIndiansavages,whoseknownruleofwarfare,isundistinguisheddestructionofallages,sexesandconditions.\n"
+ "Ineverystageoftheseoppressionswehavepetitionedforredressinthemosthumbleterms:ourrepeatedpetitionshave"
+ "beenansweredonlybyrepeatedinjury.Aprince,whosecharacteristhusmarkedbyeveryactwhichmaydefineatyrant,is"
+ "unfittobetherulerofafreepeople.\n"
+ "NorhavewebeenwantinginattentiontoourBritishbrethren.Wehavewarnedthemfromtimetotimeofattemptsbytheir"
+ "legislaturetoextendanunwarrantablejurisdictionoverus.Wehaveremindedthemofthecircumstancesofouremigration"
+ "andsettlementhere.Wehaveappealedtotheirnativejusticeandmagnanimity,andwehaveconjuredthembythetiesofour"
+ "commonkindredtodisavowtheseusurpations,which,wouldinevitablyinterruptourconnectionsandcorrespondence.We"
+ "must,therefore,acquiesceinthenecessity,whichdenouncesourseparation,andholdthem,asweholdtherestofmankind,"
+ "enemiesinwar,inpeacefriends.\n"
+ "We,therefore,therepresentativesoftheUnitedStatesofAmerica,inGeneralCongress,assembled,appealingtothe"
+ "SupremeJudgeoftheworldfortherectitudeofourintentions,do,inthename,andbytheauthorityofthegoodpeopleof"
+ "thesecolonies,solemnlypublishanddeclare,thattheseunitedcoloniesare,andofrightoughttobefreeandindependent"
+ "states;thattheyareabsolvedfromallallegiancetotheBritishCrown,andthatallpoliticalconnectionbetweenthemandthe"
+ "stateofGreatBritain,isandoughttobetotallydissolved;andthatasfreeandindependentstates,theyhavefullpowerto"
+ "leveywar,concludepeace,contractalliances,establishcommerce,andtodoallotheractsandthingswhichindependent"
+ "statesmayofrightdo.Andforthesupportofthisdeclaration,withafirmrelianceontheprotectionofDivineProvidence,we"
+ "mutuallypledgetoeachotherourlives,ourfortunesandoursacredhonor.\n";
}
public void handleEnumChanged()
{
String s = bound.getSelectedItem();
if (s.equals("Char")) {
errorText("getCharacterInstance");
enum = BreakIterator.getCharacterInstance();
}
else if (s.equals("Word")) {
errorText("getWordInstance");
enum = BreakIterator.getWordInstance();
}
else if (s.equals("Line Break")) {
errorText("getLineInstance");
enum = BreakIterator.getLineInstance();
}
else /* if (s.equals("Sentence")) */ {
errorText("getSentenceInstance");
enum = BreakIterator.getSentenceInstance();
}
enum.setText(text.getText());
selectRange(0, 0);
//text.select(0,0);
}
public void handleForward()
{
try {
// System.out.println("entering handleForward");
enum.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
// System.out.println("handleForward: oldStart=" + oldStart + ", oldEnd=" + oldEnd);
if (oldEnd < 1) {
selectRange(0, enum.following(0));
}
else {
int s = enum.following(oldEnd-1);
int e = enum.next();
if (e == -1) {
e = s;
}
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" +
s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void handleBackward()
{
try {
enum.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
if (oldStart < 1) {
selectRange(0, 0);
}
else {
int e = enum.following(oldStart-1);
int s = enum.previous();
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" + s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void itemStateChanged(ItemEvent evt)
{
if (evt.getSource() instanceof Choice) {
handleEnumChanged();
}
}
public void errorText(String s)
{
if (DEBUG)
System.out.println(s);
}
protected void processWindowEvent(WindowEvent evt)
{
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getWindow() == this) {
hide();
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
protected void processKeyEvent(KeyEvent evt)
{
switch (evt.getID()) {
case KeyEvent.KEY_PRESSED :
if (evt.getKeyCode() == KeyEvent.VK_CONTROL) {
isctrldown_ = true;
}
break;
case KeyEvent.KEY_RELEASED :
// key detection for left and right buttons are removed
// to emulate the old release behaviour
int key = evt.getKeyCode();
if (key == KeyEvent.VK_N && isctrldown_) {
handleForward();
}
else
if (key == KeyEvent.VK_P && isctrldown_) {
handleBackward();
}
else
if (key == KeyEvent.VK_CONTROL) {
isctrldown_ = false;
}
break;
}
}
}

View File

@ -1,454 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/rbbi/Attic/RBBIDemo.java,v $
* $Date: 2001/11/12 23:44:44 $
* $Revision: 1.4 $
*
*****************************************************************************************
*/
package com.ibm.demo.rbbi;
import com.ibm.demo.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.KeyEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import java.util.*;
import com.ibm.text.BreakIterator;
public class RBBIDemo extends DemoApplet
{
public static void main(String argv[]) {
Locale.setDefault(new Locale("en", "US"));
new RBBIDemo().showDemo();
}
public Frame createDemoFrame(DemoApplet applet) {
return new RBBIFrame(applet);
}
}
class RBBIFrame extends Frame implements ItemListener
{
private static final String creditString =
"v1.1a9, Demo";
private static final int FIELD_COLUMNS = 45;
private static final Font choiceFont = null;
private static final boolean DEBUG = false;
private DemoApplet applet;
final String right = "-->";
final String left = "<--";
private BreakIterator enum;
private boolean isctrldown_ = false;
JTextArea text;
// TextArea text;
Choice bound;
public RBBIFrame(DemoApplet applet)
{
this.applet = applet;
init();
start();
}
public void run()
{
/*
while (true) {
try {
checkChange();
Thread.sleep(250);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
catch (Throwable e) {
}
}
*/
}
int s, e;
int ts, te;
public void checkChange()
{
// System.out.println("checkChange...");
if ((text.getSelectionStart() & 0x7FFF) != ts ||
(text.getSelectionEnd() & 0x7FFF) != te) {
// not used int tempS = text.getSelectionStart() & 0x7FFF;
// not used int tempE = text.getSelectionEnd() & 0x7FFF;
// System.out.println(">");
// select(0, 0);
// select(tempS, tempE);
//select(tempS - (ts - s), tempE - (te - e));
// System.out.println("<");
// if (s != ts || e != te) System.out.println(" s("+s+") ts("+ts+") e("+e+") te("+te+")");
// if (tempS != ts || tempE != te) System.out.println(">s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// select(s - (ts - s), e - (te - e));
// if (tempS != ts || tempE != te) System.out.println("s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// System.out.println("lkdslksj");
}
}
public void select(int sIn, int eIn)
{
s = sIn;
e = eIn;
text.select(s, e);
ts = text.getSelectionStart() & 0x7FFF;
te = text.getSelectionEnd() & 0x7FFF;
// if (s != ts || e != te) {
// System.out.println(">s("+s+") ts("+ts+") e("+e+") te("+te+")");
// System.out.println(" "+(ts-s)+","+(te-e));
// }
}
public int getSelectionStart()
{
checkChange();
// return s;
return text.getSelectionStart() & 0x7FFF;
}
public int getSelectionEnd()
{
checkChange();
// return e;
return text.getSelectionEnd() & 0x7FFF;
}
public final synchronized void selectRange(int s, int e)
{
try {
//if (getSelectionStart() != s || getSelectionEnd() != e) {
//text.select(s, e);
select(s,e);
//}
// if (getSelectionStart() != s || getSelectionEnd() != e) {
// System.out.println("AGH! select("+s+","+e+") -> ("+
// getSelectionStart()+","+getSelectionEnd()+")");
// text.select(s - (getSelectionStart() - s), e - (getSelectionEnd() - e));
// }
} catch (Exception exp) {
errorText(exp.toString());
}
}
public void init()
{
buildGUI();
}
public void start()
{
}
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout());
Panel topPanel = new Panel();
Label titleLabel =
new Label("Deva Text Boundary Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
topPanel.add(titleLabel);
//Label demo=new Label(creditString, Label.CENTER);
//demo.setFont(DemoUtility.creditFont);
//topPanel.add(demo);
Panel choicePanel = new Panel();
Label demo1=new Label("Boundaries", Label.LEFT);
demo1.setFont(DemoUtility.labelFont);
choicePanel.add(demo1);
bound = new Choice();
bound.setBackground(DemoUtility.choiceColor);
bound.addItem("Sentence");
bound.addItem("Line Break");
bound.addItem("Word");
bound.addItem("Char");
bound.addItemListener(this);
if (choiceFont != null)
bound.setFont(choiceFont);
choicePanel.add(bound);
topPanel.add(choicePanel);
DemoUtility.fixGrid(topPanel,1);
add("North", topPanel);
int ROWS = 15;
int COLUMNS = 50;
// text = new TextArea(getInitialText(), ROWS, COLUMNS);
text = new JTextArea(getInitialText(), ROWS, COLUMNS);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(true);
text.selectAll();
text.setFont(new Font("Devanagari MT for IBM", Font.PLAIN, 48));
text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
add("Center", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright1, Label.LEFT),DemoUtility.creditFont);
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright2, Label.LEFT),DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add("South", copyrightPanel);
//layout();
handleEnumChanged();
enableEvents(WindowEvent.WINDOW_CLOSING);
enableEvents(KeyEvent.KEY_PRESSED);
enableEvents(KeyEvent.KEY_RELEASED);
// (new Thread(this)).start();
}
public String getInitialText()
{
return
"\u0936\u094d\u0930\u0940\u092e\u0926\u094d " +
"\u092d\u0917\u0935\u0926\u094d\u0917\u0940\u0924\u093e " +
"\u0905\u0927\u094d\u092f\u093e\u092f " +
"\u0905\u0930\u094d\u091c\u0941\u0928 " +
"\u0935\u093f\u0937\u093e\u0926 " +
"\u092f\u094b\u0917 " +
"\u0927\u0943\u0924\u0930\u093e\u0937\u094d\u091f\u094d\u0930 " +
"\u0909\u0935\u093E\u091A\u0943 " +
"\u0927\u0930\u094d\u092e\u0915\u094d\u0937\u0947\u0924\u094d\u0930\u0947 " +
"\u0915\u0941\u0930\u0941\u0915\u094d\u0937\u0947\u0924\u094d\u0930\u0947 " +
"\u0938\u092e\u0935\u0947\u0924\u093e " +
"\u092f\u0941\u092f\u0941\u0924\u094d\u0938\u0935\u0903 " +
"\u092e\u093e\u092e\u0915\u093e\u0903 " +
"\u092a\u093e\u0923\u094d\u0921\u0935\u093e\u0936\u094d\u091a\u0948\u0935 " +
"\u0915\u093f\u092e\u0915\u0941\u0930\u094d\u0935\u0924 " +
"\u0938\u0902\u091c\u0935";
}
public void handleEnumChanged()
{
String s = bound.getSelectedItem();
if (s.equals("Char")) {
errorText("getCharacterInstance");
enum = BreakIterator.getCharacterInstance();
}
else if (s.equals("Word")) {
errorText("tWordBreak");
enum = BreakIterator.getWordInstance();
}
else if (s.equals("Line Break")) {
errorText("getLineInstance");
enum = BreakIterator.getLineInstance();
}
else /* if (s.equals("Sentence")) */ {
errorText("getSentenceInstance");
enum = BreakIterator.getSentenceInstance();
}
enum.setText(text.getText());
selectRange(0, 0);
//text.select(0,0);
}
public void handleForward()
{
try {
// System.out.println("entering handleForward");
enum.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
// System.out.println("handleForward: oldStart=" + oldStart + ", oldEnd=" + oldEnd);
if (oldEnd < 1) {
selectRange(0, enum.following(0));
}
else {
int s = enum.following(oldEnd-1);
int e = enum.next();
if (e == -1) {
e = s;
}
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" +
s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void handleBackward()
{
try {
enum.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
if (oldStart < 1) {
selectRange(0, 0);
}
else {
int e = enum.following(oldStart-1);
int s = enum.previous();
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" + s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
/*
public boolean action(Event evt, Object obj)
{
if(evt.target instanceof Button && left.equals(obj))
{
handleBackward();
return true;
}
else if(evt.target instanceof Button && right.equals(obj))
{
handleForward();
return true;
}
else if(evt.target instanceof Choice)
{
handleEnumChanged();
return true;
}
return false;
}
public boolean handleEvent(Event evt)
{
if (evt.id == Event.KEY_PRESS || evt.id == Event.KEY_ACTION) {
if (evt.key == Event.RIGHT || (evt.key == 0x0E && evt.controlDown())) {
handleForward();
return true;
}
else if (evt.key == Event.LEFT || (evt.key == 0x10 && evt.controlDown())) {
handleBackward();
return true;
}
}
else
if (evt.id == Event.WINDOW_DESTROY && evt.target == this) {
this.hide();
this.dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
return true;
}
return super.handleEvent(evt);
}*/
public void itemStateChanged(ItemEvent evt)
{
if (evt.getSource() instanceof Choice) {
handleEnumChanged();
}
}
public void errorText(String s)
{
if (DEBUG)
System.out.println(s);
}
protected void processWindowEvent(WindowEvent evt)
{
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getWindow() == this) {
hide();
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
protected void processKeyEvent(KeyEvent evt)
{
switch (evt.getID()) {
case KeyEvent.KEY_PRESSED :
if (evt.getKeyCode() == KeyEvent.VK_CONTROL) {
isctrldown_ = true;
}
break;
case KeyEvent.KEY_RELEASED :
// key detection for left and right buttons are removed
// to emulate the old release behaviour
int key = evt.getKeyCode();
if (key == KeyEvent.VK_N && isctrldown_) {
handleForward();
}
else
if (key == KeyEvent.VK_P && isctrldown_) {
handleBackward();
}
else
if (key == KeyEvent.VK_CONTROL) {
isctrldown_ = false;
}
break;
}
}
}

View File

@ -1,435 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/rbbi/Attic/TextBoundDemo.java,v $
* $Date: 2001/11/12 23:44:44 $
* $Revision: 1.6 $
*
*****************************************************************************************
*/
package com.ibm.demo.rbbi;
import com.ibm.demo.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import java.util.*;
import com.ibm.text.BreakIterator;
public class TextBoundDemo extends DemoApplet
{
public static void main(String argv[]) {
new TextBoundDemo().showDemo();
}
public Frame createDemoFrame(DemoApplet applet) {
return new TextBoundFrame(applet);
}
}
class TextBoundFrame extends Frame implements ItemListener
{
private static final String creditString =
"v1.1a9, Demo";
private static final int FIELD_COLUMNS = 45;
private static final Font choiceFont = null;
private static final boolean DEBUG = false;
private DemoApplet applet;
final String right = "-->";
final String left = "<--";
private BreakIterator enum;
private boolean isctrldown_ = false;
JTextArea text;
// TextArea text;
Choice bound;
public TextBoundFrame(DemoApplet applet)
{
this.applet = applet;
init();
start();
}
public void run()
{
/*
while (true) {
try {
checkChange();
Thread.sleep(250);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
catch (Throwable e) {
}
}
*/
}
int s, e;
int ts, te;
public void checkChange()
{
// System.out.println("checkChange...");
if ((text.getSelectionStart() & 0x7FFF) != ts ||
(text.getSelectionEnd() & 0x7FFF) != te) {
// not used int tempS = text.getSelectionStart() & 0x7FFF;
// not used int tempE = text.getSelectionEnd() & 0x7FFF;
// System.out.println(">");
// select(0, 0);
// select(tempS, tempE);
//select(tempS - (ts - s), tempE - (te - e));
// System.out.println("<");
// if (s != ts || e != te) System.out.println(" s("+s+") ts("+ts+") e("+e+") te("+te+")");
// if (tempS != ts || tempE != te) System.out.println(">s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// select(s - (ts - s), e - (te - e));
// if (tempS != ts || tempE != te) System.out.println("s("+s+") tempS("+tempS+") e("+e+") tempE("+tempE+")");
// System.out.println("lkdslksj");
}
}
public void select(int sIn, int eIn)
{
s = sIn;
e = eIn;
text.select(s, e);
ts = text.getSelectionStart() & 0x7FFF;
te = text.getSelectionEnd() & 0x7FFF;
// if (s != ts || e != te) {
// System.out.println(">s("+s+") ts("+ts+") e("+e+") te("+te+")");
// System.out.println(" "+(ts-s)+","+(te-e));
// }
}
public int getSelectionStart()
{
checkChange();
// return s;
return text.getSelectionStart() & 0x7FFF;
}
public int getSelectionEnd()
{
checkChange();
// return e;
return text.getSelectionEnd() & 0x7FFF;
}
public final synchronized void selectRange(int s, int e)
{
try {
//if (getSelectionStart() != s || getSelectionEnd() != e) {
//text.select(s, e);
select(s,e);
//}
// if (getSelectionStart() != s || getSelectionEnd() != e) {
// System.out.println("AGH! select("+s+","+e+") -> ("+
// getSelectionStart()+","+getSelectionEnd()+")");
// text.select(s - (getSelectionStart() - s), e - (getSelectionEnd() - e));
// }
} catch (Exception exp) {
errorText(exp.toString());
}
}
public void init()
{
buildGUI();
}
public void start()
{
}
void addWithFont(Container container, Component foo, Font font) {
if (font != null)
foo.setFont(font);
container.add(foo);
}
public void buildGUI()
{
setBackground(DemoUtility.bgColor);
setLayout(new BorderLayout());
Panel topPanel = new Panel();
Label titleLabel =
new Label("Text Boundary Demo", Label.CENTER);
titleLabel.setFont(DemoUtility.titleFont);
topPanel.add(titleLabel);
//Label demo=new Label(creditString, Label.CENTER);
//demo.setFont(DemoUtility.creditFont);
//topPanel.add(demo);
Panel choicePanel = new Panel();
Label demo1=new Label("Boundaries", Label.LEFT);
demo1.setFont(DemoUtility.labelFont);
choicePanel.add(demo1);
bound = new Choice();
bound.setBackground(DemoUtility.choiceColor);
bound.addItem("Sentence");
bound.addItem("Line Break");
bound.addItem("Word");
bound.addItem("Char");
bound.addItemListener(this);
if (choiceFont != null)
bound.setFont(choiceFont);
choicePanel.add(bound);
topPanel.add(choicePanel);
DemoUtility.fixGrid(topPanel,1);
add("North", topPanel);
int ROWS = 15;
int COLUMNS = 50;
// text = new TextArea(getInitialText(), ROWS, COLUMNS);
text = new JTextArea(getInitialText(), ROWS, COLUMNS);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setEditable(true);
text.selectAll();
text.setFont(DemoUtility.editFont);
text.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
add("Center", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
Panel copyrightPanel = new Panel();
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright1, Label.LEFT),DemoUtility.creditFont);
addWithFont (copyrightPanel,
new Label(DemoUtility.copyright2, Label.LEFT),DemoUtility.creditFont);
DemoUtility.fixGrid(copyrightPanel,1);
add("South", copyrightPanel);
//layout();
handleEnumChanged();
enableEvents(WindowEvent.WINDOW_CLOSING);
enableEvents(KeyEvent.KEY_PRESSED);
enableEvents(KeyEvent.KEY_RELEASED);
// (new Thread(this)).start();
}
public String getInitialText()
{
return
/*
"\"This is a sentence.\" This is not.\" \"because. And go. " +
"This is a simple 012.566,5 sample sentence. \n"+
"It does not have to make any sense as you can see. \n"+
"Nel mezzo del cammin di nostra vita, mi ritrovai in "+
"una selva oscura. \n"+
"Che la dritta via aveo smarrita. \n"+
"He said, that I said, that you said!! \n"+
"Don't rock the boat.\n\n"+
"Because I am the daddy, that is why. \n"+
"Not on my time (el timo.)! \n"+
"Tab\tTab\rTab\tWow."+
"So what!!\n\n"+
"Is this a question??? " +
"I wonder...Hmm.\n" +
"Harris thumbed down several, including \"Away We Go\" "+
"(which became the huge success Oklahoma!). \n"+
"One species, B. anthracis, is highly virulent.\n"+
"Wolf said about Sounder: \"Beautifully thought-out and "+
"directed.\"\n"+
"Have you ever said, \"This is where I shall live\"? \n"+
"He 1000,233,456.000 answered, \"You may not!\" \n"+
"Another popular saying is: \"How do you do?\". \n"+
"What is the proper use of the abbreviation pp.? \n"+
"Yes, I am 1,23.322% definatelly 12\" tall!!";
*/
"(\"This is a complete sentence.\") This is (\"not.\") also. "
+"An abbreviation in the middle, etc. and one at the end, etc. "+
"This "
+"is a simple sample 012.566,5 sentence. It doesn't "
+"have to make any sense, as you can see. Nel mezzo del c"
+"ammin di nostra vita, mi ritrovai in una selva oscura. Che "
+"la dritta via aveo smarrita. Not on my time (el timo.)! And "
+"tabulated columns: \tCol1\tCol2\t3,456%.\t "
+"Is this a question??? I wonder... Hmm. Harris thumbed "
+"down several, including \"Away We Go\" (which became the "
+"huge success Oklahoma!). One species, B. anthracis, is "
+"highly virulent. Wolf said about Sounder: \"Beautifully "
+"thought-out and directed.\" Have you ever said, \"This is "+
"where I "
+"shall live\"? He said 1000,233,456.000 and answered, \"You "+
"may not!\" "
+"Another popular saying is: \"How do you do?\". What is the "
+"proper use of the abbreviation pp.? Yes, I am 12\' 3\" tall!!";
}
public void handleEnumChanged()
{
String s = bound.getSelectedItem();
if (s.equals("Char")) {
errorText("getCharacterInstance");
enum = BreakIterator.getCharacterInstance();
}
else if (s.equals("Word")) {
errorText("tWordBreak");
enum = BreakIterator.getWordInstance();
}
else if (s.equals("Line Break")) {
errorText("getLineInstance");
enum = BreakIterator.getLineInstance();
}
else /* if (s.equals("Sentence")) */ {
errorText("getSentenceInstance");
enum = BreakIterator.getSentenceInstance();
}
enum.setText(text.getText());
selectRange(0, 0);
//text.select(0,0);
}
public void handleForward()
{
try {
// System.out.println("entering handleForward");
enum.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
// System.out.println("handleForward: oldStart=" + oldStart + ", oldEnd=" + oldEnd);
if (oldEnd < 1) {
selectRange(0, enum.following(0));
}
else {
int s = enum.following(oldEnd-1);
int e = enum.next();
if (e == -1) {
e = s;
}
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" +
s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void handleBackward()
{
try {
enum.setText(text.getText());
int oldStart = getSelectionStart();
int oldEnd = getSelectionEnd();
if (oldStart < 1) {
selectRange(0, 0);
}
else {
int e = enum.following(oldStart-1);
int s = enum.previous();
selectRange(s, e);
}
//text.select(s, e);
errorText("<" + oldStart + "," + oldEnd + "> -> <" + s + "," + e + ">");
}
catch (Exception exp) {
errorText(exp.toString());
}
}
public void itemStateChanged(ItemEvent evt)
{
if (evt.getSource() instanceof Choice) {
handleEnumChanged();
}
}
public void errorText(String s)
{
if (DEBUG)
System.out.println(s);
}
protected void processWindowEvent(WindowEvent evt)
{
if (evt.getID() == WindowEvent.WINDOW_CLOSING &&
evt.getWindow() == this) {
hide();
dispose();
if (applet != null) {
applet.demoClosed();
} else System.exit(0);
}
}
protected void processKeyEvent(KeyEvent evt)
{
switch (evt.getID()) {
case KeyEvent.KEY_PRESSED :
if (evt.getKeyCode() == KeyEvent.VK_CONTROL) {
isctrldown_ = true;
}
break;
case KeyEvent.KEY_RELEASED :
// key detection for left and right buttons are removed
// to emulate the old release behaviour
int key = evt.getKeyCode();
if (key == KeyEvent.VK_N && isctrldown_) {
handleForward();
}
else
if (key == KeyEvent.VK_P && isctrldown_) {
handleBackward();
}
else
if (key == KeyEvent.VK_CONTROL) {
isctrldown_ = false;
}
break;
}
}
}

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/rbbi/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 17:43:53 $
-->
</head>
<body bgcolor="white">
RuleBasedBreakIterator and DictionaryBasedBreakIterator demo applications.
</body>
</html>

View File

@ -1,533 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/rbnf/Attic/RbnfDemo.java,v $
* $Date: 2000/03/10 03:47:43 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
package com.ibm.demo.rbnf;
import com.ibm.demo.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.text.BreakIterator;
import java.text.ParsePosition;
import java.util.Locale;
import com.ibm.text.RuleBasedNumberFormat;
public class RbnfDemo extends DemoApplet {
/**
* Puts a copyright in the .class file
*/
private static final String copyrightNotice
= "Copyright \u00a91997-1998 IBM Corp. All rights reserved.";
/*
* code to run the demo as an application
*/
public static void main(String[] argv) {
new RbnfDemo().showDemo();
}
protected Dimension getDefaultFrameSize(DemoApplet applet, Frame f) {
return new Dimension(430,270);
}
protected Frame createDemoFrame(DemoApplet applet) {
final Frame window = new Frame("Number Spellout Demo");
window.setSize(800, 600);
window.setLayout(new BorderLayout());
Panel mainPanel = new Panel();
mainPanel.setLayout(new GridLayout(1,2));
commentaryField = new TextArea("", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY);
commentaryField.setSize(800, 50);
commentaryField.setText(RbnfSampleRuleSets.sampleRuleSetCommentary[0]);
commentaryField.setEditable(false);
commentaryField.setFont(new Font("Helvetica", Font.PLAIN, 14));
spelloutFormatter = new RuleBasedNumberFormat(RbnfSampleRuleSets.usEnglish, Locale.US);
spelloutFormatter.setLenientParseMode(lenientParse);
populateRuleSetMenu();
numberFormatter = new DecimalFormat("#,##0.##########");
parsePosition = new ParsePosition(0);
theNumber = 0;
numberField = new TextField();
numberField.setFont(new Font("Serif", Font.PLAIN, 24));
textField = new DemoTextFieldHolder();
textField.setFont(new Font("Serif", Font.PLAIN, 24));
rulesField = new DemoTextFieldHolder();
rulesField.setFont(new Font("Serif", Font.PLAIN, 14));
lenientParseButton = new Checkbox("Lenient parse", lenientParse);
numberField.addTextListener(new TextListener() {
public void textValueChanged(TextEvent e) {
if (!numberFieldHasFocus)
return;
String fieldText = ((TextComponent)(e.getSource())).getText();
parsePosition.setIndex(0);
Number temp = numberFormatter.parse(fieldText, parsePosition);
if (temp == null || parsePosition.getIndex() == 0) {
theNumber = 0;
textField.setText("PARSE ERROR");
}
else {
theNumber = temp.doubleValue();
textField.setText(spelloutFormatter.format(theNumber, ruleSetName));
}
}
} );
numberField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
numberFieldHasFocus = false;
numberField.setText(numberFormatter.format(theNumber));
}
public void focusGained(FocusEvent e) {
numberFieldHasFocus = true;
numberField.selectAll();
}
} );
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\t') {
String fieldText = ((TextComponent)(e.getSource())).getText();
parsePosition.setIndex(0);
theNumber = spelloutFormatter.parse(fieldText, parsePosition)
.doubleValue();
if (parsePosition.getIndex() == 0) {
theNumber = 0;
numberField.setText("PARSE ERROR");
textField.selectAll();
}
else if (parsePosition.getIndex() < fieldText.length()) {
textField.select(parsePosition.getIndex(), fieldText.length());
numberField.setText(numberFormatter.format(theNumber));
}
else {
textField.selectAll();
numberField.setText(numberFormatter.format(theNumber));
}
e.consume();
}
}
} );
textField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
String fieldText = ((TextComponent)(e.getSource())).getText();
parsePosition.setIndex(0);
theNumber = spelloutFormatter.parse(fieldText, parsePosition)
.doubleValue();
if (parsePosition.getIndex() == 0)
numberField.setText("PARSE ERROR");
else
numberField.setText(numberFormatter.format(theNumber));
textField.setText(textField.getText()); // textField.repaint() didn't work right
}
public void focusGained(FocusEvent e) {
textField.selectAll();
}
} );
rulesField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\t') {
String fieldText = ((TextComponent)(e.getSource())).getText();
if (formatterMenu.getSelectedItem().equals("Custom") || !fieldText.equals(
RbnfSampleRuleSets.sampleRuleSets[formatterMenu.getSelectedIndex()])) {
try {
RuleBasedNumberFormat temp = new RuleBasedNumberFormat(fieldText);
temp.setLenientParseMode(lenientParse);
populateRuleSetMenu();
spelloutFormatter = temp;
customRuleSet = fieldText;
formatterMenu.select("Custom");
commentaryField.setText(RbnfSampleRuleSets.
sampleRuleSetCommentary[RbnfSampleRuleSets.
sampleRuleSetCommentary.length - 1]);
redisplay();
}
catch (Exception x) {
textField.setText(x.toString());
}
}
e.consume();
}
}
} );
rulesField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
String fieldText = ((TextComponent)(e.getSource())).getText();
if (formatterMenu.getSelectedItem().equals("Custom") || !fieldText.equals(
RbnfSampleRuleSets.sampleRuleSets[formatterMenu.getSelectedIndex()])) {
try {
RuleBasedNumberFormat temp = new RuleBasedNumberFormat(fieldText);
temp.setLenientParseMode(lenientParse);
populateRuleSetMenu();
spelloutFormatter = temp;
customRuleSet = fieldText;
formatterMenu.select("Custom");
redisplay();
}
catch (Exception x) {
textField.setText(x.toString());
}
}
rulesField.setText(rulesField.getText()); // rulesField.repaint() didn't work right
}
} );
lenientParseButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
lenientParse = lenientParseButton.getState();
spelloutFormatter.setLenientParseMode(lenientParse);
}
} );
numberField.setText(numberFormatter.format(theNumber));
numberField.selectAll();
textField.setText(spelloutFormatter.format(theNumber, ruleSetName));
Panel leftPanel = new Panel();
leftPanel.setLayout(new BorderLayout());
Panel panel = new Panel();
panel.setLayout(new BorderLayout());
Panel panel1 = new Panel();
panel1.setLayout(new GridLayout(3, 1));
panel1.add(new Panel());
panel1.add(numberField, "Center");
panel1.add(lenientParseButton);
panel.add(panel1, "Center");
Panel panel2 = new Panel();
panel2.setLayout(new GridLayout(3, 3));
Button button = new Button("+100");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(100);
}
} );
panel2.add(button);
button = new Button("+10");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(10);
}
} );
panel2.add(button);
button = new Button("+1");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(1);
}
} );
panel2.add(button);
button = new Button("<");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
theNumber *= 10;
redisplay();
}
} );
panel2.add(button);
panel2.add(new Panel());
button = new Button(">");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
theNumber /= 10;
redisplay();
}
} );
panel2.add(button);
button = new Button("-100");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(-100);
}
} );
panel2.add(button);
button = new Button("-10");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(-10);
}
} );
panel2.add(button);
button = new Button("-1");
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
roll(-1);
}
} );
panel2.add(button);
panel.add(panel2, "East");
leftPanel.add(panel, "North");
leftPanel.add(textField, "Center");
Panel rightPanel = new Panel();
rightPanel.setLayout(new BorderLayout());
formatterMenu = new Choice();
for (int i = 0; i < RbnfSampleRuleSets.sampleRuleSetNames.length; i++)
formatterMenu.addItem(RbnfSampleRuleSets.sampleRuleSetNames[i]);
formatterMenu.addItem("Custom");
formatterMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Choice source = (Choice)(e.getSource());
int item = source.getSelectedIndex();
Locale locale = RbnfSampleRuleSets.sampleRuleSetLocales[item];
commentaryField.setText(RbnfSampleRuleSets.
sampleRuleSetCommentary[item]);
if (locale != null && (locale.getLanguage().equals("iw")
|| locale.getLanguage().equals("ru") || locale.getLanguage().equals("ja")
|| locale.getLanguage().equals("el")
|| locale.getLanguage().equals("zh"))) {
textField.togglePanes(false);
rulesField.togglePanes(false);
}
else {
textField.togglePanes(true);
rulesField.togglePanes(true);
}
makeNewSpelloutFormatter();
redisplay();
}
} );
ruleSetMenu = new Choice();
populateRuleSetMenu();
ruleSetMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
ruleSetName = ruleSetMenu.getSelectedItem();
redisplay();
}
} );
Panel menuPanel = new Panel();
menuPanel.setLayout(new GridLayout(1, 2));
menuPanel.add(formatterMenu);
menuPanel.add(ruleSetMenu);
rightPanel.add(menuPanel, "North");
rulesField.setText(RbnfSampleRuleSets.sampleRuleSets[formatterMenu.getSelectedIndex()]);
rightPanel.add(rulesField, "Center");
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
window.add(mainPanel, "Center");
window.add(commentaryField, "South");
window.doLayout();
window.show();
return window;
}
void roll(int delta) {
theNumber += delta;
redisplay();
}
void redisplay() {
numberField.setText(numberFormatter.format(theNumber));
textField.setText(spelloutFormatter.format(theNumber, ruleSetName));
}
void makeNewSpelloutFormatter() {
int item = formatterMenu.getSelectedIndex();
String formatterMenuItem = formatterMenu.getSelectedItem();
if (formatterMenuItem.equals("Custom")) {
rulesField.setText(customRuleSet);
spelloutFormatter = new RuleBasedNumberFormat(customRuleSet);
}
else {
rulesField.setText(RbnfSampleRuleSets.sampleRuleSets[item]);
Locale locale = RbnfSampleRuleSets.sampleRuleSetLocales[item];
if (locale == null)
locale = Locale.getDefault();
spelloutFormatter = new RuleBasedNumberFormat(RbnfSampleRuleSets.
sampleRuleSets[item], locale);
}
spelloutFormatter.setLenientParseMode(lenientParse);
populateRuleSetMenu();
}
void populateRuleSetMenu() {
String[] ruleSetNames = spelloutFormatter.getRuleSetNames();
if (ruleSetMenu != null) {
ruleSetMenu.removeAll();
for (int i = 0; i < ruleSetNames.length; i++)
ruleSetMenu.addItem(ruleSetNames[i]);
ruleSetName = ruleSetMenu.getSelectedItem();
}
else
ruleSetName = ruleSetNames[0];
}
private Frame demoWindow = null;
private TextComponent numberField;
private DemoTextFieldHolder textField;
private DemoTextFieldHolder rulesField;
private TextComponent commentaryField;
private Checkbox lenientParseButton;
private boolean numberFieldHasFocus = true;
private RuleBasedNumberFormat spelloutFormatter;
private DecimalFormat numberFormatter;
private ParsePosition parsePosition;
private boolean lenientParse = true;
private double theNumber = 0;
private boolean canEdit = true;
private Choice formatterMenu;
private Choice ruleSetMenu;
private String ruleSetName;
private String customRuleSet = "NO RULES!";
}
class DemoTextField extends Component {
public DemoTextField() {
}
public void setText(String text) {
this.text = text;
this.repaint();
}
public String getText() {
return text;
}
public void paint(Graphics g) {
Font font = getFont();
FontMetrics fm = g.getFontMetrics();
g.setFont(font);
String text = getText();
BreakIterator bi = BreakIterator.getLineInstance();
bi.setText(text);
int lineHeight = fm.getHeight();
int width = getSize().width;
int penY = fm.getAscent();
int lineStart = 0;
int tempLineEnd = bi.first();
int lineEnd = 0;
int maxLineEnd = 0;
totalHeight = 0;
while (lineStart < text.length()) {
maxLineEnd = text.indexOf('\n', lineStart);
if (maxLineEnd == -1)
maxLineEnd = Integer.MAX_VALUE;
while (tempLineEnd != BreakIterator.DONE && fm.stringWidth(text.substring(
lineStart, tempLineEnd)) < width) {
lineEnd = tempLineEnd;
tempLineEnd = bi.next();
}
if (lineStart >= lineEnd) {
if (tempLineEnd == BreakIterator.DONE)
lineEnd = text.length();
else
lineEnd = tempLineEnd;
}
if (lineEnd > maxLineEnd)
lineEnd = maxLineEnd;
g.drawString(text.substring(lineStart, lineEnd), 0, penY);
penY += lineHeight;
totalHeight += lineHeight;
lineStart = lineEnd;
if (lineStart < text.length() && text.charAt(lineStart) == '\n')
++lineStart;
}
}
/*
public Dimension getPreferredSize() {
Dimension size = getParent().getSize();
return new Dimension(size.width, totalHeight);
}
*/
private String text;
private int totalHeight;
}
class DemoTextFieldHolder extends Panel {
public DemoTextFieldHolder() {
tf1 = new TextArea("", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY);
tf2 = new DemoTextField();
sp = new ScrollPane();
setLayout(new CardLayout());
sp.add(tf2, "TextField1");
sp.setVisible(false);
add(tf1, "TestField2");
add(sp, "ScrollPane");
}
public void addFocusListener(FocusListener l) {
tf1.addFocusListener(l);
}
public void addKeyListener(KeyListener l) {
tf1.addKeyListener(l);
}
public void setText(String text) {
tf1.setText(text);
tf2.setText(text);
}
public String getText() {
return tf1.getText();
}
public void select(int start, int end) {
tf1.select(start, end);
}
public void selectAll() {
tf1.selectAll();
}
public void togglePanes(boolean canShowRealTextField) {
if (canShowRealTextField != showingRealTextField) {
CardLayout layout = (CardLayout)(getLayout());
layout.next(this);
showingRealTextField = canShowRealTextField;
}
}
private TextArea tf1 = null;
private DemoTextField tf2 = null;
private ScrollPane sp = null;
private boolean showingRealTextField = true;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/rbnf/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 17:44:02 $
-->
</head>
<body bgcolor="white">
RuleBasedNumberFormat demo appliation.
</body>
</html>

View File

@ -1,589 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/translit/Attic/Demo.java,v $
* $Date: 2001/11/29 17:28:38 $
* $Revision: 1.11 $
*
*****************************************************************************************
*/
package com.ibm.demo.translit;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import com.ibm.icu.demo.components.*;
import com.ibm.text.*;
/**
* A frame that allows the user to experiment with keyboard
* transliteration. This class has a main() method so it can be run
* as an application. The frame contains an editable text component
* and uses keyboard transliteration to process keyboard events.
*
* <p>Copyright (c) IBM Corporation 1999. All rights reserved.
*
* @author Alan Liu
* @version $RCSfile: Demo.java,v $ $Revision: 1.11 $ $Date: 2001/11/29 17:28:38 $
*/
public class Demo extends Frame {
static final boolean DEBUG = true;
Transliterator translit = null;
String fontName = "Arial Unicode MS";
int fontSize = 36;
/*
boolean compound = false;
Transliterator[] compoundTranslit = new Transliterator[MAX_COMPOUND];
static final int MAX_COMPOUND = 128;
int compoundCount = 0;
*/
TransliteratingTextComponent text = null;
Menu translitMenu;
CheckboxMenuItem translitItem;
CheckboxMenuItem noTranslitItem;
static final String NO_TRANSLITERATOR = "None";
private static final String COPYRIGHT =
"\u00A9 IBM Corporation 1999. All rights reserved.";
public static void main(String[] args) {
Frame f = new Demo(600, 200);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
public Demo(int width, int height) {
super("Transliteration Demo");
initMenus();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
handleClose();
}
});
text = new TransliteratingTextComponent();
Font font = new Font(fontName, Font.PLAIN, fontSize);
text.setFont(font);
text.setSize(width, height);
text.setVisible(true);
text.setText("\u03B1\u05D0\u3042\u4E80");
add(text);
setSize(width, height);
setTransliterator("Latin-Greek");
}
private void initMenus() {
MenuBar mbar;
Menu menu;
MenuItem mitem;
CheckboxMenuItem citem;
setMenuBar(mbar = new MenuBar());
mbar.add(menu = new Menu("File"));
menu.add(mitem = new MenuItem("Quit"));
mitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleClose();
}
});
/*
final ItemListener setTransliteratorListener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
CheckboxMenuItem item = (CheckboxMenuItem) e.getSource();
if (e.getStateChange() == ItemEvent.DESELECTED) {
// Don't let the current transliterator be deselected.
// Just reselect it.
item.setState(true);
} else if (compound) {
// Adding an item to a compound transliterator
handleAddToCompound(item.getLabel());
} else if (item != translitItem) {
// Deselect previous choice. Don't need to call
// setState(true) on new choice.
translitItem.setState(false);
translitItem = item;
handleSetTransliterator(item.getLabel());
}
}
};
*/
/*
translitMenu.add(translitItem = noTranslitItem =
new CheckboxMenuItem(NO_TRANSLITERATOR, true));
noTranslitItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
// Can't uncheck None -- any action here sets None to true
setNoTransliterator();
}
});
translitMenu.addSeparator();
*/
/*
translitMenu.add(citem = new CheckboxMenuItem("Compound"));
citem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
CheckboxMenuItem item = (CheckboxMenuItem) e.getSource();
if (e.getStateChange() == ItemEvent.DESELECTED) {
// If compound gets deselected, then select NONE
setNoTransliterator();
} else if (!compound) {
// Switching from non-compound to compound
translitItem.setState(false);
translitItem = item;
translit = null;
compound = true;
compoundCount = 0;
for (int i=0; i<MAX_COMPOUND; ++i) {
compoundTranslit[i] = null;
}
}
}
});
translitMenu.addSeparator();
*/
/*
for (Enumeration e=getSystemTransliteratorNames().elements();
e.hasMoreElements(); ) {
String s = (String) e.nextElement();
translitMenu.add(citem = new CheckboxMenuItem(s));
citem.addItemListener(setTransliteratorListener);
}
*/
Menu fontMenu = new Menu("Font");
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (int i = 0; i < fonts.length; ++i) {
MenuItem mItem = new MenuItem(fonts[i]);
mItem.addActionListener(new FontActionListener(fonts[i]));
fontMenu.add(mItem);
}
mbar.add(fontMenu);
Menu sizeMenu = new Menu("Size");
int[] sizes = {9, 10, 12, 14, 18, 24, 36, 48, 72};
for (int i = 0; i < sizes.length; ++i) {
MenuItem mItem = new MenuItem("" + sizes[i]);
mItem.addActionListener(new SizeActionListener(sizes[i]));
sizeMenu.add(mItem);
}
mbar.add(sizeMenu);
translit = null;
mbar.add(translitMenu = new Menu("Transliterator"));
translitMenu.add(convertSelectionItem = new MenuItem("Transliterate",
new MenuShortcut(KeyEvent.VK_K)));
convertSelectionItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleBatchTransliterate(translit);
}
});
translitMenu.add(invertSelectionItem = new MenuItem("Invert",
new MenuShortcut(KeyEvent.VK_K, true)));
invertSelectionItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleBatchTransliterate(translit.getInverse());
}
});
translitMenu.add(swapSelectionItem = new MenuItem("Swap",
new MenuShortcut(KeyEvent.VK_S)));
swapSelectionItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Transliterator inv = translit.getInverse();
setTransliterator(inv.getID());
}
});
translitMenu.add(convertTypingItem = new MenuItem("No Typing Conversion",
new MenuShortcut(KeyEvent.VK_T)));
convertTypingItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!transliterateTyping) {
text.setTransliterator(translit);
convertTypingItem.setLabel("No Typing Conversion");
} else {
text.flush();
text.setTransliterator(null);
convertTypingItem.setLabel("Convert Typing");
}
transliterateTyping = !transliterateTyping;
}
});
translitMenu.add(historyMenu = new Menu("Recent"));
helpDialog = new InfoDialog(this, "Simple Demo", "Instructions",
"CTL A, X, C, V have customary meanings.\n"
+ "Arrow keys, delete and backspace work.\n"
+ "To get a character from its control point, type the hex, then hit CTL Q"
);
helpDialog.getArea().setEditable(false);
Menu helpMenu;
mbar.add(helpMenu = new Menu("Extras"));
helpMenu.add(mitem = new MenuItem("Help"));
mitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
helpDialog.show();
}
});
hexDialog = new InfoDialog(this, "Hex Entry", "Use U+..., \\u..., \\x{...}, or &#x...;",
"\u00E1"
);
Button button = new Button("Insert");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String hexValue = hexDialog.getArea().getText();
text.insertText(fromHex.transliterate(hexValue));
}
});
hexDialog.getBottom().add(button);
helpMenu.add(mitem = new MenuItem("Hex...",
new MenuShortcut(KeyEvent.VK_H)));
mitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hexDialog.show();
}
});
// Compound Transliterator
compoundDialog = new InfoDialog(this, "Compound Transliterator", "",
"[^\\u0000-\\u00FF] hex"
);
button = new Button("Set");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String compound = "";
try {
compound = compoundDialog.getArea().getText();
setTransliterator(compound);
} catch (RuntimeException ex) {
compoundDialog.getArea().setText(compound + "\n" + ex.getMessage());
}
}
});
compoundDialog.getBottom().add(button);
translitMenu.add(mitem = new MenuItem("Multiple...",
new MenuShortcut(KeyEvent.VK_M)));
mitem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
compoundDialog.show();
}
});
// Flesh out the menu with the installed transliterators
translitMenu.addSeparator();
Iterator sources = add(new TreeSet(), Transliterator.getAvailableSources()).iterator();
while(sources.hasNext()) {
String source = (String) sources.next();
Iterator targets = add(new TreeSet(), Transliterator.getAvailableTargets(source)).iterator();
Menu targetMenu = new Menu(source);
while(targets.hasNext()) {
String target = (String) targets.next();
Set variantSet = add(new TreeSet(), Transliterator.getAvailableVariants(source, target));
if (variantSet.size() < 2) {
mitem = new MenuItem(target);
mitem.addActionListener(new TransliterationListener(source + "-" + target));
targetMenu.add(mitem);
} else {
Iterator variants = variantSet.iterator();
Menu variantMenu = new Menu(target);
while(variants.hasNext()) {
String variant = (String) variants.next();
mitem = new MenuItem(variant == "" ? "<default>" : variant);
mitem.addActionListener(new TransliterationListener(source + "-" + target + "/" + variant));
variantMenu.add(mitem);
}
targetMenu.add(variantMenu);
}
}
translitMenu.add(targetMenu);
}
}
boolean transliterateTyping = true;
Transliterator fromHex = Transliterator.getInstance("Hex-Any");
InfoDialog helpDialog;
InfoDialog hexDialog;
InfoDialog compoundDialog;
MenuItem convertSelectionItem = null;
MenuItem invertSelectionItem = null;
MenuItem swapSelectionItem = null;
MenuItem convertTypingItem = null;
Menu historyMenu;
Map historyMap = new HashMap();
Set historySet = new TreeSet(new Comparator() {
public int compare(Object a, Object b) {
MenuItem aa = (MenuItem)a;
MenuItem bb = (MenuItem)b;
return aa.getLabel().compareTo(bb.getLabel());
}
});
void setTransliterator(String name) {
System.out.println("Got: " + name);
translit = Transliterator.getInstance(name);
text.flush();
text.setTransliterator(translit);
convertSelectionItem.setLabel(Transliterator.getDisplayName(translit.getID()));
addHistory(translit);
Transliterator inv = translit.getInverse();
if (inv != null) {
addHistory(inv);
invertSelectionItem.setEnabled(true);
swapSelectionItem.setEnabled(true);
invertSelectionItem.setLabel(Transliterator.getDisplayName(inv.getID()));
} else {
invertSelectionItem.setEnabled(false);
swapSelectionItem.setEnabled(false);
invertSelectionItem.setLabel("No inverse");
}
}
void addHistory(Transliterator translit) {
String name = translit.getID();
MenuItem cmi = (MenuItem) historyMap.get(name);
if (cmi == null) {
cmi = new MenuItem(translit.getDisplayName(name));
cmi.addActionListener(new TransliterationListener(name));
historyMap.put(name, cmi);
historySet.add(cmi);
historyMenu.removeAll();
Iterator it = historySet.iterator();
while (it.hasNext()) {
historyMenu.add((MenuItem)it.next());
}
}
}
class TransliterationListener implements ActionListener, ItemListener {
String name;
public TransliterationListener(String name) {
this.name = name;
}
public void actionPerformed(ActionEvent e) {
setTransliterator(name);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == e.SELECTED) {
setTransliterator(name);
} else {
setTransliterator("Any-Null");
}
}
}
class FontActionListener implements ActionListener {
String name;
public FontActionListener(String name) {
this.name = name;
}
public void actionPerformed(ActionEvent e) {
System.out.println("Font: " + name);
fontName = name;
text.setFont(new Font(fontName, Font.PLAIN, fontSize));
}
}
class SizeActionListener implements ActionListener {
int size;
public SizeActionListener(int size) {
this.size = size;
}
public void actionPerformed(ActionEvent e) {
System.out.println("Size: " + size);
fontSize = size;
text.setFont(new Font(fontName, Font.PLAIN, fontSize));
}
}
Set add(Set s, Enumeration enum) {
while(enum.hasMoreElements()) {
s.add(enum.nextElement());
}
return s;
}
/**
* Get a sorted list of the system transliterators.
*/
/*
private static Vector getSystemTransliteratorNames() {
Vector v = new Vector();
for (Enumeration e=Transliterator.getAvailableIDs();
e.hasMoreElements(); ) {
v.addElement(e.nextElement());
}
// Insertion sort, O(n^2) acceptable for small n
for (int i=0; i<(v.size()-1); ++i) {
String a = (String) v.elementAt(i);
for (int j=i+1; j<v.size(); ++j) {
String b = (String) v.elementAt(j);
if (a.compareTo(b) > 0) {
v.setElementAt(b, i);
v.setElementAt(a, j);
a = b;
}
}
}
return v;
}
*/
/*
private void setNoTransliterator() {
translitItem = noTranslitItem;
noTranslitItem.setState(true);
handleSetTransliterator(noTranslitItem.getLabel());
compound = false;
for (int i=0; i<translitMenu.getItemCount(); ++i) {
MenuItem it = translitMenu.getItem(i);
if (it != noTranslitItem && it instanceof CheckboxMenuItem) {
((CheckboxMenuItem) it).setState(false);
}
}
}
*/
/*
private void handleAddToCompound(String name) {
if (compoundCount < MAX_COMPOUND) {
compoundTranslit[compoundCount] = decodeTranslitItem(name);
++compoundCount;
Transliterator t[] = new Transliterator[compoundCount];
System.arraycopy(compoundTranslit, 0, t, 0, compoundCount);
translit = new CompoundTransliterator(t);
text.setTransliterator(translit);
}
}
*/
/*
private void handleSetTransliterator(String name) {
translit = decodeTranslitItem(name);
text.setTransliterator(translit);
}
*/
/**
* Decode a menu item that looks like <translit name>.
*/
/*
private static Transliterator decodeTranslitItem(String name) {
return (name.equals(NO_TRANSLITERATOR))
? null : Transliterator.getInstance(name);
}
*/
private void handleBatchTransliterate(Transliterator translit) {
if (translit == null) {
return;
}
int start = text.getSelectionStart();
int end = text.getSelectionEnd();
ReplaceableString s =
new ReplaceableString(text.getText().substring(start, end));
StringBuffer log = null;
if (DEBUG) {
log = new StringBuffer();
log.append('"' + s.toString() + "\" (start " + start +
", end " + end + ") -> \"");
}
translit.transliterate(s);
String str = s.toString();
if (DEBUG) {
log.append(str + "\"");
System.out.println("Batch " + translit.getID() + ": " + log.toString());
}
text.replaceRange(str, start, end);
text.select(start, start + str.length());
}
private void handleClose() {
helpDialog.dispose();
dispose();
}
class InfoDialog extends Dialog {
protected Button button;
protected TextArea area;
protected Dialog me;
protected Panel bottom;
public TextArea getArea() {
return area;
}
public Panel getBottom() {
return bottom;
}
InfoDialog(Frame parent, String title, String label, String message) {
super(parent, title, false);
me = this;
this.setLayout(new BorderLayout());
if (label.length() != 0) {
this.add("North", new Label(label));
}
area = new TextArea(message, 8, 80, TextArea.SCROLLBARS_VERTICAL_ONLY);
this.add("Center", area);
button = new Button("Hide");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
me.hide();
}
});
bottom = new Panel();
bottom.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
bottom.add(button);
this.add("South", bottom);
this.pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
me.hide();
}
});
}
}
}

View File

@ -1,74 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/translit/Attic/DemoApplet.java,v $
* $Date: 2001/11/28 19:27:09 $
* $Revision: 1.5 $
*
*****************************************************************************************
*/
package com.ibm.demo.translit;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import com.ibm.icu.demo.components.AppletFrame;
/**
* A simple Applet that shows a button. When pressed, the button
* shows the DemoAppletFrame. This Applet is meant to be embedded
* in a web page.
*
* <p>Copyright (c) IBM Corporation 1999. All rights reserved.
*
* @author Alan Liu
* @version $RCSfile: DemoApplet.java,v $ $Revision: 1.5 $ $Date: 2001/11/28 19:27:09 $
*/
public class DemoApplet extends Applet {
Demo frame = null;
private static final String COPYRIGHT =
"\u00A9 IBM Corporation 1999. All rights reserved.";
public static void main(String args[]) {
final DemoApplet applet = new DemoApplet();
new AppletFrame("Transliteration Demo", applet, 640, 480);
}
public void init() {
Button button = new Button("Transliteration Demo");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (frame == null) {
frame = new Demo(600, 200);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
frame = null;
}
});
}
frame.setVisible(true);
frame.toFront();
}
});
add(button);
Dimension size = button.getPreferredSize();
size.width += 10;
size.height += 10;
resize(size);
}
public void stop() {
if (frame != null) {
frame.dispose();
}
frame = null;
}
}

View File

@ -1,19 +0,0 @@
REM /*
REM *******************************************************************************
REM * Copyright (C) 1996-2000, International Business Machines Corporation and *
REM * others. All Rights Reserved. *
REM *******************************************************************************
REM *
REM * $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/translit/Attic/demo.bat,v $
REM * $Date: 2000/03/10 03:47:44 $
REM * $Revision: 1.2 $
REM *
REM *****************************************************************************************
REM */
REM For best results, run the demo as an applet inside of Netscape
REM with Bitstream Cyberbit installed.
REM setup your JDK 1.1.x path and classpath here:
call JDK11
set CLASSPATH=../translit.jar;%CLASSPATH%
javaw Demo

View File

@ -1,27 +0,0 @@
<HTML>
<HEAD>
<TITLE>Transliteration Demo</TITLE>
</HEAD>
<BODY>
<APPLET CODE="com.ibm.demo.translit.DemoApplet.class" WIDTH=140 HEIGHT=33></APPLET>
<HR>
If you don't see a button above, then your browser is failing to
locate the necessary Java class files.
<P>
One way to make this work is to copy this HTML file to
<code>icu4j/src</code>, and make sure the Java files in the directories
under <code>icu4j/src/com</code> are built. Then open this HTML file
using a browser or appletviewer.
<P>
For best results, run this demo as an applet within Netscape with
Bitstream Cyberbit installed.
</BODY>
</HTML>

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/demo/translit/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 17:44:12 $
-->
</head>
<body bgcolor="white">
Transliterator demo appliation.
</body>
</html>

View File

@ -1,152 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/demo/components/Attic/AppletFrame.java,v $
* $Date: 2001/12/03 17:49:03 $
* $Revision: 1.3 $
*
*****************************************************************************************
*/
package com.ibm.icu.demo.components;
import java.applet.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.awt.*;
import java.awt.event.*;
import java.io.InputStream;
import java.io.IOException;
/**
* <p>A Frame that runs an Applet within itself, making it possible
* for an applet to run as an application. Usage:
*
* <pre>
* public class MyApplet extends Applet {
* public static void main(String args[]) {
* MyApplet applet = new MyApplet();
* new AppletFrame("My Applet Running As An App", applet, 640, 480);
* }
* ...
* }
* <pre>
*
* <p>Copyright &copy; IBM Corporation 1999. All rights reserved.
*
* @author Alan Liu
* @version $RCSfile: AppletFrame.java,v $ $Revision: 1.3 $ $Date: 2001/12/03 17:49:03 $
*/
public class AppletFrame extends Frame implements AppletStub, AppletContext {
Applet applet;
private static final String COPYRIGHT =
"\u00A9 IBM Corporation 1999. All rights reserved.";
/**
* Construct a Frame running the given Applet with the default size
* of 640 by 480.
* When the Frame is closed, the applet's stop() method is called,
* the Frame is dispose()d of, and System.exit(0) is called.
*
* @param name the Frame title
* @param applet the applet to be run
*/
public AppletFrame(String name, Applet applet) {
this(name, applet, 640, 480);
}
/**
* Construct a Frame running the given Applet with the given size.
* When the Frame is closed, the applet's stop() method is called,
* the Frame is dispose()d of, and System.exit(0) is called.
*
* @param name the Frame title
* @param applet the applet to be run
* @param width width of the Frame
* @param height height of the Frame
*/
public AppletFrame(String name, Applet applet, int width, int height) {
super(name);
this.applet = applet;
applet.setStub(this);
setSize(width, height);
add("Center", applet);
show();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
AppletFrame.this.applet.stop();
dispose();
System.exit(0);
}
});
applet.init();
applet.start();
}
// AppletStub API
public void appletResize(int width, int height) {
setSize(width, height);
}
public AppletContext getAppletContext() {
return this;
}
public URL getCodeBase() {
return null;
}
public URL getDocumentBase() {
return null;
}
public String getParameter(String name) {
return "PARAMETER";
}
public boolean isActive() {
return true;
}
// AppletContext API
public Applet getApplet(String name) {
return applet;
}
public Enumeration getApplets() {
return null;
}
public AudioClip getAudioClip(URL url) {
return null;
}
public Image getImage(URL url) {
return null;
}
public void showDocument(URL url) {}
public void showDocument(URL url, String target) {}
public void showStatus(String status) {
System.out.println(status);
}
public void setStream(String key, InputStream stream) throws IOException {
}
public InputStream getStream(String key) {
return null;
}
public Iterator getStreamKeys() {
return null;
}
}

View File

@ -1,796 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/demo/components/Attic/DumbTextComponent.java,v $
* $Date: 2001/11/29 17:28:37 $
* $Revision: 1.4 $
*
*****************************************************************************************
*/
package com.ibm.icu.demo.components;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.awt.datatransfer.*;
// LIU: Changed from final to non-final
public class DumbTextComponent extends Canvas
implements KeyListener, MouseListener, MouseMotionListener, FocusListener
{
private transient static final String copyright =
"Copyright \u00A9 1998, Mark Davis. All Rights Reserved.";
private transient static boolean DEBUG = false;
private String contents = "";
private Selection selection = new Selection();
private int activeStart = -1;
private boolean editable = true;
private transient Selection tempSelection = new Selection();
private transient boolean focus;
private transient BreakIterator lineBreaker = BreakIterator.getLineInstance();
private transient BreakIterator wordBreaker = BreakIterator.getWordInstance();
private transient BreakIterator charBreaker = BreakIterator.getCharacterInstance();
private transient int lineAscent;
private transient int lineHeight;
private transient int lineLeading;
private transient int lastHeight = 10;
private transient int lastWidth = 50;
private static final int MAX_LINES = 200; // LIU: Use symbolic name
private transient int[] lineStarts = new int[MAX_LINES]; // LIU
private transient int lineCount = 1;
private transient boolean valid = false;
private transient FontMetrics fm;
private transient boolean redoLines = true;
private transient boolean doubleClick = false;
private transient TextListener textListener;
private transient ActionListener selectionListener;
private transient Image cacheImage;
private transient Dimension mySize;
private transient int xInset = 5;
private transient int yInset = 5;
private transient Point startPoint = new Point();
private transient Point endPoint = new Point();
private transient Point caretPoint = new Point();
private transient Point activePoint = new Point();
//private transient static String clipBoard;
private static final char CR = '\015'; // LIU
// ============================================
public DumbTextComponent() {
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
addFocusListener(this);
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
}
// ================ Events ====================
public boolean isFocusTraversable() { return true; }
public void addActionListener(ActionListener l) {
selectionListener = AWTEventMulticaster.add(selectionListener, l);
}
public void removeActionListener(ActionListener l) {
selectionListener = AWTEventMulticaster.remove(selectionListener, l);
}
public void addTextListener(TextListener l) {
textListener = AWTEventMulticaster.add(textListener, l);
}
public void removeTextListener(TextListener l) {
textListener = AWTEventMulticaster.remove(textListener, l);
}
private transient boolean pressed;
public void mousePressed(MouseEvent e) {
if (DEBUG) System.out.println("mousePressed");
if (pressed) {
select(e,false);
} else {
doubleClick = e.getClickCount() > 1;
requestFocus();
select(e, true);
pressed = true;
}
}
public void mouseDragged(MouseEvent e) {
if (DEBUG) System.out.println("mouseDragged");
select(e, false);
}
public void mouseReleased(MouseEvent e) {
if (DEBUG) System.out.println("mouseReleased");
pressed = false;
}
public void mouseEntered(MouseEvent e) {
//if (pressed) select(e, false);
}
public void mouseExited(MouseEvent e){
//if (pressed) select(e, false);
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void focusGained(FocusEvent e) {
if (DEBUG) System.out.println("focusGained");
focus = true;
valid = false;
repaint(16);
}
public void focusLost(FocusEvent e) {
if (DEBUG) System.out.println("focusLost");
focus = false;
valid = false;
repaint(16);
}
public void select(MouseEvent e, boolean first) {
setKeyStart(-1);
point2Offset(e.getPoint(), tempSelection);
if (first) {
if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) {
tempSelection.anchor = tempSelection.caret;
}
}
// fix words
if (doubleClick) {
tempSelection.expand(wordBreaker);
}
select(tempSelection);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (DEBUG) System.out.println("keyPressed "
+ hex((char)code) + ", " + hex((char)e.getModifiers()));
int start = selection.getStart();
int end = selection.getEnd();
boolean shift = (e.getModifiers() & KeyEvent.SHIFT_MASK) != 0;
boolean ctrl = (e.getModifiers() & KeyEvent.CTRL_MASK) != 0;
switch (code) {
case KeyEvent.VK_Q:
if (!ctrl || !editable) break;
setKeyStart(-1);
fixHex();
break;
case KeyEvent.VK_V:
if (!ctrl) break;
if (!editable) {
this.getToolkit().beep();
} else {
paste();
}
break;
case KeyEvent.VK_C:
if (!ctrl) break;
copy();
break;
case KeyEvent.VK_X:
if (!ctrl) break;
if (!editable) {
this.getToolkit().beep();
} else {
copy();
insertText("");
}
break;
case KeyEvent.VK_A:
if (!ctrl) break;
setKeyStart(-1);
select(Integer.MAX_VALUE, 0, false);
break;
case KeyEvent.VK_RIGHT:
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.nextBound(ctrl ? wordBreaker : charBreaker, +1, shift);
select(tempSelection);
break;
case KeyEvent.VK_LEFT:
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.nextBound(ctrl ? wordBreaker : charBreaker, -1, shift);
select(tempSelection);
break;
case KeyEvent.VK_UP: // LIU: Add support for up arrow
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.caret = lineDelta(tempSelection.caret, -1);
if (!shift) {
tempSelection.anchor = tempSelection.caret;
}
select(tempSelection);
break;
case KeyEvent.VK_DOWN: // LIU: Add support for down arrow
setKeyStart(-1);
tempSelection.set(selection);
tempSelection.caret = lineDelta(tempSelection.caret, +1);
if (!shift) {
tempSelection.anchor = tempSelection.caret;
}
select(tempSelection);
break;
case KeyEvent.VK_DELETE: // LIU: Add delete key support
if (!editable) break;
setKeyStart(-1);
if (contents.length() == 0) break;
start = selection.getStart();
end = selection.getEnd();
if (start == end) {
++end;
if (end > contents.length()) {
getToolkit().beep();
return;
}
}
replaceRange("", start, end);
break;
}
}
void copy() {
Clipboard cb = this.getToolkit().getSystemClipboard();
StringSelection ss = new StringSelection(
contents.substring(selection.getStart(), selection.getEnd()));
cb.setContents(ss, ss);
}
void paste () {
Clipboard cb = this.getToolkit().getSystemClipboard();
Transferable t = cb.getContents(this);
if (t == null) {
this.getToolkit().beep();
return;
}
try {
String temp = (String) t.getTransferData(DataFlavor.stringFlavor);
insertText(temp);
} catch (Exception e) {
this.getToolkit().beep();
}
}
/**
* LIU: Given an offset into contents, moves up or down by lines,
* according to lineStarts[].
* @param off the offset into contents
* @param delta how many lines to move up (< 0) or down (> 0)
* @return the new offset into contents
*/
private int lineDelta(int off, int delta) {
int line = findLine(off, false);
int posInLine = off - lineStarts[line];
// System.out.println("off=" + off + " at " + line + ":" + posInLine);
line += delta;
if (line < 0) {
line = posInLine = 0;
} else if (line >= lineCount) {
return contents.length();
}
off = lineStarts[line] + posInLine;
if (off >= lineStarts[line+1]) {
off = lineStarts[line+1] - 1;
}
return off;
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if (DEBUG) System.out.println("keyReleased "
+ hex((char)code) + ", " + hex((char)e.getModifiers()));
}
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
if (DEBUG) System.out.println("keyTyped "
+ hex((char)ch) + ", " + hex((char)e.getModifiers()));
if ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0) return;
int start, end;
switch (ch) {
case KeyEvent.CHAR_UNDEFINED:
break;
case KeyEvent.VK_BACK_SPACE:
setKeyStart(-1);
if (!editable) break;
if (contents.length() == 0) break;
start = selection.getStart();
end = selection.getEnd();
if (start == end) {
--start;
if (start < 0) {
getToolkit().beep(); // LIU: Add audio feedback of NOP
return;
}
}
replaceRange("", start, end);
break;
case KeyEvent.VK_DELETE:
setKeyStart(-1);
if (!editable) break;
if (contents.length() == 0) break;
start = selection.getStart();
end = selection.getEnd();
if (start == end) {
++end;
if (end > contents.length()) {
getToolkit().beep(); // LIU: Add audio feedback of NOP
return;
}
}
replaceRange("", start, end);
break;
default:
if (!editable) break;
// LIU: Dispatch to subclass API
handleKeyTyped(e);
break;
}
}
// LIU: Subclass API for handling of key typing
protected void handleKeyTyped(KeyEvent e) {
insertText(String.valueOf(e.getKeyChar()));
}
protected void setKeyStart(int keyStart) {
if (activeStart != keyStart) {
activeStart = keyStart;
repaint(10);
}
}
protected int getKeyStart() {
return activeStart;
}
// ===================== Control ======================
public synchronized void setEditable(boolean b) {
editable = b;
}
public boolean isEditable() {
return editable;
}
public void select(Selection newSelection) {
newSelection.pin(contents);
if (!selection.equals(newSelection)) {
selection.set(newSelection);
if (selectionListener != null) {
selectionListener.actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
"Selection Changed", 0));
}
repaint(10);
valid = false;
}
}
public void select(int start, int end) {
select(start, end, false);
}
public void select(int start, int end, boolean clickAfter) {
tempSelection.set(start, end, clickAfter);
select(tempSelection);
}
public int getSelectionStart() {
return selection.getStart();
}
public int getSelectionEnd() {
return selection.getEnd();
}
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x,y,w,h);
redoLines = true;
}
public Dimension getPreferredSize() {
return new Dimension(lastWidth,lastHeight);
}
public Dimension getMaximumSize() {
return new Dimension(lastWidth,lastHeight);
}
public Dimension getMinimumSize() {
return new Dimension(lastHeight,lastHeight);
}
public void setText(String text) {
setText2(text);
select(tempSelection.set(selection).pin(contents));
}
public void setText2(String text) {
contents = text;
charBreaker.setText(text);
wordBreaker.setText(text);
lineBreaker.setText(text);
redoLines = true;
if (textListener != null)
textListener.textValueChanged(
new TextEvent(this, TextEvent.TEXT_VALUE_CHANGED));
repaint(16);
}
public void insertText(String text) {
if (activeStart == -1) activeStart = selection.getStart();
replaceRange(text, selection.getStart(), selection.getEnd());
}
public void replaceRange(String s, int start, int end) {
setText2(contents.substring(0,start) + s
+ contents.substring(end));
select(tempSelection.set(selection).
fixAfterReplace(start, end, s.length()));
}
public String getText() {
return contents;
}
public void setFont(Font font) {
super.setFont(font);
redoLines = true;
repaint(16);
}
// ================== Graphics ======================
public void update(Graphics g) {
if (DEBUG) System.out.println("update");
paint(g);
}
public void paint(Graphics g) {
mySize = getSize();
if (cacheImage == null
|| cacheImage.getHeight(this) != mySize.height
|| cacheImage.getWidth(this) != mySize.width) {
cacheImage = createImage(mySize.width, mySize.height);
valid = false;
}
if (!valid || redoLines) {
if (DEBUG) System.out.println("painting");
paint2(cacheImage.getGraphics());
valid = true;
}
//getToolkit().sync();
if (DEBUG) System.out.println("copying");
g.drawImage(cacheImage,
0, 0, mySize.width, mySize.height,
0, 0, mySize.width, mySize.height,
this);
}
public void paint2(Graphics g) {
g.clearRect(0, 0, mySize.width, mySize.height);
if (DEBUG) System.out.println("print");
if (focus) g.setColor(Color.black);
else g.setColor(Color.gray);
g.drawRect(0,0,mySize.width-1,mySize.height-1);
g.setClip(1,1,
mySize.width-2,mySize.height-2);
g.setColor(Color.black);
g.setFont(getFont());
fm = g.getFontMetrics();
lineAscent = fm.getAscent();
lineLeading = fm.getLeading();
lineHeight = lineAscent + fm.getDescent() + lineLeading;
int y = yInset + lineAscent;
String lastSubstring = "";
if (redoLines) fixLineStarts(mySize.width-xInset-xInset);
for (int i = 0; i < lineCount; y += lineHeight, ++i) {
// LIU: Don't display terminating ^M characters
int lim = lineStarts[i+1];
if (lim > 0 && contents.length() > 0 &&
contents.charAt(lim-1) == CR) --lim;
lastSubstring = contents.substring(lineStarts[i],lim);
g.drawString(lastSubstring, xInset, y);
}
drawSelection(g, lastSubstring);
lastHeight = y + yInset - lineHeight + yInset;
lastWidth = mySize.width-xInset-xInset;
}
void paintRect(Graphics g, int x, int y, int w, int h) {
if (focus) {
g.fillRect(x, y, w, h);
} else {
g.drawRect(x, y, w-1, h-1);
}
}
public void drawSelection(Graphics g, String lastSubstring) {
g.setXORMode(Color.black);
if (activeStart != -1) {
offset2Point(activeStart, false, activePoint);
g.setColor(Color.magenta);
int line = activePoint.x - 1;
g.fillRect(line, activePoint.y, 1, lineHeight);
}
if (selection.isCaret()) {
offset2Point(selection.caret, selection.clickAfter, caretPoint);
} else {
if (focus) g.setColor(Color.blue);
else g.setColor(Color.yellow);
offset2Point(selection.getStart(), true, startPoint);
offset2Point(selection.getEnd(), false, endPoint);
if (selection.getStart() == selection.caret)
caretPoint.setLocation(startPoint);
else caretPoint.setLocation(endPoint);
if (startPoint.y == endPoint.y) {
paintRect(g, startPoint.x, startPoint.y,
Math.max(1,endPoint.x-startPoint.x), lineHeight);
} else {
paintRect(g, startPoint.x, startPoint.y,
(mySize.width-xInset)-startPoint.x, lineHeight);
if (startPoint.y + lineHeight < endPoint.y)
paintRect(g, xInset, startPoint.y + lineHeight,
(mySize.width-xInset)-xInset, endPoint.y - startPoint.y - lineHeight);
paintRect(g, xInset, endPoint.y, endPoint.x-xInset, lineHeight);
}
}
if (focus || selection.isCaret()) {
if (focus) g.setColor(Color.green);
else g.setColor(Color.red);
int line = caretPoint.x - (selection.clickAfter ? 0 : 1);
g.fillRect(line, caretPoint.y, 1, lineHeight);
int w = lineHeight/12 + 1;
int braces = line - (selection.clickAfter ? -1 : w);
g.fillRect(braces, caretPoint.y, w, 1);
g.fillRect(braces, caretPoint.y + lineHeight - 1, w, 1);
}
}
public Point offset2Point(int off, boolean start, Point p) {
int line = findLine(off, start);
int width = 0;
try {
width = fm.stringWidth(
contents.substring(lineStarts[line], off));
} catch (Exception e) {
System.out.println(e);
}
p.x = width + xInset;
if (p.x > mySize.width - xInset)
p.x = mySize.width - xInset;
p.y = lineHeight * line + yInset;
return p;
}
private int findLine(int off, boolean start) {
// if it is start, then go to the next line!
if (start) ++off;
for (int i = 1; i < lineCount; ++i) {
// LIU: This was <= ; changed to < to make caret after
// final CR in line appear at START of next line.
if (off < lineStarts[i]) return i-1;
}
// LIU: Check for special case; after CR at end of the last line
if (off == lineStarts[lineCount] &&
off > 0 && contents.length() > 0 && contents.charAt(off-1) == CR) {
return lineCount;
}
return lineCount-1;
}
// offsets on any line will go from start,true to end,false
// excluding start,false and end,true
public Selection point2Offset(Point p, Selection o) {
if (p.y < yInset) {
o.caret = 0;
o.clickAfter = true;
return o;
}
int line = (p.y - yInset)/lineHeight;
if (line >= lineCount) {
o.caret = contents.length();
o.clickAfter = false;
return o;
}
int target = p.x - xInset;
if (target <= 0) {
o.caret = lineStarts[line];
o.clickAfter = true;
return o;
}
int lowGuess = lineStarts[line];
int lowWidth = 0;
int highGuess = lineStarts[line+1];
int highWidth = fm.stringWidth(contents.substring(lineStarts[line],highGuess));
if (target >= highWidth) {
o.caret = lineStarts[line+1];
o.clickAfter = false;
return o;
}
while (lowGuess < highGuess - 1) {
int guess = (lowGuess + highGuess)/2;
int width = fm.stringWidth(contents.substring(lineStarts[line],guess));
if (width <= target) {
lowGuess = guess;
lowWidth = width;
if (width == target) break;
} else {
highGuess = guess;
highWidth = width;
}
}
// at end, either lowWidth < target < width(low+1), or lowWidth = target
int highBound = charBreaker.following(lowGuess);
int lowBound = charBreaker.previous();
// we are now at character boundaries
if (lowBound != lowGuess)
lowWidth = fm.stringWidth(contents.substring(lineStarts[line],lowBound));
if (highBound != highGuess)
highWidth = fm.stringWidth(contents.substring(lineStarts[line],highBound));
// we now have the right widths
if (target - lowWidth < highWidth - target) {
o.caret = lowBound;
o.clickAfter = true;
} else {
o.caret = highBound;
o.clickAfter = false;
}
// we now have the closest!
return o;
}
private void fixLineStarts(int width) {
lineCount = 1;
lineStarts[0] = 0;
if (contents.length() == 0) {
lineStarts[1] = 0;
return;
}
int end = 0;
// LIU: Add check for MAX_LINES
for (int start = 0; start < contents.length() && lineCount < MAX_LINES;
start = end) {
end = nextLine(fm, start, width);
lineStarts[lineCount++] = end;
if (end == start) { // LIU: Assertion
throw new RuntimeException("nextLine broken");
}
}
--lineCount;
redoLines = false;
}
// LIU: Enhanced to wrap long lines. Bug with return of start fixed.
public int nextLine(FontMetrics fm, int start, int width) {
int len = contents.length();
for (int i = start; i < len; ++i) {
// check for line separator
char ch = (contents.charAt(i));
if (ch >= 0x000A && ch <= 0x000D || ch == 0x2028 || ch == 0x2029) {
len = i + 1;
if (ch == 0x000D && i+1 < len && contents.charAt(i+1) == 0x000A) // crlf
++len; // grab extra char
break;
}
}
String subject = contents.substring(start,len);
if (visibleWidth(fm, subject) <= width)
return len;
// LIU: Remainder of this method rewritten to accomodate lines
// longer than the component width by first trying to break
// into lines; then words; finally chars.
int n = findFittingBreak(fm, subject, width, lineBreaker);
if (n == 0) {
n = findFittingBreak(fm, subject, width, wordBreaker);
}
if (n == 0) {
n = findFittingBreak(fm, subject, width, charBreaker);
}
return n > 0 ? start + n : len;
}
/**
* LIU: Finds the longest substring that fits a given width
* composed of subunits returned by a BreakIterator. If the smallest
* subunit is too long, returns 0.
* @param fm metrics to use
* @param line the string to be fix into width
* @param width line.substring(0, result) must be <= width
* @param breaker the BreakIterator that will be used to find subunits
* @return maximum characters, at boundaries returned by breaker,
* that fit into width, or zero on failure
*/
private int findFittingBreak(FontMetrics fm, String line, int width,
BreakIterator breaker) {
breaker.setText(line);
int last = breaker.first();
int end = breaker.next();
while (end != BreakIterator.DONE &&
visibleWidth(fm, line.substring(0, end)) <= width) {
last = end;
end = breaker.next();
}
return last;
}
public int visibleWidth(FontMetrics fm, String s) {
int i;
for (i = s.length()-1; i >= 0; --i) {
char ch = s.charAt(i);
if (!(ch == ' ' || ch >= 0x000A && ch <= 0x000D || ch == 0x2028 || ch == 0x2029))
return fm.stringWidth(s.substring(0,i+1));;
}
return 0;
}
// =============== Utility ====================
private void fixHex() {
if (selection.getEnd() == 0) return;
int store = 0;
int places = 1;
int count = 0;
int min = Math.min(8,selection.getEnd());
for (int i = 0; i < min; ++i) {
char ch = contents.charAt(selection.getEnd()-1-i);
int value = Character.getNumericValue(ch);
if (value < 0 || value > 15) break;
store += places * value;
++count;
places *= 16;
}
String add = "";
int bottom = store & 0xFFFF;
if (store >= 0xD8000000 && store < 0xDC000000
&& bottom >= 0xDC00 && bottom < 0xE000) { // surrogates
add = "" + (char)(store >> 16) + (char)bottom;
} else if (store > 0xFFFF && store <= 0x10FFFF) {
store -= 0x10000;
add = "" + (char)(((store >> 10) & 0x3FF) + 0xD800)
+ (char)((store & 0x3FF) + 0xDC00);
} else if (count >= 4) {
count = 4;
add = ""+(char)(store & 0xFFFF);
} else {
count = 1;
char ch = contents.charAt(selection.getEnd()-1);
add = hex(ch);
if (ch >= 0xDC00 && ch <= 0xDFFF && selection.getEnd() > 1) {
ch = contents.charAt(selection.getEnd()-2);
if (ch >= 0xD800 && ch <= 0xDBFF) {
count = 2;
add = hex(ch) + add;
}
}
}
replaceRange(add, selection.getEnd()-count, selection.getEnd());
}
public static String hex(char ch) {
String result = Integer.toString(ch,16).toUpperCase();
result = "0000".substring(result.length(),4) + result;
return result;
}
}

View File

@ -1,167 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/demo/components/Attic/Selection.java,v $
* $Date: 2001/11/28 19:27:09 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
package com.ibm.icu.demo.components;
import java.text.*;
public final class Selection {
public int anchor;
public int caret;
public boolean clickAfter;
public int getStart() {
return anchor < caret ? anchor : caret;
}
public int getEnd() {
return anchor > caret ? anchor : caret;
}
public boolean isCaret() {
return anchor == caret;
}
public Selection set(Selection other) {
anchor = other.anchor;
caret = other.caret;
clickAfter = other.clickAfter;
return this;
}
public Selection set(int anchor, int caret, boolean clickAfter) {
this.anchor = anchor;
this.caret = caret;
this.clickAfter = clickAfter;
return this;
}
public boolean equals(Object other) {
Selection other2 = (Selection)other;
return anchor == other2.anchor
&& caret == other2.caret
&& clickAfter == other2.clickAfter;
}
public boolean isLessThan(Selection other) {
return getStart() < other.getEnd();
}
public Selection pin(String text) {
if (anchor > text.length()) {
anchor = text.length();
} else if (anchor < 0) {
anchor = 0;
}
if (caret > text.length()) {
caret = text.length();
clickAfter = true;
} else if (caret < 0) {
caret = 0;
clickAfter = false;
}
return this;
}
public Selection swap(Selection after) {
int temp = anchor;
anchor = after.anchor;
after.anchor = temp;
temp = caret;
caret = after.caret;
after.caret = temp;
boolean b = clickAfter;
clickAfter = after.clickAfter;
after.clickAfter = b;
return this;
}
public Selection fixAfterReplace(int start, int end, int len) {
if (anchor >= start) {
if (anchor < end) anchor = end;
anchor = start + len + anchor - end;
}
if (caret >= start) {
if (caret < end) caret = end;
caret = start + len + caret - end;
}
return this;
}
// Mac & Windows considerably different
// Mac: end++. If start!=end, start=end
// SHIFT: move end right
// CTL: no different
// Windows:
// UNSHIFTED: if start!=end, start = end, else start=end=end+1;
// anchor = tip = start
// SHIFT: tip++
// CTL: if start!=end, start = end = nextbound(end-1),
// else start=end=nextbound(end)
// anchor = tip = start
// CTL/SHIFT: tip = nextbound(tip)
public Selection nextBound(BreakIterator breaker,
int direction, boolean extend) {
if (!extend && anchor != caret) caret -= direction;
caret = next(caret, breaker, direction, true);
if (!extend) anchor = caret;
clickAfter = false;
return this;
}
// expand start and end to word breaks--if they are not already on one
public void expand(BreakIterator breaker) {
if (anchor <= caret) {
anchor = next(anchor,breaker,-1,false);
caret = next(caret,breaker,1,false);
/*
try {
breaker.following(anchor);
anchor = breaker.previous();
} catch (Exception e) {}
try {
caret = breaker.following(caret-1);
} catch (Exception e) {}
*/
} else {
anchor = next(anchor,breaker,1,false);
caret = next(caret,breaker,-1,false);
/*
try {
breaker.following(caret);
caret = breaker.previous();
} catch (Exception e) {}
try {
anchor = breaker.following(anchor-1);
} catch (Exception e) {}
*/
}
}
// different = false - move to next boundary, unless on one
// true - move to next boundary, even if on one
public static int next(int position, BreakIterator breaker,
int direction, boolean different) {
if (!different) position -= direction;
try {
if (direction > 0) {
position = breaker.following(position);
} else {
breaker.following(position-1);
position = breaker.previous();
}
} catch (Exception e) {}
return position;
}
}

View File

@ -1,261 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/demo/components/Attic/TransliteratingTextComponent.java,v $
* $Date: 2001/11/28 22:24:29 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
package com.ibm.icu.demo.components;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.awt.datatransfer.*;
import com.ibm.text.*;
/**
* A subclass of {@link DumbTextComponent} that passes key events through
* a {@link com.ibm.text.Transliterator}.
*
* <p>Copyright &copy; IBM Corporation 1999. All rights reserved.
*
* @author Alan Liu
* @version $RCSfile: TransliteratingTextComponent.java,v $ $Revision: 1.2 $ $Date: 2001/11/28 22:24:29 $
*/
public class TransliteratingTextComponent extends DumbTextComponent {
private static boolean DEBUG = true;
private Transliterator translit = null;
// NOTE: DISABLE THE START AND CURSOR UNTIL WE CAN GET IT TO WORK AT ALL
// Index into getText() where the start of transliteration is.
// As we commit text during transliteration, we advance
// this.
//private int start = 0;
// Index into getText() where the cursor is; cursor >= start
//private int cursor = 0;
private static final String COPYRIGHT =
"\u00A9 IBM Corporation 1999. All rights reserved.";
/**
* Constructor.
*/
public TransliteratingTextComponent() {
super();
/*
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// We get an ActionEvent only when the selection changes
resetTransliterationStart();
}
});
*/
}
/**
* {@link DumbTextComponent} API. Framework method that is called
* when a <code>KeyEvent</code> is received. This implementation
* runs the new character through the current
* <code>Transliterator</code>, if one is set, and inserts the
* transliterated text into the buffer.
*/
protected void handleKeyTyped(KeyEvent e) {
char ch = e.getKeyChar();
if (translit == null) {
setKeyStart(-1);
super.handleKeyTyped(e);
return;
}
transliterate(ch, false);
}
public void flush() {
if (translit != null) transliterate('\uFFFF', true);
}
protected void transliterate(char ch, boolean flush) {
// ------------------------------------------------------------
// The following case motivates the two lines that recompute
// start and cursor below.
// " "
// a b c q r|s t u m m
// 0 1 2 3 4 5 6 7 8 9
// 0 1 2
// start 3, cursor 5, sel 6 -> { 0, 3, 2 }
// : new int[] { 0, sel - start, cursor - start };
// sz>99|9
// " { "
// a b c q r 9 9|9 t u m m
// 0 1 2 3 4 5 6 7 8 9 a b
// 0 1 2 3 4
// { 3, 5, 4 } -> start 6, cursor 7, sel 8
// : start += index[0];
// : cursor = start + index[2] - index[0];
// ------------------------------------------------------------
// Need to save start because calls to replaceRange will update
// start and cursor.
//int saveStart = start;
int end = flush ? getSelectionEnd() : getSelectionStart();
String sourceText = getText().substring(0,end);
ReplaceableString buf = new ReplaceableString(sourceText);
/*buf.replace(0, 1, getText().substring(start,
getSelectionStart()));*/
Transliterator.Position index = new Transliterator.Position();
index.contextLimit = buf.length();
index.contextStart = 0;
index.start = getKeyStart();
if (index.start == -1) index.start = getSelectionStart();
index.limit = buf.length();
StringBuffer log = null;
if (DEBUG) {
System.out.println("Transliterator: " + translit.getID());
System.out.println("From:\t" + '"' + buf.toString() + '"'
+ "; {cs: " + index.contextStart
+ ", s: " + index.start
+ ", l: " + index.limit
+ ", cl: " + index.contextLimit
+ "}" + "; '" + ch + "'"
+ " " + getKeyStart()
);
}
if (flush) {
translit.finishTransliteration(buf, index);
} else {
translit.transliterate(buf, index, ch);
}
if (DEBUG) {
System.out.println("To:\t" + '"' + buf.toString() + '"'
+ "; {cs: " + index.contextStart
+ ", s: " + index.start
+ ", l: " + index.limit
+ ", cl: " + index.contextLimit
+ "}"
);
System.out.println();
}
/*
buf.replace(buf.length(), buf.length(), String.valueOf(ch));
translit.transliterate(buf);
*/
String result = buf.toString();
//if (result.equals(sourceText + ch)) return;
replaceRange(result, 0, getSelectionEnd());
setKeyStart(index.start);
// At this point start has been changed by the callback to
// resetTransliteratorStart() via replaceRange() -- so use our
// local copy, saveStart.
// The START index is zero-based. On entry to transliterate(),
// it was zero. We can therefore just add it to our original
// getText()-based index value of start (in saveStart) to get
// the new getText()-based start.
// start = saveStart + index.contextStart;
// Make the cursor getText()-based. The CURSOR index is zero-based.
// cursor = start + index.start - index.contextStart;
/*
if (DEBUG) {
String out = buf.toString();
log.append(out.substring(0, index.contextStart)).
append('{').
append(out.substring(index.contextStart, index.start)).
append('|').
append(out.substring(index.start)).
append('"');
log.append(", {" + index.contextStart + ", " + index.contextLimit + ", " + index.start + "}, ");
// log.append("start " + start + ", cursor " + cursor);
log.append(", sel " + getSelectionStart());
System.out.println(escape(log.toString()));
}
*/
}
/**
* Set the {@link com.ibm.text.Transliterator} and direction to
* use to process incoming <code>KeyEvent</code>s.
* @param t the {@link com.ibm.text.Transliterator} to use
*/
public void setTransliterator(Transliterator t) {
/*
if (translit != t) { // [sic] pointer compare ok; singletons
resetTransliterationStart();
}
*/
translit = t;
}
public Transliterator getTransliterator() {
return translit;
}
/**
* Reset the start point at which transliteration begins. This
* needs to be done when the user moves the cursor or when the
* current {@link com.ibm.text.Transliterator} is changed.
*/
/*
private void resetTransliterationStart() {
start = getSelectionStart();
cursor = start;
}
*/
/**
* Escape non-ASCII characters as Unicode.
* JUST FOR DEBUGGING OUTPUT.
*/
public static final String escape(String s) {
StringBuffer buf = new StringBuffer();
for (int i=0; i<s.length(); ++i) {
char c = s.charAt(i);
if (c >= ' ' && c <= 0x007F) {
if (c == '\\') {
buf.append("\\\\"); // That is, "\\"
} else {
buf.append(c);
}
} else {
buf.append("\\u");
if (c < 0x1000) {
buf.append('0');
if (c < 0x100) {
buf.append('0');
if (c < 0x10) {
buf.append('0');
}
}
}
buf.append(Integer.toHexString(c));
}
}
return buf.toString();
}
}

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/demo/components/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2001/11/28 19:27:09 $
-->
</head>
<body bgcolor="white">
GUI components for use with Transliterator.
</body>
</html>

View File

@ -1,150 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/internal/Attic/ICUBinary.java,v $
* $Date: 2002/02/08 23:22:40 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
package com.ibm.icu.internal;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;
public final class ICUBinary
{
/**
* <p>ICU data header reader method.
* Takes a ICU generated big-endian input stream, parse the ICU standard
* file header and authenticates them.</p>
* <p>Header format:
* <ul>
* <li> Header size (char)
* <li> Magic number 1 (byte)
* <li> Magic number 2 (byte)
* <li> Rest of the header size (char)
* <li> Reserved word (char)
* <li> Big endian indicator (byte)
* <li> Character set family indicator (byte)
* <li> Size of a char (byte) for c++ and c use
* <li> Reserved byte (byte)
* <li> Data format identifier (4 bytes), each ICU data has its own
* identifier to distinguish them. [0] major [1] minor
* [2] milli [3] micro
* <li> Data version (4 bytes), the change version of the ICU data
* [0] major [1] minor [2] milli [3] micro
* <li> Unicode version (4 bytes) this ICU is based on.
* </ul>
* </p>
* <p>
* Example of use:<br>
* <pre>
* try {
* FileInputStream input = new FileInputStream(filename);
* If (Utility.readICUDataHeader(input, dataformat, dataversion,
* unicode) {
* System.out.println("Verified file header, this is a ICU data file");
* }
* } catch (IOException e) {
* System.out.println("This is not a ICU data file");
* }
* </pre>
* </p>
* @param inputStream input stream that contains the ICU data header
* @param dataFormatIDExpected Data format expected. An array of 4 bytes
* information about the data format.
* E.g. data format ID 1.2.3.4. will became an array of
* {1, 2, 3, 4}
* @param dataVersionExpected Data version expected. An array of 4 bytes
* information about the data version.
* E.g. data version 1.2.3.4. will became an array of
* {1, 2, 3, 4}
* @param unicodeVersionExpected Unicode version expected. An array of 4
* bytes information about the unicode
* version this set of data belongs to.
* E.g. unicode version 3.1.1.0. will became an array
* of {3, 1, 1, 0}
* @exception IOException thrown if there is a read error or
* when header authentication fails.
* @draft 2.1
*/
public static final void readHeader(InputStream inputStream,
byte dataFormatIDExpected[],
byte dataVersionExpected[],
byte unicodeVersionExpected[])
throws IOException
{
DataInputStream input = new DataInputStream(inputStream);
char headersize = input.readChar();
headersize -= 2;
//reading the header format
byte magic1 = input.readByte();
headersize --;
byte magic2 = input.readByte();
headersize --;
if (magic1 != MAGIC1 || magic2 != MAGIC2) {
throw new IOException(MAGIC_NUMBER_AUTHENTICATION_FAILED_);
}
input.readChar(); // reading size
headersize -= 2;
input.readChar(); // reading reserved word
headersize -= 2;
byte bigendian = input.readByte();
headersize --;
byte charset = input.readByte();
headersize --;
byte charsize = input.readByte();
headersize --;
input.readByte(); // reading reserved byte
headersize --;
byte dataFormatID[] = new byte[4];
input.readFully(dataFormatID);
headersize -= 4;
byte dataVersion[] = new byte[4];
input.readFully(dataVersion);
headersize -= 4;
byte unicodeVersion[] = new byte[4];
input.readFully(unicodeVersion);
headersize -= 4;
input.skipBytes(headersize);
if (bigendian != BIG_ENDIAN_ || charset != CHAR_SET_ ||
charsize != CHAR_SIZE_ ||
!Arrays.equals(dataFormatIDExpected, dataFormatID) ||
!Arrays.equals(dataVersionExpected, dataVersion) ||
!Arrays.equals(unicodeVersionExpected, unicodeVersion)) {
throw new IOException(HEADER_AUTHENTICATION_FAILED_);
}
}
// private variables -------------------------------------------------
/**
* Magic numbers to authenticate the data file
*/
private static final byte MAGIC1 = (byte)0xda;
private static final byte MAGIC2 = (byte)0x27;
/**
* File format authentication values
*/
private static final byte BIG_ENDIAN_ = 1;
private static final byte CHAR_SET_ = 0;
private static final byte CHAR_SIZE_ = 2;
/**
* Error messages
*/
private static final String MAGIC_NUMBER_AUTHENTICATION_FAILED_ =
"ICU data file error: Not an ICU data file";
private static final String HEADER_AUTHENTICATION_FAILED_ =
"ICU data file error: Header authentication failed, please check if you have the most updated ICU data file";
}

View File

@ -1,610 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/internal/Attic/UInfo.java,v $
* $Date: 2001/09/08 01:13:38 $
* $Revision: 1.3 $
*
*****************************************************************************************
*/
package com.ibm.icu.internal;
import java.io.*;
import java.util.*;
import com.ibm.util.Utility;
public final class UInfo {
static final boolean DEBUG = false;
static final int UINFO_VERSION = 5;
// these values are aligned with the java.lang.Character constants
public static final byte
UNASSIGNED = 0,
UPPERCASE_LETTER = 1,
LOWERCASE_LETTER = 2,
TITLECASE_LETTER = 3,
MODIFIER_LETTER = 4,
OTHER_LETTER = 5,
NON_SPACING_MARK = 6,
ENCLOSING_MARK = 7,
COMBINING_SPACING_MARK = 8,
DECIMAL_DIGIT_NUMBER = 9,
LETTER_NUMBER = 10,
OTHER_NUMBER = 11,
SPACE_SEPARATOR = 12,
LINE_SEPARATOR = 13,
PARAGRAPH_SEPARATOR = 14,
CONTROL = 15,
FORMAT = 16,
PRIVATE_USE = 18,
SURROGATE = 19,
DASH_PUNCTUATION = 20,
START_PUNCTUATION = 21,
END_PUNCTUATION = 22,
CONNECTOR_PUNCTUATION = 23,
OTHER_PUNCTUATION = 24,
MATH_SYMBOL = 25,
CURRENCY_SYMBOL = 26,
MODIFIER_SYMBOL = 27,
OTHER_SYMBOL = 28;
public String getName(char ch) {return getInfo(ch).name;}
public String getDecomposition(char ch) {return getInfo(ch).decomposition;}
public String getName10(char ch) {return getInfo(ch).name10;}
public String getComment(char ch) {return getInfo(ch).comment;}
public float getNumeric(char ch) {return getInfo(ch).numeric;}
public short getCanonicalClass(char ch) {return getInfo(ch).canonical;}
public short getDecimal(char ch) {return getInfo(ch).decimal;}
public short getDigit(char ch) {return getInfo(ch).digit;}
public char getUppercase(char ch) {return getInfo(ch).uppercase;}
public char getLowercase(char ch) {return getInfo(ch).lowercase;}
public char getTitlecase(char ch) {return getInfo(ch).titlecase;}
public byte getCategory(char ch) {return getInfo(ch).category;}
public byte getBidiClass(char ch) {return getInfo(ch).bidi;}
public boolean getMirrored(char ch) {return getInfo(ch).mirrored;}
public boolean isDisparaged(char ch) { return getDecomposition(ch).length() == 4; }
public boolean isLetter(char ch) {
return (0 != ((1<<getCategory(ch)) &
((1<<UPPERCASE_LETTER)
| (1<<LOWERCASE_LETTER)
| (1<<TITLECASE_LETTER)
| (1<<MODIFIER_LETTER)
| (1<<MODIFIER_LETTER))));
}
public boolean isMark(char ch) {
return (0 != ((1<<getCategory(ch)) &
((1<<NON_SPACING_MARK)
| (1<<ENCLOSING_MARK)
| (1<<COMBINING_SPACING_MARK))));
}
public boolean isNumber(char ch) {
return (0 != ((1<<getCategory(ch)) &
((1<<DECIMAL_DIGIT_NUMBER)
| (1<<LETTER_NUMBER)
| (1<<OTHER_NUMBER))));
}
public boolean isSeparator(char ch) {
return (0 != ((1<<getCategory(ch)) &
((1<<SPACE_SEPARATOR)
| (1<<LINE_SEPARATOR)
| (1<<PARAGRAPH_SEPARATOR))));
}
public boolean isFormat(char ch) {
return (0 != ((1<<getCategory(ch)) &
((1<<CONTROL)
| (1<<FORMAT))));
}
public boolean isPunctuation(char ch) {
return (0 != ((1<<getCategory(ch)) &
((1<<DASH_PUNCTUATION)
| (1<<START_PUNCTUATION)
| (1<<END_PUNCTUATION)
| (1<<CONNECTOR_PUNCTUATION)
| (1<<START_PUNCTUATION)
| (1<<END_PUNCTUATION)
| (1<<OTHER_PUNCTUATION))));
}
public boolean isSymbol(char ch) {
return (0 != ((1<<getCategory(ch)) &
((1<<MATH_SYMBOL)
| (1<<CURRENCY_SYMBOL)
| (1<<MODIFIER_SYMBOL)
| (1<<OTHER_SYMBOL))));
}
//
// Characters excluded from composition. This is read from the Unicode
// file CompositionExclusions.txt.
//
String composeExclude = "";
/**
* Is this character excluded from the composition algorithm by virtue
* of being listed in the composition exclusion table in Tech Report #15?
*/
public boolean isExcludedComposition(char ch) {
return isDisparaged(ch)
|| composeExclude.indexOf(ch) >= 0
|| getCanonicalClass(getDecompositionChars(ch).charAt(0)) != 0;
}
public String getName(String s) {
return getName(s,true);
}
public String getName(String s, boolean shortVersion) {
StringBuffer temp = new StringBuffer();
for (int i = 0; i < s.length(); ++i) {
if (i != 0) temp.append(", ");
temp.append(getName(s.charAt(i), shortVersion));
}
return temp.toString();
}
public String getName(char ch, boolean shortVersion) {
String result = getName(ch);
if (!shortVersion) return result;
result = replace(result,"LETTER ","");
result = replace(result,"CHARACTER ","");
result = replace(result,"SIGN ","");
result = replace(result,"CAPITAL ","UC ");
if (getCategory(ch) == LOWERCASE_LETTER)
result = replace(result,"SMALL ","LC ");
result = replace(result,"COMBINING ","-");
result = replace(result,"WITH ","");
result = replace(result,"AND ","");
result = replace(result,"VARIA","GRAVE");
result = replace(result,"OXIA","ACUTE");
result = replace(result,"VRACHY","BREVE");
result = replace(result,"VERTICAL LINE ABOVE","TONOS");
result = replace(result,"PSILI","SMOOTH");
result = replace(result,"DASIA","ROUGH");
result = replace(result,"COMMA ABOVE","SMOOTH");
result = replace(result,"REVERSED COMMA ABOVE","ROUGH");
result = replace(result,"YPOGEGRAMMENI","IOTA-SUB");
result = replace(result,"PROSGEGRAMMENI","IOTA-AD");
result = replace(result,"DIALYTIKA","DIAERESIS");
result = replace(result,"PERISPOMENI","CIRCUMFLEX");
result = replace(result,"VOICED SOUND MARK","VOICED SIGN");
result = replace(result,"PROLONGED SOUND MARK","VOICED SIGN");
result = replace(result,"KATAKANA-HIRAGANA","KANA");
result = replace(result,"COMPATIBILITY IDEOGRAPH-","");
result = replace(result,"CHOSEONG","INITIAL");
result = replace(result,"JUNGSEONG","MEDIAL");
result = replace(result,"JONGSEONG","FINAL");
return result.substring(0,1)
+ result.substring(1,result.length()).toLowerCase();
}
public String replace(String source,
String replacee, String replacer) {
int p = source.indexOf(replacee);
if (p == -1) return source;
return source.substring(0,p)
+ replacer
+ source.substring(p+replacee.length(),source.length());
}
public boolean isCCS(String s) {
if (s.length() < 2) return false;
if (isMark(s.charAt(0))) return false;
for (int i = 1; i < s.length(); ++i) {
if (!isMark(s.charAt(i))) return false;
}
return true;
}
// combining base sequence := <cat_zero>+ <cat_pos>*
public boolean isCBS(String s) {
if (s.length() == 0) return false;
if (getCanonicalClass(s.charAt(0)) != 0) return false;
boolean gotGreater = false;
for (int i = 1; i < s.length(); ++i) {
if (getCanonicalClass(s.charAt(i)) == 0) {
if (gotGreater) return false;
} else {
gotGreater = true;
}
}
return true;
}
public boolean hasCanonicalDecomposition(char ch) {
String decomp = getDecomposition(ch);
return (decomp.length() != 0 && decomp.indexOf('<') == -1);
}
public boolean hasCompatibilityDecomposition(char ch) {
String decomp = getDecomposition(ch);
return (decomp.length() != 0 && decomp.indexOf('<') != -1);
}
public boolean isEquivalent(
String a, String b, boolean canonical) {
return getFullDecomposition(a, canonical).equals(
getFullDecomposition(b, canonical));
}
// use very dumb algorithm. Don't need lower order one.
public String getFullDecomposition(
String s, boolean canonical) {
StringBuffer output = new StringBuffer();
for (int i = 0; i < s.length(); ++i) {
getFullDecomp2(s.charAt(i),canonical,output);
}
return fixCanonical(output).toString();
}
public StringBuffer getFullDecomposition(
char ch, boolean canonical, StringBuffer output) {
StringBuffer result = getFullDecomp2(ch,canonical,output);
return fixCanonical(result);
}
public String getFullDecomposition(
char ch, boolean canonical) {
return getFullDecomposition(ch, canonical, new StringBuffer()).toString();
}
/**
* Given a decomposed string of characters, put it in canonical
* order by finding and processing all exchangeable pairs.
*/
public StringBuffer fixCanonical(StringBuffer target) {
for (int i = 1; i < target.length(); ++i) {
char ch = target.charAt(i);
short canClass = getCanonicalClass(ch);
char chPrev = target.charAt(i-1);
short canClassPrev = getCanonicalClass(chPrev);
if (canClass != 0 && canClass < canClassPrev) {
target.setCharAt(i-1, ch);
target.setCharAt(i, chPrev);
if (i > 1) i -= 2; // backup (-1 to compensate for loop)
}
}
return target;
}
public String fixCanonical(String source) {
return fixCanonical(new StringBuffer(source)).toString();
}
// ============================================
// PRIVATES
// ============================================
static class CharData {
public CharData() {
};
String name = "";
String decomposition = "";
String name10 = "";
String comment = "";
float numeric = Float.MIN_VALUE;
short canonical = 0;
short decimal = Short.MIN_VALUE;
short digit = Short.MIN_VALUE;
char uppercase;
char lowercase;
char titlecase;
byte category;
byte bidi = 0;
boolean mirrored;
};
private static final CharData UNASSIGNED_INFO = new CharData();
private static char cachedChar = 0xFFFF;
private CharData getInfo(char ch) {
if (ch == cachedChar) return UNASSIGNED_INFO;
// remap special ranges
if (ch >= 0x4E00 && ch < 0xF900) {
if (ch <= 0x9FA5) ch = 0x4E00;
else if (ch >= 0xAC00 && ch <= 0xD7A3) ch = 0xAC00;
else if (ch >= 0xD800 && ch <= 0xDFFF) ch = 0xD800;
else if (ch >= 0xE000) ch = 0xE000;
}
Object value = cache[ch];
CharData result;
if (value == null) {
result = UNASSIGNED_INFO;
} else if (value instanceof String) {
result = updateCache((String)value);
} else {
result = (CharData)value;
}
return result;
}
private StringBuffer getFullDecomp2(
char ch, boolean canonical, StringBuffer output) {
String decomp = getDecomposition(ch);
if (decomp.length() == 0
|| (canonical && decomp.indexOf('<') != -1)) {
output.append(ch);
return output;
}
boolean inBrackets = false;
for (int i = 0; i < decomp.length(); ++i) {
char c = decomp.charAt(i);
if (c == '<') inBrackets = true;
else if (c == '>') inBrackets = false;
else if (inBrackets) ; // skip
else if (c == ' ') ; // skip
else {
String tempString = decomp.substring(i,i+4);
char temp = (char)Integer.parseInt(tempString,16);
getFullDecomposition(temp,canonical,output);
i+= 3;
}
}
return output;
}
public String getDecompositionChars(char ch) {
StringBuffer output = new StringBuffer();
String decomp = getDecomposition(ch);
if (decomp.length() == 0) {
output.append(ch);
return output.toString();
}
boolean inBrackets = false;
for (int i = 0; i < decomp.length(); ++i) {
char c = decomp.charAt(i);
if (c == '<') inBrackets = true;
else if (c == '>') inBrackets = false;
else if (inBrackets) ; // skip
else if (c == ' ') ; // skip
else {
String tempString = decomp.substring(i,i+4);
char temp = (char)Integer.parseInt(tempString,16);
output.append(temp);
i+= 3;
}
}
return output.toString();
}
public UInfo(String fileName, String composeExcludeFileName) {
// not used long startTime,endTime;
BufferedReader input = null;
String line = null;
try {
input = new BufferedReader(new FileReader(fileName),64*1024);
for (int count = 0;;++count) {
line = input.readLine();
if (line == null) break;
if (line.length() == 0) continue;
char ch = charFrom(line.substring(0,4));
if (DEBUG) if ((count % 100) == 0)
System.out.println("[" + count + "," + Utility.hex(ch) + ']');
cache[ch] = line;
}
// Read composition exlusions
input = new BufferedReader(new FileReader(composeExcludeFileName),64*1024);
StringBuffer ce = new StringBuffer();
for (;;) {
line = input.readLine();
if (line == null) break;
if (line.length() == 0 ||
Character.digit(line.charAt(0), 16) < 0) continue;
ce.append(charFrom(line.substring(0,4)));
}
composeExclude = ce.toString();
} catch (Exception ex) {
try {
input.close();
} catch (Exception ex2) {
System.out.print("");
}
ex.printStackTrace();
throw new IllegalArgumentException("Couldn't read file "
+ ex.getClass().getName() + " " + ex.getMessage()
+ " line = " + line
);
}
}
public UInfo() {
// FIX
// This is bad...this path must be correct relative to the
// user's current directory. I have changed it so that it's
// relative to the root icu4j directory, so it works as long
// as code is run from that directory, e.g., "java -classpath
// classes...". A better way to do this might be to get it
// from a system property that is defined on the command line,
// e.g., "java -Dicu4j=D:/icu4j..." - liu
this("src/data/unicode/UnicodeData-3.0.0.txt",
"src/data/unicode/CompositionExclusions-1.txt");
}
/*
0 Code value in 4-digit hexadecimal format.
1 Unicode 2.1 Character Name. These names match exactly the
2 General Category. This is a useful breakdown into various "character
3 Canonical Combining Classes. The classes used for the
4 Bidirectional Category. See the list below for an explanation of the
5 Character Decomposition. In the Unicode Standard, not all of
6 Decimal digit value. This is a numeric field. If the character
7 Digit value. This is a numeric field. If the character represents a
8 Numeric value. This is a numeric field. If the character has the
9 If the characters has been identified as a "mirrored" character in
10 Unicode 1.0 Name. This is the old name as published in Unicode 1.0.
11 10646 Comment field. This field is informative.
12 Upper case equivalent mapping. If a character is part of an
13 Lower case equivalent mapping. Similar to 12. This field is informative.
14 Title case equivalent mapping. Similar to 12. This field is informative.
*/
private CharData updateCache(String line) {
try {
String[] parts = new String[30];
Utility.split(line,';',parts);
CharData info = new CharData();
char ch = charFrom(parts[0]);
info.name = parts[1];
info.category = (byte)Utility.lookup(parts[2], CATEGORY_TABLE);
info.canonical = shortFrom(parts[3]);
info.bidi = (byte)Utility.lookup(parts[4], BIDI_TABLE);
info.decomposition = parts[5];
info.decimal = shortFrom(parts[6]);
info.digit = shortFrom(parts[7]);
info.numeric = floatFrom(parts[8]);
info.mirrored = charFrom(parts[9]) == 'Y';
info.name10 = parts[10];
info.comment = parts[11];
info.uppercase = charFrom(parts[12]);
if (info.uppercase == 0) info.uppercase = ch;
info.lowercase = charFrom(parts[13]);
if (info.lowercase == 0) info.lowercase = ch;
info.titlecase = charFrom(parts[14]);
if (info.titlecase == 0) info.titlecase = info.uppercase;
String trial = Utility.hex(ch) + ";" + info;
if (DEBUG) if (!trial.equals(line)) {
System.out.println("Difference between:");
System.out.println(line);
System.out.println(trial);
}
cache[ch] = info;
return info;
}
catch (NumberFormatException e) {
System.out.println("updateCache: error parsing '" + line + "'");
throw e;
}
}
private static CharData typeInfo = new CharData();
private boolean latin1(char c) {
return ((c >= 20 && c <= 0x7F) || c > 0xA0);
}
private static final String[] YN_TABLE = {"N", "Y"};
private static final String[] CATEGORY_TABLE = {
"Cn", // = Other, Not Assigned
"Lu", // = Letter, Uppercase
"Ll", // = Letter, Lowercase
"Lt", // = Letter, Titlecase
"Lm", // = Letter, Modifier
"Lo", // = Letter, Other
"Mn", // = Mark, Non-Spacing
"Me", // = Mark, Enclosing
"Mc", // = Mark, Spacing Combining
"Nd", // = Number, Decimal Digit
"Nl", // = Number, Letter
"No", // = Number, Other
"Zs", // = Separator, Space
"Zl", // = Separator, Line
"Zp", // = Separator, Paragraph
"Cc", // = Other, Control
"Cf", // = Other, Format
"", // unused
"Co", // = Other, Private Use
"Cs", // = Other, Surrogate
"Pd", // = Punctuation, Dash
"Ps", // = Punctuation, Open
"Pe", // = Punctuation, Close
"Pc", // = Punctuation, Connector
"Po", // = Punctuation, Other
"Sm", // = Symbol, Math
"Sc", // = Symbol, Currency
"Sk", // = Symbol, Modifier
"So", // = Symbol, Other
"Pi", // = Punctuation, Initial quote (may behave like Ps or Pe depending on usage)
"Pf", // = Punctuation, Final quote (may behave like Ps or Pe dependingon usage)
};
private static String[] BIDI_TABLE = {
"L", // Left-Right; Most alphabetic, syllabic, and logographic characters (e.g., CJK ideographs)
"R", // Right-Left; Arabic, Hebrew, and punctuation specific to those scripts
"EN", // European Number
"ES", // European Number Separator
"ET", // European Number Terminator
"AN", // Arabic Number
"CS", // Common Number Separator
"B", // Block Separator
"S", // Segment Separator
"WS", // Whitespace
"ON" // Other Neutrals ; All other characters: punctuation, symbols
};
private static short shortFrom(String p) {
if (p.length() == 0) return Short.MIN_VALUE;
return Short.parseShort(p);
}
private static float floatFrom(String p) {
try {
if (p.length() == 0) return Float.MIN_VALUE;
int fract = p.indexOf('/');
if (fract == -1) return Float.valueOf(p).floatValue();
String q = p.substring(0,fract);
float num = 0;
if (q.length() != 0) num = Integer.parseInt(q);
p = p.substring(fract+1,p.length());
float den = 0;
if (p.length() != 0) den = Integer.parseInt(p);
return num/den;
}
catch (NumberFormatException e) {
System.out.println("floatFrom: error parsing '" + p + "'");
throw e;
}
}
private static char charFrom(String p) {
if (p.length() == 0) return '\u0000';
else if (p.length() == 1) return p.charAt(0);
int temp = Integer.parseInt(p, 16);
if (temp < 0 || temp > 0xFFFF)
throw new NumberFormatException(
"Hex char out of range: " + p);
return (char)temp;
}
private Object[] cache = new Object[65536];
}

View File

@ -1,391 +0,0 @@
/*
******************************************************************************
* Copyright (C) 1996-2002, International Business Machines Corporation and *
* others. All Rights Reserved. *
******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/internal/util/Attic/Trie.java,v $
* $Date: 2002/02/08 01:08:38 $
* $Revision: 1.1 $
*
******************************************************************************
*/
package com.ibm.icu.internal.util;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.IOException;
import com.ibm.text.UTF16;
import com.ibm.text.UCharacter;
/**
* <p>A trie is a kind of compressed, serializable table of values
* associated with Unicode code points (0..0x10ffff).</p>
* <p>This class defines the basic structure of a trie and provides methods
* to <b>retrieve the offsets to the actual data</b>.</p>
* <p>Data will be the form of an array of basic types, char or int.</p>
* <p>The actual data format will have to be specified by the user in the
* inner static interface com.ibm.icu.util.Trie.DataManipulate.</p>
* <p>This trie implementation is optimized for getting offset while walking
* forward through a UTF-16 string.
* Therefore, the simplest and fastest access macros are the
* fromLead() and fromOffsetTrail() methods.
* The fromBMP() method are a little more complicated; they get offsets even
* for lead surrogate codepoints, while the fromLead() method get special
* "folded" offsets for lead surrogate code units if there is relevant data
* associated with them.
* From such a folded offsets, an offset needs to be extracted to supply
* to the fromOffsetTrail() methods.
* To handle such supplementary codepoints, some offset information are kept
* in the data.</p>
* <p>Methods in com.ibm.icu.util.Trie.DataManipulate are called to retrieve that
* offset from the folded value for the lead surrogate unit.</p>
* <p>For examples of use, see com.ibm.icu.util.CharTrie or
* com.ibm.icu.util.IntTrie.</p>
* @author synwee
* @see com.ibm.icu.util.CharTrie
* @see com.ibm.icu.util.IntTrie
* @since release 2.1, Jan 01 2002
*/
public abstract class Trie
{
// public class declaration ----------------------------------------
/**
* Character data in com.ibm.util.Trie have different user-specified format
* for different purposes.
* This interface specifies methods to be implemented in order for
* com.ibm.util.Trie, to surrogate offset information encapsulated within
* the data.
* @draft 2.1
*/
public static interface DataManipulate
{
/**
* Called by com.ibm.icu.util.Trie to extract from a lead surrogate's
* data
* the index array offset of the indexes for that lead surrogate.
* @param value data value for a surrogate from the trie, including the
* folding offset
* @return data offset or 0 if there is no data for the lead surrogate
* @draft 2.1
*/
public int getFoldingOffset(int value);
}
// protected constructor -------------------------------------------
/**
* Trie constructor for CharTrie use.
* @param inputStream ICU data file input stream which contains the
* trie
* @param datamanipulate object containing the information to parse the
* trie data
* @exception IOException thrown when input stream does not have the
* right header.
* @draft 2.1
*/
protected Trie(InputStream inputStream,
DataManipulate dataManipulate) throws IOException
{
DataInputStream input = new DataInputStream(inputStream);
// Magic number to authenticate the data.
int signature = input.readInt();
m_options_ = input.readInt();
if (!checkHeader(signature)) {
throw new IllegalArgumentException("ICU data file error: Trie header authentication failed, please check if you have the most updated ICU data file");
}
m_dataManipulate_ = dataManipulate;
m_isLatin1Linear_ = (m_options_ &
HEADER_OPTIONS_LATIN1_IS_LINEAR_MASK_) != 0;
m_dataOffset_ = input.readInt();
m_dataLength_ = input.readInt();
unserialize(inputStream);
}
// protected data members ------------------------------------------
/**
* Shift size for shifting right the input index. 1..9
* @draft 2.1
*/
protected static final int INDEX_STAGE_1_SHIFT_ = 5;
/**
* Shift size for shifting left the index array values.
* Increases possible data size with 16-bit index values at the cost
* of compactability.
* This requires blocks of stage 2 data to be aligned by
* DATA_GRANULARITY.
* 0..INDEX_STAGE_1_SHIFT
* @draft 2.1
*/
protected static final int INDEX_STAGE_2_SHIFT_ = 2;
/**
* Mask for getting the lower bits from the input index.
* DATA_BLOCK_LENGTH_ - 1.
* @draft 2.1
*/
protected static final int INDEX_STAGE_3_MASK_ =
(1 << INDEX_STAGE_1_SHIFT_) - 1;
/**
* Surrogate mask to use when shifting offset to retrieve supplementary
* values
* @draft 2.1
*/
protected static final int SURROGATE_MASK_ = 0x3FF;
/**
* Index or UTF16 characters
* @draft 2.1
*/
protected char m_index_[];
/**
* Internal TrieValue which handles the parsing of the data value.
* This class is to be implemented by the user
* @draft 2.1
*/
protected DataManipulate m_dataManipulate_;
/**
* Start index of the data portion of the trie. CharTrie combines
* index and data into a char array, so this is used to indicate the
* initial offset to the data portion.
* @draft 2.1
*/
protected int m_dataOffset_;
/**
* Length of the data array
*/
protected int m_dataLength_;
// protected methods -----------------------------------------------
/**
* Gets the offset to the data which the surrogate pair points to.
* @param lead lead surrogate
* @param trail trailing surrogate
* @return offset to data
* @draft 2.1
*/
protected abstract int getSurrogateOffset(char lead, char trail);
/**
* Gets the value at the argument index
* @param index value at index will be retrieved
* @return 32 bit value
* @draft 2.1
*/
protected abstract int getValue(int index);
/**
* Gets the default initial value
* @return 32 bit value
* @draft 2.1
*/
protected abstract int getInitialValue();
/**
* Gets the offset to the data which the index ch after variable offset
* points to.
* Note for locating a non-supplementary character data offset, calling
* <p>
* getRawOffset(0, ch);
* </p>
* will do. Otherwise if it is a supplementary character formed by
* surrogates lead and trail. Then we would have to call getRawOffset()
* with getFoldingIndexOffset(). See getSurrogateOffset().
* This is different from the C macro, because macros does not need to
* handle types.
* @param offset index offset which ch is to start from
* @param ch index to be used after offset
* @return offset to the data
* @draft 2.1
*/
protected final int getRawOffset(int offset, char ch)
{
return (m_index_[offset + (ch >> INDEX_STAGE_1_SHIFT_)] <<
INDEX_STAGE_2_SHIFT_) + (ch & INDEX_STAGE_3_MASK_);
}
/**
* Gets the offset to data which the BMP character points to
* Treats a lead surrogate as a normal code point.
* @param ch BMP character
* @return offset to data
* @draft 2.1
*/
protected final int getBMPOffset(char ch)
{
int offset = 0;
if (UTF16.isLeadSurrogate(ch)) {
offset = LEAD_INDEX_OFFSET_;
}
return getRawOffset(offset, ch);
}
/**
* Gets the offset to the data which this lead surrogate character points
* to.
* Data at the returned offset may contain folding offset information for
* the next trailing surrogate character.
* @param ch lead surrogate character
* @return offset to data
* @draft 2.1
*/
protected final int getLeadOffset(char ch)
{
return getRawOffset(0, ch);
}
/**
* Internal trie getter from a code point.
* Could be faster(?) but longer with
* if((c32)<=0xd7ff) { (result)=_TRIE_GET_RAW(trie, data, 0, c32); }
* Gets the offset to data which the codepoint points to
* @param ch codepoint
* @return offset to data
* @draft 2.1
*/
protected final int getCodePointOffset(int ch)
{
if (UCharacter.isBMP(ch)) {
// BMP codepoint
return getBMPOffset((char)ch);
}
if (ch <= UCharacter.MAX_VALUE)
{
char lead = UTF16.getLeadSurrogate(ch);
// look at the construction of supplementary characters
// trail forms the ends of it.
return getSurrogateOffset(lead, (char)(ch & SURROGATE_MASK_));
}
// return -1 if there is an error, in this case we return the default
// value: m_initialValue_
return -1;
}
/**
* <p>Parses the inputstream and creates the trie index with it.</p>
* <p>This is overwritten by the child classes.
* @param inputStream input stream containing the trie information
* @exception IOException thrown when data reading fails.
* @draft 2.1
*/
protected void unserialize(InputStream inputStream) throws IOException
{
//indexLength is a multiple of 1024 >> INDEX_STAGE_2_SHIFT_
m_index_ = new char[m_dataOffset_];
DataInputStream input = new DataInputStream(inputStream);
for (int i = 0; i < m_dataOffset_; i ++) {
m_index_[i] = input.readChar();
}
}
/**
* Determines if this is a 32 bit trie
* @return true if options specifies this is a 32 bit trie
* @draft 2.1
*/
protected final boolean isIntTrie()
{
return (m_options_ & HEADER_OPTIONS_DATA_IS_32_BIT_) != 0;
}
/**
* Determines if this is a 16 bit trie
* @return true if this is a 16 bit trie
* @draft 2.1
*/
protected final boolean isCharTrie()
{
return (m_options_ & HEADER_OPTIONS_DATA_IS_32_BIT_) == 0;
}
// private data members --------------------------------------------
/**
* Lead surrogate code points' index displacement in the index array.
* 0x10000-0xd800=0x2800
* 0x2800 >> INDEX_STAGE_1_SHIFT_
*/
private static final int LEAD_INDEX_OFFSET_ =
0x2800 >> 5;
/**
* Signature index
*/
private static final int HEADER_SIGNATURE_INDEX_ = 0;
/**
* Options index
*/
private static final int HEADER_OPTIONS_INDEX_ = 1 << 1;
/**
* Index length index
*/
private static final int HEADER_INDEX_LENGTH_INDEX_ = 2 << 1;
/**
* Data length index
*/
private static final int HEADER_DATA_LENGTH_INDEX_ = 3 << 1;
/**
* Size of header
*/
private static final int HEADER_LENGTH_ = 4 << 1;
/**
* Latin 1 option mask
*/
private static final int HEADER_OPTIONS_LATIN1_IS_LINEAR_MASK_ = 0x200;
/**
* Constant number to authenticate the byte block
*/
private static final int HEADER_SIGNATURE_ = 0x54726965;
/**
* Header option formatting
*/
private static final int HEADER_OPTIONS_SHIFT_MASK_ = 0xF;
private static final int HEADER_OPTIONS_INDEX_SHIFT_ = 4;
private static final int HEADER_OPTIONS_DATA_IS_32_BIT_ = 0x100;
/**
* Flag indicator for Latin quick access data block
*/
private boolean m_isLatin1Linear_;
/**
* <p>Trie options field.</p>
* <p>options bit field:<br>
* 9 1 = Latin-1 data is stored linearly at data + DATA_BLOCK_LENGTH<br>
* 8 0 = 16-bit data, 1=32-bit data<br>
* 7..4 INDEX_STAGE_1_SHIFT // 0..INDEX_STAGE_2_SHIFT<br>
* 3..0 INDEX_STAGE_2_SHIFT // 1..9<br>
*/
private int m_options_;
// private methods ---------------------------------------------------
/**
* Authenticates raw data header.
* Checking the header information, signature and options.
* @param rawdata array of char data to be checked
* @return true if the header is authenticated valid
* @draft 2.1
*/
private final boolean checkHeader(int signature)
{
// check the signature
// Trie in big-endian US-ASCII (0x54726965).
// Magic number to authenticate the data.
if (signature != HEADER_SIGNATURE_) {
return false;
}
if ((m_options_ & HEADER_OPTIONS_SHIFT_MASK_) !=
INDEX_STAGE_1_SHIFT_ ||
((m_options_ >> HEADER_OPTIONS_INDEX_SHIFT_) &
HEADER_OPTIONS_SHIFT_MASK_)
!= INDEX_STAGE_2_SHIFT_) {
return false;
}
return true;
}
}

View File

@ -1,477 +0,0 @@
/*
******************************************************************************
* Copyright (C) 1996-2002, International Business Machines Corporation and *
* others. All Rights Reserved. *
******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/internal/util/Attic/TrieIterator.java,v $
* $Date: 2002/02/08 23:44:22 $
* $Revision: 1.2 $
*
******************************************************************************
*/
package com.ibm.icu.internal.util;
import com.ibm.text.UCharacter;
import com.ibm.text.UTF16;
import com.ibm.icu.util.RangeValueIterator;
/**
* <p>Class enabling iteration of the values in a Trie.</p>
* <p>Result of each iteration contains the interval of codepoints that have
* the same value type and the value type itself.</p>
* <p>The comparison of each codepoint value is done via extract(), which the
* default implementation is to return the value as it is.</p>
* <p>Method extract() can be overwritten to perform manipulations on
* codepoint values in order to perform specialized comparison.</p>
* <p>TrieIterator is designed to be a generic iterator for the CharTrie
* and the IntTrie, hence to accommodate both types of data, the return
* result will be in terms of int (32 bit) values.</p>
* <p>See com.ibm.icu.text.UCharacterTypeIterator for examples of use.</p>
* @author synwee
* @see com.ibm.icu.util.Trie
* @see com.ibm.icu.text.UCharacterTypeIterator
* @since release 2.1, Jan 17 2002
*/
public class TrieIterator implements RangeValueIterator
{
// public constructor ---------------------------------------------
/**
* TrieEnumeration constructor
* @param trie to be used
* @exception IllegalArgumentException throw when argument is null.
* @draft 2.1
*/
protected TrieIterator(Trie trie)
{
if (trie == null) {
throw new IllegalArgumentException(
"Argument trie cannot be null");
}
m_trie_ = trie;
// synwee: check that extract belongs to the child class
m_initialValue_ = extract(m_trie_.getInitialValue());
reset();
}
// public methods -------------------------------------------------
/**
* <p>Returns true if we are not at the end of the iteration, false
* otherwise.</p>
* <p>The next set of codepoints with the same value type will be
* calculated during this call and returned in the arguement element.</p>
* @param element return result
* @return true if we are not at the end of the iteration, false otherwise.
* @exception NoSuchElementException - if no more elements exist.
* @see #getStart()
* @see #getLimit()
* @see #getValue()
* @draft 2.1
*/
public final boolean next(Element element)
{
if (m_nextCodepoint_ > UCharacter.MAX_VALUE) {
return false;
}
if (m_nextCodepoint_ < UCharacter.SUPPLEMENTARY_MIN_VALUE &&
calculateNextBMPElement(element)) {
return true;
}
calculateNextSupplementaryElement(element);
return true;
}
/**
* Resets the iterator to the beginning of the iteration
* @draft 2.1
*/
public final void reset()
{
m_currentCodepoint_ = 0;
m_nextCodepoint_ = 0;
m_nextIndex_ = 0;
m_nextBlock_ = m_trie_.m_index_[0] << Trie.INDEX_STAGE_2_SHIFT_;
if (m_nextBlock_ == 0) {
m_nextValue_ = m_initialValue_;
}
else {
m_nextValue_ = extract(m_trie_.getValue(m_nextBlock_));
}
m_nextBlockIndex_ = 0;
m_nextTrailIndexOffset_ = TRAIL_SURROGATE_INDEX_BLOCK_LENGTH_;
}
// protected methods ----------------------------------------------
/**
* Called by next() to extracts a 32 bit value from a trie value
* used for comparison.
* This method is to be overwritten if special manipulation is to be done
* to retrieve a relevant comparison.
* The default function is to return the value as it is.
* @param value a value from the trie
* @return extracted value
* @draft 2.1
*/
protected int extract(int value)
{
return value;
}
// private methods ------------------------------------------------
/**
* Set the result values
* @param element return result object
* @param start codepoint of range
* @param limit (end + 1) codepoint of range
* @param value common value of range
*/
private final void setResult(Element element, int start, int limit,
int value)
{
element.start = start;
element.limit = limit;
element.value = value;
}
/**
* Finding the next element.
* This method is called just before returning the result of
* next().
* We always store the next element before it is requested.
* In the case that we have to continue calculations into the
* supplementary planes, a false will be returned.
* @param element return result object
* @return true if the next range is found, false if we have to proceed to
* the supplementary range.
*/
private final boolean calculateNextBMPElement(Element element)
{
int currentBlock = m_nextBlock_;
int currentValue = m_nextValue_;
m_currentCodepoint_ = m_nextCodepoint_;
m_nextCodepoint_ ++;
m_nextBlockIndex_ ++;
if (!checkBlockDetail(currentValue)) {
setResult(element, m_currentCodepoint_, m_nextCodepoint_,
currentValue);
return true;
}
// enumerate BMP - the main loop enumerates data blocks
while (m_nextCodepoint_ < UCharacter.SUPPLEMENTARY_MIN_VALUE) {
m_nextIndex_ ++;
// because of the way the character is split to form the index
// the lead surrogate and trail surrogate can not be in the
// mid of a block
if (m_nextCodepoint_ == LEAD_SURROGATE_MIN_VALUE_) {
// skip lead surrogate code units,
// go to lead surrogate codepoints
m_nextIndex_ = BMP_INDEX_LENGTH_;
}
else if (m_nextCodepoint_ == TRAIL_SURROGATE_MIN_VALUE_) {
// go back to regular BMP code points
m_nextIndex_ = m_nextCodepoint_ >> Trie.INDEX_STAGE_1_SHIFT_;
}
m_nextBlockIndex_ = 0;
if (!checkBlock(currentBlock, currentValue)) {
setResult(element, m_currentCodepoint_, m_nextCodepoint_,
currentValue);
return true;
}
}
m_nextCodepoint_ --; // step one back since this value has not been
m_nextBlockIndex_ --; // retrieved yet.
return false;
}
/**
* Finds the next supplementary element.
* For each entry in the trie, the value to be delivered is passed through
* extract().
* We always store the next element before it is requested.
* Called after calculateNextBMP() completes its round of BMP characters.
* There is a slight difference in the usage of m_currentCodepoint_
* here as compared to calculateNextBMP(). Though both represents the
* lower bound of the next element, in calculateNextBMP() it gets set
* at the start of any loop, where-else, in calculateNextSupplementary()
* since m_currentCodepoint_ already contains the lower bound of the
* next element (passed down from calculateNextBMP()), we keep it till
* the end before resetting it to the new value.
* Note, if there are no more iterations, it will never get to here.
* Blocked out by next().
* @param element return result object
* @draft 2.1
*/
private final void calculateNextSupplementaryElement(Element element)
{
int currentValue = m_nextValue_;
int currentBlock = m_nextBlock_;
m_nextCodepoint_ ++;
m_nextBlockIndex_ ++;
if (!checkNullNextTrailIndex() && !checkBlockDetail(currentValue)) {
setResult(element, m_currentCodepoint_, m_nextCodepoint_,
currentValue);
m_currentCodepoint_ = m_nextCodepoint_;
return;
}
// we have cleared one block
m_nextIndex_ ++;
m_nextTrailIndexOffset_ ++;
if (!checkTrailBlock(currentBlock, currentValue)) {
setResult(element, m_currentCodepoint_, m_nextCodepoint_,
currentValue);
m_currentCodepoint_ = m_nextCodepoint_;
return;
}
int nextLead = UTF16.getLeadSurrogate(m_nextCodepoint_);
// enumerate supplementary code points
while (nextLead < TRAIL_SURROGATE_MIN_VALUE_) {
// lead surrogate access
int leadBlock =
m_trie_.m_index_[nextLead >> Trie.INDEX_STAGE_1_SHIFT_] <<
Trie.INDEX_STAGE_2_SHIFT_;
if (leadBlock == m_trie_.m_dataOffset_) {
// no entries for a whole block of lead surrogates
nextLead += DATA_BLOCK_LENGTH_;
// number of total affected supplementary codepoints in one
// block
m_nextCodepoint_ += DATA_BLOCK_SUPPLEMENTARY_LENGTH_;
continue;
}
if (m_trie_.m_dataManipulate_ == null) {
throw new NullPointerException(
"The field DataManipulate in this Trie is null");
}
// enumerate trail surrogates for this lead surrogate
m_nextIndex_ = m_trie_.m_dataManipulate_.getFoldingOffset(
m_trie_.getValue(leadBlock +
(nextLead & Trie.INDEX_STAGE_3_MASK_)));
if (m_nextIndex_ <= 0) {
// no data for this lead surrogate
if (currentValue != m_initialValue_) {
m_nextValue_ = m_initialValue_;
m_nextBlock_ = 0;
m_nextBlockIndex_ = 0;
setResult(element, m_currentCodepoint_, m_nextCodepoint_,
currentValue);
m_currentCodepoint_ = m_nextCodepoint_;
return;
}
m_nextCodepoint_ += TRAIL_SURROGATE_COUNT_;
} else {
m_nextTrailIndexOffset_ = 0;
if (!checkTrailBlock(currentBlock, currentValue)) {
setResult(element, m_currentCodepoint_, m_nextCodepoint_,
currentValue);
m_currentCodepoint_ = m_nextCodepoint_;
return;
}
}
nextLead ++;
}
// deliver last range
setResult(element, m_currentCodepoint_, UCharacter.MAX_VALUE + 1,
currentValue);
}
/**
* Internal block value calculations
* Performs calculations on a data block to find codepoints in m_nextBlock_
* after the index m_nextBlockIndex_ that has the same value.
* Note m_*_ variables at this point is the next codepoint whose value
* has not been calculated.
* But when returned with false, it will be the last codepoint whose
* value has been calculated.
* @param currentValue the value which other codepoints are tested against
* @return true if the whole block has the same value as currentValue or if
* the whole block has been calculated, false otherwise.
*/
private final boolean checkBlockDetail(int currentValue)
{
while (m_nextBlockIndex_ < DATA_BLOCK_LENGTH_) {
m_nextValue_ = extract(m_trie_.getValue(m_nextBlock_ +
m_nextBlockIndex_));
if (m_nextValue_ != currentValue) {
return false;
}
++ m_nextBlockIndex_;
++ m_nextCodepoint_;
}
return true;
}
/**
* Internal block value calculations
* Performs calculations on a data block to find codepoints in m_nextBlock_
* that has the same value.
* Will call checkBlockDetail() if highlevel check fails.
* Note m_*_ variables at this point is the next codepoint whose value
* has not been calculated.
* @param currentBlock the initial block containing all currentValue
* @param currentValue the value which other codepoints are tested against
* @return true if the whole block has the same value as currentValue or if
* the whole block has been calculated, false otherwise.
*/
private final boolean checkBlock(int currentBlock, int currentValue)
{
m_nextBlock_ = m_trie_.m_index_[m_nextIndex_] <<
Trie.INDEX_STAGE_2_SHIFT_;
if (m_nextBlock_ == currentBlock) {
// the block is the same as the previous one, filled with
// currentValue
m_nextCodepoint_ += DATA_BLOCK_LENGTH_;
}
else if (m_nextBlock_ == 0) {
// this is the all-initial-value block
if (currentValue != m_initialValue_) {
m_nextValue_ = m_initialValue_;
m_nextBlockIndex_ = 0;
return false;
}
m_nextCodepoint_ += DATA_BLOCK_LENGTH_;
}
else {
if (!checkBlockDetail(currentValue)) {
return false;
}
}
return true;
}
/**
* Internal block value calculations
* Performs calculations on multiple data blocks for a set of trail
* surrogates to find codepoints in m_nextBlock_ that has the same value.
* Will call checkBlock() for internal block checks.
* Note m_*_ variables at this point is the next codepoint whose value
* has not been calculated.
* @param currentBlock the initial block containing all currentValue
* @param currentValue the value which other codepoints are tested against
* @return true if the whole block has the same value as currentValue or if
* the whole block has been calculated, false otherwise.
*/
private final boolean checkTrailBlock(int currentBlock,
int currentValue)
{
// enumerate code points for this lead surrogate
while (m_nextTrailIndexOffset_ < TRAIL_SURROGATE_INDEX_BLOCK_LENGTH_)
{
// if we ever reach here, we are at the start of a new block
m_nextBlockIndex_ = 0;
// copy of most of the body of the BMP loop
if (!checkBlock(currentBlock, currentValue)) {
return false;
}
m_nextTrailIndexOffset_ ++;
m_nextIndex_ ++;
}
return true;
}
/**
* Checks if we are beginning at the start of a initial block.
* If we are then the rest of the codepoints in this initial block
* has the same values.
* We increment m_nextCodepoint_ and relevant data members if so.
* This is used only in for the supplementary codepoints because
* the offset to the trail indexes could be 0.
* @return true if we are at the start of a initial block.
*/
private final boolean checkNullNextTrailIndex()
{
if (m_nextIndex_ <= 0) {
m_nextCodepoint_ += TRAIL_SURROGATE_COUNT_ - 1;
int nextLead = UTF16.getLeadSurrogate(m_nextCodepoint_);
int leadBlock =
m_trie_.m_index_[nextLead >> Trie.INDEX_STAGE_1_SHIFT_] <<
Trie.INDEX_STAGE_2_SHIFT_;
if (m_trie_.m_dataManipulate_ == null) {
throw new NullPointerException(
"The field DataManipulate in this Trie is null");
}
m_nextIndex_ = m_trie_.m_dataManipulate_.getFoldingOffset(
m_trie_.getValue(leadBlock +
(nextLead & Trie.INDEX_STAGE_3_MASK_)));
m_nextIndex_ --;
m_nextBlockIndex_ = DATA_BLOCK_LENGTH_;
return true;
}
return false;
}
// private data members --------------------------------------------
/**
* Size of the stage 1 BMP indexes
*/
private static final int BMP_INDEX_LENGTH_ =
0x10000 >> Trie.INDEX_STAGE_1_SHIFT_;
/**
* Lead surrogate minimum value
*/
private static final int LEAD_SURROGATE_MIN_VALUE_ = 0xD800;
/**
* Trail surrogate minimum value
*/
private static final int TRAIL_SURROGATE_MIN_VALUE_ = 0xDC00;
/**
* Trail surrogate maximum value
*/
private static final int TRAIL_SURROGATE_MAX_VALUE_ = 0xDFFF;
/**
* Number of trail surrogate
*/
private static final int TRAIL_SURROGATE_COUNT_ = 0x400;
/**
* Number of stage 1 indexes for supplementary calculations that maps to
* each lead surrogate character.
* See second pass into getRawOffset for the trail surrogate character.
* 10 for significant number of bits for trail surrogates, 5 for what we
* discard during shifting.
*/
private static final int TRAIL_SURROGATE_INDEX_BLOCK_LENGTH_ =
1 << (10 - Trie.INDEX_STAGE_1_SHIFT_);
/**
* Number of data values in a stage 2 (data array) block.
*/
private static final int DATA_BLOCK_LENGTH_ =
1 << Trie.INDEX_STAGE_1_SHIFT_;
/**
* Number of codepoints in a stage 2 block
*/
private static final int DATA_BLOCK_SUPPLEMENTARY_LENGTH_ =
DATA_BLOCK_LENGTH_ << 10;
/**
* Trie instance
*/
private Trie m_trie_;
/**
* Initial value for trie values
*/
private int m_initialValue_;
/**
* Next element results and data.
*/
private int m_currentCodepoint_;
private int m_nextCodepoint_;
private int m_nextValue_;
private int m_nextIndex_;
private int m_nextBlock_;
private int m_nextBlockIndex_;
private int m_nextTrailIndexOffset_;
/**
* This is the return result element
*/
private int m_start_;
private int m_limit_;
private int m_value_;
}

View File

@ -1,166 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/DateFormatMiscTests.java,v $
* $Date: 2001/10/29 12:49:02 $
* $Revision: 1.4 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : DateFormatMiscTests
* Source File: $ICU4CRoot/source/test/intltest/miscdtfm.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.text.FieldPosition;
import java.text.ParseException;
import java.util.Locale;
import java.util.Date;
/**
* Performs miscellaneous tests for DateFormat, SimpleDateFormat, DateFormatSymbols
**/
public class DateFormatMiscTests extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception{
new DateFormatMiscTests().run(args);
}
/*
* @bug 4097450
*/
public void Test4097450() {
//
// Date parse requiring 4 digit year.
//
String dstring[] = {
"97", "1997", "97", "1997", "01", "2001", "01", "2001",
"1", "1", "11", "11", "111", "111"};
String dformat[] =
{
"yy", "yy", "yyyy", "yyyy", "yy", "yy", "yyyy", "yyyy",
"yy", "yyyy", "yy", "yyyy", "yy", "yyyy"};
SimpleDateFormat formatter;
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy");
logln("Format\tSource\tResult");
logln("-------\t-------\t-------");
for (int i = 0; i < dstring.length ; i++) {
log(dformat[i] + "\t" + dstring[i] + "\t");
formatter = new SimpleDateFormat(dformat[i]);
try {
StringBuffer str = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
logln(resultFormatter.format(formatter.parse(dstring[i]), str, pos).toString());
}
catch (ParseException exception) {
errln("exception --> " + exception);
}
logln("");
}
}
/* @Bug 4099975
* SimpleDateFormat constructor SimpleDateFormat(String, DateFormatSymbols)
* should clone the DateFormatSymbols parameter
*/
public void Test4099975new() {
Date d = new Date();
//test SimpleDateFormat Constructor
{
DateFormatSymbols symbols = new DateFormatSymbols(Locale.US);
SimpleDateFormat df = new SimpleDateFormat("E hh:mm", symbols);
SimpleDateFormat dfClone = (SimpleDateFormat) df.clone();
logln(df.toLocalizedPattern());
String s0 = df.format(d);
String s_dfClone = dfClone.format(d);
symbols.setLocalPatternChars("abcdefghijklmonpqr"); // change value of field
logln(df.toLocalizedPattern());
String s1 = df.format(d);
if (!s1.equals(s0) || !s1.equals(s_dfClone)) {
errln("Constructor: the formats are not equal");
}
if (!df.equals(dfClone)) {
errln("The Clone Object does not equal with the orignal source");
}
}
//test SimpleDateFormat.setDateFormatSymbols()
{
DateFormatSymbols symbols = new DateFormatSymbols(Locale.US);
SimpleDateFormat df = new SimpleDateFormat("E hh:mm");
df.setDateFormatSymbols(symbols);
SimpleDateFormat dfClone = (SimpleDateFormat) df.clone();
logln(df.toLocalizedPattern());
String s0 = df.format(d);
String s_dfClone = dfClone.format(d);
symbols.setLocalPatternChars("abcdefghijklmonpqr"); // change value of field
logln(df.toLocalizedPattern());
String s1 = df.format(d);
if (!s1.equals(s0) || !s1.equals(s_dfClone)) {
errln("setDateFormatSymbols: the formats are not equal");
}
if (!df.equals(dfClone)) {
errln("The Clone Object does not equal with the orignal source");
}
}
}
/*
* @bug 4117335
*/
public void Test4117335() {
//char bcC[] = {0x7D00, 0x5143, 0x524D};
String bc = "\u7D00\u5143\u524D";
String ad = "\u897f\u66a6";
//char adC[] = {0x897F, 0x66A6};
String jstLong = "\u65e5\u672c\u6a19\u6e96\u6642";
//char jstLongC[] = {0x65e5, 0x672c, 0x6a19, 0x6e96, 0x6642}; //The variable is never used
String jstShort = "JST";
DateFormatSymbols symbols = new DateFormatSymbols(Locale.JAPAN);
final String[] eras = symbols.getEras();
//int eraCount = eras.length; //The variable is never used
logln("BC = " + eras[0]);
if (!eras[0].equals(bc)) {
errln("*** Should have been " + bc);
}
logln("AD = " + eras[1]);
if (!eras[1].equals(ad)) {
errln("*** Should have been " + ad);
}
final String zones[][] = symbols.getZoneStrings();
//int rowCount = zones.length, colCount = zones[0].length; //The variable is never used
logln("Long zone name = " + zones[0][1]);
if (!zones[0][1].equals(jstLong)) {
errln("*** Should have been " + jstLong);
}
logln("Short zone name = " + zones[0][2]);
if (!zones[0][2].equals(jstShort)) {
errln("*** Should have been " + jstShort);
}
logln("Long zone name = " + zones[0][3]);
if (zones[0][3] != jstLong) {
errln("*** Should have been " + jstLong);
}
logln("SHORT zone name = " + zones[0][4]);
if (zones[0][4] != jstShort) {
errln("*** Should have been " + jstShort);
}
}
}

View File

@ -1,882 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/DateFormatRegressionTest.java,v $
* $Date: 2001/10/23 13:08:50 $
* $Revision: 1.3 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : DateFormatRegressionTest
* Source File: $ICU4CRoot/source/test/intltest/dtfmrgts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.Format;
import java.io.*;
/**
* Performs regression test for DateFormat
**/
public class DateFormatRegressionTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception{
new DateFormatRegressionTest().run(args);
}
/**
* @bug 4029195
*/
public void Test4029195() {
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
logln("today: " + today);
SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();
String pat = sdf.toPattern();
logln("pattern: " + pat);
StringBuffer fmtd = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
fmtd = sdf.format(today, fmtd, pos);
logln("today: " + fmtd);
sdf.applyPattern("G yyyy DDD");
StringBuffer todayS = new StringBuffer("");
todayS = sdf.format(today, todayS, pos);
logln("today: " + todayS);
try {
today = sdf.parse(todayS.toString());
logln("today date: " + today);
} catch (Exception e) {
errln("Error reparsing date: " + e.getMessage());
}
try {
StringBuffer rt = new StringBuffer("");
rt = sdf.format(sdf.parse(todayS.toString()), rt, pos);
logln("round trip: " + rt);
if (!rt.toString().equals(todayS.toString()))
errln("Fail: Want " + todayS + " Got " + rt);
} catch (ParseException e) {
errln("Fail: " + e);
e.printStackTrace();
}
}
/**
* @bug 4052408
*/
public void Test4052408() {
DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(97 + 1900, Calendar.MAY, 3, 8, 55);
Date dt = cal.getTime();
String str = fmt.format(dt);
logln(str);
if (!str.equals("5/3/97 8:55 AM"))
errln("Fail: Test broken; Want 5/3/97 8:55 AM Got " + str);
String expected[] = {
"", //"ERA_FIELD",
"97", //"YEAR_FIELD",
"5", //"MONTH_FIELD",
"3", //"DATE_FIELD",
"", //"HOUR_OF_DAY1_FIELD",
"", //"HOUR_OF_DAY0_FIELD",
"55", //"MINUTE_FIELD",
"", //"SECOND_FIELD",
"", //"MILLISECOND_FIELD",
"", //"DAY_OF_WEEK_FIELD",
"", //"DAY_OF_YEAR_FIELD",
"", //"DAY_OF_WEEK_IN_MONTH_FIELD",
"", //"WEEK_OF_YEAR_FIELD",
"", //"WEEK_OF_MONTH_FIELD",
"AM", //"AM_PM_FIELD",
"8", //"HOUR1_FIELD",
"", //"HOUR0_FIELD",
"" //"TIMEZONE_FIELD"
};
String fieldNames[] = {
"ERA_FIELD",
"YEAR_FIELD",
"MONTH_FIELD",
"DATE_FIELD",
"HOUR_OF_DAY1_FIELD",
"HOUR_OF_DAY0_FIELD",
"MINUTE_FIELD",
"SECOND_FIELD",
"MILLISECOND_FIELD",
"DAY_OF_WEEK_FIELD",
"DAY_OF_YEAR_FIELD",
"DAY_OF_WEEK_IN_MONTH_FIELD",
"WEEK_OF_YEAR_FIELD",
"WEEK_OF_MONTH_FIELD",
"AM_PM_FIELD",
"HOUR1_FIELD",
"HOUR0_FIELD",
"TIMEZONE_FIELD"};
boolean pass = true;
for (int i = 0; i <= 17; ++i) {
FieldPosition pos = new FieldPosition(i);
StringBuffer buf = new StringBuffer("");
fmt.format(dt, buf, pos);
//char[] dst = new char[pos.getEndIndex() - pos.getBeginIndex()];
String dst = buf.substring(pos.getBeginIndex(), pos.getEndIndex());
str = dst;
log(i + ": " + fieldNames[i] + ", \"" + str + "\", "
+ pos.getBeginIndex() + ", " + pos.getEndIndex());
String exp = expected[i];
if ((exp.length() == 0 && str.length() == 0) || str.equals(exp))
logln(" ok");
else {
logln(" expected " + exp);
pass = false;
}
}
if (!pass)
errln("Fail: FieldPosition not set right by DateFormat");
}
/**
* @bug 4056591
* Verify the function of the [s|g]et2DigitYearStart() API.
*/
public void Test4056591() {
try {
SimpleDateFormat fmt = new SimpleDateFormat("yyMMdd", Locale.US);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1809, Calendar.DECEMBER, 25);
Date start = cal.getTime();
fmt.set2DigitYearStart(start);
if ((fmt.get2DigitYearStart() != start))
errln("get2DigitYearStart broken");
cal.clear();
cal.set(1809, Calendar.DECEMBER, 25);
Date d1 = cal.getTime();
cal.clear();
cal.set(1909, Calendar.DECEMBER, 24);
Date d2 = cal.getTime();
cal.clear();
cal.set(1809, Calendar.DECEMBER, 26);
Date d3 = cal.getTime();
cal.clear();
cal.set(1861, Calendar.DECEMBER, 25);
Date d4 = cal.getTime();
Date dates[] = {d1, d2, d3, d4};
String strings[] = {"091225", "091224", "091226", "611225"};
for (int i = 0; i < 4; i++) {
String s = strings[i];
Date exp = dates[i];
Date got = fmt.parse(s);
logln(s + " . " + got + "; exp " + exp);
if (got.getTime() != exp.getTime())
errln("set2DigitYearStart broken");
}
} catch (ParseException e) {
errln("Fail: " + e);
e.printStackTrace();
}
}
/**
* @bug 4059917
*/
public void Test4059917() {
SimpleDateFormat fmt;
String myDate;
fmt = new SimpleDateFormat("yyyy/MM/dd");
myDate = "1997/01/01";
aux917( fmt, myDate );
fmt = new SimpleDateFormat("yyyyMMdd");
myDate = "19970101";
aux917( fmt, myDate );
}
public void aux917(SimpleDateFormat fmt, String str) {
String pat = fmt.toPattern();
logln("==================");
logln("testIt: pattern=" + pat + " string=" + str);
ParsePosition pos = new ParsePosition(0);
Object o = fmt.parseObject(str, pos);
//logln( UnicodeString("Parsed object: ") + o );
StringBuffer formatted = new StringBuffer("");
FieldPosition poss = new FieldPosition(0);
formatted = fmt.format(o, formatted, poss);
logln("Formatted string: " + formatted);
if (!formatted.toString().equals(str))
errln("Fail: Want " + str + " Got " + formatted);
}
/**
* @bug 4060212
*/
public void Test4060212() {
String dateString = "1995-040.05:01:29";
logln("dateString= " + dateString);
logln("Using yyyy-DDD.hh:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-DDD.hh:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date myDate = formatter.parse(dateString, pos);
DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.LONG);
String myString = fmt.format(myDate);
logln(myString);
Calendar cal = new GregorianCalendar();
cal.setTime(myDate);
if ((cal.get(Calendar.DAY_OF_YEAR) != 40))
errln("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + " Want 40");
logln("Using yyyy-ddd.hh:mm:ss");
formatter = new SimpleDateFormat("yyyy-ddd.hh:mm:ss");
pos.setIndex(0);
myDate = formatter.parse(dateString, pos);
myString = fmt.format(myDate);
logln(myString);
cal.setTime(myDate);
if ((cal.get(Calendar.DAY_OF_YEAR) != 40))
errln("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + " Want 40");
}
/**
* @bug 4061287
*/
public void Test4061287() {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
logln(df.parse("35/01/1971").toString());
} catch (ParseException e) {
errln("Fail: " + e);
e.printStackTrace();
}
df.setLenient(false);
boolean ok = false;
try {
logln(df.parse("35/01/1971").toString());
} catch (ParseException e) {
ok = true;
}
if (!ok)
errln("Fail: Lenient not working");
}
/**
* @bug 4065240
*/
public void Test4065240() {
Date curDate;
DateFormat shortdate, fulldate;
String strShortDate, strFullDate;
Locale saveLocale = Locale.getDefault();
TimeZone saveZone = TimeZone.getDefault();
try {
Locale curLocale = new Locale("de", "DE");
Locale.setDefault(curLocale);
// {sfb} adoptDefault instead of setDefault
//TimeZone.setDefault(TimeZone.createTimeZone("EST"));
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(98 + 1900, 0, 1);
curDate = cal.getTime();
shortdate = DateFormat.getDateInstance(DateFormat.SHORT);
fulldate = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
strShortDate = "The current date (short form) is ";
String temp;
temp = shortdate.format(curDate);
strShortDate += temp;
strFullDate = "The current date (long form) is ";
String temp2 = fulldate.format(curDate);
strFullDate += temp2;
logln(strShortDate);
logln(strFullDate);
// {sfb} What to do with resource bundle stuff?????
// Check to see if the resource is present; if not, we can't test
//ResourceBundle bundle = //The variable is never used
// ResourceBundle.getBundle("java.text.resources.DateFormatZoneData", curLocale);
// {sfb} API change to ResourceBundle -- add getLocale()
/*if (bundle.getLocale().getLanguage().equals("de")) {
// UPDATE THIS AS ZONE NAME RESOURCE FOR <EST> in de_DE is updated
if (!strFullDate.endsWith("GMT-05:00"))
errln("Fail: Want GMT-05:00");
} else {
logln("*** TEST COULD NOT BE COMPLETED BECAUSE DateFormatZoneData ***");
logln("*** FOR LOCALE de OR de_DE IS MISSING ***");
}*/
} catch (Exception e) {
logln(e.getMessage());
} finally {
Locale.setDefault(saveLocale);
TimeZone.setDefault(saveZone);
}
}
/*
DateFormat.equals is too narrowly defined. As a result, MessageFormat
does not work correctly. DateFormat.equals needs to be written so
that the Calendar sub-object is not compared using Calendar.equals,
but rather compared for equivalency. This may necessitate adding a
(package private) method to Calendar to test for equivalency.
Currently this bug breaks MessageFormat.toPattern
*/
/**
* @bug 4071441
*/
public void Test4071441() {
DateFormat fmtA = DateFormat.getInstance();
DateFormat fmtB = DateFormat.getInstance();
// {sfb} Is it OK to cast away const here?
Calendar calA = fmtA.getCalendar();
Calendar calB = fmtB.getCalendar();
calA.clear();
calA.set(1900, 0 ,0);
calB.clear();
calB.set(1900, 0, 0);
if (!calA.equals(calB))
errln("Fail: Can't complete test; Calendar instances unequal");
if (!fmtA.equals(fmtB))
errln("Fail: DateFormat unequal when Calendars equal");
calB.clear();
calB.set(1961, Calendar.DECEMBER, 25);
if (calA.equals(calB))
errln("Fail: Can't complete test; Calendar instances equal");
if (!fmtA.equals(fmtB))
errln("Fail: DateFormat unequal when Calendars equivalent");
logln("DateFormat.equals ok");
}
/* The java.text.DateFormat.parse(String) method expects for the
US locale a string formatted according to mm/dd/yy and parses it
correctly.
When given a string mm/dd/yyyy it only parses up to the first
two y's, typically resulting in a date in the year 1919.
Please extend the parsing method(s) to handle strings with
four-digit year values (probably also applicable to various
other locales. */
/**
* @bug 4073003
*/
public void Test4073003() {
try {
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
String tests[] = {"12/25/61", "12/25/1961", "4/3/2010", "4/3/10"};
for (int i = 0; i < 4; i += 2) {
Date d = fmt.parse(tests[i]);
Date dd = fmt.parse(tests[i + 1]);
String s;
s = fmt.format(d);
String ss;
ss = fmt.format(dd);
if (d.getTime() != dd.getTime())
errln("Fail: " + d + " != " + dd);
if (!s.equals(ss))
errln("Fail: " + s + " != " + ss);
logln("Ok: " + s + " " + d);
}
} catch (ParseException e) {
errln("Fail: " + e);
e.printStackTrace();
}
}
/**
* @bug 4089106
*/
public void Test4089106() {
TimeZone def = TimeZone.getDefault();
try {
TimeZone z = new SimpleTimeZone((int) (1.25 * 3600000), "FAKEZONE");
TimeZone.setDefault(z);
SimpleDateFormat f = new SimpleDateFormat();
if (!f.getTimeZone().equals(z))
errln("Fail: SimpleTimeZone should use TimeZone.getDefault()");
} finally {
TimeZone.setDefault(def);
}
}
/**
* @bug 4100302
*/
public void Test4100302() {
Locale locales[] = {
Locale.CANADA, Locale.CANADA_FRENCH, Locale.CHINA,
Locale.CHINESE, Locale.ENGLISH, Locale.FRANCE, Locale.FRENCH,
Locale.GERMAN, Locale.GERMANY, Locale.ITALIAN, Locale.ITALY,
Locale.JAPAN, Locale.JAPANESE, Locale.KOREA, Locale.KOREAN,
Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN,
Locale.TRADITIONAL_CHINESE, Locale.UK, Locale.US};
try {
boolean pass = true;
for (int i = 0; i < 21; i++) {
Format format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locales[i]);
byte[] bytes;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(format);
oos.flush();
baos.close();
bytes = baos.toByteArray();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
Object o = ois.readObject();
if (!format.equals(o)) {
pass = false;
logln("DateFormat instance for locale " + locales[i] + " is incorrectly serialized/deserialized.");
} else {
logln("DateFormat instance for locale " + locales[i] + " is OKAY.");
}
}
if (!pass)
errln("Fail: DateFormat serialization/equality bug");
} catch (OptionalDataException e) {
errln("Fail: " + e);
} catch (IOException e) {
errln("Fail: " + e);
} catch (ClassNotFoundException e) {
errln("Fail: " + e);
} catch (Exception e) {
errln("Fail: " + e);
}
}
/**
* @bug 4101483
*/
public void Test4101483() {
SimpleDateFormat sdf = new SimpleDateFormat("z", Locale.US);
FieldPosition fp = new FieldPosition(DateFormat.TIMEZONE_FIELD);
Date d = new Date(9234567890L);
StringBuffer buf = new StringBuffer("");
sdf.format(d, buf, fp);
logln(sdf.format(d, buf, fp).toString());
logln("beginIndex = " + fp.getBeginIndex());
logln("endIndex = " + fp.getEndIndex());
if (fp.getBeginIndex() == fp.getEndIndex())
errln("Fail: Empty field");
}
/**
* @bug 4103340
* @bug 4138203
* This bug really only works in Locale.US, since that's what the locale
* used for Date.toString() is. Bug 4138203 reports that it fails on Korean
* NT; it would actually have failed on any non-US locale. Now it should
* work on all locales.
*/
public void Test4103340() {
// choose a date that is the FIRST of some month
// and some arbitrary time
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1997, 3, 1, 1, 1, 1);
Date d = cal.getTime();
SimpleDateFormat df = new SimpleDateFormat("MMMM", Locale.US);
String s = d.toString();
StringBuffer s2 = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
s2 = df.format(d, s2, pos);
logln("Date=" + s);
logln("DF=" + s2);
String substr = s2.substring(0,2);
if (s.indexOf(substr) == -1)
errln("Months should match");
}
/**
* @bug 4103341
*/
public void Test4103341() {
TimeZone saveZone = TimeZone.getDefault();
try {
// {sfb} changed from adoptDefault to setDefault
TimeZone.setDefault(TimeZone.getTimeZone("CST"));
SimpleDateFormat simple = new SimpleDateFormat("MM/dd/yyyy HH:mm");
TimeZone temp = TimeZone.getDefault();
if (!simple.getTimeZone().equals(temp))
errln("Fail: SimpleDateFormat not using default zone");
} finally {
TimeZone.setDefault(saveZone);
}
}
/**
* @bug 4104136
*/
public void Test4104136() {
SimpleDateFormat sdf = new SimpleDateFormat();
String pattern = "'time' hh:mm";
sdf.applyPattern(pattern);
logln("pattern: \"" + pattern + "\"");
String strings[] = {"time 10:30", "time 10:x", "time 10x"};
ParsePosition ppos[] = {new ParsePosition(10), new ParsePosition(0), new ParsePosition(0)};
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1970, Calendar.JANUARY, 1, 10, 30);
Date dates[] = {cal.getTime(), new Date(-1), new Date(-1)};
for (int i = 0; i < 3; i++) {
String text = strings[i];
ParsePosition finish = ppos[i];
Date exp = dates[i];
ParsePosition pos = new ParsePosition(0);
Date d = sdf.parse(text, pos);
logln(" text: \"" + text + "\"");
logln(" index: %d" + pos.getIndex());
logln(" result: " + d);
if (pos.getIndex() != finish.getIndex())
errln("Fail: Expected pos " + finish.getIndex());
if (!((d == null && exp.equals(new Date(-1))) || (d.equals(exp))))
errln( "Fail: Expected result " + exp);
}
}
/**
* @bug 4104522
* CANNOT REPRODUCE
* According to the bug report, this test should throw a
* StringIndexOutOfBoundsException during the second parse. However,
* this is not seen.
*/
public void Test4104522() {
SimpleDateFormat sdf = new SimpleDateFormat();
String pattern = "'time' hh:mm";
sdf.applyPattern(pattern);
logln("pattern: \"" + pattern + "\"");
// works correctly
ParsePosition pp = new ParsePosition(0);
String text = "time ";
Date dt = sdf.parse(text, pp);
logln(" text: \"" + text + "\"" + " date: " + dt);
// works wrong
pp.setIndex(0);
text = "time";
dt = sdf.parse(text, pp);
logln(" text: \"" + text + "\"" + " date: " + dt);
}
/**
* @bug 4106807
*/
public void Test4106807() {
Date dt;
DateFormat df = DateFormat.getDateTimeInstance();
SimpleDateFormat sdfs[] = {
new SimpleDateFormat("yyyyMMddHHmmss"),
new SimpleDateFormat("yyyyMMddHHmmss'Z'"),
new SimpleDateFormat("yyyyMMddHHmmss''"),
new SimpleDateFormat("yyyyMMddHHmmss'a''a'"),
new SimpleDateFormat("yyyyMMddHHmmss %")};
String strings[] = {
"19980211140000",
"19980211140000",
"19980211140000",
"19980211140000a",
"19980211140000 "};
GregorianCalendar gc = new GregorianCalendar();
TimeZone timeZone = TimeZone.getDefault();
TimeZone gmt = (TimeZone) timeZone.clone();
gmt.setRawOffset(0);
for (int i = 0; i < 5; i++) {
SimpleDateFormat format = sdfs[i];
String dateString = strings[i];
try {
format.setTimeZone(gmt);
dt = format.parse(dateString);
// {sfb} some of these parses will fail purposely
StringBuffer fmtd = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
fmtd = df.format(dt, fmtd, pos);
logln(fmtd.toString());
//logln(df.format(dt));
gc.setTime(dt);
logln("" + gc.get(Calendar.ZONE_OFFSET));
StringBuffer s = new StringBuffer("");
s = format.format(dt, s, pos);
logln(s.toString());
} catch (ParseException e) {
logln("No way Jose");
}
}
}
/*
Synopsis: Chinese time zone CTT is not recogonized correctly.
Description: Platform Chinese Windows 95 - ** Time zone set to CST **
*/
/**
* @bug 4108407
*/
// {sfb} what to do with this one ??
public void Test4108407() {
/*
long l = System.currentTimeMillis();
logln("user.timezone = " + System.getProperty("user.timezone", "?"));
logln("Time Zone :" +
DateFormat.getDateInstance().getTimeZone().getID());
logln("Default format :" +
DateFormat.getDateInstance().format(new Date(l)));
logln("Full format :" +
DateFormat.getDateInstance(DateFormat.FULL).format(new
Date(l)));
logln("*** Set host TZ to CST ***");
logln("*** THE RESULTS OF THIS TEST MUST BE VERIFIED MANUALLY ***");
*/
}
/**
* @bug 4134203
* SimpleDateFormat won't parse "GMT"
*/
public void Test4134203() {
String dateFormat = "MM/dd/yy HH:mm:ss zzz";
SimpleDateFormat fmt = new SimpleDateFormat(dateFormat);
ParsePosition p0 = new ParsePosition(0);
Date d = fmt.parse("01/22/92 04:52:00 GMT", p0);
logln(d.toString());
if(p0.equals(new ParsePosition(0)))
errln("Fail: failed to parse 'GMT'");
// In the failure case an exception is thrown by parse();
// if no exception is thrown, the test passes.
}
/**
* @bug 4151631
* SimpleDateFormat incorrect handling of 2 single quotes in format()
*/
public void Test4151631() {
String pattern =
"'TO_DATE('''dd'-'MM'-'yyyy HH:mm:ss''' , ''DD-MM-YYYY HH:MI:SS'')'";
logln("pattern=" + pattern);
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US);
StringBuffer result = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1998, Calendar.JUNE, 30, 13, 30, 0);
Date d = cal.getTime();
result = format.format(d, result, pos);
if (!result.toString().equals("TO_DATE('30-06-1998 13:30:00' , 'DD-MM-YYYY HH:MI:SS')")) {
errln("Fail: result=" + result);
} else {
logln("Pass: result=" + result);
}
}
/**
* @bug 4151706
* 'z' at end of date format throws index exception in SimpleDateFormat
* CANNOT REPRODUCE THIS BUG ON 1.2FCS
*/
public void Test4151706() {
String dateString = "Thursday, 31-Dec-98 23:00:00 GMT";
SimpleDateFormat fmt = new SimpleDateFormat("EEEE, dd-MMM-yy HH:mm:ss z", Locale.US);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.US);
cal.clear();
cal.set(1998, Calendar.DECEMBER, 31, 23, 0, 0);
Date d = new Date();
try {
d = fmt.parse(dateString);
// {sfb} what about next two lines?
if (d.getTime() != cal.getTime().getTime())
errln("Incorrect value: " + d);
} catch (Exception e) {
errln("Fail: " + e);
}
StringBuffer temp = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
logln(dateString + " . " + fmt.format(d, temp, pos));
}
/**
* @bug 4162071
* Cannot reproduce this bug under 1.2 FCS -- it may be a convoluted duplicate
* of some other bug that has been fixed.
*/
public void Test4162071() {
String dateString = "Thu, 30-Jul-1999 11:51:14 GMT";
String format = "EEE', 'dd-MMM-yyyy HH:mm:ss z"; // RFC 822/1123
SimpleDateFormat df = new SimpleDateFormat(format, Locale.US);
try {
Date x = df.parse(dateString);
StringBuffer temp = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
logln(dateString + " -> " + df.format(x, temp, pos));
} catch (Exception e) {
errln("Parse format \"" + format + "\" failed.");
}
}
/**
* DateFormat shouldn't parse year "-1" as a two-digit year (e.g., "-1" . 1999).
*/
public void Test4182066() {
SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yy", Locale.US);
SimpleDateFormat dispFmt = new SimpleDateFormat("MMM dd yyyy HH:mm:ss GG", Locale.US);
/* We expect 2-digit year formats to put 2-digit years in the right
* window. Out of range years, that is, anything less than "00" or
* greater than "99", are treated as literal years. So "1/2/3456"
* becomes 3456 AD. Likewise, "1/2/-3" becomes -3 AD == 2 BC.
*/
final String STRINGS[] =
{"02/29/00", "01/23/01", "04/05/-1", "01/23/-9", "11/12/1314", "10/31/1", "09/12/+1", "09/12/001",};
int STRINGS_COUNT = STRINGS.length;
Calendar cal = Calendar.getInstance();
Date FAIL_DATE = cal.getTime();
cal.clear();
cal.set(2000, Calendar.FEBRUARY, 29);
Date d0 = cal.getTime();
cal.clear();
cal.set(2001, Calendar.JANUARY, 23);
Date d1 = cal.getTime();
cal.clear();
cal.set(-1, Calendar.APRIL, 5);
Date d2 = cal.getTime();
cal.clear();
cal.set(-9, Calendar.JANUARY, 23);
Date d3 = cal.getTime();
cal.clear();
cal.set(1314, Calendar.NOVEMBER, 12);
Date d4 = cal.getTime();
cal.clear();
cal.set(1, Calendar.OCTOBER, 31);
Date d5 = cal.getTime();
cal.clear();
cal.set(1, Calendar.SEPTEMBER, 12);
Date d7 = cal.getTime();
Date DATES[] = {d0, d1, d2, d3, d4, d5, FAIL_DATE, d7};
String out = "";
boolean pass = true;
for (int i = 0; i < STRINGS_COUNT; ++i) {
String str = STRINGS[i];
Date expected = DATES[i];
Date actual = null;
try {
actual = fmt.parse(str);
} catch (ParseException e) {
actual = FAIL_DATE;
}
String actStr = "";
if ((actual.getTime()) == FAIL_DATE.getTime()) {
actStr += "null";
} else {
// Yuck: See j25
actStr = ((DateFormat) dispFmt).format(actual);
}
if (expected.getTime() == (actual.getTime())) {
out += str + " => " + actStr + "\n";
} else {
String expStr = "";
if (expected.getTime() == FAIL_DATE.getTime()) {
expStr += "null";
} else {
// Yuck: See j25
expStr = ((DateFormat) dispFmt).format(expected);
}
out += "FAIL: " + str + " => " + actStr + ", expected " + expStr + "\n";
pass = false;
}
}
if (pass) {
log(out);
} else {
err(out);
}
}
/**
* j32 {JDK Bug 4210209 4209272}
* DateFormat cannot parse Feb 29 2000 when setLenient(false)
*/
public void Test4210209() {
String pattern = "MMM d, yyyy";
SimpleDateFormat sfmt = new SimpleDateFormat(pattern, Locale.US);
SimpleDateFormat sdisp = new SimpleDateFormat("MMM dd yyyy GG", Locale.US);
DateFormat fmt = (DateFormat) sfmt; // Yuck: See j25
DateFormat disp = (DateFormat) sdisp; // Yuck: See j25
Calendar calx = (Calendar) fmt.getCalendar(); // cast away const!
calx.setLenient(false);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2000, Calendar.FEBRUARY, 29);
Date d = calendar.getTime();
String s = fmt.format(d);
logln(disp.format(d) + " f> " + pattern + " => \"" + s + "\"");
ParsePosition pos = new ParsePosition(0);
d = fmt.parse(s, pos);
logln("\"" + s + "\" p> " + pattern + " => " + disp.format(d));
logln("Parse pos = " + pos.getIndex() + ", error pos = " + pos.getErrorIndex());
if (pos.getErrorIndex() != -1) {
errln("FAIL: Error index should be -1");
}
// The underlying bug is in GregorianCalendar. If the following lines
// succeed, the bug is fixed. If the bug isn't fixed, they will throw
// an exception.
GregorianCalendar cal = new GregorianCalendar();
cal.clear();
cal.setLenient(false);
cal.set(2000, Calendar.FEBRUARY, 29); // This should work!
logln("Attempt to set Calendar to Feb 29 2000: " + disp.format(cal.getTime()));
}
public void Test714() {
//TimeZone Offset
TimeZone defaultTZ = TimeZone.getDefault();
TimeZone PST = TimeZone.getTimeZone("PST");
int defaultOffset = defaultTZ.getRawOffset();
int PSTOffset = PST.getRawOffset();
Date d = new Date(978103543000l - (defaultOffset - PSTOffset));
d = new Date(d.getTime() - (defaultTZ.inDaylightTime(d) ? 3600000 : 0));
DateFormat fmt = DateFormat.getDateTimeInstance(-1, DateFormat.MEDIUM, Locale.US);
String tests = "7:25:43 AM";
String s = fmt.format(d);
if (!s.equals(tests)) {
errln("Fail: " + s + " != " + tests);
} else {
logln("OK: " + s + " == " + tests);
}
}
}

View File

@ -1,285 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/DateFormatRegressionTestJ.java,v $
* $Date: 2001/10/23 13:10:05 $
* $Revision: 1.3 $
*
*****************************************************************************************
*/
/*
* New added, 2001-10-17 [Jing/GCL]
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Date;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
import java.text.FieldPosition;
public class DateFormatRegressionTestJ extends com.ibm.test.TestFmwk {
static final String TIME_STRING = "2000/11/17 08:01:00";
static final long UTC_LONG = 974476860000L;
static SimpleDateFormat sdf_ = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static void main(String[] args) throws Exception {
new DateFormatRegressionTestJ().run(args);
}
//Return value of getAmPmStrings
public void Test4103926() {
String act_Ampms[];
String exp_Ampms[]={"AM","PM"};
Locale.setDefault(Locale.US);
DateFormatSymbols dfs = new DateFormatSymbols();
act_Ampms = dfs.getAmPmStrings();
if(act_Ampms.length != exp_Ampms.length) {
errln("The result is not expected!");
} else {
for(int i =0; i<act_Ampms.length; i++) {
if(!act_Ampms[i].equals(exp_Ampms[i]))
errln("The result is not expected!");
}
}
}
//Missing digit in millisecone format in SimpleDateFormat
public void Test4148168() {
Date d = new Date(1002705212906l);
String[] ISOPattern = {
"''yyyy-MM-dd-hh.mm.ss.S''", "''yyyy-MM-dd-hh.mm.ss.SS''",
"''yyyy-MM-dd-hh.mm.ss.SSS''", "''yyyy-MM-dd-hh.mm.ss.SSSS''",
"''yyyy-MM-dd-hh.mm.ss.SSSSS''", "''yyyy-MM-dd-hh.mm.ss.SSSSSS''",
"''yyyy-MM-dd-hh.mm.ss.SSSSSSS''", "''yyyy-MM-dd-hh.mm.ss.SSS000''"};
SimpleDateFormat aSimpleDF = (SimpleDateFormat)DateFormat.getDateTimeInstance();
for(int i = 0; i<ISOPattern.length; i++) {
aSimpleDF.applyPattern( ISOPattern[i] );
logln( "Pattern = " + aSimpleDF.toPattern());
logln( "Format = " + aSimpleDF.format(d));
}
}
//DateFormat getDateTimeInstance(int, int), invalid styles no exception
public void Test4213086() {
Date someDate = new Date();
String d;
try {
DateFormat df2 = DateFormat.getDateTimeInstance(2, -2);
d = df2.format(someDate);
errln("we should catch an exception here");
} catch(Exception e){
logln("dateStyle = 2" + "\t timeStyle = -2");
logln("Exception caught!");
}
try {
DateFormat df3 = DateFormat.getDateTimeInstance(4, 2);
d = df3.format(someDate);
errln("we should catch an exception here");
} catch(Exception e){
logln("dateStyle = 4" + "\t timeStyle = 2");
logln("Exception caught!");
logln("********************************************");
}
try {
DateFormat df4 = DateFormat.getDateTimeInstance(-12, -12);
d = df4.format(someDate);
errln("we should catch an exception here");
} catch(Exception e){
logln("dateStyle = -12" + "\t timeStyle = -12");
logln("Exception caught!");
logln("********************************************");
}
try{
DateFormat df5 = DateFormat.getDateTimeInstance(2, 123);
d = df5.format(someDate);
errln("we should catch an exception here");
} catch(Exception e){
logln("dateStyle = 2" + "\t timeStyle = 123");
logln("Exception caught!");
logln("********************************************");
}
}
//DateFormat.format works wrongly?
public void Test4250359() {
Locale.setDefault(Locale.US);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(101 + 1900, 9, 9, 17, 53);
Date d = cal.getTime();
DateFormat tf = DateFormat.getTimeInstance(DateFormat.SHORT);
String act_result = tf.format(d);
String exp_result = "5:53 PM";
if(!act_result.equals(exp_result)){
errln("The result is not expected");
}
}
//pattern "s.S, parse '1ms'"
public void Test4253490() {
Date d = new Date(1002705212231l);
String[] ISOPattern = {
"''yyyy-MM-dd-hh.mm.ss.S''",
"''yyyy-MM-dd-hh.mm.ss.SS''",
"''yyyy-MM-dd-hh.mm.ss.SSS''",
"''yyyy-MM-dd-hh.mm.ss.SSSS''",
"''yyyy-MM-dd-hh.mm.ss.SSSSS''",
"''yyyy-MM-dd-hh.mm.ss.SSSSSS''",
"''yyyy-MM-dd-hh.mm.ss.SSSSSSS''"};
SimpleDateFormat aSimpleDF = (SimpleDateFormat) DateFormat.getDateTimeInstance();
for (int i = 0; i < ISOPattern.length; i++) {
aSimpleDF.applyPattern(ISOPattern[i]);
logln("Pattern = " + aSimpleDF.toPattern());
logln("Format = " + aSimpleDF.format(d));
}
}
//about regression test
public void Test4266432() {
Locale.setDefault(Locale.JAPAN);
Locale loc = Locale.getDefault();
String dateFormat = "MM/dd/yy HH:mm:ss zzz";
SimpleDateFormat fmt = new SimpleDateFormat(dateFormat);
ParsePosition p0 = new ParsePosition(0);
logln("Under " + loc +" locale");
Date d = fmt.parse("01/22/92 04:52:00 GMT", p0);
logln(d.toString());
}
//SimpleDateFormat inconsistent for number of digits for years
public void Test4358730() {
SimpleDateFormat sdf = new SimpleDateFormat();
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2001,11,10);
Date today = cal.getTime();
sdf.applyPattern("MM d y");
logln(sdf.format(today));
sdf.applyPattern("MM d yy");
logln(sdf.format(today));
sdf.applyPattern("MM d yyy");
logln(sdf.format(today));
sdf.applyPattern("MM d yyyy");
logln(sdf.format(today));
sdf.applyPattern("MM d yyyyy");
logln(sdf.format(today));
}
//Parse invalid string
public void Test4375399() {
final String pattern = new String("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.JAPAN);
try{
Date currentTime = sdf.parse("vggf 20 01.0 9.29 ap. J.-C. at 05:26:33 GMT+08:00",
new ParsePosition(0));
if(currentTime ==null)
logln("parse right");
} catch(Exception e){
errln("Error");
}
}
/*
public void Test4407042() {
DateParseThread d1 = new DateParseThread();
DateFormatThread d2 = new DateFormatThread();
d1.start();
d2.start();
try {
logln("test");
Thread.sleep(1000);
} catch (Exception e) {}
}*/
public void Test4468663() {
Date d =new Date(-93716671115767l);
String origin_d = d.toString();
String str;
final String pattern = new String("EEEE, MMMM d, yyyy");
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if (sdf.getTimeZone().useDaylightTime()) {
logln("original date: " + origin_d.toString());
str = sdf.format(d);
logln(" after format----->" + str);
d = sdf.parse(str, new ParsePosition(0));
logln(" after parse----->" + d.toString());
str = sdf.format(d);
logln(" after format----->" + str);
d = sdf.parse(str, new ParsePosition(0));
logln(" after parse----->" + d.toString());
str = sdf.format(d);
logln(" after format----->" + str);
}
}
//Class used by Test4407042
class DateParseThread extends Thread {
public void run() {
SimpleDateFormat sdf = (SimpleDateFormat) sdf_.clone();
TimeZone defaultTZ = TimeZone.getDefault();
TimeZone PST = TimeZone.getTimeZone("PST");
int defaultOffset = defaultTZ.getRawOffset();
int PSTOffset = PST.getRawOffset();
int offset = defaultOffset - PSTOffset;
long ms = UTC_LONG - offset;
try {
int i = 0;
while (i < 10000) {
Date date = sdf.parse(TIME_STRING);
long t = date.getTime();
i++;
if (t != ms) {
throw new ParseException("Parse Error: " + i + " (" + sdf.format(date)
+ ") " + t + " != " + ms, 0);
}
}
} catch (Exception e) {
errln("parse error: " + e.getMessage());
}
}
}
//Class used by Test4407042
class DateFormatThread extends Thread {
public void run() {
SimpleDateFormat sdf = (SimpleDateFormat) sdf_.clone();
TimeZone tz = TimeZone.getTimeZone("PST");
sdf.setTimeZone(tz);
int i = 0;
while (i < 10000) {
i++;
String s = sdf.format(new Date(UTC_LONG));
if (!s.equals(TIME_STRING)) {
errln("Format Error: " + i + " " + s + " != "
+ TIME_STRING);
}
}
}
}
}

View File

@ -1,272 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/DateFormatRoundTripTest.java,v $
* $Date: 2001/11/06 11:07:16 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : DateFormatRoundTripTest
* Source File: $ICU4CRoot/source/test/intltest/dtfmtrtts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.util.Date;
import java.util.Random;
import java.text.FieldPosition;
import java.text.ParseException;
/**
* Performs round-trip tests for DateFormat
**/
public class DateFormatRoundTripTest extends com.ibm.test.TestFmwk {
public boolean INFINITE = false;
public boolean quick = true;
private SimpleDateFormat dateFormat;
private Calendar getFieldCal;
private int SPARSENESS = 18;
private int TRIALS = 4;
private int DEPTH = 5;
private Random ran = new Random();
public static void main(String[] args) throws Exception {
new DateFormatRoundTripTest().run(args);
}
public void TestDateFormatRoundTrip() {
dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss.SSS zzz yyyy G");
getFieldCal = Calendar.getInstance();
final Locale[] avail = DateFormat.getAvailableLocales();
int locCount = avail.length;
logln("DateFormat available locales: " + locCount);
if (quick) {
if (locCount > 5)
locCount = 5;
logln("Quick mode: only testing first 5 Locales");
}
TimeZone tz = TimeZone.getDefault();
logln("Default TimeZone: " + tz.getID());
if (INFINITE) {
// Special infinite loop test mode for finding hard to reproduce errors
Locale loc = Locale.getDefault();
logln("ENTERING INFINITE TEST LOOP FOR Locale: " + loc.getDisplayName());
for (;;) {
_test(loc);
}
} else {
_test(Locale.getDefault());
for (int i = 0; i < locCount; ++i) {
_test(avail[i]);
}
}
}
public String styleName(int s) {
switch (s) {
case DateFormat.SHORT :
return "SHORT";
case DateFormat.MEDIUM :
return "MEDIUM";
case DateFormat.LONG :
return "LONG";
case DateFormat.FULL :
return "FULL";
default :
return "Unknown";
}
}
public void _test(Locale loc) {
if (!INFINITE) {
logln("Locale: " + loc.getDisplayName());
}
// Total possibilities = 24
// 4 date
// 4 time
// 16 date-time
boolean[] TEST_TABLE = new boolean[24];
int i = 0;
for (i = 0; i < 24; ++i)
TEST_TABLE[i] = true;
// If we have some sparseness, implement it here. Sparseness decreases
// test time by eliminating some tests, up to 23.
for (i = 0; i < SPARSENESS; i++) {
int random = (int) (ran.nextDouble() * 24);
if (random >= 0 && random < 24 && TEST_TABLE[i]) {
TEST_TABLE[random] = false;
}
}
int itable = 0;
int style = 0;
for (style = DateFormat.FULL; style <= DateFormat.SHORT; ++style) {
if (TEST_TABLE[itable++]) {
logln("Testing style " + styleName(style));
DateFormat df = DateFormat.getDateInstance(style, loc);
_test(df, false);
}
}
for (style = DateFormat.FULL; style <= DateFormat.SHORT; ++style) {
if (TEST_TABLE[itable++]) {
logln("Testing style " + styleName(style));
DateFormat df = DateFormat.getTimeInstance(style, loc);
_test(df, true);
}
}
for (int dstyle = DateFormat.FULL; dstyle <= DateFormat.SHORT; ++dstyle) {
for (int tstyle = DateFormat.FULL; tstyle <= DateFormat.SHORT; ++tstyle) {
if (TEST_TABLE[itable++]) {
logln("Testing dstyle " + styleName(dstyle) + ", tstyle " + styleName(tstyle));
DateFormat df = DateFormat.getDateTimeInstance(dstyle, tstyle, loc);
_test(df, false);
}
}
}
}
public void _test(DateFormat fmt, boolean timeOnly) {
if (!(fmt instanceof SimpleDateFormat)) {
errln("DateFormat wasn't a SimpleDateFormat");
return;
}
String pat = ((SimpleDateFormat) fmt).toPattern();
logln(pat);
// NOTE TO MAINTAINER
// This indexOf check into the pattern needs to be refined to ignore
// quoted characters. Currently, this isn't a problem with the locale
// patterns we have, but it may be a problem later.
boolean hasEra = (pat.indexOf("G") != -1);
boolean hasZone = (pat.indexOf("z") != -1);
// Because patterns contain incomplete data representing the Date,
// we must be careful of how we do the roundtrip. We start with
// a randomly generated Date because they're easier to generate.
// From this we get a string. The string is our real starting point,
// because this string should parse the same way all the time. Note
// that it will not necessarily parse back to the original date because
// of incompleteness in patterns. For example, a time-only pattern won't
// parse back to the same date.
try {
for (int i = 0; i < TRIALS; ++i) {
Date[] d = new Date[DEPTH];
String[] s = new String[DEPTH];
d[0] = generateDate();
// We go through this loop until we achieve a match or until
// the maximum loop count is reached. We record the points at
// which the date and the string starts to match. Once matching
// starts, it should continue.
int loop;
int dmatch = 0; // d[dmatch].getTime() == d[dmatch-1].getTime()
int smatch = 0; // s[smatch].equals(s[smatch-1])
for (loop = 0; loop < DEPTH; ++loop) {
if (loop > 0) {
d[loop] = fmt.parse(s[loop - 1]);
}
s[loop] = fmt.format(d[loop]);
if (loop > 0) {
if (smatch == 0) {
boolean match = s[loop].equals(s[loop - 1]);
if (smatch == 0) {
if (match)
smatch = loop;
} else
if (!match)
errln("FAIL: String mismatch after match");
}
if (dmatch == 0) {
// {sfb} watch out here, this might not work
boolean match = d[loop].getTime() == d[loop - 1].getTime();
if (dmatch == 0) {
if (match)
dmatch = loop;
} else
if (!match)
errln("FAIL: Date mismatch after match");
}
if (smatch != 0 && dmatch != 0)
break;
}
}
// At this point loop == DEPTH if we've failed, otherwise loop is the
// max(smatch, dmatch), that is, the index at which we have string and
// date matching.
// Date usually matches in 2. Exceptions handled below.
int maxDmatch = 2;
int maxSmatch = 1;
if (dmatch > maxDmatch || smatch > maxSmatch) {
//If the Date is BC
if (!timeOnly && !hasEra && getField(d[0], Calendar.ERA) == GregorianCalendar.BC) {
maxDmatch = 3;
maxSmatch = 2;
}
if (hasZone && (fmt.getTimeZone().inDaylightTime(d[0]) || fmt.getTimeZone().inDaylightTime(d[1]) )) {
maxSmatch = 2;
if (timeOnly) {
maxDmatch = 3;
}
}
}
if (dmatch > maxDmatch || smatch > maxSmatch) {
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM d, yyyy HH:mm:ss, z G", Locale.US);
logln("Date = " + sdf.format(d[0]) + "; ms = " + d[0].getTime());
logln("Dmatch: " + dmatch + " maxD: " + maxDmatch + " Smatch:" + smatch + " maxS:" + maxSmatch);
errln("Pattern: " + pat + " failed to match" + "; ms = " + d[0].getTime());
for (int j = 0; j <= loop && j < DEPTH; ++j) {
StringBuffer temp = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
logln((j > 0 ? " P> " : " ") + dateFormat.format(d[j], temp, pos)
+ " F> " + s[j] + (j > 0 && d[j].getTime() == d[j - 1].getTime() ? " d==" : "")
+ (j > 0 && s[j].equals(s[j - 1]) ? " s==" : ""));
}
}
}
} catch (ParseException e) {
errln("Exception: " + e.getMessage());
logln(e.toString());
}
}
public int getField(Date d, int f) {
getFieldCal.setTime(d);
int ret = getFieldCal.get(f);
return ret;
}
public Date generateDate() {
double a = ran.nextDouble();
// Now 'a' ranges from 0..1; scale it to range from 0 to 8000 years
a *= 8000;
// Range from (4000-1970) BC to (8000-1970) AD
a -= 4000;
// Now scale up to ms
a *= 365.25 * 24 * 60 * 60 * 1000;
return new Date((long)a);
}
}

View File

@ -1,763 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/DateFormatTest.java,v $
* $Date: 2001/12/07 17:32:27 $
* $Revision: 1.5 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : DateFormatTest
* Source File: $ICU4CRoot/source/test/intltest/dtfmttst.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Date;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
import java.text.FieldPosition;
public class DateFormatTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new DateFormatTest().run(args);
}
// Test written by Wally Wedel and emailed to me.
public void TestWallyWedel() {
/*
* Instantiate a TimeZone so we can get the ids.
*/
//TimeZone tz = new SimpleTimeZone(7, ""); //The variable is never used
/*
* Computational variables.
*/
int offset, hours, minutes;
/*
* Instantiate a SimpleDateFormat set up to produce a full time
zone name.
*/
SimpleDateFormat sdf = new SimpleDateFormat("zzzz");
/*
* A String array for the time zone ids.
*/
final String[] ids = TimeZone.getAvailableIDs();
int ids_length = ids.length; //when fixed the bug should comment it out
/*
* How many ids do we have?
*/
logln("Time Zone IDs size:" + ids_length);
/*
* Column headings (sort of)
*/
logln("Ordinal ID offset(h:m) name");
/*
* Loop through the tzs.
*/
Date today = new Date();
Calendar cal = Calendar.getInstance();
for (int i = 0; i < ids_length; i++) {
logln(i + " " + ids[i]);
TimeZone ttz = TimeZone.getTimeZone(ids[i]);
// offset = ttz.getRawOffset();
cal.setTimeZone(ttz);
cal.setTime(today);
offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET);
// logln(i + " " + ids[i] + " offset " + offset);
String sign = "+";
if (offset < 0) {
sign = "-";
offset = -offset;
}
hours = offset / 3600000;
minutes = (offset % 3600000) / 60000;
String dstOffset = sign + (hours < 10 ? "0" : "") + hours
+ ":" + (minutes < 10 ? "0" : "") + minutes;
/*
* Instantiate a date so we can display the time zone name.
*/
sdf.setTimeZone(ttz);
/*
* Format the output.
*/
StringBuffer fmtOffset = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
try {
fmtOffset = sdf.format(today, fmtOffset, pos);
} catch (Exception e) {
logln("Exception:" + e);
continue;
}
// UnicodeString fmtOffset = tzS.toString();
String fmtDstOffset = null;
if (fmtOffset.toString().startsWith("GMT")) {
//fmtDstOffset = fmtOffset.substring(3);
fmtDstOffset = fmtOffset.substring(3, fmtOffset.length());
}
/*
* Show our result.
*/
boolean ok = fmtDstOffset == null || fmtDstOffset.equals(dstOffset);
//fix the jdk resources differences between jdk 1.2/1.3.0 and jdk 1.3.1
String javaVersion = System.getProperty("java.version");
ok = ok || ((javaVersion.startsWith("1.2") || javaVersion.startsWith("1.3.0")) && (fmtDstOffset != null) && fmtDstOffset.equals(""));
if (ok) {
logln(i + " " + ids[i] + " " + dstOffset + " "
+ fmtOffset + (fmtDstOffset != null ? " ok" : " ?"));
} else {
errln(i + " " + ids[i] + " " + dstOffset + " " + fmtOffset + " *** FAIL ***");
}
}
}
public void TestEquals() {
DateFormat fmtA = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL);
DateFormat fmtB = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL);
if (!fmtA.equals(fmtB))
errln("FAIL");
}
/**
* Test the parsing of 2-digit years.
*/
public void TestTwoDigitYearDSTParse() {
SimpleDateFormat fullFmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss.SSS zzz yyyy G");
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yy h:mm:ss 'o''clock' a z", Locale.ENGLISH);
String s = "03-Apr-04 2:20:47 o'clock AM PST";
/*
* SimpleDateFormat(pattern, locale) Construct a SimpleDateDateFormat using
* the givening pattern, the locale and using the TimeZone.getDefault();
* So it need to add the timezone offset on hour field.
* ps. the Method Calendar.getTime() used by SimpleDateFormat.parse() always
* return Date vaule with TimeZone.getDefault() [Richard/GCL]
*/
TimeZone defaultTZ = TimeZone.getDefault();
TimeZone PST = TimeZone.getTimeZone("PST");
int defaultOffset = defaultTZ.getRawOffset();
int PSTOffset = PST.getRawOffset();
int hour = 2 + (defaultOffset - PSTOffset) / (60*60*1000);
hour = (hour < 0) ? hour + 24 : hour;
try {
Date d = fmt.parse(s);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
//DSTOffset
hour += defaultTZ.inDaylightTime(d) ? 1 : 0;
logln(s + " P> " + ((DateFormat) fullFmt).format(d));
int hr = cal.get(Calendar.HOUR_OF_DAY);
if (hr != hour)
errln("FAIL: Should parse to hour " + hour);
} catch (ParseException e) {
errln("Parse Error:" + e.getMessage());
}
}
/**
* Verify that returned field position indices are correct.
*/
public void TestFieldPosition() {
DateFormat[] dateFormats = new DateFormat[4];
int dateFormats_length = dateFormats.length;
String fieldNames[] = {
"ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", "DAY_OF_YEAR",
"DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR","HOUR_OF_DAY","MINUTE",
"SECOND", "MILLISECOND", "ZONE_OFFSET" };
/* {sfb} This test was coded incorrectly.
/ FieldPosition uses the fields in the class you are formatting with
/ So, for example, to get the DATE field from a DateFormat use
/ DateFormat.DATE_FIELD, __not__ Calendar.DATE
/ The ordering of the expected values used previously was wrong.
/ instead of re-ordering this mess of strings, just transform the index values */
/* field values, in Calendar order */
final String[] expected =
{ "", "1997", "August", "", "", "13", "", "Wednesday", "", "PM", "2", "", "34", "12", "", "PDT",
/* Following two added by weiv for two new fields */"", "1997", "#",
/* # is a marker for "ao\xfbt" == "aou^t" */
"", "", "13", "", "mercredi", "", "", "", "14", "34", "", "", "PDT",
/* Following two added by weiv for two new fields */
"AD", "1997", "8", "33", "3", "13", "225", "Wed", "2", "PM", "2", "14", "34", "12", "513", "PDT",
/* Following two added by weiv for two new fields */
"AD", "1997", "August", "0033", "0003", "0013", "0225", "Wednesday", "0002",
"PM", "0002", "0014", "0034", "0012", "0513", "Pacific Daylight Time",
/* Following two added by weiv for two new fields */ "1997", "0004", "" };
Date someDate = new Date((long) 871508052513.0);
int j, exp;
dateFormats[0] = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
dateFormats[1] = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.FRANCE);
dateFormats[2] = new SimpleDateFormat("G, y, M, d, k, H, m, s, S, E, D, F, w, W, a, h, K, z, y, E", Locale.US);
dateFormats[3] = new SimpleDateFormat("GGGG, yyyy, MMMM, dddd, kkkk, HHHH, mmmm, ssss, SSSS, EEEE, DDDD, FFFF, wwww, WWWW, aaaa, hhhh, KKKK, zzzz, yyyy, EEEE", Locale.US);
//fix the jdk resources differences between jdk 1.2 and jdk 1.3
String javaVersion = System.getProperty("java.version");
for (j = 0, exp = 0; j < dateFormats_length; ++j) {
String str;
DateFormat df = dateFormats[j];
TimeZone tz = TimeZone.getTimeZone("PST");
((SimpleTimeZone)tz).setDSTSavings(3600000);
df.setTimeZone(tz);
logln(" Pattern = " + ((SimpleDateFormat) df).toPattern());
str = "";
try {
logln(" Result = " + df.format(someDate));
} catch (Exception e) {
System.out.println(e);
}
for (int i = 0; i < fieldNames.length; ++i) {
String field = getFieldText(df, i, someDate);
String expStr = "";
if (!expected[exp].substring(0).equals("#")) {
expStr = expected[exp];
} else {
// we cannot have latin-1 characters in source code, therefore we fix up the string for "aou^t"
expStr = expStr + "\u0061" + "\u006f" + "\u00fb" + "\u0074";
}
if (javaVersion.startsWith("1.2") && (exp==31)) {
expStr = "GMT-07:00";
}
if (!field.equals(expStr))
errln("FAIL: field #" + i + " " + fieldNames[i] + " = \"" + field + "\", expected \"" + expStr + "\"");
++exp;
}
}
}
// internal utility function
public String getFieldText(DateFormat df, int field, Date date) {
final int[] fgCalendarToDateFormatField ={
DateFormat.ERA_FIELD,
DateFormat.YEAR_FIELD,
DateFormat.MONTH_FIELD,
DateFormat.WEEK_OF_YEAR_FIELD,
DateFormat.WEEK_OF_MONTH_FIELD,
DateFormat.DATE_FIELD,
DateFormat.DAY_OF_YEAR_FIELD,
DateFormat.DAY_OF_WEEK_FIELD,
DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD,
DateFormat.AM_PM_FIELD,
DateFormat.HOUR1_FIELD,
DateFormat.HOUR_OF_DAY0_FIELD,
DateFormat.MINUTE_FIELD,
DateFormat.SECOND_FIELD,
DateFormat.MILLISECOND_FIELD,
DateFormat.TIMEZONE_FIELD
};
StringBuffer formatResult = new StringBuffer("");
// {sfb} added to convert Calendar Fields to DateFormat fields
FieldPosition pos = new FieldPosition(fgCalendarToDateFormatField[field]);
formatResult = df.format(date, formatResult, pos);
return formatResult.substring(pos.getBeginIndex(), pos.getEndIndex());
}
/**
* Verify that strings which contain incomplete specifications are parsed
* correctly. In some instances, this means not being parsed at all, and
* returning an appropriate error.
*/
public void TestPartialParse994() {
SimpleDateFormat f = new SimpleDateFormat();
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1997, 1 - 1, 17, 10, 11, 42);
Date date = null;
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 10:11:42", cal.getTime());
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 10:", date);
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 10", date);
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 ", date);
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17", date);
}
// internal test subroutine, used by TestPartialParse994
public void tryPat994(SimpleDateFormat format, String pat, String str, Date expected) {
Date Null = null;
logln("Pattern \"" + pat + "\" String \"" + str + "\"");
try {
format.applyPattern(pat);
Date date = format.parse(str);
String f = ((DateFormat) format).format(date);
logln(" parse(" + str + ") -> " + date);
logln(" format -> " + f);
if (expected.equals(Null) || !date.equals(expected))
errln("FAIL: Expected null"); //" + expected);
if (!f.equals(str))
errln("FAIL: Expected " + str);
} catch (ParseException e) {
logln("ParseException: " + e.getMessage());
if (!(expected ==Null))
errln("FAIL: Expected " + expected);
} catch (Exception e) {
errln("*** Exception:");
e.printStackTrace();
}
}
/**
* Verify the behavior of patterns in which digits for different fields run together
* without intervening separators.
*/
public void TestRunTogetherPattern985() {
String format = "yyyyMMddHHmmssSSS";
String now, then;
//UBool flag;
SimpleDateFormat formatter = new SimpleDateFormat(format);
Date date1 = new Date();
now = ((DateFormat) formatter).format(date1);
logln(now);
ParsePosition pos = new ParsePosition(0);
Date date2 = formatter.parse(now, pos);
if (date2 == null)
then = "Parse stopped at " + pos.getIndex();
else
then = ((DateFormat) formatter).format(date2);
logln(then);
if (!date2.equals(date1))
errln("FAIL");
}
/**
* Verify the behavior of patterns in which digits for different fields run together
* without intervening separators.
*/
public void TestRunTogetherPattern917() {
SimpleDateFormat fmt;
String myDate;
fmt = new SimpleDateFormat("yyyy/MM/dd");
myDate = "1997/02/03";
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1997, 2 - 1, 3);
_testIt917(fmt, myDate, cal.getTime());
fmt = new SimpleDateFormat("yyyyMMdd");
myDate = "19970304";
cal.clear();
cal.set(1997, 3 - 1, 4);
_testIt917(fmt, myDate, cal.getTime());
}
// internal test subroutine, used by TestRunTogetherPattern917
public void _testIt917(SimpleDateFormat fmt, String str, Date expected) {
logln("pattern=" + fmt.toPattern() + " string=" + str);
Date o = new Date();
o = (Date) ((DateFormat) fmt).parseObject(str, new ParsePosition(0));
logln("Parsed object: " + o);
if (!o.equals(expected))
errln("FAIL: Expected " + expected);
String formatted = ((DateFormat) fmt).format(o);
logln( "Formatted string: " + formatted);
if (!formatted.equals(str))
errln( "FAIL: Expected " + str);
}
/**
* Verify the handling of Czech June and July, which have the unique attribute that
* one is a proper prefix substring of the other.
*/
public void TestCzechMonths459() {
DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, new Locale("cs", "", ""));
logln("Pattern " + ((SimpleDateFormat) fmt).toPattern());
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1997, Calendar.JUNE, 15);
Date june = cal.getTime();
cal.clear();
cal.set(1997, Calendar.JULY, 15);
Date july = cal.getTime();
String juneStr = fmt.format(june);
String julyStr = fmt.format(july);
try {
logln("format(June 15 1997) = " + juneStr);
Date d = fmt.parse(juneStr);
String s = fmt.format(d);
int month, yr, day, hr, min, sec;
cal.setTime(d);
yr = cal.get(Calendar.YEAR) - 1900;
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_WEEK);
hr = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
logln(" . parse . " + s + " (month = " + month + ")");
if (month != Calendar.JUNE)
errln("FAIL: Month should be June");
logln("format(July 15 1997) = " + julyStr);
d = fmt.parse(julyStr);
s = fmt.format(d);
cal.setTime(d);
yr = cal.get(Calendar.YEAR) - 1900;
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_WEEK);
hr = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
sec = cal.get(Calendar.SECOND);
logln(" . parse . " + s + " (month = " + month + ")");
if (month != Calendar.JULY)
errln("FAIL: Month should be July");
} catch (ParseException e) {
errln(e.getMessage());
}
}
/**
* Test the handling of 'D' in patterns.
*/
public void TestLetterDPattern212() {
String dateString = "1995-040.05:01:29";
String bigD = "yyyy-DDD.hh:mm:ss";
String littleD = "yyyy-ddd.hh:mm:ss";
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1995, 0, 1, 5, 1, 29);
Date expLittleD = cal.getTime();
Date expBigD = new Date((long) (expLittleD.getTime() + 39 * 24 * 3600000.0));
expLittleD = expBigD; // Expect the same, with default lenient parsing
logln("dateString= " + dateString);
SimpleDateFormat formatter = new SimpleDateFormat(bigD);
ParsePosition pos = new ParsePosition(0);
Date myDate = formatter.parse(dateString, pos);
logln("Using " + bigD + " . " + myDate);
if (!myDate.equals(expBigD))
errln("FAIL: Expected " + expBigD);
formatter = new SimpleDateFormat(littleD);
pos = new ParsePosition(0);
myDate = formatter.parse(dateString, pos);
logln("Using " + littleD + " . " + myDate);
if (!myDate.equals(expLittleD))
errln("FAIL: Expected " + expLittleD);
}
/**
* Test the day of year pattern.
*/
public void TestDayOfYearPattern195() {
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
int year,month,day;
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
cal.clear();
cal.set(year, month, day);
Date expected = cal.getTime();
logln("Test Date: " + today);
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();
tryPattern(sdf, today, null, expected);
tryPattern(sdf, today, "G yyyy DDD", expected);
}
// interl test subroutine, used by TestDayOfYearPattern195
public void tryPattern(SimpleDateFormat sdf, Date d, String pattern, Date expected) {
if (pattern != null)
sdf.applyPattern(pattern);
logln("pattern: " + sdf.toPattern());
String formatResult = ((DateFormat) sdf).format(d);
logln(" format -> " + formatResult);
try {
Date d2 = sdf.parse(formatResult);
logln(" parse(" + formatResult + ") -> " + d2);
if (!d2.equals(expected))
errln("FAIL: Expected " + expected);
String format2 = ((DateFormat) sdf).format(d2);
logln(" format -> " + format2);
if (!formatResult.equals(format2))
errln("FAIL: Round trip drift");
} catch (Exception e) {
errln(e.getMessage());
}
}
/**
* Test the handling of single quotes in patterns.
*/
public void TestQuotePattern161() {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy 'at' hh:mm:ss a zzz", Locale.US);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(1997, Calendar.AUGUST, 13, 10, 42, 28);
Date currentTime_1 = cal.getTime();
String dateString = ((DateFormat) formatter).format(currentTime_1);
String exp = "08/13/1997 at 10:42:28 AM ";
logln("format(" + currentTime_1 + ") = " + dateString);
if (!dateString.substring(0, exp.length()).equals(exp))
errln("FAIL: Expected " + exp);
}
/**
* Verify the correct behavior when handling invalid input strings.
*/
public void TestBadInput135() {
int looks[] = {DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL};
int looks_length = looks.length;
final String[] strings = {"Mar 15", "Mar 15 1997", "asdf", "3/1/97 1:23:", "3/1/00 1:23:45 AM"};
int strings_length = strings.length;
DateFormat full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US);
String expected = "March 1, 2000 1:23:45 AM ";
for (int i = 0; i < strings_length; ++i) {
final String text = strings[i];
for (int j = 0; j < looks_length; ++j) {
int dateLook = looks[j];
for (int k = 0; k < looks_length; ++k) {
int timeLook = looks[k];
DateFormat df = DateFormat.getDateTimeInstance(dateLook, timeLook, Locale.US);
String prefix = text + ", " + dateLook + "/" + timeLook + ": ";
try {
Date when = df.parse(text);
if (when == null) {
errln(prefix + "SHOULD NOT HAPPEN: parse returned null.");
continue;
}
if (when != null) {
String format;
format = full.format(when);
logln(prefix + "OK: " + format);
if (!format.substring(0, expected.length()).equals(expected))
errln("FAIL: Expected " + expected);
}
} catch(java.text.ParseException e) {
logln(e.getMessage());
}
}
}
}
}
/**
* Verify the correct behavior when parsing an array of inputs against an
* array of patterns, with known results. The results are encoded after
* the input strings in each row.
*/
public void TestBadInput135a() {
SimpleDateFormat dateParse = new SimpleDateFormat("", Locale.US);
final String ss;
Date date;
String[] parseFormats ={"MMMM d, yyyy", "MMMM d yyyy", "M/d/yy",
"d MMMM, yyyy", "d MMMM yyyy", "d MMMM",
"MMMM d", "yyyy", "h:mm a MMMM d, yyyy" };
String[] inputStrings = {
"bogus string", null, null, null, null, null, null, null, null, null,
"April 1, 1997", "April 1, 1997", null, null, null, null, null, "April 1", null, null,
"Jan 1, 1970", "January 1, 1970", null, null, null, null, null, "January 1", null, null,
"Jan 1 2037", null, "January 1 2037", null, null, null, null, "January 1", null, null,
"1/1/70", null, null, "1/1/70", null, null, null, null, "0001", null,
"5 May 1997", null, null, null, null, "5 May 1997", "5 May", null, "0005", null,
"16 May", null, null, null, null, null, "16 May", null, "0016", null,
"April 30", null, null, null, null, null, null, "April 30", null, null,
"1998", null, null, null, null, null, null, null, "1998", null,
"1", null, null, null, null, null, null, null, "0001", null,
"3:00 pm Jan 1, 1997", null, null, null, null, null, null, null, "0003", "3:00 PM January 1, 1997",
};
final int PF_LENGTH = parseFormats.length;
final int INPUT_LENGTH = inputStrings.length;
dateParse.applyPattern("d MMMM, yyyy");
dateParse.setTimeZone(TimeZone.getDefault());
ss = "not parseable";
// String thePat;
logln("Trying to parse \"" + ss + "\" with " + dateParse.toPattern());
try {
date = dateParse.parse(ss);
} catch (Exception ex) {
logln("FAIL:" + ex);
}
for (int i = 0; i < INPUT_LENGTH; i += (PF_LENGTH + 1)) {
ParsePosition parsePosition = new ParsePosition(0);
String s = inputStrings[i];
for (int index = 0; index < PF_LENGTH; ++index) {
final String expected = inputStrings[i + 1 + index];
dateParse.applyPattern(parseFormats[index]);
dateParse.setTimeZone(TimeZone.getDefault());
try {
parsePosition.setIndex(0);
date = dateParse.parse(s, parsePosition);
if (parsePosition.getIndex() != 0) {
String s1, s2;
s1 = s.substring(0, parsePosition.getIndex());
s2 = s.substring(parsePosition.getIndex(), s.length());
if (date == null) {
errln("ERROR: null result fmt=\"" + parseFormats[index]
+ "\" pos=" + parsePosition.getIndex()
+ " " + s1 + "|" + s2);
} else {
String result = ((DateFormat) dateParse).format(date);
logln("Parsed \"" + s + "\" using \"" + dateParse.toPattern() + "\" to: " + result);
if (expected == null)
errln("FAIL: Expected parse failure");
else
if (!result.equals(expected))
errln("FAIL: Expected " + expected);
}
} else
if (expected != null) {
errln("FAIL: Expected " + expected + " from \"" + s
+ "\" with \"" + dateParse.toPattern()+ "\"");
}
} catch (Exception ex) {
logln("FAIL:" + ex);
}
}
}
}
/**
* Test the parsing of two-digit years.
*/
public void TestTwoDigitYear() {
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(117 + 1900, Calendar.JUNE, 5);
parse2DigitYear(fmt, "6/5/17", cal.getTime());
cal.clear();
cal.set(34 + 1900, Calendar.JUNE, 4);
parse2DigitYear(fmt, "6/4/34", cal.getTime());
}
// internal test subroutine, used by TestTwoDigitYear
public void parse2DigitYear(DateFormat fmt, String str, Date expected) {
try {
Date d = fmt.parse(str);
logln("Parsing \""+ str+ "\" with "+ ((SimpleDateFormat) fmt).toPattern()
+ " => "+ d);
if (!d.equals(expected))
errln( "FAIL: Expected " + expected);
} catch (ParseException e) {
errln(e.getMessage());
}
}
/**
* Test the formatting of time zones.
*/
public void TestDateFormatZone061() {
Date date;
DateFormat formatter;
date = new Date(859248000000l);
logln("Date 1997/3/25 00:00 GMT: " + date);
formatter = new SimpleDateFormat("dd-MMM-yyyyy HH:mm", Locale.UK);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
String temp = formatter.format(date);
logln("Formatted in GMT to: " + temp);
try {
Date tempDate = formatter.parse(temp);
logln("Parsed to: " + tempDate);
if (!tempDate.equals(date))
errln("FAIL: Expected " + date);
} catch (Throwable t) {
System.out.println(t);
}
}
/**
* Test the formatting of time zones.
*/
public void TestDateFormatZone146() {
TimeZone saveDefault = TimeZone.getDefault();
//try {
TimeZone thedefault = TimeZone.getTimeZone("GMT");
TimeZone.setDefault(thedefault);
// java.util.Locale.setDefault(new java.util.Locale("ar", "", ""));
// check to be sure... its GMT all right
TimeZone testdefault = TimeZone.getDefault();
String testtimezone = testdefault.getID();
if (testtimezone.equals("GMT"))
logln("Test timezone = " + testtimezone);
else
errln("Test timezone should be GMT, not " + testtimezone);
// now try to use the default GMT time zone
GregorianCalendar greenwichcalendar = new GregorianCalendar(1997, 3, 4, 23, 0);
//*****************************greenwichcalendar.setTimeZone(TimeZone.getDefault());
//greenwichcalendar.set(1997, 3, 4, 23, 0);
// try anything to set hour to 23:00 !!!
greenwichcalendar.set(Calendar.HOUR_OF_DAY, 23);
// get time
Date greenwichdate = greenwichcalendar.getTime();
// format every way
String DATA[] = {
"simple format: ", "04/04/97 23:00 GMT",
"MM/dd/yy HH:mm z", "full format: ",
"Friday, April 4, 1997 11:00:00 o'clock PM GMT",
"EEEE, MMMM d, yyyy h:mm:ss 'o''clock' a z",
"long format: ", "April 4, 1997 11:00:00 PM GMT",
"MMMM d, yyyy h:mm:ss a z", "default format: ",
"04-Apr-97 11:00:00 PM", "dd-MMM-yy h:mm:ss a",
"short format: ", "4/4/97 11:00 PM",
"M/d/yy h:mm a"};
int DATA_length = DATA.length;
for (int i = 0; i < DATA_length; i += 3) {
DateFormat fmt = new SimpleDateFormat(DATA[i + 2], Locale.ENGLISH);
fmt.setCalendar(greenwichcalendar);
String result = fmt.format(greenwichdate);
logln(DATA[i] + result);
if (!result.equals(DATA[i + 1]))
errln("FAIL: Expected " + DATA[i + 1] + ", got " + result);
}
//}
//finally {
TimeZone.setDefault(saveDefault);
//}
}
/**
* Test the formatting of dates in different locales.
*/
public void TestLocaleDateFormat() {
Date testDate = new Date(874306800000l); //Mon Sep 15 00:00:00 PDT 1997
DateFormat dfFrench = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.FRENCH);
DateFormat dfUS = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
//Set TimeZone = PDT
TimeZone tz = TimeZone.getTimeZone("PST");
((SimpleTimeZone)tz).setDSTSavings(3600000);
dfFrench.setTimeZone(tz);
dfUS.setTimeZone(tz);
String expectedFRENCH_JDK12 = "lundi 15 septembre 1997 00 h 00 GMT-07:00";
String expectedFRENCH = "lundi 15 septembre 1997 00 h 00 PDT";
String expectedUS = "Monday, September 15, 1997 12:00:00 AM PDT";
logln("Date set to : " + testDate);
String out = dfFrench.format(testDate);
logln("Date Formated with French Locale " + out);
//fix the jdk resources differences between jdk 1.2 and jdk 1.3
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.2")) {
if (!out.equals(expectedFRENCH_JDK12))
errln("FAIL: Expected " + expectedFRENCH_JDK12);
} else {
if (!out.equals(expectedFRENCH))
errln("FAIL: Expected " + expectedFRENCH);
}
out = dfUS.format(testDate);
logln("Date Formated with US Locale " + out);
if (!out.equals(expectedUS))
errln("FAIL: Expected " + expectedUS);
}
}

View File

@ -1,270 +0,0 @@
/***************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDateFormat.java,v $
* $Date: 2001/10/23 13:11:35 $
* $Revision: 1.3 $
*
*****************************************************************************************
*/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDateFormat
* Source File: java/text/format/IntlTestDateFormat.java
**/
/*
@test 1.4 98/03/06
@summary test International Date Format
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.text.FieldPosition;
import java.text.ParseException;
import java.util.Locale;
import java.util.Random;
import java.util.Date;
public class IntlTestDateFormat extends com.ibm.test.TestFmwk {
// Values in milliseconds (== Date)
private static final long ONESECOND = 1000;
private static final long ONEMINUTE = 60 * ONESECOND;
private static final long ONEHOUR = 60 * ONEMINUTE;
private static final long ONEDAY = 24 * ONEHOUR;
//private static final double ONEYEAR = 365.25 * ONEDAY; // Approximate //The variable is never used
// EModes
//private static final byte GENERIC = 0;
//private static final byte TIME = GENERIC + 1; //The variable is never used
//private static final byte DATE = TIME + 1; //The variable is never used
//private static final byte DATE_TIME = DATE + 1; //The variable is never used
private DateFormat fFormat = DateFormat.getInstance();
private String fTestName = new String("getInstance");
private int fLimit = 3; // How many iterations it should take to reach convergence
public IntlTestDateFormat() {
//Constructure
}
public static void main(String[] args) throws Exception {
new IntlTestDateFormat().run(args);
}
public void TestLocale() {
localeTest(Locale.getDefault(), "Default Locale");
}
// This test does round-trip testing (format -> parse -> format -> parse -> etc.) of DateFormat.
public void localeTest(final Locale locale, final String localeName) {
int timeStyle, dateStyle;
// For patterns including only time information and a timezone, it may take
// up to three iterations, since the timezone may shift as the year number
// is determined. For other patterns, 2 iterations should suffice.
fLimit = 3;
for(timeStyle = 0; timeStyle < 4; timeStyle++) {
fTestName = new String("Time test " + timeStyle + " (" + localeName + ")");
try {
fFormat = DateFormat.getTimeInstance(timeStyle, locale);
}
catch(StringIndexOutOfBoundsException e) {
errln("FAIL: localeTest time getTimeInstance exception");
throw e;
}
TestFormat();
}
fLimit = 2;
for(dateStyle = 0; dateStyle < 4; dateStyle++) {
fTestName = new String("Date test " + dateStyle + " (" + localeName + ")");
try {
fFormat = DateFormat.getDateInstance(dateStyle, locale);
}
catch(StringIndexOutOfBoundsException e) {
errln("FAIL: localeTest date getTimeInstance exception");
throw e;
}
TestFormat();
}
for(dateStyle = 0; dateStyle < 4; dateStyle++) {
for(timeStyle = 0; timeStyle < 4; timeStyle++) {
fTestName = new String("DateTime test " + dateStyle + "/" + timeStyle + " (" + localeName + ")");
try {
fFormat = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
}
catch(StringIndexOutOfBoundsException e) {
errln("FAIL: localeTest date/time getDateTimeInstance exception");
throw e;
}
TestFormat();
}
}
}
public void TestFormat() {
if (fFormat == null) {
errln("FAIL: DateFormat creation failed");
return;
}
// logln("TestFormat: " + fTestName);
Date now = new Date();
tryDate(new Date(0));
tryDate(new Date((long) 1278161801778.0));
tryDate(now);
// Shift 6 months into the future, AT THE SAME TIME OF DAY.
// This will test the DST handling.
tryDate(new Date(now.getTime() + 6*30*ONEDAY));
Date limit = new Date(now.getTime() * 10); // Arbitrary limit
for (int i=0; i<2; ++i)
// tryDate(new Date(floor(randDouble() * limit)));
tryDate(new Date((long) (randDouble() * limit.getTime())));
}
private void describeTest() {
if (fFormat == null) {
errln("FAIL: no DateFormat");
return;
}
// Assume it's a SimpleDateFormat and get some info
SimpleDateFormat s = (SimpleDateFormat) fFormat;
logln(fTestName + " Pattern " + s.toPattern());
}
private void tryDate(Date theDate) {
final int DEPTH = 10;
Date[] date = new Date[DEPTH];
StringBuffer[] string = new StringBuffer[DEPTH];
int dateMatch = 0;
int stringMatch = 0;
boolean dump = false;
int i;
for (i=0; i<DEPTH; ++i) string[i] = new StringBuffer();
for (i=0; i<DEPTH; ++i) {
if (i == 0) date[i] = theDate;
else {
try {
date[i] = fFormat.parse(string[i-1].toString());
}
catch (ParseException e) {
describeTest();
errln("********** FAIL: Parse of " + string[i-1] + " failed.");
dump = true;
break;
}
}
FieldPosition position = new FieldPosition(0);
fFormat.format(date[i], string[i], position);
if (i > 0) {
if (dateMatch == 0 && date[i] == date[i-1]) dateMatch = i;
else if (dateMatch > 0 && date[i] != date[i-1]) {
describeTest();
errln("********** FAIL: Date mismatch after match.");
dump = true;
break;
}
if (stringMatch == 0 && string[i] == string[i-1]) stringMatch = i;
else if (stringMatch > 0 && string[i] != string[i-1]) {
describeTest();
errln("********** FAIL: String mismatch after match.");
dump = true;
break;
}
}
if (dateMatch > 0 && stringMatch > 0) break;
}
if (i == DEPTH) --i;
if (stringMatch > fLimit || dateMatch > fLimit) {
describeTest();
errln("********** FAIL: No string and/or date match within " + fLimit + " iterations.");
dump = true;
}
if (dump) {
for (int k=0; k<=i; ++k) {
logln("" + k + ": " + date[k] + " F> " + string[k] + " P> ");
}
}
}
// Return a random double from 0.01 to 1, inclusive
private double randDouble() {
// Assume 8-bit (or larger) rand values. Also assume
// that the system rand() function is very poor, which it always is.
// double d;
// int i;
// do {
// for (i=0; i < sizeof(double); ++i)
// {
// char poke = (char*)&d;
// poke[i] = (rand() & 0xFF);
// }
// } while (TPlatformUtilities.isNaN(d) || TPlatformUtilities.isInfinite(d));
// if (d < 0.0) d = -d;
// if (d > 0.0)
// {
// double e = floor(log10(d));
// if (e < -2.0) d *= pow(10.0, -e-2);
// else if (e > -1.0) d /= pow(10.0, e+1);
// }
// return d;
Random rand = new Random();
return rand.nextDouble();
}
public void TestAvailableLocales() {
final Locale[] locales = DateFormat.getAvailableLocales();
long count = locales.length;
logln("" + count + " available locales");
if (locales != null && count != 0) {
StringBuffer all = new StringBuffer();
for (int i=0; i<count; ++i) {
if (i!=0) all.append(", ");
all.append(locales[i].getDisplayName());
}
logln(all.toString());
}
else errln("********** FAIL: Zero available locales or null array pointer");
}
/* This test is too slow; we disable it for now
public void TestMonster() {
final Locale[] locales = DateFormat.getAvailableLocales();
long count = locales.length;
if (locales != null && count != 0) {
for (int i=0; i<count; ++i) {
String name = locales[i].getDisplayName();
logln("Testing " + name + "...");
try {
localeTest(locales[i], name);
}
catch(Exception e) {
errln("FAIL: TestMonster localeTest exception" + e);
}
}
}
}
*/
}
//eof

View File

@ -1,212 +0,0 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDateFormatAPI.java,v $
* $Date: 2001/11/21 19:26:09 $
* $Revision: 1.4 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDateFormatAPI
* Source File: java/text/format/IntlTestDateFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Date Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.util.*;
import com.ibm.text.*;
import java.util.Locale;
import java.util.Date;
import java.text.ParsePosition;
import java.text.FieldPosition;
import java.text.ParseException;
public class IntlTestDateFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDateFormatAPI().run(args);
}
// Test that the equals method works correctly.
public void TestEquals()
{
// Create two objects at different system times
DateFormat a = DateFormat.getInstance();
Date start = Calendar.getInstance().getTime();
while (true) {
// changed to remove compiler warnings.
if (!start.equals(Calendar.getInstance().getTime())) {
break; // Wait for time to change
}
}
DateFormat b = DateFormat.getInstance();
if (!(a.equals(b)))
errln("FAIL: DateFormat objects created at different times are unequal.");
// Why has this test been disabled??? - aliu
// if (b instanceof SimpleDateFormat)
// {
// //double ONE_YEAR = 365*24*60*60*1000.0; //The variable is never used
// try {
// ((SimpleDateFormat)b).setTwoDigitStartDate(start.getTime() + 50*ONE_YEAR);
// if (a.equals(b))
// errln("FAIL: DateFormat objects with different two digit start dates are equal.");
// }
// catch (Exception e) {
// errln("FAIL: setTwoDigitStartDate failed.");
// }
// }
}
// This test checks various generic API methods in DateFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("DateFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DateFormat constructors");
DateFormat def = DateFormat.getInstance();
DateFormat fr = DateFormat.getTimeInstance(DateFormat.FULL, Locale.FRENCH);
DateFormat it = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALIAN);
DateFormat de = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.GERMAN);
// ======= Test equality
logln("Testing equality operator");
if( fr.equals(it) ) {
errln("ERROR: equals failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
Date d = new Date((long)837039928046.0);
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
String res3 = new String();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
res1 = fr.format(d, res1, pos1);
logln("" + d.getTime() + " formatted to " + res1);
res2 = it.format(d, res2, pos2);
logln("" + d.getTime() + " formatted to " + res2);
res3 = de.format(d);
logln("" + d.getTime() + " formatted to " + res3);
// ======= Test parse()
logln("Testing parse()");
String text = new String("02/03/76 2:50 AM, CST");
Object result1 = new Date();
Date result2 = new Date();
Date result3 = new Date();
ParsePosition pos = new ParsePosition(0);
ParsePosition pos01 = new ParsePosition(0);
result1 = def.parseObject(text, pos);
if (result1 == null) {
errln("ERROR: parseObject() failed for " + text);
}
logln(text + " parsed into " + ((Date)result1).getTime());
try {
result2 = def.parse(text);
}
catch (ParseException e) {
errln("ERROR: parse() failed");
}
logln(text + " parsed into " + result2.getTime());
result3 = def.parse(text, pos01);
if (result3 == null) {
errln("ERROR: parse() failed for " + text);
}
logln(text + " parsed into " + result3.getTime());
// ======= Test getters and setters
logln("Testing getters and setters");
final Locale[] locales = DateFormat.getAvailableLocales();
long count = locales.length;
logln("Got " + count + " locales" );
for(int i = 0; i < count; i++) {
String name;
name = locales[i].getDisplayName();
logln(name);
}
fr.setLenient(it.isLenient());
if(fr.isLenient() != it.isLenient()) {
errln("ERROR: setLenient() failed");
}
final Calendar cal = def.getCalendar();
Calendar newCal = (Calendar) cal.clone();
de.setCalendar(newCal);
it.setCalendar(newCal);
if( ! de.getCalendar().equals(it.getCalendar())) {
errln("ERROR: set Calendar() failed");
}
final NumberFormat nf = def.getNumberFormat();
NumberFormat newNf = (NumberFormat) nf.clone();
de.setNumberFormat(newNf);
it.setNumberFormat(newNf);
if( ! de.getNumberFormat().equals(it.getNumberFormat())) {
errln("ERROR: set NumberFormat() failed");
}
final TimeZone tz = def.getTimeZone();
TimeZone newTz = (TimeZone) tz.clone();
de.setTimeZone(newTz);
it.setTimeZone(newTz);
if( ! de.getTimeZone().equals(it.getTimeZone())) {
errln("ERROR: set TimeZone() failed");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// DateFormat test = new SimpleDateFormat();
// if (! (test instanceof SimpleDateFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DateFormat");
// }
}
}

View File

@ -1,159 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDateFormatAPIC.java,v $
* $Date: 2001/10/19 11:43:37 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestDateFormatAPI
* Source File: $ICU4CRoot/source/test/intltest/dtfmapts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Date;
import java.text.FieldPosition;
import java.text.ParsePosition;
/*
* This is an API test, not a unit test. It doesn't test very many cases, and doesn't
* try to test the full functionality. It just calls each function in the class and
* verifies that it works on a basic level.
*/
public class IntlTestDateFormatAPIC extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new IntlTestDateFormatAPIC().run(args);
}
/**
* Test hiding of parse() and format() APIs in the Format hierarchy.
* We test the entire hierarchy, even though this test is located in
* the DateFormat API test.
*/
public void TestNameHiding() {
// N.B.: This test passes if it COMPILES, since it's a test of
// compile-time name hiding.
Date dateObj = new Date(0);
Number numObj = new Double(3.1415926535897932384626433832795);
StringBuffer strBuffer = new StringBuffer("");
String str;
FieldPosition fpos = new FieldPosition(0);
ParsePosition ppos = new ParsePosition(0);
// DateFormat calling Format API
{
logln("DateFormat");
DateFormat dateFmt = DateFormat.getInstance();
if (dateFmt != null) {
str = dateFmt.format(dateObj);
strBuffer = dateFmt.format(dateObj, strBuffer, fpos);
} else {
errln("FAIL: Can't create DateFormat");
}
}
// SimpleDateFormat calling Format & DateFormat API
{
logln("SimpleDateFormat");
SimpleDateFormat sdf = new SimpleDateFormat();
// Format API
str = sdf.format(dateObj);
strBuffer = sdf.format(dateObj, strBuffer, fpos);
// DateFormat API
strBuffer = sdf.format(new Date(0), strBuffer, fpos);
str = sdf.format(new Date(0));
try {
sdf.parse(str);
sdf.parse(str, ppos);
} catch (java.text.ParseException pe) {
System.out.println(pe);
}
}
// NumberFormat calling Format API
{
logln("NumberFormat");
NumberFormat fmt = NumberFormat.getInstance();
if (fmt != null) {
str = fmt.format(numObj);
strBuffer = fmt.format(numObj, strBuffer, fpos);
} else {
errln("FAIL: Can't create NumberFormat");
}
}
// DecimalFormat calling Format & NumberFormat API
{
logln("DecimalFormat");
DecimalFormat fmt = new DecimalFormat();
// Format API
str = fmt.format(numObj);
strBuffer = fmt.format(numObj, strBuffer, fpos);
// NumberFormat API
str = fmt.format(2.71828);
str = fmt.format(1234567);
strBuffer = fmt.format(1.41421, strBuffer, fpos);
strBuffer = fmt.format(9876543, strBuffer, fpos);
Number obj = fmt.parse(str, ppos);
try {
obj = fmt.parse(str);
} catch (java.text.ParseException pe) {
System.out.println(pe);
}
}
//ICU4J have not the classes ChoiceFormat and MessageFormat
/*
// ChoiceFormat calling Format & NumberFormat API
{
logln("ChoiceFormat");
ChoiceFormat fmt = new ChoiceFormat("0#foo|1#foos|2#foos");
// Format API
str = fmt.format(numObj);
strBuffer = fmt.format(numObj, strBuffer, fpos);
// NumberFormat API
str = fmt.format(2.71828);
str = fmt.format(1234567);
strBuffer = fmt.format(1.41421, strBuffer, fpos);
strBuffer = fmt.format(9876543, strBuffer, fpos);
Number obj = fmt.parse(str, ppos);
try {
obj = fmt.parse(str);
} catch (java.text.ParseException pe) {
System.out.println(pe);
}
}
// MessageFormat calling Format API
{
logln("MessageFormat");
MessageFormat fmt = new MessageFormat("");
// Format API
// We use dateObj, which MessageFormat should reject.
// We're testing name hiding, not the format method.
try {
str = fmt.format(dateObj);
} catch (Exception e) {
//e.printStackTrace();
}
try {
strBuffer = fmt.format(dateObj, strBuffer, fpos);
} catch (Exception e) {
//e.printStackTrace();
}
}
*/
}
}

View File

@ -1,198 +0,0 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDateFormatSymbols.java,v $
* $Date: 2001/10/23 13:12:31 $
* $Revision: 1.2 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDateFormatSymbols
* Source File: java/text/format/IntlTestDateFormatSymbols.java
**/
/*
@test 1.4 98/03/06
@summary test International Date Format Symbols
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
public class IntlTestDateFormatSymbols extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDateFormatSymbols().run(args);
}
// Test getMonths
public void TestGetMonths()
{
final String[] month;
DateFormatSymbols symbol;
symbol=new DateFormatSymbols(Locale.getDefault());
month=symbol.getMonths();
int cnt = month.length;
logln("size = " + cnt);
for (int i=0; i<cnt; ++i)
{
logln(month[i]);
}
}
// Test the API of DateFormatSymbols; primarily a simple get/set set.
public void TestSymbols()
{
DateFormatSymbols fr = new DateFormatSymbols(Locale.FRENCH);
DateFormatSymbols en = new DateFormatSymbols(Locale.ENGLISH);
if(en.equals(fr)) {
errln("ERROR: English DateFormatSymbols equal to French");
}
// just do some VERY basic tests to make sure that get/set work
long count;
final String[] eras = en.getEras();
fr.setEras(eras);
final String[] eras1 = fr.getEras();
count = eras.length;
if( count != eras1.length) {
errln("ERROR: setEras() failed (different size array)");
}
else {
for(int i = 0; i < count; i++) {
if(! eras[i].equals(eras1[i])) {
errln("ERROR: setEras() failed (different string values)");
}
}
}
final String[] months = en.getMonths();
fr.setMonths(months);
final String[] months1 = fr.getMonths();
count = months.length;
if( count != months1.length) {
errln("ERROR: setMonths() failed (different size array)");
}
else {
for(int i = 0; i < count; i++) {
if(! months[i].equals(months1[i])) {
errln("ERROR: setMonths() failed (different string values)");
}
}
}
final String[] shortMonths = en.getShortMonths();
fr.setShortMonths(shortMonths);
final String[] shortMonths1 = fr.getShortMonths();
count = shortMonths.length;
if( count != shortMonths1.length) {
errln("ERROR: setShortMonths() failed (different size array)");
}
else {
for(int i = 0; i < count; i++) {
if(! shortMonths[i].equals(shortMonths1[i])) {
errln("ERROR: setShortMonths() failed (different string values)");
}
}
}
final String[] weekdays = en.getWeekdays();
fr.setWeekdays(weekdays);
final String[] weekdays1 = fr.getWeekdays();
count = weekdays.length;
if( count != weekdays1.length) {
errln("ERROR: setWeekdays() failed (different size array)");
}
else {
for(int i = 0; i < count; i++) {
if(! weekdays[i].equals(weekdays1[i])) {
errln("ERROR: setWeekdays() failed (different string values)");
}
}
}
final String[] shortWeekdays = en.getShortWeekdays();
fr.setShortWeekdays(shortWeekdays);
final String[] shortWeekdays1 = fr.getShortWeekdays();
count = shortWeekdays.length;
if( count != shortWeekdays1.length) {
errln("ERROR: setShortWeekdays() failed (different size array)");
}
else {
for(int i = 0; i < count; i++) {
if(! shortWeekdays[i].equals(shortWeekdays1[i])) {
errln("ERROR: setShortWeekdays() failed (different string values)");
}
}
}
final String[] ampms = en.getAmPmStrings();
fr.setAmPmStrings(ampms);
final String[] ampms1 = fr.getAmPmStrings();
count = ampms.length;
if( count != ampms1.length) {
errln("ERROR: setAmPmStrings() failed (different size array)");
}
else {
for(int i = 0; i < count; i++) {
if(! ampms[i].equals(ampms1[i])) {
errln("ERROR: setAmPmStrings() failed (different string values)");
}
}
}
long rowCount = 0, columnCount = 0;
final String[][] strings = en.getZoneStrings();
fr.setZoneStrings(strings);
final String[][] strings1 = fr.getZoneStrings();
rowCount = strings.length;
for(int i = 0; i < rowCount; i++) {
columnCount = strings[i].length;
for(int j = 0; j < columnCount; j++) {
if( strings[i][j] != strings1[i][j] ) {
errln("ERROR: setZoneStrings() failed");
}
}
}
// final String pattern = DateFormatSymbols.getPatternChars();
String localPattern; // pat1, pat2; //The variable is never used
localPattern = en.getLocalPatternChars();
fr.setLocalPatternChars(localPattern);
if(! en.getLocalPatternChars().equals(fr.getLocalPatternChars())) {
errln("ERROR: setLocalPatternChars() failed");
}
//DateFormatSymbols foo = new DateFormatSymbols(); //The variable is never used
en = (DateFormatSymbols) fr.clone();
if(! en.equals(fr)) {
errln("ERROR: Clone failed");
}
}
}

View File

@ -1,236 +0,0 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatAPI.java,v $
* $Date: 2001/10/19 12:09:26 $
* $Revision: 1.1 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatAPI
* Source File: java/text/format/IntlTestDecimalFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Decimal Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.Format;
import java.text.FieldPosition;
public class IntlTestDecimalFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatAPI().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("DecimalFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DecimalFormat constructors");
DecimalFormat def = new DecimalFormat();
final String pattern = new String("#,##0.# FF");
DecimalFormat pat = null;
try {
pat = new DecimalFormat(pattern);
}
catch (IllegalArgumentException e) {
errln("ERROR: Could not create DecimalFormat (pattern)");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
// ======= Test clone(), assignment, and equality
logln("Testing clone() and equality operators");
Format clone = (Format) def.clone();
if( ! def.equals(clone)) {
errln("ERROR: Clone() failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
logln("" + d + " is the double value");
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln("" + d + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln("" + l + " formatted to " + res2);
res3 = cust1.format(d, res3, pos3);
logln("" + d + " formatted to " + res3);
res4 = cust1.format(l, res4, pos4);
logln("" + l + " formatted to " + res4);
// ======= Test parse()
logln("Testing parse()");
String text = new String("-10,456.0037");
ParsePosition pos = new ParsePosition(0);
String patt = new String("#,##0.#");
pat.applyPattern(patt);
double d2 = pat.parse(text, pos).doubleValue();
if(d2 != d) {
errln("ERROR: Roundtrip failed (via parse(" + d2 + " != " + d + ")) for " + text);
}
logln(text + " parsed into " + (long) d2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
def.setDecimalFormatSymbols(syms);
if( ! pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
errln("ERROR: set DecimalFormatSymbols() failed");
}
String posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix();
logln("Positive prefix (should be +): " + posPrefix);
if(posPrefix != "+") {
errln("ERROR: setPositivePrefix() failed");
}
String negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix();
logln("Negative prefix (should be -): " + negPrefix);
if(negPrefix != "-") {
errln("ERROR: setNegativePrefix() failed");
}
String posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix();
logln("Positive suffix (should be _): " + posSuffix);
if(posSuffix != "_") {
errln("ERROR: setPositiveSuffix() failed");
}
String negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix();
logln("Negative suffix (should be ~): " + negSuffix);
if(negSuffix != "~") {
errln("ERROR: setNegativeSuffix() failed");
}
long multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln("Multiplier (should be 8): " + multiplier);
if(multiplier != 8) {
errln("ERROR: setMultiplier() failed");
}
int groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln("Grouping size (should be 2): " + (long) groupingSize);
if(groupingSize != 2) {
errln("ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(true);
boolean tf = pat.isDecimalSeparatorAlwaysShown();
logln("DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
if(tf != true) {
errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
}
String funkyPat;
funkyPat = pat.toPattern();
logln("Pattern is " + funkyPat);
String locPat;
locPat = pat.toLocalizedPattern();
logln("Localized pattern is " + locPat);
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("#,##0.0#;(#,##0.0#)");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2;
s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if( ! s2.equals(p1) ) {
errln("ERROR: toPattern() result did not match pattern applied");
}
String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
logln("Applying pattern " + p2);
pat.applyLocalizedPattern(p2);
String s3;
s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if( ! s3.equals(p2) ) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
}

View File

@ -1,287 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatAPIC.java,v $
* $Date: 2001/10/19 12:10:26 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestDecimalFormatAPI
* Source File: $ICU4CRoot/source/test/intltest/dcfmapts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.Format;
import com.ibm.text.*;
import java.text.FieldPosition;
// This is an API test, not a unit test. It doesn't test very many cases, and doesn't
// try to test the full functionality. It just calls each function in the class and
// verifies that it works on a basic level.
public class IntlTestDecimalFormatAPIC extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatAPIC().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI() {
logln("DecimalFormat API test---");
logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DecimalFormat constructors");
DecimalFormat def = new DecimalFormat();
final String pattern = new String("#,##0.# FF");
DecimalFormat pat = null;
try {
pat = new DecimalFormat(pattern);
} catch (IllegalArgumentException e) {
errln("ERROR: Could not create DecimalFormat (pattern)");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
// ======= Test clone(), assignment, and equality
logln("Testing clone() and equality operators");
Format clone = (Format) def.clone();
if (!def.equals(clone)) {
errln("ERROR: Clone() failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
logln("" + Double.toString(d) + " is the double value");
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln("" + Double.toString(d) + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln("" + l + " formatted to " + res2);
res3 = cust1.format(d, res3, pos3);
logln("" + Double.toString(d) + " formatted to " + res3);
res4 = cust1.format(l, res4, pos4);
logln("" + l + " formatted to " + res4);
// ======= Test parse()
logln("Testing parse()");
String text = new String("-10,456.0037");
ParsePosition pos = new ParsePosition(0);
String patt = new String("#,##0.#");
pat.applyPattern(patt);
double d2 = pat.parse(text, pos).doubleValue();
if (d2 != d) {
errln(
"ERROR: Roundtrip failed (via parse(" + Double.toString(d2) + " != " + Double.toString(d) + ")) for " + text);
}
logln(text + " parsed into " + (long) d2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
def.setDecimalFormatSymbols(syms);
if (!pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
errln("ERROR: set DecimalFormatSymbols() failed");
}
String posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix();
logln("Positive prefix (should be +): " + posPrefix);
if (posPrefix != "+") {
errln("ERROR: setPositivePrefix() failed");
}
String negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix();
logln("Negative prefix (should be -): " + negPrefix);
if (negPrefix != "-") {
errln("ERROR: setNegativePrefix() failed");
}
String posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix();
logln("Positive suffix (should be _): " + posSuffix);
if (posSuffix != "_") {
errln("ERROR: setPositiveSuffix() failed");
}
String negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix();
logln("Negative suffix (should be ~): " + negSuffix);
if (negSuffix != "~") {
errln("ERROR: setNegativeSuffix() failed");
}
long multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln("Multiplier (should be 8): " + multiplier);
if (multiplier != 8) {
errln("ERROR: setMultiplier() failed");
}
int groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln("Grouping size (should be 2): " + (long) groupingSize);
if (groupingSize != 2) {
errln("ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(true);
boolean tf = pat.isDecimalSeparatorAlwaysShown();
logln(
"DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
if (tf != true) {
errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
}
String funkyPat;
funkyPat = pat.toPattern();
logln("Pattern is " + funkyPat);
String locPat;
locPat = pat.toLocalizedPattern();
logln("Localized pattern is " + locPat);
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("#,##0.0#;(#,##0.0#)");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2;
s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if (!s2.equals(p1)) {
errln("ERROR: toPattern() result did not match pattern applied");
}
String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
logln("Applying pattern " + p2);
pat.applyLocalizedPattern(p2);
String s3;
s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if (!s3.equals(p2)) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
public void TestRounding() {
double Roundingnumber = 2.55;
double Roundingnumber1 = -2.55;
//+2.55 results -2.55 results
double result[] = {
3, -3,
2, -2,
3, -2,
2, -3,
3, -3,
3, -3,
3, -3
};
DecimalFormat pat = new DecimalFormat();
String s = "";
s = pat.toPattern();
logln("pattern = " + s);
int mode;
int i = 0;
String message;
String resultStr;
for (mode = 0; mode < 7; mode++) {
pat.setRoundingMode(mode);
if (pat.getRoundingMode() != mode) {
errln(
"SetRoundingMode or GetRoundingMode failed for mode=" + mode);
}
//for +2.55 with RoundingIncrement=1.0
pat.setRoundingIncrement(1.0);
resultStr = pat.format(Roundingnumber);
message = "round(" + (double) Roundingnumber
+ "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
verify(message, resultStr, result[i++]);
message = "";
resultStr = "";
//for -2.55 with RoundingIncrement=1.0
resultStr = pat.format(Roundingnumber1);
message = "round(" + (double) Roundingnumber1
+ "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
verify(message, resultStr, result[i++]);
message = "";
resultStr = "";
}
}
/*Helper functions */
public void verify(String message, String got, double expected) {
logln(message + got + " Expected : " + (long)expected);
String expectedStr = "";
expectedStr=expectedStr + (long)expected;
if(!got.equals(expectedStr) ) {
errln("ERROR: Round() failed: " + message + got + " Expected : " + expectedStr);
}
}
}

View File

@ -1,132 +0,0 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatSymbols.java,v $
* $Date: 2001/10/23 13:12:49 $
* $Revision: 1.2 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatSymbols
* Source File: java/text/format/IntlTestDecimalFormatSymbols.java
**/
/*
@test 1.4 98/03/06
@summary test International Decimal Format Symbols
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.FieldPosition;
public class IntlTestDecimalFormatSymbols extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatSymbols().run(args);
}
// Test the API of DecimalFormatSymbols; primarily a simple get/set set.
public void TestSymbols()
{
DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH);
if(en.equals(fr)) {
errln("ERROR: English DecimalFormatSymbols equal to French");
}
// just do some VERY basic tests to make sure that get/set work
char zero = en.getZeroDigit();
fr.setZeroDigit(zero);
if(fr.getZeroDigit() != en.getZeroDigit()) {
errln("ERROR: get/set ZeroDigit failed");
}
char group = en.getGroupingSeparator();
fr.setGroupingSeparator(group);
if(fr.getGroupingSeparator() != en.getGroupingSeparator()) {
errln("ERROR: get/set GroupingSeparator failed");
}
char decimal = en.getDecimalSeparator();
fr.setDecimalSeparator(decimal);
if(fr.getDecimalSeparator() != en.getDecimalSeparator()) {
errln("ERROR: get/set DecimalSeparator failed");
}
char perMill = en.getPerMill();
fr.setPerMill(perMill);
if(fr.getPerMill() != en.getPerMill()) {
errln("ERROR: get/set PerMill failed");
}
char percent = en.getPercent();
fr.setPercent(percent);
if(fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char digit = en.getDigit();
fr.setDigit(digit);
if(fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char patternSeparator = en.getPatternSeparator();
fr.setPatternSeparator(patternSeparator);
if(fr.getPatternSeparator() != en.getPatternSeparator()) {
errln("ERROR: get/set PatternSeparator failed");
}
String infinity = en.getInfinity();
fr.setInfinity(infinity);
String infinity2 = fr.getInfinity();
if(! infinity.equals(infinity2)) {
errln("ERROR: get/set Infinity failed");
}
String nan = en.getNaN();
fr.setNaN(nan);
String nan2 = fr.getNaN();
if(! nan.equals(nan2)) {
errln("ERROR: get/set NaN failed");
}
char minusSign = en.getMinusSign();
fr.setMinusSign(minusSign);
if(fr.getMinusSign() != en.getMinusSign()) {
errln("ERROR: get/set MinusSign failed");
}
// char exponential = en.getExponentialSymbol();
// fr.setExponentialSymbol(exponential);
// if(fr.getExponentialSymbol() != en.getExponentialSymbol()) {
// errln("ERROR: get/set Exponential failed");
// }
//DecimalFormatSymbols foo = new DecimalFormatSymbols(); //The variable is never used
en = (DecimalFormatSymbols) fr.clone();
if(! en.equals(fr)) {
errln("ERROR: Clone failed");
}
}
}

View File

@ -1,147 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatSymbolsC.java,v $
* $Date: 2001/10/23 13:13:25 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestDecimalFormatSymbols
* Source File: $ICU4CRoot/source/test/intltest/tsdcfmsy.cpp
**/
package com.ibm.icu.test.format;
import java.text.FieldPosition;
import com.ibm.util.*;
import java.util.Locale;
import com.ibm.text.*;
/**
* Tests for DecimalFormatSymbols
**/
public class IntlTestDecimalFormatSymbolsC extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatSymbolsC().run(args);
}
/**
* Test the API of DecimalFormatSymbols; primarily a simple get/set set.
*/
public void TestSymbols() {
DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH);
if (en.equals(fr)) {
errln("ERROR: English DecimalFormatSymbols equal to French");
}
// just do some VERY basic tests to make sure that get/set work
char zero = en.getZeroDigit();
fr.setZeroDigit(zero);
if (fr.getZeroDigit() != en.getZeroDigit()) {
errln("ERROR: get/set ZeroDigit failed");
}
char group = en.getGroupingSeparator();
fr.setGroupingSeparator(group);
if (fr.getGroupingSeparator() != en.getGroupingSeparator()) {
errln("ERROR: get/set GroupingSeparator failed");
}
char decimal = en.getDecimalSeparator();
fr.setDecimalSeparator(decimal);
if (fr.getDecimalSeparator() != en.getDecimalSeparator()) {
errln("ERROR: get/set DecimalSeparator failed");
}
char perMill = en.getPerMill();
fr.setPerMill(perMill);
if (fr.getPerMill() != en.getPerMill()) {
errln("ERROR: get/set PerMill failed");
}
char percent = en.getPercent();
fr.setPercent(percent);
if (fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char digit = en.getDigit();
fr.setDigit(digit);
if (fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char patternSeparator = en.getPatternSeparator();
fr.setPatternSeparator(patternSeparator);
if (fr.getPatternSeparator() != en.getPatternSeparator()) {
errln("ERROR: get/set PatternSeparator failed");
}
String infinity = en.getInfinity();
fr.setInfinity(infinity);
String infinity2 = fr.getInfinity();
if (!infinity.equals(infinity2)) {
errln("ERROR: get/set Infinity failed");
}
String nan = en.getNaN();
fr.setNaN(nan);
String nan2 = fr.getNaN();
if (!nan.equals(nan2)) {
errln("ERROR: get/set NaN failed");
}
char minusSign = en.getMinusSign();
fr.setMinusSign(minusSign);
if (fr.getMinusSign() != en.getMinusSign()) {
errln("ERROR: get/set MinusSign failed");
}
// char exponential = en.getExponentialSymbol();
// fr.setExponentialSymbol(exponential);
// if(fr.getExponentialSymbol() != en.getExponentialSymbol()) {
// errln("ERROR: get/set Exponential failed");
// }
//DecimalFormatSymbols foo = new DecimalFormatSymbols(); //The variable is never used
en = (DecimalFormatSymbols) fr.clone();
if (!en.equals(fr)) {
errln("ERROR: Clone failed");
}
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
verify(34.5, "00.00", sym, "34.50");
sym.setDecimalSeparator('S');
verify(34.5, "00.00", sym, "34S50");
sym.setPercent('P');
verify(34.5, "00 %", sym, "3450 P");
sym.setCurrencySymbol("D");
verify(34.5, "\u00a4##.##", sym, "D34.5");
sym.setGroupingSeparator('|');
verify(3456.5, "0,000.##", sym, "3|456S5");
}
/** helper functions**/
public void verify(double value, String pattern, DecimalFormatSymbols sym, String expected) {
DecimalFormat df = new DecimalFormat(pattern, sym);
StringBuffer buffer = new StringBuffer("");
FieldPosition pos = new FieldPosition(-1);
buffer = df.format(value, buffer, pos);
if(!buffer.toString().equals(expected)){
errln("ERROR: format failed after setSymbols()\n Expected" +
expected + ", Got " + buffer);
}
}
}

View File

@ -1,291 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestNumberFormat.java,v $
* $Date: 2001/10/23 13:13:49 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestNumberFormat
* Source File: $ICU4CRoot/source/test/intltest/tsnmfmt.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
/**
* This test does round-trip testing (format -> parse -> format -> parse -> etc.) of
* NumberFormat.
*/
public class IntlTestNumberFormat extends com.ibm.test.TestFmwk {
public NumberFormat fNumberFormat = NumberFormat.getInstance();
public static void main(String[] args) throws Exception {
new IntlTestNumberFormat().run(args);
}
/*
* Internal use
**/
public void _testLocale(java.util.Locale locale, String localeName) {
String name;
// locale = java.util.Locale.getDefault();
// localeName = locale.getDisplayName();
name = "Number test";
logln(name + " ( " + localeName + " ) ");
fNumberFormat = NumberFormat.getInstance(locale);
TestFormat();
name = "Currency test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getCurrencyInstance(locale);
TestFormat(/* par */);
name = "Percent test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getPercentInstance(locale);
TestFormat(/* par */);
}
/**
* call TestFormat for currency, percent and plain number instances
**/
public void TestLocale() {
String name;
String localeName;
java.util.Locale locale = java.util.Locale.getDefault();
localeName = locale.getDisplayName();
name = "Number test";
logln(name + " ( " + localeName + " ) ");
fNumberFormat = NumberFormat.getInstance();
TestFormat();
name = "Currency test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getCurrencyInstance();
TestFormat(/* par */);
name = "Percent test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getPercentInstance();
TestFormat(/* par */);
}
/**
* call tryIt with many variations, called by testLocale
**/
public void TestFormat() {
if (fNumberFormat == null){
errln("**** FAIL: Null format returned by createXxxInstance.");
return;
}
DecimalFormat s = (DecimalFormat)fNumberFormat;
logln("pattern :" + s.toPattern());
tryIt(-2.02147304840132e-68);
tryIt(3.88057859588817e-68);
tryIt(-2.64651110485945e+65);
tryIt(9.29526819488338e+64);
tryIt(-2.02147304840132e-100);
tryIt(3.88057859588817e-096);
tryIt(-2.64651110485945e+306);
tryIt(9.29526819488338e+250);
tryIt(-9.18228054496402e+64);
tryIt(-9.69413034454191e+64);
tryIt(-9.18228054496402e+255);
tryIt(-9.69413034454191e+273);
tryIt(1.234e-200);
tryIt(-2.3e-168);
tryIt(Double.NaN);
tryIt(Double.POSITIVE_INFINITY);
tryIt(Double.NEGATIVE_INFINITY);
tryIt(251887531);
tryIt(5e-20 / 9);
tryIt(5e20 / 9);
tryIt(1.234e-50);
tryIt(9.99999999999996);
tryIt(9.999999999999996);
tryIt(Integer.MIN_VALUE);
tryIt(Integer.MAX_VALUE);
tryIt((double)Integer.MIN_VALUE);
tryIt((double)Integer.MAX_VALUE);
tryIt((double)Integer.MIN_VALUE - 1.0);
tryIt((double)Integer.MAX_VALUE + 1.0);
tryIt(5.0 / 9.0 * 1e-20);
tryIt(4.0 / 9.0 * 1e-20);
tryIt(5.0 / 9.0 * 1e+20);
tryIt(4.0 / 9.0 * 1e+20);
tryIt(2147483647.);
tryIt(0);
tryIt(0.0);
tryIt(1);
tryIt(10);
tryIt(100);
tryIt(-1);
tryIt(-10);
tryIt(-100);
tryIt(-1913860352);
for (int j = 0; j < 10; j++) {
double d = Math.random()*2e10 - 1e10;
tryIt(d);
}
}
/**
* perform tests using aNumber and fNumberFormat, called in many variations
**/
public void tryIt(double aNumber) {
final int DEPTH = 10;
double[] number = new double[DEPTH];
String[] string = new String[DEPTH];
int numberMatch = 0;
int stringMatch = 0;
boolean dump = false;
int i;
for (i = 0; i < DEPTH; i++) {
if (i == 0) {
number[i] = aNumber;
} else {
try {
number[i - 1] = fNumberFormat.parse(string[i - 1]).doubleValue();
} catch(java.text.ParseException pe) {
errln("**** FAIL: Parse of " + string[i-1] + " failed.");
dump = true;
break;
}
}
string[i] = fNumberFormat.format(number[i]);
if (i > 0)
{
if (numberMatch == 0 && number[i] == number[i-1])
numberMatch = i;
else if (numberMatch > 0 && number[i] != number[i-1])
{
errln("**** FAIL: Numeric mismatch after match.");
dump = true;
break;
}
if (stringMatch == 0 && string[i] == string[i-1])
stringMatch = i;
else if (stringMatch > 0 && string[i] != string[i-1])
{
errln("**** FAIL: String mismatch after match.");
dump = true;
break;
}
}
if (numberMatch > 0 && stringMatch > 0)
break;
if (i == DEPTH)
--i;
if (stringMatch > 2 || numberMatch > 2)
{
errln("**** FAIL: No string and/or number match within 2 iterations.");
dump = true;
}
if (dump)
{
for (int k=0; k<=i; ++k)
{
logln(k + ": " + number[k] + " F> " +
string[k] + " P> ");
}
}
}
}
/**
* perform tests using aNumber and fNumberFormat, called in many variations
**/
public void tryIt(int aNumber) {
long number;;
String stringNum = fNumberFormat.format(aNumber);
try {
number = fNumberFormat.parse(stringNum).longValue();
} catch (java.text.ParseException pe) {
errln("**** FAIL: Parse of " + stringNum + " failed.");
return;
}
if (number != aNumber) {
errln("**** FAIL: Parse of " + stringNum + " failed. Got:" + number
+ " Expected:" + aNumber);
}
}
/**
* test NumberFormat::getAvailableLocales
**/
public void TestAvailableLocales() {
final java.util.Locale[] locales = NumberFormat.getAvailableLocales();
int count = locales.length;
logln(count + " available locales");
if (count != 0)
{
String all = "";
for (int i = 0; i< count; ++i)
{
if (i!=0)
all += ", ";
all += locales[i].getDisplayName();
}
logln(all);
}
else
errln("**** FAIL: Zero available locales or null array pointer");
}
/**
* call testLocale for all locales
**/
public void TestMonster() {
final String SEP = "============================================================\n";
int count;
final java.util.Locale[] locales = NumberFormat.getAvailableLocales();
count = locales.length;
if (count != 0)
{
count = 3; // just test 3 locales
for (int i=0; i<count; ++i)
{
String name = locales[i].getDisplayName();
logln(SEP);
_testLocale(/* par, */locales[i], name);
}
}
logln(SEP);
}
}

View File

@ -1,215 +0,0 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestNumberFormatAPI.java,v $
* $Date: 2001/10/23 13:14:05 $
* $Revision: 1.2 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestNumberFormatAPI
* Source File: java/text/format/IntlTestNumberFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Number Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.ParseException;
public class IntlTestNumberFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestNumberFormatAPI().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("NumberFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing NumberFormat constructors");
NumberFormat def = NumberFormat.getInstance();
NumberFormat fr = NumberFormat.getInstance(Locale.FRENCH);
NumberFormat cur = NumberFormat.getCurrencyInstance();
NumberFormat cur_fr = NumberFormat.getCurrencyInstance(Locale.FRENCH);
NumberFormat per = NumberFormat.getPercentInstance();
NumberFormat per_fr = NumberFormat.getPercentInstance(Locale.FRENCH);
NumberFormat integer = NumberFormat.getIntegerInstance();
NumberFormat int_fr = NumberFormat.getIntegerInstance(Locale.FRENCH);
//Fix "The variable is never used" compilation warnings
logln("Currency : " + cur.format(1234.5));
logln("Percent : " + per.format(1234.5));
logln("Integer : " + integer.format(1234.5));
logln("Int_fr : " + int_fr.format(1234.5));
// ======= Test equality
logln("Testing equality operator");
if( per_fr.equals(cur_fr) ) {
errln("ERROR: == failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
String res1 = new String();
String res2 = new String();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
StringBuffer res5 = new StringBuffer();
StringBuffer res6 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = cur_fr.format(d);
logln( "" + d + " formatted to " + res1);
res2 = cur_fr.format(l);
logln("" + l + " formatted to " + res2);
res3 = cur_fr.format(d, res3, pos1);
logln( "" + d + " formatted to " + res3);
res4 = cur_fr.format(l, res4, pos2);
logln("" + l + " formatted to " + res4);
res5 = cur_fr.format(d, res5, pos3);
logln("" + d + " formatted to " + res5);
res6 = cur_fr.format(l, res6, pos4);
logln("" + l + " formatted to " + res6);
// ======= Test parse()
logln("Testing parse()");
// String text = new String("-10,456.0037");
String text = new String("-10456,0037");
ParsePosition pos = new ParsePosition(0);
ParsePosition pos01 = new ParsePosition(0);
double d1 = ((Number)fr.parseObject(text, pos)).doubleValue();
if(d1 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d1);
double d2 = fr.parse(text, pos01).doubleValue();
if(d2 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d2);
double d3 = 0;
try {
d3 = fr.parse(text).doubleValue();
}
catch (ParseException e) {
errln("ERROR: parse() failed");
}
if(d3 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d3);
// ======= Test getters and setters
logln("Testing getters and setters");
final Locale[] locales = NumberFormat.getAvailableLocales();
long count = locales.length;
logln("Got " + count + " locales" );
for(int i = 0; i < count; i++) {
String name;
name = locales[i].getDisplayName();
logln(name);
}
fr.setParseIntegerOnly( def.isParseIntegerOnly() );
if(fr.isParseIntegerOnly() != def.isParseIntegerOnly() ) {
errln("ERROR: setParseIntegerOnly() failed");
}
fr.setGroupingUsed( def.isGroupingUsed() );
if(fr.isGroupingUsed() != def.isGroupingUsed() ) {
errln("ERROR: setGroupingUsed() failed");
}
fr.setMaximumIntegerDigits( def.getMaximumIntegerDigits() );
if(fr.getMaximumIntegerDigits() != def.getMaximumIntegerDigits() ) {
errln("ERROR: setMaximumIntegerDigits() failed");
}
fr.setMinimumIntegerDigits( def.getMinimumIntegerDigits() );
if(fr.getMinimumIntegerDigits() != def.getMinimumIntegerDigits() ) {
errln("ERROR: setMinimumIntegerDigits() failed");
}
fr.setMaximumFractionDigits( def.getMaximumFractionDigits() );
if(fr.getMaximumFractionDigits() != def.getMaximumFractionDigits() ) {
errln("ERROR: setMaximumFractionDigits() failed");
}
fr.setMinimumFractionDigits( def.getMinimumFractionDigits() );
if(fr.getMinimumFractionDigits() != def.getMinimumFractionDigits() ) {
errln("ERROR: setMinimumFractionDigits() failed");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
}

View File

@ -1,179 +0,0 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestSimpleDateFormatAPI.java,v $
* $Date: 2001/10/23 13:14:20 $
* $Revision: 1.2 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestSimpleDateFormatAPI
* Source File: java/text/format/IntlTestSimpleDateFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Simple Date Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.util.*;
import com.ibm.text.*;
import java.util.Locale;
import java.util.Date;
import java.text.ParsePosition;
import java.text.Format;
import java.text.FieldPosition;
import java.text.ParseException;
public class IntlTestSimpleDateFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestSimpleDateFormatAPI().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("SimpleDateFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing SimpleDateFormat constructors");
SimpleDateFormat def = new SimpleDateFormat();
final String pattern = new String("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat pat = new SimpleDateFormat(pattern);
SimpleDateFormat pat_fr = new SimpleDateFormat(pattern, Locale.FRENCH);
DateFormatSymbols symbols = new DateFormatSymbols(Locale.FRENCH);
SimpleDateFormat cust1 = new SimpleDateFormat(pattern, symbols);
// ======= Test clone() and equality
logln("Testing clone(), assignment and equality operators");
Format clone = (Format) def.clone();
if( ! clone.equals(def) ) {
errln("ERROR: Format clone or equals failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
Date d = new Date((long)837039928046.0);
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln( "" + d.getTime() + " formatted to " + res1);
res2 = cust1.format(d, res2, pos2);
logln("" + d.getTime() + " formatted to " + res2);
// ======= Test parse()
logln("Testing parse()");
String text = new String("02/03/76 2:50 AM, CST");
Date result1 = new Date();
Date result2 = new Date();
ParsePosition pos= new ParsePosition(0);
result1 = def.parse(text, pos);
logln(text + " parsed into " + result1);
try {
result2 = def.parse(text);
}
catch (ParseException e) {
errln("ERROR: parse() failed");
}
logln(text + " parsed into " + result2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DateFormatSymbols syms = pat.getDateFormatSymbols();
def.setDateFormatSymbols(syms);
pat_fr.setDateFormatSymbols(syms);
if( ! pat.getDateFormatSymbols().equals(def.getDateFormatSymbols()) ) {
errln("ERROR: set DateFormatSymbols() failed");
}
/*
DateFormatSymbols has not the method getTwoDigitStartDate();
//Date startDate = null; //The variable is never used
try {
// startDate = pat.getTwoDigitStartDate();
}
catch (Exception e) {
errln("ERROR: getTwoDigitStartDate() failed");
}
try {
// pat_fr.setTwoDigitStartDate(startDate);
}
catch (Exception e) {
errln("ERROR: setTwoDigitStartDate() failed");
}*/
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("yyyy.MM.dd G 'at' hh:mm:ss z");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if( ! s2.equals(p1) ) {
errln("ERROR: toPattern() result did not match pattern applied");
}
logln("Applying pattern " + p1);
pat.applyLocalizedPattern(p1);
String s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if( ! s3.equals(p1) ) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof");
// try {
// DateFormat test = new SimpleDateFormat();
// if (! (test instanceof SimpleDateFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a SimpleDateFormat");
// }
}
}

View File

@ -1,187 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/NumberFormatRegressionTest.java,v $
* $Date: 2001/10/26 06:29:50 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : NumberFormatRegressionTest
* Source File: $ICU4CRoot/source/test/intltest/numrgts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.util.Date;
import java.text.ParseException;
import java.io.*;
/**
* Performs regression test for MessageFormat
**/
public class NumberFormatRegressionTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception{
new NumberFormatRegressionTest().run(args);
}
/**
* alphaWorks upgrade
*/
public void Test4161100() {
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
double a = -0.09;
String s = nf.format(a);
logln(a + " x " +
((DecimalFormat) nf).toPattern() + " = " + s);
if (!s.equals("-0.1")) {
errln("FAIL");
}
}
/**
* DateFormat should call setIntegerParseOnly(TRUE) on adopted
* NumberFormat objects.
*/
public void TestJ691() {
Locale loc = new Locale("fr", "CH");
// set up the input date string & expected output
String udt = "11.10.2000";
String exp = "11.10.00";
// create a Calendar for this locale
Calendar cal = Calendar.getInstance(loc);
// create a NumberFormat for this locale
NumberFormat nf = NumberFormat.getInstance(loc);
// *** Here's the key: We don't want to have to do THIS:
//nf.setParseIntegerOnly(true);
// create the DateFormat
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
df.setCalendar(cal);
df.setNumberFormat(nf);
// set parsing to lenient & parse
Date ulocdat = new Date();
df.setLenient(true);
try {
ulocdat = df.parse(udt);
} catch (java.text.ParseException pe) {
errln(pe.getMessage());
}
// format back to a string
String outString = df.format(ulocdat);
if (!outString.equals(exp)) {
errln("FAIL: " + udt + " => " + outString);
}
}
/**
* Test getIntegerInstance();
*/
public void Test4408066() {
NumberFormat nf1 = NumberFormat.getIntegerInstance();
NumberFormat nf2 = NumberFormat.getIntegerInstance(Locale.CHINA);
//test isParseIntegerOnly
if (!nf1.isParseIntegerOnly() || !nf2.isParseIntegerOnly()) {
errln("Failed : Integer Number Format Instance should set setParseIntegerOnly(true)");
}
//Test format
{
double[] data = {
-3.75, -2.5, -1.5,
-1.25, 0, 1.0,
1.25, 1.5, 2.5,
3.75, 10.0, 255.5
};
String[] expected = {
"-4", "-2", "-2",
"-1", "0", "1",
"1", "2", "2",
"4", "10", "256"
};
for (int i = 0; i < data.length; ++i) {
String result = nf1.format(data[i]);
if (!result.equals(expected[i])) {
errln("Failed => Source: " + Double.toString(data[i])
+ ";Formatted : " + result
+ ";but expectted: " + expected[i]);
}
}
}
//Test parse, Parsing should stop at "."
{
String data[] = {
"-3.75", "-2.5", "-1.5",
"-1.25", "0", "1.0",
"1.25", "1.5", "2.5",
"3.75", "10.0", "255.5"
};
long[] expected = {
-3, -2, -1,
-1, 0, 1,
1, 1, 2,
3, 10, 255
};
for (int i = 0; i < data.length; ++i) {
Number n = null;
try {
n = nf1.parse(data[i]);
} catch (ParseException e) {
errln("Failed: " + e.getMessage());
}
if (!(n instanceof Long) || (n instanceof Integer)) {
errln("Failed: Integer Number Format should parse string to Long/Integer");
}
if (n.longValue() != expected[i]) {
errln("Failed=> Source: " + data[i]
+ ";result : " + n.toString()
+ ";expected :" + Long.toString(expected[i]));
}
}
}
}
//Test New serialized DecimalFormat(2.0) read old serialized forms of DecimalFormat(1.3.1.1)
public void TestSerialization() throws IOException, ClassNotFoundException{
byte[][] contents = NumberFormatSerialTestData.getContent();
double data = 1234.56;
String[] expected = {
"1,234.56", "$1,234.56", "123,456%", "1.23456E3"};
for (int i = 0; i < 4; ++i) {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(contents[i]));
try {
NumberFormat format = (NumberFormat) ois.readObject();
String result = format.format(data);
if (result.equals(expected[i])) {
logln("OK: Deserialized bogus NumberFormat(new version read old version)");
} else {
errln("FAIL: the test data formats are not euqal");
}
} catch (Exception e) {
errln("FAIL: " + e.getMessage());
}
}
}
}

View File

@ -1,235 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/NumberFormatRoundTripTest.java,v $
* $Date: 2001/10/19 12:14:56 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Porting From: ICU4C v1.8.1 : format : NumberFormatRoundTripTest
* Source File: $ICU4CRoot/source/test/intltest/nmfmtrt.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
/**
* Performs round-trip tests for NumberFormat
**/
public class NumberFormatRoundTripTest extends com.ibm.test.TestFmwk {
public double MAX_ERROR = 1e-14;
public double max_numeric_error = 0.0;
public double min_numeric_error = 1.0;
public boolean verbose = false;
public boolean STRING_COMPARE = false;
public boolean EXACT_NUMERIC_COMPARE = false;
public boolean DEBUG = false;
public boolean quick = true;
public static void main(String[] args) throws Exception {
new NumberFormatRoundTripTest().run(args);
}
public void TestNumberFormatRoundTrip() {
NumberFormat fmt = null;
logln("Default Locale");
logln("Default Number format");
fmt = NumberFormat.getInstance();
_test(fmt);
logln("Currency Format");
fmt = NumberFormat.getCurrencyInstance();
_test(fmt);
logln("Percent Format");
fmt = NumberFormat.getPercentInstance();
_test(fmt);
int locCount = 0;
final Locale[] loc = NumberFormat.getAvailableLocales();
if(quick) {
if(locCount > 5)
locCount = 5;
logln("Quick mode: only _testing first 5 Locales");
}
for(int i = 0; i < locCount; ++i) {
logln(loc[i].getDisplayName());
fmt = NumberFormat.getInstance(loc[i]);
_test(fmt);
fmt = NumberFormat.getCurrencyInstance(loc[i]);
_test(fmt);
fmt = NumberFormat.getPercentInstance(loc[i]);
_test(fmt);
}
logln("Numeric error " + min_numeric_error + " to " + max_numeric_error);
}
/**
* Return a random value from -range..+range.
*/
public double randomDouble(double range) {
return Math.random() * range;
}
public void _test(NumberFormat fmt) {
_test(fmt, Double.NaN);
_test(fmt, Double.POSITIVE_INFINITY);
_test(fmt, Double.NEGATIVE_INFINITY);
_test(fmt, 500);
_test(fmt, 0);
_test(fmt, -0);
_test(fmt, 0.0);
double negZero = 0.0;
negZero /= -1.0;
_test(fmt, negZero);
_test(fmt, 9223372036854775808.0d);
_test(fmt, -9223372036854775809.0d);
//_test(fmt, 6.936065876100493E74d);
// _test(fmt, 6.212122845281909E48d);
for (int i = 0; i < 10; ++i) {
_test(fmt, randomDouble(1));
_test(fmt, randomDouble(10000));
_test(fmt, Math.floor((randomDouble(10000))));
_test(fmt, randomDouble(1e50));
_test(fmt, randomDouble(1e-50));
_test(fmt, randomDouble(1e100));
_test(fmt, randomDouble(1e75));
_test(fmt, randomDouble(1e308) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e75) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e65) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e-292));
_test(fmt, randomDouble(1e-78));
_test(fmt, randomDouble(1e-323));
_test(fmt, randomDouble(1e-100));
_test(fmt, randomDouble(1e-78));
}
}
public void _test(NumberFormat fmt, double value) {
_test(fmt, new Double(value));
}
public void _test(NumberFormat fmt, long value) {
_test(fmt, new Long(value));
}
public void _test(NumberFormat fmt, Number value) {
logln("test data = " + value);
fmt.setMaximumFractionDigits(999);
String s, s2;
if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
s = fmt.format(value.doubleValue());
else
s = fmt.format(value.longValue());
Number n = new Double(0);
boolean show = verbose;
if (DEBUG)
logln(
/*value.getString(temp) +*/ " F> " + s);
try {
n = fmt.parse(s);
} catch (java.text.ParseException e) {
System.out.println(e);
}
if (DEBUG)
logln(s + " P> " /*+ n.getString(temp)*/);
if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
s2 = fmt.format(n.doubleValue());
else
s2 = fmt.format(n.longValue());
if (DEBUG)
logln(/*n.getString(temp) +*/ " F> " + s2);
if (STRING_COMPARE) {
if (!s.equals(s2)) {
errln("*** STRING ERROR \"" + s + "\" != \"" + s2 + "\"");
show = true;
}
}
if (EXACT_NUMERIC_COMPARE) {
if (value != n) {
errln("*** NUMERIC ERROR");
show = true;
}
} else {
// Compute proportional error
double error = proportionalError(value, n);
if (error > MAX_ERROR) {
errln("*** NUMERIC ERROR " + error);
show = true;
}
if (error > max_numeric_error)
max_numeric_error = error;
if (error < min_numeric_error)
min_numeric_error = error;
}
if (show)
logln(
/*value.getString(temp) +*/ value.getClass().getName() + " F> " + s + " P> " +
/*n.getString(temp) +*/ n.getClass().getName() + " F> " + s2);
}
public double proportionalError(Number a, Number b) {
double aa,bb;
if(a.getClass().getName().equalsIgnoreCase("java.lang.Double"))
aa = a.doubleValue();
else
aa = a.longValue();
if(a.getClass().getName().equalsIgnoreCase("java.lang.Double"))
bb = b.doubleValue();
else
bb = b.longValue();
double error = aa - bb;
if(aa != 0 && bb != 0)
error /= aa;
return Math.abs(error);
}
}

View File

@ -1,282 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/NumberFormatSerialTestData.java,v $
* $Date: 2001/10/26 06:30:22 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
package com.ibm.icu.test.format;
public class NumberFormatSerialTestData {
//get Content
public static byte[][] getContent() {
return content;
}
//NumberFormat.getInstance(Locale.US)
static byte[] generalInstance = {
-84,-19, 0, 5, 115, 114, 0, 26, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46,
68, 101, 99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 11, -1, 3, 98, -40, 114, 48,
58, 2, 0, 18, 90, 0, 27, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97,
116, 111, 114, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110, 90, 0, 23, 101, 120, 112,
111, 110, 101, 110, 116, 83, 105, 103, 110, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110,
73, 0, 11, 102, 111, 114, 109, 97, 116, 87, 105, 100, 116, 104, 66, 0, 12, 103, 114, 111,
117, 112, 105, 110, 103, 83, 105, 122, 101, 66, 0, 13, 103, 114, 111, 117, 112, 105, 110, 103,
83, 105, 122, 101, 50, 66, 0, 17, 109, 105, 110, 69, 120, 112, 111, 110, 101, 110, 116, 68,
105, 103, 105, 116, 115, 73, 0, 10, 109, 117, 108, 116, 105, 112, 108, 105, 101, 114, 67, 0,
3, 112, 97, 100, 73, 0, 11, 112, 97, 100, 80, 111, 115, 105, 116, 105, 111, 110, 73, 0,
12, 114, 111, 117, 110, 100, 105, 110, 103, 77, 111, 100, 101, 73, 0, 21, 115, 101, 114, 105,
97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97, 109, 90, 0, 22,
117, 115, 101, 69, 120, 112, 111, 110, 101, 110, 116, 105, 97, 108, 78, 111, 116, 97, 116, 105,
111, 110, 76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 116,
0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59,
76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 83, 117, 102, 102, 105, 120, 113, 0, 126,
0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 113,
0, 126, 0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 83, 117, 102, 102, 105,
120, 113, 0, 126, 0, 1, 76, 0, 17, 114, 111, 117, 110, 100, 105, 110, 103, 73, 110, 99,
114, 101, 109, 101, 110, 116, 116, 0, 22, 76, 106, 97, 118, 97, 47, 109, 97, 116, 104, 47,
66, 105, 103, 68, 101, 99, 105, 109, 97, 108, 59, 76, 0, 7, 115, 121, 109, 98, 111, 108,
115, 116, 0, 35, 76, 99, 111, 109, 47, 105, 98, 109, 47, 116, 101, 120, 116, 47, 68, 101,
99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 83, 121, 109, 98, 111, 108, 115, 59, 120,
114, 0, 25, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46, 78, 117, 109, 98,
101, 114, 70, 111, 114, 109, 97, 116, -33, -10, -77, -65, 19, 125, 7, -24, 3, 0, 11, 90,
0, 12, 103, 114, 111, 117, 112, 105, 110, 103, 85, 115, 101, 100, 66, 0, 17, 109, 97, 120,
70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 66, 0, 16, 109, 97, 120,
73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73, 0, 21, 109, 97, 120, 105,
109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 73, 0, 20,
109, 97, 120, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115,
66, 0, 17, 109, 105, 110, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115,
66, 0, 16, 109, 105, 110, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73,
0, 21, 109, 105, 110, 105, 109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103,
105, 116, 115, 73, 0, 20, 109, 105, 110, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114,
68, 105, 103, 105, 116, 115, 90, 0, 16, 112, 97, 114, 115, 101, 73, 110, 116, 101, 103, 101,
114, 79, 110, 108, 121, 73, 0, 21, 115, 101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111,
110, 79, 110, 83, 116, 114, 101, 97, 109, 120, 114, 0, 16, 106, 97, 118, 97, 46, 116, 101,
120, 116, 46, 70, 111, 114, 109, 97, 116, -5, -40, -68, 18, -23, 15, 24, 67, 2, 0, 0,
120, 112, 1, 3, 127, 0, 0, 0, 3, 127, -1, -1, -1, 0, 1, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 1, 120, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,
0, 1, 0, 32, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 2, 0, 116, 0, 1,
45, 116, 0, 0, 116, 0, 0, 116, 0, 0, 112, 115, 114, 0, 33, 99, 111, 109, 46, 105,
98, 109, 46, 116, 101, 120, 116, 46, 68, 101, 99, 105, 109, 97, 108, 70, 111, 114, 109, 97,
116, 83, 121, 109, 98, 111, 108, 115, 80, 29, 23, -103, 8, 104, -109, -100, 2, 0, 18, 67,
0, 16, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97, 116, 111, 114, 67, 0,
5, 100, 105, 103, 105, 116, 67, 0, 11, 101, 120, 112, 111, 110, 101, 110, 116, 105, 97, 108,
67, 0, 17, 103, 114, 111, 117, 112, 105, 110, 103, 83, 101, 112, 97, 114, 97, 116, 111, 114,
67, 0, 9, 109, 105, 110, 117, 115, 83, 105, 103, 110, 67, 0, 17, 109, 111, 110, 101, 116,
97, 114, 121, 83, 101, 112, 97, 114, 97, 116, 111, 114, 67, 0, 9, 112, 97, 100, 69, 115,
99, 97, 112, 101, 67, 0, 16, 112, 97, 116, 116, 101, 114, 110, 83, 101, 112, 97, 114, 97,
116, 111, 114, 67, 0, 7, 112, 101, 114, 77, 105, 108, 108, 67, 0, 7, 112, 101, 114, 99,
101, 110, 116, 67, 0, 8, 112, 108, 117, 115, 83, 105, 103, 110, 73, 0, 21, 115, 101, 114,
105, 97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97, 109, 67, 0,
9, 122, 101, 114, 111, 68, 105, 103, 105, 116, 76, 0, 3, 78, 97, 78, 113, 0, 126, 0,
1, 76, 0, 14, 99, 117, 114, 114, 101, 110, 99, 121, 83, 121, 109, 98, 111, 108, 113, 0,
126, 0, 1, 76, 0, 17, 101, 120, 112, 111, 110, 101, 110, 116, 83, 101, 112, 97, 114, 97,
116, 111, 114, 113, 0, 126, 0, 1, 76, 0, 8, 105, 110, 102, 105, 110, 105, 116, 121, 113,
0, 126, 0, 1, 76, 0, 18, 105, 110, 116, 108, 67, 117, 114, 114, 101, 110, 99, 121, 83,
121, 109, 98, 111, 108, 113, 0, 126, 0, 1, 120, 112, 0, 46, 0, 35, 0, 0, 0, 44,
0, 45, 0, 46, 0, 42, 0, 59, 32, 48, 0, 37, 0, 43, 0, 0, 0, 2, 0, 48,
116, 0, 3, -17, -65, -67, 116, 0, 1, 36, 116, 0, 1, 69, 116, 0, 3, -30, -120, -98,
116, 0, 3, 85, 83, 68};
//NumberFormat.getCurrencyInstance(Locale.US);
static byte[] currencyInstance = {
-84, -19, 0, 5, 115, 114, 0, 26, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46,
68, 101, 99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 11, -1, 3, 98, -40, 114, 48,
58, 2, 0, 18, 90, 0, 27, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97,
116, 111, 114, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110, 90, 0, 23, 101, 120, 112,
111, 110, 101, 110, 116, 83, 105, 103, 110, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110,
73, 0, 11, 102, 111, 114, 109, 97, 116, 87, 105, 100, 116, 104, 66, 0, 12, 103, 114, 111,
117, 112, 105, 110, 103, 83, 105, 122, 101, 66, 0, 13, 103, 114, 111, 117, 112, 105, 110, 103,
83, 105, 122, 101, 50, 66, 0, 17, 109, 105, 110, 69, 120, 112, 111, 110, 101, 110, 116, 68,
105, 103, 105, 116, 115, 73, 0, 10, 109, 117, 108, 116, 105, 112, 108, 105, 101, 114, 67, 0,
3, 112, 97, 100, 73, 0, 11, 112, 97, 100, 80, 111, 115, 105, 116, 105, 111, 110, 73, 0,
12, 114, 111, 117, 110, 100, 105, 110, 103, 77, 111, 100, 101, 73, 0, 21, 115, 101, 114, 105,
97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97, 109, 90, 0, 22,
117, 115, 101, 69, 120, 112, 111, 110, 101, 110, 116, 105, 97, 108, 78, 111, 116, 97, 116, 105,
111, 110, 76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 116,
0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59,
76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 83, 117, 102, 102, 105, 120, 113, 0, 126,
0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 113,
0, 126, 0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 83, 117, 102, 102, 105,
120, 113, 0, 126, 0, 1, 76, 0, 17, 114, 111, 117, 110, 100, 105, 110, 103, 73, 110, 99,
114, 101, 109, 101, 110, 116, 116, 0, 22, 76, 106, 97, 118, 97, 47, 109, 97, 116, 104, 47,
66, 105, 103, 68, 101, 99, 105, 109, 97, 108, 59, 76, 0, 7, 115, 121, 109, 98, 111, 108,
115, 116, 0, 35, 76, 99, 111, 109, 47, 105, 98, 109, 47, 116, 101, 120, 116, 47, 68, 101,
99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 83, 121, 109, 98, 111, 108, 115, 59, 120,
114, 0, 25, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46, 78, 117, 109, 98,
101, 114, 70, 111, 114, 109, 97, 116, -33, -10, -77, -65, 19, 125, 7, -24, 3, 0, 11, 90,
0, 12, 103, 114, 111, 117, 112, 105, 110, 103, 85, 115, 101, 100, 66, 0, 17, 109, 97, 120,
70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 66, 0, 16, 109, 97, 120,
73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73, 0, 21, 109, 97, 120, 105,
109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 73, 0, 20,
109, 97, 120, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115,
66, 0, 17, 109, 105, 110, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115,
66, 0, 16, 109, 105, 110, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73,
0, 21, 109, 105, 110, 105, 109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103,
105, 116, 115, 73, 0, 20, 109, 105, 110, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114,
68, 105, 103, 105, 116, 115, 90, 0, 16, 112, 97, 114, 115, 101, 73, 110, 116, 101, 103, 101,
114, 79, 110, 108, 121, 73, 0, 21, 115, 101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111,
110, 79, 110, 83, 116, 114, 101, 97, 109, 120, 114, 0, 16, 106, 97, 118, 97, 46, 116, 101,
120, 116, 46, 70, 111, 114, 109, 97, 116, -5, -40, -68, 18, -23, 15, 24, 67, 2, 0, 0,
120, 112, 1, 2, 127, 0, 0, 0, 2, 127, -1, -1, -1, 2, 1, 0, 0, 0, 2, 0,
0, 0, 1, 0, 0, 0, 0, 1, 120, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,
0, 1, 0, 32, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 2, 0, 116, 0, 2,
40, 36, 116, 0, 1, 41, 116, 0, 1, 36, 116, 0, 0, 112, 115, 114, 0, 33, 99, 111,
109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46, 68, 101, 99, 105, 109, 97, 108, 70, 111,
114, 109, 97, 116, 83, 121, 109, 98, 111, 108, 115, 80, 29, 23, -103, 8, 104, -109, -100, 2,
0, 18, 67, 0, 16, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97, 116, 111,
114, 67, 0, 5, 100, 105, 103, 105, 116, 67, 0, 11, 101, 120, 112, 111, 110, 101, 110, 116,
105, 97, 108, 67, 0, 17, 103, 114, 111, 117, 112, 105, 110, 103, 83, 101, 112, 97, 114, 97,
116, 111, 114, 67, 0, 9, 109, 105, 110, 117, 115, 83, 105, 103, 110, 67, 0, 17, 109, 111,
110, 101, 116, 97, 114, 121, 83, 101, 112, 97, 114, 97, 116, 111, 114, 67, 0, 9, 112, 97,
100, 69, 115, 99, 97, 112, 101, 67, 0, 16, 112, 97, 116, 116, 101, 114, 110, 83, 101, 112,
97, 114, 97, 116, 111, 114, 67, 0, 7, 112, 101, 114, 77, 105, 108, 108, 67, 0, 7, 112,
101, 114, 99, 101, 110, 116, 67, 0, 8, 112, 108, 117, 115, 83, 105, 103, 110, 73, 0, 21,
115, 101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97,
109, 67, 0, 9, 122, 101, 114, 111, 68, 105, 103, 105, 116, 76, 0, 3, 78, 97, 78, 113,
0, 126, 0, 1, 76, 0, 14, 99, 117, 114, 114, 101, 110, 99, 121, 83, 121, 109, 98, 111,
108, 113, 0, 126, 0, 1, 76, 0, 17, 101, 120, 112, 111, 110, 101, 110, 116, 83, 101, 112,
97, 114, 97, 116, 111, 114, 113, 0, 126, 0, 1, 76, 0, 8, 105, 110, 102, 105, 110, 105,
116, 121, 113, 0, 126, 0, 1, 76, 0, 18, 105, 110, 116, 108, 67, 117, 114, 114, 101, 110,
99, 121, 83, 121, 109, 98, 111, 108, 113, 0, 126, 0, 1, 120, 112, 0, 46, 0, 35, 0,
0, 0, 44, 0, 45, 0, 46, 0, 42, 0, 59, 32, 48, 0, 37, 0, 43, 0, 0, 0,
2, 0, 48, 116, 0, 3, -17, -65, -67, 116, 0, 1, 36, 116, 0, 1, 69, 116, 0, 3,
-30, -120, -98, 116, 0, 3, 85, 83, 68};
//NumberFormat.getPercentInstance(Locale.US)
static byte[] percentInstance = {
-84, -19, 0, 5, 115, 114, 0, 26, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46,
68, 101, 99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 11, -1, 3, 98, -40, 114, 48,
58, 2, 0, 18, 90, 0, 27, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97,
116, 111, 114, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110, 90, 0, 23, 101, 120, 112,
111, 110, 101, 110, 116, 83, 105, 103, 110, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110,
73, 0, 11, 102, 111, 114, 109, 97, 116, 87, 105, 100, 116, 104, 66, 0, 12, 103, 114, 111,
117, 112, 105, 110, 103, 83, 105, 122, 101, 66, 0, 13, 103, 114, 111, 117, 112, 105, 110, 103,
83, 105, 122, 101, 50, 66, 0, 17, 109, 105, 110, 69, 120, 112, 111, 110, 101, 110, 116, 68,
105, 103, 105, 116, 115, 73, 0, 10, 109, 117, 108, 116, 105, 112, 108, 105, 101, 114, 67, 0,
3, 112, 97, 100, 73, 0, 11, 112, 97, 100, 80, 111, 115, 105, 116, 105, 111, 110, 73, 0,
12, 114, 111, 117, 110, 100, 105, 110, 103, 77, 111, 100, 101, 73, 0, 21, 115, 101, 114, 105,
97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97, 109, 90, 0, 22,
117, 115, 101, 69, 120, 112, 111, 110, 101, 110, 116, 105, 97, 108, 78, 111, 116, 97, 116, 105,
111, 110, 76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 116,
0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59,
76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 83, 117, 102, 102, 105, 120, 113, 0, 126,
0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 113,
0, 126, 0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 83, 117, 102, 102, 105,
120, 113, 0, 126, 0, 1, 76, 0, 17, 114, 111, 117, 110, 100, 105, 110, 103, 73, 110, 99,
114, 101, 109, 101, 110, 116, 116, 0, 22, 76, 106, 97, 118, 97, 47, 109, 97, 116, 104, 47,
66, 105, 103, 68, 101, 99, 105, 109, 97, 108, 59, 76, 0, 7, 115, 121, 109, 98, 111, 108,
115, 116, 0, 35, 76, 99, 111, 109, 47, 105, 98, 109, 47, 116, 101, 120, 116, 47, 68, 101,
99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 83, 121, 109, 98, 111, 108, 115, 59, 120,
114, 0, 25, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46, 78, 117, 109, 98,
101, 114, 70, 111, 114, 109, 97, 116, -33, -10, -77, -65, 19, 125, 7, -24, 3, 0, 11, 90,
0, 12, 103, 114, 111, 117, 112, 105, 110, 103, 85, 115, 101, 100, 66, 0, 17, 109, 97, 120,
70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 66, 0, 16, 109, 97, 120,
73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73, 0, 21, 109, 97, 120, 105,
109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 73, 0, 20,
109, 97, 120, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115,
66, 0, 17, 109, 105, 110, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115,
66, 0, 16, 109, 105, 110, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73,
0, 21, 109, 105, 110, 105, 109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103,
105, 116, 115, 73, 0, 20, 109, 105, 110, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114,
68, 105, 103, 105, 116, 115, 90, 0, 16, 112, 97, 114, 115, 101, 73, 110, 116, 101, 103, 101,
114, 79, 110, 108, 121, 73, 0, 21, 115, 101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111,
110, 79, 110, 83, 116, 114, 101, 97, 109, 120, 114, 0, 16, 106, 97, 118, 97, 46, 116, 101,
120, 116, 46, 70, 111, 114, 109, 97, 116, -5, -40, -68, 18, -23, 15, 24, 67, 2, 0, 0,
120, 112, 1, 0, 127, 0, 0, 0, 0, 127, -1, -1, -1, 0, 1, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 1, 120, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,
0, 100, 0, 32, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 2, 0, 116, 0, 1,
45, 116, 0, 1, 37, 116, 0, 0, 113, 0, 126, 0, 8, 112, 115, 114, 0, 33, 99, 111,
109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46, 68, 101, 99, 105, 109, 97, 108, 70, 111,
114, 109, 97, 116, 83, 121, 109, 98, 111, 108, 115, 80, 29, 23, -103, 8, 104, -109, -100, 2,
0, 18, 67, 0, 16, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97, 116, 111,
114, 67, 0, 5, 100, 105, 103, 105, 116, 67, 0, 11, 101, 120, 112, 111, 110, 101, 110, 116,
105, 97, 108, 67, 0, 17, 103, 114, 111, 117, 112, 105, 110, 103, 83, 101, 112, 97, 114, 97,
116, 111, 114, 67, 0, 9, 109, 105, 110, 117, 115, 83, 105, 103, 110, 67, 0, 17, 109, 111,
110, 101, 116, 97, 114, 121, 83, 101, 112, 97, 114, 97, 116, 111, 114, 67, 0, 9, 112, 97,
100, 69, 115, 99, 97, 112, 101, 67, 0, 16, 112, 97, 116, 116, 101, 114, 110, 83, 101, 112,
97, 114, 97, 116, 111, 114, 67, 0, 7, 112, 101, 114, 77, 105, 108, 108, 67, 0, 7, 112,
101, 114, 99, 101, 110, 116, 67, 0, 8, 112, 108, 117, 115, 83, 105, 103, 110, 73, 0, 21,
115, 101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97,
109, 67, 0, 9, 122, 101, 114, 111, 68, 105, 103, 105, 116, 76, 0, 3, 78, 97, 78, 113,
0, 126, 0, 1, 76, 0, 14, 99, 117, 114, 114, 101, 110, 99, 121, 83, 121, 109, 98, 111,
108, 113, 0, 126, 0, 1, 76, 0, 17, 101, 120, 112, 111, 110, 101, 110, 116, 83, 101, 112,
97, 114, 97, 116, 111, 114, 113, 0, 126, 0, 1, 76, 0, 8, 105, 110, 102, 105, 110, 105,
116, 121, 113, 0, 126, 0, 1, 76, 0, 18, 105, 110, 116, 108, 67, 117, 114, 114, 101, 110,
99, 121, 83, 121, 109, 98, 111, 108, 113, 0, 126, 0, 1, 120, 112, 0, 46, 0, 35, 0,
0, 0, 44, 0, 45, 0, 46, 0, 42, 0, 59, 32, 48, 0, 37, 0, 43, 0, 0, 0,
2, 0, 48, 116, 0, 3, -17, -65, -67, 116, 0, 1, 36, 116, 0, 1, 69, 116, 0, 3,
-30, -120, -98, 116, 0, 3, 85, 83, 68};
//NumberFormat.getScientificInstance(Locale.US)
static byte[] scientificInstance = {
-84, -19, 0, 5, 115, 114, 0, 26, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46,
68, 101, 99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 11, -1, 3, 98, -40, 114, 48,
58, 2, 0, 18, 90, 0, 27, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97,
116, 111, 114, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110, 90, 0, 23, 101, 120, 112,
111, 110, 101, 110, 116, 83, 105, 103, 110, 65, 108, 119, 97, 121, 115, 83, 104, 111, 119, 110,
73, 0, 11, 102, 111, 114, 109, 97, 116, 87, 105, 100, 116, 104, 66, 0, 12, 103, 114, 111,
117, 112, 105, 110, 103, 83, 105, 122, 101, 66, 0, 13, 103, 114, 111, 117, 112, 105, 110, 103,
83, 105, 122, 101, 50, 66, 0, 17, 109, 105, 110, 69, 120, 112, 111, 110, 101, 110, 116, 68,
105, 103, 105, 116, 115, 73, 0, 10, 109, 117, 108, 116, 105, 112, 108, 105, 101, 114, 67, 0,
3, 112, 97, 100, 73, 0, 11, 112, 97, 100, 80, 111, 115, 105, 116, 105, 111, 110, 73, 0,
12, 114, 111, 117, 110, 100, 105, 110, 103, 77, 111, 100, 101, 73, 0, 21, 115, 101, 114, 105,
97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97, 109, 90, 0, 22,
117, 115, 101, 69, 120, 112, 111, 110, 101, 110, 116, 105, 97, 108, 78, 111, 116, 97, 116, 105,
111, 110, 76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 116,
0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59,
76, 0, 14, 110, 101, 103, 97, 116, 105, 118, 101, 83, 117, 102, 102, 105, 120, 113, 0, 126,
0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 80, 114, 101, 102, 105, 120, 113,
0, 126, 0, 1, 76, 0, 14, 112, 111, 115, 105, 116, 105, 118, 101, 83, 117, 102, 102, 105,
120, 113, 0, 126, 0, 1, 76, 0, 17, 114, 111, 117, 110, 100, 105, 110, 103, 73, 110, 99,
114, 101, 109, 101, 110, 116, 116, 0, 22, 76, 106, 97, 118, 97, 47, 109, 97, 116, 104, 47,
66, 105, 103, 68, 101, 99, 105, 109, 97, 108, 59, 76, 0, 7, 115, 121, 109, 98, 111, 108,
115, 116, 0, 35, 76, 99, 111, 109, 47, 105, 98, 109, 47, 116, 101, 120, 116, 47, 68, 101,
99, 105, 109, 97, 108, 70, 111, 114, 109, 97, 116, 83, 121, 109, 98, 111, 108, 115, 59, 120,
114, 0, 25, 99, 111, 109, 46, 105, 98, 109, 46, 116, 101, 120, 116, 46, 78, 117, 109, 98,
101, 114, 70, 111, 114, 109, 97, 116, -33, -10, -77, -65, 19, 125, 7, -24, 3, 0, 11, 90,
0, 12, 103, 114, 111, 117, 112, 105, 110, 103, 85, 115, 101, 100, 66, 0, 17, 109, 97, 120,
70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 66, 0, 16, 109, 97, 120,
73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73, 0, 21, 109, 97, 120, 105,
109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115, 73, 0, 20,
109, 97, 120, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115,
66, 0, 17, 109, 105, 110, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103, 105, 116, 115,
66, 0, 16, 109, 105, 110, 73, 110, 116, 101, 103, 101, 114, 68, 105, 103, 105, 116, 115, 73,
0, 21, 109, 105, 110, 105, 109, 117, 109, 70, 114, 97, 99, 116, 105, 111, 110, 68, 105, 103,
105, 116, 115, 73, 0, 20, 109, 105, 110, 105, 109, 117, 109, 73, 110, 116, 101, 103, 101, 114,
68, 105, 103, 105, 116, 115, 90, 0, 16, 112, 97, 114, 115, 101, 73, 110, 116, 101, 103, 101,
114, 79, 110, 108, 121, 73, 0, 21, 115, 101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111,
110, 79, 110, 83, 116, 114, 101, 97, 109, 120, 114, 0, 16, 106, 97, 118, 97, 46, 116, 101,
120, 116, 46, 70, 111, 114, 109, 97, 116, -5, -40, -68, 18, -23, 15, 24, 67, 2, 0, 0,
120, 112, 0, 6, 1, 0, 0, 0, 6, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 1, 120, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 1, 0, 32, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 2, 1, 116, 0, 1,
45, 116, 0, 0, 116, 0, 0, 113, 0, 126, 0, 8, 112, 115, 114, 0, 33, 99, 111, 109,
46, 105, 98, 109, 46, 116, 101, 120, 116, 46, 68, 101, 99, 105, 109, 97, 108, 70, 111, 114,
109, 97, 116, 83, 121, 109, 98, 111, 108, 115, 80, 29, 23, -103, 8, 104, -109, -100, 2, 0,
18, 67, 0, 16, 100, 101, 99, 105, 109, 97, 108, 83, 101, 112, 97, 114, 97, 116, 111, 114,
67, 0, 5, 100, 105, 103, 105, 116, 67, 0, 11, 101, 120, 112, 111, 110, 101, 110, 116, 105,
97, 108, 67, 0, 17, 103, 114, 111, 117, 112, 105, 110, 103, 83, 101, 112, 97, 114, 97, 116,
111, 114, 67, 0, 9, 109, 105, 110, 117, 115, 83, 105, 103, 110, 67, 0, 17, 109, 111, 110,
101, 116, 97, 114, 121, 83, 101, 112, 97, 114, 97, 116, 111, 114, 67, 0, 9, 112, 97, 100,
69, 115, 99, 97, 112, 101, 67, 0, 16, 112, 97, 116, 116, 101, 114, 110, 83, 101, 112, 97,
114, 97, 116, 111, 114, 67, 0, 7, 112, 101, 114, 77, 105, 108, 108, 67, 0, 7, 112, 101,
114, 99, 101, 110, 116, 67, 0, 8, 112, 108, 117, 115, 83, 105, 103, 110, 73, 0, 21, 115,
101, 114, 105, 97, 108, 86, 101, 114, 115, 105, 111, 110, 79, 110, 83, 116, 114, 101, 97, 109,
67, 0, 9, 122, 101, 114, 111, 68, 105, 103, 105, 116, 76, 0, 3, 78, 97, 78, 113, 0,
126, 0, 1, 76, 0, 14, 99, 117, 114, 114, 101, 110, 99, 121, 83, 121, 109, 98, 111, 108,
113, 0, 126, 0, 1, 76, 0, 17, 101, 120, 112, 111, 110, 101, 110, 116, 83, 101, 112, 97,
114, 97, 116, 111, 114, 113, 0, 126, 0, 1, 76, 0, 8, 105, 110, 102, 105, 110, 105, 116,
121, 113, 0, 126, 0, 1, 76, 0, 18, 105, 110, 116, 108, 67, 117, 114, 114, 101, 110, 99,
121, 83, 121, 109, 98, 111, 108, 113, 0, 126, 0, 1, 120, 112, 0, 46, 0, 35, 0, 0,
0, 44, 0, 45, 0, 46, 0, 42, 0, 59, 32, 48, 0, 37, 0, 43, 0, 0, 0, 2,
0, 48, 116, 0, 3, -17, -65, -67, 116, 0, 1, 36, 116, 0, 1, 69, 116, 0, 3, -30,
-120, -98, 116, 0, 3, 85, 83, 68};
//content
final static byte[][] content = {generalInstance, currencyInstance, percentInstance, scientificInstance};
}

View File

@ -1,695 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/NumberFormatTest.java,v $
* $Date: 2001/10/23 13:14:40 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : NumberFormatTest
* Source File: $ICU4CRoot/source/test/intltest/numfmtst.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.ParseException;
import java.text.FieldPosition;
public class NumberFormatTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new NumberFormatTest().run(args);
}
// Test various patterns
public void TestPatterns() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
final String pat[] = { "#.#", "#.", ".#", "#" };
int pat_length = pat.length;
final String newpat[] = { "#0.#", "#0.", "#.0", "#" };
final String num[] = { "0", "0.", ".0", "0" };
for (int i=0; i<pat_length; ++i)
{
DecimalFormat fmt = new DecimalFormat(pat[i], sym);
String newp = fmt.toPattern();
if (!newp.equals(newpat[i]))
errln("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] +
"; " + newp + " seen instead");
String s = ((NumberFormat)fmt).format(0);
if (!s.equals(num[i]))
{
errln("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] +
"; " + s + " seen instead");
logln("Min integer digits = " + fmt.getMinimumIntegerDigits());
}
}
}
// Test exponential pattern
public void TestExponential() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
final String pat[] = { "0.####E0", "00.000E00", "##0.######E000", "0.###E0;[0.###E0]" };
int pat_length = pat.length;
double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 };
int val_length = val.length;
final String valFormat[] = {
// 0.####E0
"1.234E-2", "1.2346E8", "1.23E300", "-3.1416E-271",
// 00.000E00
"12.340E-03", "12.346E07", "12.300E299", "-31.416E-272",
// ##0.######E000
"12.34E-003", "123.4568E006", "1.23E300", "-314.1593E-273",
// 0.###E0;[0.###E0]
"1.234E-2", "1.235E8", "1.23E300", "[3.142E-271]" };
/*double valParse[] =
{
0.01234, 123460000, 1.23E300, -3.1416E-271,
0.01234, 123460000, 1.23E300, -3.1416E-271,
0.01234, 123456800, 1.23E300, -3.141593E-271,
0.01234, 123500000, 1.23E300, -3.142E-271,
};*/ //The variable is never used
int lval[] = { 0, -1, 1, 123456789 };
int lval_length = lval.length;
final String lvalFormat[] = {
// 0.####E0
"0E0", "-1E0", "1E0", "1.2346E8",
// 00.000E00
"00.000E00", "-10.000E-01", "10.000E-01", "12.346E07",
// ##0.######E000
"0E000", "-1E000", "1E000", "123.4568E006",
// 0.###E0;[0.###E0]
"0E0", "[1E0]", "1E0", "1.235E8" };
int lvalParse[] =
{
0, -1, 1, 123460000,
0, -1, 1, 123460000,
0, -1, 1, 123456800,
0, -1, 1, 123500000,
};
int ival = 0, ilval = 0;
for (int p = 0; p < pat_length; ++p) {
DecimalFormat fmt = new DecimalFormat(pat[p], sym);
logln("Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern() + "\"");
int v;
for (v = 0; v < val_length; ++v) {
String s;
s = ((NumberFormat) fmt).format(val[v]);
logln(" " + val[v] + " -format-> " + s);
if (!s.equals(valFormat[v + ival]))
errln("FAIL: Expected " + valFormat[v + ival]);
ParsePosition pos = new ParsePosition(0);
double a = fmt.parse(s, pos).doubleValue();
if (pos.getIndex() == s.length()) {
logln(" -parse-> " + Double.toString(a));
// Use epsilon comparison as necessary
} else
errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a);
}
for (v = 0; v < lval_length; ++v) {
String s;
s = ((NumberFormat) fmt).format(lval[v]);
logln(" " + lval[v] + "L -format-> " + s);
if (!s.equals(lvalFormat[v + ilval]))
errln("ERROR: Expected " + lvalFormat[v + ilval] + " Got: " + s);
ParsePosition pos = new ParsePosition(0);
long a = 0;
Number A = fmt.parse(s, pos);
if (A != null) {
a = A.longValue();
if (pos.getIndex() == s.length()) {
logln(" -parse-> " + a);
if (a != lvalParse[v + ilval])
errln("FAIL: Expected " + lvalParse[v + ilval]);
} else
errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + Long.toString(a));
} else {
errln("Fail to parse the string: " + s);
}
}
ival += val_length;
ilval += lval_length;
}
}
// Test the handling of quotes
public void TestQuotes() {
StringBuffer pat;
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
pat = new StringBuffer("a'fo''o'b#");
DecimalFormat fmt = new DecimalFormat(pat.toString(), sym);
String s = ((NumberFormat)fmt).format(123);
logln("Pattern \"" + pat + "\"");
logln(" Format 123 . " + s);
if (!s.equals("afo'ob123"))
errln("FAIL: Expected afo'ob123");
s ="";
pat = new StringBuffer("a''b#");
fmt = new DecimalFormat(pat.toString(), sym);
s = ((NumberFormat)fmt).format(123);
logln("Pattern \"" + pat + "\"");
logln(" Format 123 . " + s);
if (!s.equals("a'b123"))
errln("FAIL: Expected a'b123");
}
/**
* Test the handling of the currency symbol in patterns.
**/
public void TestCurrencySign() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
StringBuffer pat = new StringBuffer("");
char currency = 0x00A4;
// "\xA4#,##0.00;-\xA4#,##0.00"
pat.append(currency).append("#,##0.00;-").append(currency).append("#,##0.00");
DecimalFormat fmt = new DecimalFormat(pat.toString(), sym);
String s = ((NumberFormat) fmt).format(1234.56);
pat = new StringBuffer("");
logln("Pattern \"" + fmt.toPattern() + "\"");
logln(" Format " + 1234.56 + " . " + s);
if (!s.equals("$1,234.56"))
errln("FAIL: Expected $1,234.56");
s = "";
s = ((NumberFormat) fmt).format(-1234.56);
logln(" Format " + Double.toString(-1234.56) + " . " + s);
if (!s.equals("-$1,234.56"))
errln("FAIL: Expected -$1,234.56");
pat = new StringBuffer("");
// "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00"
pat.append(currency).append(currency).append(" #,##0.00;").append(currency).append(currency).append(" -#,##0.00");
fmt = new DecimalFormat(pat.toString(), sym);
s = "";
s = ((NumberFormat) fmt).format(1234.56);
logln("Pattern \"" + fmt.toPattern() + "\"");
logln(" Format " + Double.toString(1234.56) + " . " + s);
if (!s.equals("USD 1,234.56"))
errln("FAIL: Expected USD 1,234.56");
s = "";
s = ((NumberFormat) fmt).format(-1234.56);
logln(" Format " + Double.toString(-1234.56) + " . " + s);
if (!s.equals("USD -1,234.56"))
errln("FAIL: Expected USD -1,234.56");
}
/**
* Test localized currency patterns.
*/
public void TestCurrency() {
NumberFormat currencyFmt =
NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
String s;
s = currencyFmt.format(1.50);
logln("Un pauvre ici a..........." + s);
if (!s.equals("1,50 $"))
errln("FAIL: Expected 1,50 $");
s = "";
currencyFmt = NumberFormat.getCurrencyInstance(Locale.GERMANY);
s = currencyFmt.format(1.50);
logln("Un pauvre en Allemagne a.." + s);
if (!s.equals("1,50 DM"))
errln("FAIL: Expected 1,50 DM");
s = "";
currencyFmt = NumberFormat.getCurrencyInstance(Locale.FRANCE);
s = currencyFmt.format(1.50);
logln("Un pauvre en France a....." + s);
if (!s.equals("1,50 F"))
errln("FAIL: Expected 1,50 F");
}
/**
* Do rudimentary testing of parsing.
*/
public void TestParse() {
String arg = "0.0";
DecimalFormat format = new DecimalFormat("00");
double aNumber = 0l;
try {
aNumber = format.parse(arg).doubleValue();
} catch (java.text.ParseException e) {
System.out.println(e);
}
logln("parse(" + arg + ") = " + aNumber);
}
/**
* Test proper rounding by the format method.
*/
public void TestRounding487() {
NumberFormat nf = NumberFormat.getInstance();
roundingTest(nf, 0.00159999, 4, "0.0016");
roundingTest(nf, 0.00995, 4, "0.01");
roundingTest(nf, 12.3995, 3, "12.4");
roundingTest(nf, 12.4999, 0, "12");
roundingTest(nf, - 19.5, 0, "-20");
}
/**
* Test the functioning of the secondary grouping value.
*/
public void TestSecondaryGrouping() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat f = new DecimalFormat("#,##,###", US);
expect(f, 123456789L, "12,34,56,789");
expectPat(f, "#,##,###");
f.applyPattern("#,###");
f.setSecondaryGroupingSize(4);
expect(f, 123456789L, "12,3456,789");
expectPat(f, "#,####,###");
NumberFormat g = NumberFormat.getInstance(new Locale("hi", "IN"));
String out = "";
long l = 1876543210L;
out = g.format(l);
// expect "1,87,65,43,210", but with Hindi digits
// 01234567890123
boolean ok = true;
if (out.length() != 14) {
ok = false;
} else {
for (int i = 0; i < out.length(); ++i) {
boolean expectGroup = false;
switch (i) {
case 1 :
case 4 :
case 7 :
case 10 :
expectGroup = true;
break;
}
// Later -- fix this to get the actual grouping
// character from the resource bundle.
boolean isGroup = (out.charAt(i) == 0x002C);
if (isGroup != expectGroup) {
ok = false;
break;
}
}
}
if (!ok) {
errln("FAIL Expected "+ l + " x hi_IN . \"1,87,65,43,210\" (with Hindi digits), got \""
+ out + "\"");
} else {
logln("Ok " + l + " x hi_IN . \"" + out + "\"");
}
}
public void roundingTest(NumberFormat nf, double x, int maxFractionDigits, final String expected) {
nf.setMaximumFractionDigits(maxFractionDigits);
String out = nf.format(x);
logln(x + " formats with " + maxFractionDigits + " fractional digits to " + out);
if (!out.equals(expected))
errln("FAIL: Expected " + expected);
}
/**
* Upgrade to alphaWorks
*/
public void expect(NumberFormat fmt, String str, int n) {
Long num = new Long(0);
try {
num = (Long)fmt.parse(str);
} catch (java.text.ParseException e) {
logln(e.getMessage());
}
String pat = ((DecimalFormat)fmt).toPattern();
if (num.longValue() == n) {
logln("Ok \"" + str + "\" x " +
pat + " = " +
num.toString());
} else {
errln("FAIL \"" + str + "\" x " +
pat + " = " +
num.toString() + ", expected " + n + "L");
}
}
/**
* Upgrade to alphaWorks
*/
public void expect(NumberFormat fmt, final double n, final String exp) {
StringBuffer saw = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
saw = fmt.format(n, saw, pos);
String pat = ((DecimalFormat)fmt).toPattern();
if (saw.toString().equals(exp)) {
logln("Ok " + Double.toString(n) + " x " +
pat + " = \"" +
saw + "\"");
} else {
errln("FAIL " + Double.toString(n) + " x " +
pat + " = \"" +
saw + "\", expected \"" + exp + "\"");
}
}
/**
* Upgrade to alphaWorks
*/
public void TestExponent() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt1 = new DecimalFormat("0.###E0", US);
DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US);
int n = 1234;
expect(fmt1, n, "1.234E3");
expect(fmt2, n, "1.234E+3");
expect(fmt1, "1.234E3", n);
expect(fmt1, "1.234E+3", n); // Either format should parse "E+3"
expect(fmt2, "1.234E+3", n);
}
/**
* Upgrade to alphaWorks
*/
public void TestScientific() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
// Test pattern round-trip
final String PAT[] = { "#E0", "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" };
int PAT_length = PAT.length;
int DIGITS[] = {
// min int, max int, min frac, max frac
0, 1, 0, 0, // "#E0"
1, 1, 0, 4, // "0.####E0"
2, 2, 3, 3, // "00.000E00"
1, 3, 0, 4, // "##0.####E000"
1, 1, 0, 3, // "0.###E0;[0.###E0]"
};
for (int i = 0; i < PAT_length; ++i) {
String pat = PAT[i];
DecimalFormat df = new DecimalFormat(pat, US);
String pat2 = df.toPattern();
if (pat.equals(pat2)) {
logln("Ok Pattern rt \"" + pat + "\" . \"" + pat2 + "\"");
} else {
errln("FAIL Pattern rt \"" + pat + "\" . \"" + pat2 + "\"");
}
// Make sure digit counts match what we expect
if (df.getMinimumIntegerDigits() != DIGITS[4 * i]
|| df.getMaximumIntegerDigits() != DIGITS[4 * i + 1]
|| df.getMinimumFractionDigits() != DIGITS[4 * i + 2]
|| df.getMaximumFractionDigits() != DIGITS[4 * i + 3]) {
errln("FAIL \""+ pat+ "\" min/max int; min/max frac = "
+ df.getMinimumIntegerDigits() + "/"
+ df.getMaximumIntegerDigits() + ";"
+ df.getMinimumFractionDigits() + "/"
+ df.getMaximumFractionDigits() + ", expect "
+ DIGITS[4 * i] + "/"
+ DIGITS[4 * i + 1] + ";"
+ DIGITS[4 * i + 2] + "/"
+ DIGITS[4 * i + 3]);
}
}
expect(new DecimalFormat("#E0", US), 12345.0, "1.2345E4");
expect(new DecimalFormat("0E0", US), 12345.0, "1E4");
// pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0"
// so result = 1.234568E4 not 1.2345678901E4
//when the pattern problem is finalized, delete comment mark'//'
//of the following code
expect(NumberFormat.getScientificInstance(Locale.US), 12345.678901, "1.2345678901E4");
expect(new DecimalFormat("##0.###E0", US), 12345.0, "12.34E3");
expect(new DecimalFormat("##0.###E0", US), 12345.00001, "12.35E3");
expect(new DecimalFormat("##0.####E0", US), 12345, "12.345E3");
// pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0"
// so result = 1.234568E4 not 1.2345678901E4
expect(NumberFormat.getScientificInstance(Locale.FRANCE), 12345.678901, "1,2345678901E4");
expect(new DecimalFormat("##0.####E0", US), 789.12345e-9, "789.12E-9");
expect(new DecimalFormat("##0.####E0", US), 780.e-9, "780E-9");
expect(new DecimalFormat(".###E0", US), 45678.0, ".457E5");
expect(new DecimalFormat(".###E0", US), 0, ".0E0");
/*
expect(new DecimalFormat[] { new DecimalFormat("#E0", US),
new DecimalFormat("##E0", US),
new DecimalFormat("####E0", US),
new DecimalFormat("0E0", US),
new DecimalFormat("00E0", US),
new DecimalFormat("000E0", US),
},
new Long(45678000),
new String[] { "4.5678E7",
"45.678E6",
"4567.8E4",
"5E7",
"46E6",
"457E5",
}
);
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("#E0", US), 45678000, "4.5678E7");
expect(new DecimalFormat("##E0", US), 45678000, "45.678E6");
expect(new DecimalFormat("####E0", US), 45678000, "4567.8E4");
expect(new DecimalFormat("0E0", US), 45678000, "5E7");
expect(new DecimalFormat("00E0", US), 45678000, "46E6");
expect(new DecimalFormat("000E0", US), 45678000, "457E5");
/*
expect(new DecimalFormat("###E0", US, status),
new Object[] { new Double(0.0000123), "12.3E-6",
new Double(0.000123), "123E-6",
new Double(0.00123), "1.23E-3",
new Double(0.0123), "12.3E-3",
new Double(0.123), "123E-3",
new Double(1.23), "1.23E0",
new Double(12.3), "12.3E0",
new Double(123), "123E0",
new Double(1230), "1.23E3",
});
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("###E0", US), 0.0000123, "12.3E-6");
expect(new DecimalFormat("###E0", US), 0.000123, "123E-6");
expect(new DecimalFormat("###E0", US), 0.00123, "1.23E-3");
expect(new DecimalFormat("###E0", US), 0.0123, "12.3E-3");
expect(new DecimalFormat("###E0", US), 0.123, "123E-3");
expect(new DecimalFormat("###E0", US), 1.23, "1.23E0");
expect(new DecimalFormat("###E0", US), 12.3, "12.3E0");
expect(new DecimalFormat("###E0", US), 123.0, "123E0");
expect(new DecimalFormat("###E0", US), 1230.0, "1.23E3");
/*
expect(new DecimalFormat("0.#E+00", US, status),
new Object[] { new Double(0.00012), "1.2E-04",
new Long(12000), "1.2E+04",
});
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("0.#E+00", US), 0.00012, "1.2E-04");
expect(new DecimalFormat("0.#E+00", US), 12000, "1.2E+04");
}
/**
* Upgrade to alphaWorks
*/
public void TestPad() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
expect(new DecimalFormat("*^##.##", US), 0, "^^^^0");
expect(new DecimalFormat("*^##.##", US), -1.3, "^-1.3");
expect(
new DecimalFormat("##0.0####E0*_ g-m/s^2", US),
0,
"0.0E0______ g-m/s^2");
expect(
new DecimalFormat("##0.0####E0*_ g-m/s^2", US),
1.0 / 3,
"333.333E-3_ g-m/s^2");
expect(new DecimalFormat("##0.0####*_ g-m/s^2", US), 0, "0.0______ g-m/s^2");
expect(
new DecimalFormat("##0.0####*_ g-m/s^2", US),
1.0 / 3,
"0.33333__ g-m/s^2");
// Test padding before a sign
final String formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)";
expect(new DecimalFormat(formatStr, US), -10, "xxxxxxxxxx(10.0)");
expect(new DecimalFormat(formatStr, US), -1000, "xxxxxxx(1,000.0)");
expect(new DecimalFormat(formatStr, US), -1000000, "xxx(1,000,000.0)");
expect(new DecimalFormat(formatStr, US), -100.37, "xxxxxxxx(100.37)");
expect(new DecimalFormat(formatStr, US), -10456.37, "xxxxx(10,456.37)");
expect(new DecimalFormat(formatStr, US), -1120456.37, "xx(1,120,456.37)");
expect(new DecimalFormat(formatStr, US), -112045600.37, "(112,045,600.37)");
expect(new DecimalFormat(formatStr, US), -1252045600.37, "(1,252,045,600.37)");
expect(new DecimalFormat(formatStr, US), 10, "xxxxxxxxxxxx10.0");
expect(new DecimalFormat(formatStr, US), 1000, "xxxxxxxxx1,000.0");
expect(new DecimalFormat(formatStr, US), 1000000, "xxxxx1,000,000.0");
expect(new DecimalFormat(formatStr, US), 100.37, "xxxxxxxxxx100.37");
expect(new DecimalFormat(formatStr, US), 10456.37, "xxxxxxx10,456.37");
expect(new DecimalFormat(formatStr, US), 1120456.37, "xxxx1,120,456.37");
expect(new DecimalFormat(formatStr, US), 112045600.37, "xx112,045,600.37");
expect(new DecimalFormat(formatStr, US), 10252045600.37, "10,252,045,600.37");
// Test padding between a sign and a number
final String formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)";
expect(new DecimalFormat(formatStr2, US), -10, "(10.0xxxxxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -1000, "(1,000.0xxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -1000000, "(1,000,000.0xxx)");
expect(new DecimalFormat(formatStr2, US), -100.37, "(100.37xxxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -10456.37, "(10,456.37xxxxx)");
expect(new DecimalFormat(formatStr2, US), -1120456.37, "(1,120,456.37xx)");
expect(new DecimalFormat(formatStr2, US), -112045600.37, "(112,045,600.37)");
expect(new DecimalFormat(formatStr2, US), -1252045600.37, "(1,252,045,600.37)");
expect(new DecimalFormat(formatStr2, US), 10, "10.0xxxxxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1000, "1,000.0xxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1000000, "1,000,000.0xxxxx");
expect(new DecimalFormat(formatStr2, US), 100.37, "100.37xxxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 10456.37, "10,456.37xxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1120456.37, "1,120,456.37xxxx");
expect(new DecimalFormat(formatStr2, US), 112045600.37, "112,045,600.37xx");
expect(new DecimalFormat(formatStr2, US), 10252045600.37, "10,252,045,600.37");
//testing the setPadCharacter(UnicodeString) and getPadCharacterString()
DecimalFormat fmt = new DecimalFormat("#", US);
char padString = 'P';
fmt.setPadCharacter(padString);
expectPad(fmt, "*P##.##", DecimalFormat.PAD_BEFORE_PREFIX, 5, padString);
fmt.setPadCharacter('^');
expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, '^');
//commented untill implementation is complete
/* fmt.setPadCharacter((UnicodeString)"^^^");
expectPad(fmt, "*^^^#", DecimalFormat.kPadBeforePrefix, 3, (UnicodeString)"^^^");
padString.remove();
padString.append((UChar)0x0061);
padString.append((UChar)0x0302);
fmt.setPadCharacter(padString);
UChar patternChars[]={0x002a, 0x0061, 0x0302, 0x0061, 0x0302, 0x0023, 0x0000};
UnicodeString pattern(patternChars);
expectPad(fmt, pattern , DecimalFormat.kPadBeforePrefix, 4, padString);
*/
}
/**
* Upgrade to alphaWorks
*/
public void TestPatterns2() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt = new DecimalFormat("#", US);
char hat = 0x005E; /*^*/
expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, hat);
expectPad(fmt, "$*^#", DecimalFormat.PAD_AFTER_PREFIX, 2, hat);
expectPad(fmt, "#*^", DecimalFormat.PAD_BEFORE_SUFFIX, 1, hat);
expectPad(fmt, "#$*^", DecimalFormat.PAD_AFTER_SUFFIX, 2, hat);
expectPad(fmt, "$*^$#", -1);
expectPad(fmt, "#$*^$", -1);
expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat.PAD_BEFORE_SUFFIX, 12, (char) 0x0078 /*x*/);
expectPad(fmt, "''#0*x", DecimalFormat.PAD_BEFORE_SUFFIX, 3, (char) 0x0078 /*x*/);
expectPad(fmt, "'I''ll'*a###.##", DecimalFormat.PAD_AFTER_PREFIX, 10, (char) 0x0061 /*a*/);
fmt.applyPattern("AA#,##0.00ZZ");
fmt.setPadCharacter(hat);
fmt.setFormatWidth(10);
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_PREFIX);
expectPat(fmt, "*^AA#,##0.00ZZ");
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_SUFFIX);
expectPat(fmt, "AA#,##0.00*^ZZ");
fmt.setPadPosition(DecimalFormat.PAD_AFTER_SUFFIX);
expectPat(fmt, "AA#,##0.00ZZ*^");
// 12 3456789012
String exp = "AA*^#,##0.00ZZ";
fmt.setFormatWidth(12);
fmt.setPadPosition(DecimalFormat.PAD_AFTER_PREFIX);
expectPat(fmt, exp);
fmt.setFormatWidth(13);
// 12 34567890123
expectPat(fmt, "AA*^##,##0.00ZZ");
fmt.setFormatWidth(14);
// 12 345678901234
expectPat(fmt, "AA*^###,##0.00ZZ");
fmt.setFormatWidth(15);
// 12 3456789012345
expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case
fmt.setFormatWidth(16);
// 12 34567890123456
expectPat(fmt, "AA*^#,###,##0.00ZZ");
}
public void expectPad(DecimalFormat fmt, String pat, int pos) {
expectPad(fmt, pat, pos, 0, (char)0);
}
public void expectPad(DecimalFormat fmt, final String pat, int pos, int width, final char pad) {
int apos = 0, awidth = 0;
char apadStr;
try {
fmt.applyPattern(pat);
apos = fmt.getPadPosition();
awidth = fmt.getFormatWidth();
apadStr = fmt.getPadCharacter();
} catch (Exception e) {
apos = -1;
awidth = width;
apadStr = pad;
}
if (apos == pos && awidth == width && apadStr == pad) {
logln("Ok \"" + pat + "\" pos="
+ apos + ((pos == -1) ? "" : " width=" + awidth + " pad=" + apadStr));
} else {
errln("FAIL \"" + pat + "\" pos=" + apos + " width="
+ awidth + " pad=" + apadStr + ", expected "
+ pos + " " + width + " " + pad);
}
}
public void expectPat(DecimalFormat fmt, final String exp) {
String pat = fmt.toPattern();
if (pat.equals(exp)) {
logln("Ok \"" + pat + "\"");
} else {
errln("FAIL \"" + pat + "\", expected \"" + exp + "\"");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,415 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*/
package com.ibm.icu.test.text;
import com.ibm.test.TestFmwk;
import com.ibm.text.ArabicShaping;
import com.ibm.text.ArabicShapingException;
/**
* Regression test for Arabic shaping.
*/
public class ArabicShapingRegTest extends TestFmwk {
/* constants copied from ArabicShaping for convenience */
public static final int LENGTH_GROW_SHRINK = 0;
public static final int LENGTH_FIXED_SPACES_NEAR = 1;
public static final int LENGTH_FIXED_SPACES_AT_END = 2;
public static final int LENGTH_FIXED_SPACES_AT_BEGINNING = 3;
public static final int TEXT_DIRECTION_LOGICAL = 0;
public static final int TEXT_DIRECTION_VISUAL_LTR = 4;
public static final int LETTERS_NOOP = 0;
public static final int LETTERS_SHAPE = 8;
public static final int LETTERS_SHAPE_TASHKEEL_ISOLATED = 0x18;
public static final int LETTERS_UNSHAPE = 0x10;
public static final int DIGITS_NOOP = 0;
public static final int DIGITS_EN2AN = 0x20;
public static final int DIGITS_AN2EN = 0x40;
public static final int DIGITS_EN2AN_INIT_LR = 0x60;
public static final int DIGITS_EN2AN_INIT_AL = 0x80;
private static final int DIGITS_RESERVED = 0xa0;
public static final int DIGIT_TYPE_AN = 0;
public static final int DIGIT_TYPE_AN_EXTENDED = 0x100;
public static class TestData {
public int type;
public String source;
public int flags;
public String result;
public int length;
public Class error;
public static final int STANDARD = 0;
public static final int PREFLIGHT = 1;
public static final int ERROR = 2;
public static TestData standard(String source, int flags, String result) {
return new TestData(STANDARD, source, flags, result, 0, null);
}
public static TestData preflight(String source, int flags, int length) {
return new TestData(PREFLIGHT, source, flags, null, length, null);
}
public static TestData error(String source, int flags, Class error) {
return new TestData(ERROR, source, flags, null, 0, error);
}
private TestData(int type, String source, int flags, String result, int length, Class error) {
this.type = type;
this.source = source;
this.flags = flags;
this.result = result;
this.length = length;
this.error = error;
}
private static final String[] typenames = { "standard", "preflight", "error" };
public String toString() {
StringBuffer buf = new StringBuffer(super.toString());
buf.append("[\n");
buf.append(typenames[type]);
buf.append(",\n");
if (source == null) {
buf.append("null");
} else {
buf.append('"');
buf.append(escapedString(source));
buf.append('"');
}
buf.append(",\n");
buf.append(Integer.toHexString(flags));
buf.append(",\n");
if (result == null) {
buf.append("null");
} else {
buf.append('"');
buf.append(escapedString(result));
buf.append('"');
}
buf.append(",\n");
buf.append(length);
buf.append(",\n");
buf.append(error);
buf.append(']');
return buf.toString();
}
}
private static final String lamAlefSpecialVLTR =
"\u0020\u0646\u0622\u0644\u0627\u0020" +
"\u0646\u0623\u064E\u0644\u0627\u0020" +
"\u0646\u0627\u0670\u0644\u0627\u0020" +
"\u0646\u0622\u0653\u0644\u0627\u0020" +
"\u0646\u0625\u0655\u0644\u0627\u0020" +
"\u0646\u0622\u0654\u0644\u0627\u0020" +
"\uFEFC\u0639";
private static final String tashkeelSpecialVLTR =
"\u064A\u0628\u0631\u0639\u0020" +
"\u064A\u0628\u0651\u0631\u064E\u0639\u0020" +
"\u064C\u064A\u0628\u0631\u064F\u0639\u0020" +
"\u0628\u0670\u0631\u0670\u0639\u0020" +
"\u0628\u0653\u0631\u0653\u0639\u0020" +
"\u0628\u0654\u0631\u0654\u0639\u0020" +
"\u0628\u0655\u0631\u0655\u0639\u0020";
private static final String logicalUnshape =
"\u0020\u0020\u0020\uFE8D\uFEF5\u0020\uFEE5\u0020\uFE8D\uFEF7\u0020" +
"\uFED7\uFEFC\u0020\uFEE1\u0020\uFE8D\uFEDF\uFECC\uFEAE\uFE91\uFEF4" +
"\uFE94\u0020\uFE8D\uFEDF\uFEA4\uFEAE\uFE93\u0020\u0020\u0020\u0020";
private static final String numSource =
"\u0031" + /* en:1 */
"\u0627" + /* arabic:alef */
"\u0032" + /* en:2 */
"\u06f3" + /* an:3 */
"\u0061" + /* latin:a */
"\u0034"; /* en:4 */
private static final TestData[] tests = {
/* lam alef special visual ltr */
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_NEAR,
"\u0020\ufee5\u0020\ufef5\ufe8d\u0020" +
"\ufee5\u0020\ufe76\ufef7\ufe8d\u0020" +
"\ufee5\u0020\u0670\ufefb\ufe8d\u0020" +
"\ufee5\u0020\u0653\ufef5\ufe8d\u0020" +
"\ufee5\u0020\u0655\ufef9\ufe8d\u0020" +
"\ufee5\u0020\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb"),
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_AT_END,
"\u0020\ufee5\ufef5\ufe8d\u0020\ufee5" +
"\ufe76\ufef7\ufe8d\u0020\ufee5\u0670" +
"\ufefb\ufe8d\u0020\ufee5\u0653\ufef5" +
"\ufe8d\u0020\ufee5\u0655\ufef9\ufe8d" +
"\u0020\ufee5\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb\u0020\u0020\u0020\u0020" +
"\u0020\u0020"),
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_AT_BEGINNING,
"\u0020\u0020\u0020\u0020\u0020\u0020" +
"\u0020\ufee5\ufef5\ufe8d\u0020\ufee5" +
"\ufe76\ufef7\ufe8d\u0020\ufee5\u0670" +
"\ufefb\ufe8d\u0020\ufee5\u0653\ufef5" +
"\ufe8d\u0020\ufee5\u0655\ufef9\ufe8d" +
"\u0020\ufee5\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb"),
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE | TEXT_DIRECTION_VISUAL_LTR | LENGTH_GROW_SHRINK,
"\u0020\ufee5\ufef5\ufe8d\u0020\ufee5" +
"\ufe76\ufef7\ufe8d\u0020\ufee5\u0670" +
"\ufefb\ufe8d\u0020\ufee5\u0653\ufef5" +
"\ufe8d\u0020\ufee5\u0655\ufef9\ufe8d" +
"\u0020\ufee5\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb"),
/* TASHKEEL */
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE_TASHKEEL_ISOLATED | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_NEAR,
"\u0020\ufee5\u0020\ufef5\ufe8d\u0020" +
"\ufee5\u0020\ufe76\ufef7\ufe8d\u0020" +
"\ufee5\u0020\u0670\ufefb\ufe8d\u0020" +
"\ufee5\u0020\u0653\ufef5\ufe8d\u0020" +
"\ufee5\u0020\u0655\ufef9\ufe8d\u0020" +
"\ufee5\u0020\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb"),
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE_TASHKEEL_ISOLATED | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_AT_END,
"\u0020\ufee5\ufef5\ufe8d\u0020\ufee5" +
"\ufe76\ufef7\ufe8d\u0020\ufee5\u0670" +
"\ufefb\ufe8d\u0020\ufee5\u0653\ufef5" +
"\ufe8d\u0020\ufee5\u0655\ufef9\ufe8d" +
"\u0020\ufee5\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb\u0020\u0020\u0020\u0020" +
"\u0020\u0020"),
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE_TASHKEEL_ISOLATED | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_AT_BEGINNING,
"\u0020\u0020\u0020\u0020\u0020\u0020" +
"\u0020\ufee5\ufef5\ufe8d\u0020\ufee5" +
"\ufe76\ufef7\ufe8d\u0020\ufee5\u0670" +
"\ufefb\ufe8d\u0020\ufee5\u0653\ufef5" +
"\ufe8d\u0020\ufee5\u0655\ufef9\ufe8d" +
"\u0020\ufee5\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb"),
TestData.standard(lamAlefSpecialVLTR,
LETTERS_SHAPE_TASHKEEL_ISOLATED | TEXT_DIRECTION_VISUAL_LTR | LENGTH_GROW_SHRINK,
"\u0020\ufee5\ufef5\ufe8d\u0020\ufee5" +
"\ufe76\ufef7\ufe8d\u0020\ufee5\u0670" +
"\ufefb\ufe8d\u0020\ufee5\u0653\ufef5" +
"\ufe8d\u0020\ufee5\u0655\ufef9\ufe8d" +
"\u0020\ufee5\u0654\ufef5\ufe8d\u0020" +
"\ufefc\ufecb"),
/* tashkeel special visual ltr */
TestData.standard(tashkeelSpecialVLTR,
LETTERS_SHAPE | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_NEAR,
"\ufef2\ufe91\ufeae\ufecb\u0020" +
"\ufef2\ufe91\ufe7c\ufeae\ufe77\ufecb\u0020" +
"\ufe72\ufef2\ufe91\ufeae\ufe79\ufecb\u0020" +
"\ufe8f\u0670\ufeae\u0670\ufecb\u0020" +
"\ufe8f\u0653\ufeae\u0653\ufecb\u0020" +
"\ufe8f\u0654\ufeae\u0654\ufecb\u0020" +
"\ufe8f\u0655\ufeae\u0655\ufecb\u0020"),
TestData.standard(tashkeelSpecialVLTR,
LETTERS_SHAPE_TASHKEEL_ISOLATED | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_NEAR,
"\ufef2\ufe91\ufeae\ufecb\u0020" +
"\ufef2\ufe91\ufe7c\ufeae\ufe76\ufecb\u0020" +
"\ufe72\ufef2\ufe91\ufeae\ufe78\ufecb\u0020" +
"\ufe8f\u0670\ufeae\u0670\ufecb\u0020" +
"\ufe8f\u0653\ufeae\u0653\ufecb\u0020" +
"\ufe8f\u0654\ufeae\u0654\ufecb\u0020" +
"\ufe8f\u0655\ufeae\u0655\ufecb\u0020"),
/* logical unshape */
TestData.standard(logicalUnshape,
LETTERS_UNSHAPE | TEXT_DIRECTION_LOGICAL | LENGTH_FIXED_SPACES_NEAR,
"\u0020\u0020\u0020\u0627\u0644\u0622\u0646\u0020\u0627\u0644\u0623\u0642\u0644\u0627" +
"\u0645\u0020\u0627\u0644\u0639\u0631\u0628\u064a\u0629\u0020\u0627\u0644\u062d\u0631" +
"\u0629\u0020\u0020\u0020\u0020"),
TestData.standard(logicalUnshape,
LETTERS_UNSHAPE | TEXT_DIRECTION_LOGICAL | LENGTH_FIXED_SPACES_AT_END,
"\u0020\u0020\u0020\u0627\u0644\u0622\u0020\u0646\u0020\u0627\u0644\u0623\u0020\u0642" +
"\u0644\u0627\u0020\u0645\u0020\u0627\u0644\u0639\u0631\u0628\u064a\u0629\u0020\u0627" +
"\u0644\u062d\u0631\u0629\u0020"),
TestData.standard(logicalUnshape,
LETTERS_UNSHAPE | TEXT_DIRECTION_LOGICAL | LENGTH_FIXED_SPACES_AT_BEGINNING,
"\u0627\u0644\u0622\u0020\u0646\u0020\u0627\u0644\u0623\u0020\u0642\u0644\u0627\u0020" +
"\u0645\u0020\u0627\u0644\u0639\u0631\u0628\u064a\u0629\u0020\u0627\u0644\u062d\u0631" +
"\u0629\u0020\u0020\u0020\u0020"),
TestData.standard(logicalUnshape,
LETTERS_UNSHAPE | TEXT_DIRECTION_LOGICAL | LENGTH_GROW_SHRINK,
"\u0020\u0020\u0020\u0627\u0644\u0622\u0020\u0646\u0020\u0627\u0644\u0623\u0020\u0642" +
"\u0644\u0627\u0020\u0645\u0020\u0627\u0644\u0639\u0631\u0628\u064a\u0629\u0020\u0627" +
"\u0644\u062d\u0631\u0629\u0020\u0020\u0020\u0020"),
/* numbers */
TestData.standard(numSource,
DIGITS_EN2AN | DIGIT_TYPE_AN,
"\u0661\u0627\u0662\u06f3\u0061\u0664"),
TestData.standard(numSource,
DIGITS_AN2EN | DIGIT_TYPE_AN_EXTENDED,
"\u0031\u0627\u0032\u0033\u0061\u0034"),
TestData.standard(numSource,
DIGITS_EN2AN_INIT_LR | DIGIT_TYPE_AN,
"\u0031\u0627\u0662\u06f3\u0061\u0034"),
TestData.standard(numSource,
DIGITS_EN2AN_INIT_AL | DIGIT_TYPE_AN_EXTENDED,
"\u06f1\u0627\u06f2\u06f3\u0061\u0034"),
TestData.standard(numSource,
DIGITS_EN2AN_INIT_LR | DIGIT_TYPE_AN | TEXT_DIRECTION_VISUAL_LTR,
"\u0661\u0627\u0032\u06f3\u0061\u0034"),
TestData.standard(numSource,
DIGITS_EN2AN_INIT_AL | DIGIT_TYPE_AN_EXTENDED | TEXT_DIRECTION_VISUAL_LTR,
"\u06f1\u0627\u0032\u06f3\u0061\u06f4"),
/* no-op */
TestData.standard(numSource,
0,
numSource),
/* preflight */
TestData.preflight("\u0644\u0627",
LETTERS_SHAPE | LENGTH_GROW_SHRINK,
1),
TestData.preflight("\u0644\u0627\u0031",
DIGITS_EN2AN | DIGIT_TYPE_AN_EXTENDED | LENGTH_GROW_SHRINK,
3),
TestData.preflight("\u0644\u0644",
LETTERS_SHAPE | LENGTH_GROW_SHRINK,
2),
TestData.preflight("\ufef7",
LETTERS_UNSHAPE | LENGTH_GROW_SHRINK,
2),
/* bad data */
TestData.error("\u0020\ufef7\u0644\u0020",
LETTERS_UNSHAPE | LENGTH_FIXED_SPACES_NEAR,
ArabicShapingException.class),
TestData.error("\u0020\ufef7",
LETTERS_UNSHAPE | LENGTH_FIXED_SPACES_AT_END,
ArabicShapingException.class),
TestData.error("\ufef7\u0020",
LETTERS_UNSHAPE | LENGTH_FIXED_SPACES_AT_BEGINNING,
ArabicShapingException.class),
/* bad options */
TestData.error("\ufef7",
0xffffffff,
IllegalArgumentException.class),
};
public void testStandard() {
for (int i = 0; i < tests.length; ++i) {
TestData test = tests[i];
Exception ex = null;
String result = null;
ArabicShaping shaper = null;
try {
shaper = new ArabicShaping(test.flags);
result = shaper.shape(test.source);
}
catch (Exception e) {
ex = e;
}
switch (test.type) {
case TestData.STANDARD:
if (!test.result.equals(result)) {
reportTestFailure(i, test, shaper, result, ex);
}
break;
case TestData.PREFLIGHT:
if (result == null || test.length != result.length()) {
reportTestFailure(i, test, shaper, result, ex);
}
break;
case TestData.ERROR:
if (!test.error.isInstance(ex)) {
reportTestFailure(i, test, shaper, result, ex);
}
break;
}
}
}
public void reportTestFailure(int index, TestData test, ArabicShaping shaper, String result, Exception error) {
StringBuffer buf = new StringBuffer();
buf.append("*** test failure ***\n");
buf.append("index: " + index + "\n");
buf.append("test: " + test + "\n");
buf.append("shaper: " + shaper + "\n");
buf.append("result: " + escapedString(result) + "\n");
buf.append("error: " + error + "\n");
if (result != null && test.result != null && !test.result.equals(result)) {
for (int i = 0; i < Math.max(test.result.length(), result.length()); ++i) {
String temp = Integer.toString(i);
if (temp.length() < 2) {
temp = " ".concat(temp);
}
char trg = i < test.result.length() ? test.result.charAt(i) : '\uffff';
char res = i < result.length() ? result.charAt(i) : '\uffff';
buf.append("[" + temp + "] ");
buf.append(escapedString("" + trg) + " ");
buf.append(escapedString("" + res) + " ");
if (trg != res) {
buf.append("***");
}
buf.append("\n");
}
}
err(buf.toString());
}
private static String escapedString(String str) {
StringBuffer buf = new StringBuffer(str.length() * 6);
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
buf.append("\\u");
if (ch < 0x1000) {
buf.append('0');
}
if (ch < 0x0100) {
buf.append('0');
}
if (ch < 0x0010) {
buf.append('0');
}
buf.append(Integer.toHexString(ch));
}
return buf.toString();
}
public static void main(String[] args) {
try {
new ArabicShapingRegTest().run(args);
}
catch (Exception e) {
System.out.println(e);
}
}
}

View File

@ -1,286 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*/
package com.ibm.icu.test.text;
import com.ibm.text.ArabicShaping;
import com.ibm.text.ArabicShapingException;
/**
* Interactive test for Arabic shaping.
* Invoke from a command line passing args and strings. Use '-help' to see description of arguments.
*/
public class ArabicShapingTest {
private static final int COPY = 0;
private static final int INPLACE = 1;
private static final int STRING = 2;
public static final void main(String[] args) {
int testtype = COPY;
int options = 0;
int ss = 0;
int sl = -1;
int ds = 0;
int dl = -1;
String text = "$22.4 test 123 \ufef6\u0644\u0622 456 \u0664\u0665\u0666!";
for (int i = 0; i < args.length; ++i) {
String arg = args[i];
if (arg.charAt(0) == '-') {
String opt = arg.substring(1);
String val = opt;
int index = arg.indexOf(':');
if (index != -1) {
opt = opt.substring(0, Math.min(index, 3));
val = arg.substring(index + 1);
}
if (opt.equalsIgnoreCase("len")) {
options &= ~ArabicShaping.LENGTH_MASK;
if (val.equalsIgnoreCase("gs")) {
options |= ArabicShaping.LENGTH_GROW_SHRINK;
} else if (val.equalsIgnoreCase("sn")) {
options |= ArabicShaping.LENGTH_FIXED_SPACES_NEAR;
} else if (val.equalsIgnoreCase("se")) {
options |= ArabicShaping.LENGTH_FIXED_SPACES_AT_END;
} else if (val.equalsIgnoreCase("sb")) {
options |= ArabicShaping.LENGTH_FIXED_SPACES_AT_BEGINNING;
} else {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("dir")) {
options &= ~ArabicShaping.TEXT_DIRECTION_MASK;
if (val.equalsIgnoreCase("log")) {
options |= ArabicShaping.TEXT_DIRECTION_LOGICAL;
} else if (val.equalsIgnoreCase("vis")) {
options |= ArabicShaping.TEXT_DIRECTION_VISUAL_LTR;
} else {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("let")) {
options &= ~ArabicShaping.LETTERS_MASK;
if (val.equalsIgnoreCase("no")) {
options |= ArabicShaping.LETTERS_NOOP;
} else if (val.equalsIgnoreCase("sh")) {
options |= ArabicShaping.LETTERS_SHAPE;
} else if (val.equalsIgnoreCase("un")) {
options |= ArabicShaping.LETTERS_UNSHAPE;
} else if (val.equalsIgnoreCase("ta")) {
options |= ArabicShaping.LETTERS_SHAPE_TASHKEEL_ISOLATED;
} else {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("dig")) {
options &= ~ArabicShaping.DIGITS_MASK;
if (val.equalsIgnoreCase("no")) {
options |= ArabicShaping.DIGITS_NOOP;
} else if (val.equalsIgnoreCase("ea")) {
options |= ArabicShaping.DIGITS_EN2AN;
} else if (val.equalsIgnoreCase("ae")) {
options |= ArabicShaping.DIGITS_AN2EN;
} else if (val.equalsIgnoreCase("lr")) {
options |= ArabicShaping.DIGITS_EN2AN_INIT_LR;
} else if (val.equalsIgnoreCase("al")) {
options |= ArabicShaping.DIGITS_EN2AN_INIT_AL;
} else {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("typ")) {
options &= ~ArabicShaping.DIGIT_TYPE_MASK;
if (val.equalsIgnoreCase("an")) {
options |= ArabicShaping.DIGIT_TYPE_AN;
} else if (val.equalsIgnoreCase("ex")) {
options |= ArabicShaping.DIGIT_TYPE_AN_EXTENDED;
} else {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("dst")) {
try {
ds = Integer.parseInt(val);
}
catch (Exception e) {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("dln")) {
try {
dl = Integer.parseInt(val);
}
catch (Exception e) {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("sst")) {
try {
ss = Integer.parseInt(val);
}
catch (Exception e) {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("sln")) {
try {
sl = Integer.parseInt(val);
}
catch (Exception e) {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("tes")) {
if (val.equalsIgnoreCase("cp")) {
testtype = COPY;
} else if (val.equalsIgnoreCase("ip")) {
testtype = INPLACE;
} else if (val.equalsIgnoreCase("st")) {
testtype = STRING;
} else {
throwValError(opt, val);
}
} else if (opt.equalsIgnoreCase("help")) {
System.out.println(usage);
} else {
throwOptError(opt);
}
} else {
// assume text
text = parseText(arg);
}
}
if (sl < 0) {
sl = text.length() - ss;
System.out.println("sl defaulting to " + sl);
}
if (dl < 0) {
dl = 2 * sl;
System.out.println("dl defaulting to " + dl);
}
ArabicShaping shaper = new ArabicShaping(options);
System.out.println("shaper: " + shaper);
char[] src = text.toCharArray();
System.out.println(" input: '" + escapedText(src, ss, sl) + "'");
if (testtype != STRING) {
System.out.println("start: " + ss + " length: " + sl + " total length: " + src.length);
}
int result = -1;
char[] dest = null;
try {
switch (testtype) {
case COPY:
dest = new char[ds + dl];
result = shaper.shape(src, ss, sl, dest, ds, dl);
break;
case INPLACE:
shaper.shape(src, ss, sl);
ds = ss;
result = sl;
dest = src;
break;
case STRING:
dest = shaper.shape(text).toCharArray();
ds = 0;
result = dest.length;
break;
}
System.out.println("output: '" + escapedText(dest, ds, result) + "'");
System.out.println("length: " + result);
if (ds != 0 || result != dest.length) {
System.out.println("full output: '" + escapedText(dest, 0, dest.length) + "'");
}
}
catch (ArabicShapingException e) {
System.out.println("Caught ArabicShapingException");
System.out.println(e);
}
catch (Exception e) {
System.out.println("Caught Exception");
System.out.println(e);
}
}
private static void throwOptError(String opt) {
throwUsageError("unknown option: " + opt);
}
private static void throwValError(String opt, String val) {
throwUsageError("unknown value: " + val + " for option: " + opt);
}
private static void throwUsageError(String message) {
StringBuffer buf = new StringBuffer("*** usage error ***\n");
buf.append(message);
buf.append("\n");
buf.append(usage);
throw new Error(buf.toString());
}
private static final String usage =
"Usage: [option]* [text]\n" +
" where option is in the format '-opt[:val]'\n" +
" options are:\n" +
" -len:[gs|sn|se|sb] (length: grow/shrink, spaces near, spaces end, spaces beginning)\n" +
" -dir:[log|vis] (direction: logical, visual)\n" +
" -let:[no|sh|un|ta] (letters: noop, shape, unshape, tashkeel)\n" +
// " -let:[no|sh|un] (letters: noop, shape, unshape)\n" +
" -dig:[no|ea|ae|lr|al] (digits: noop, en2an, an2en, en2an_lr, en2an_al)\n" +
" -typ:[an|ex] (digit type: arabic, arabic extended)\n" +
" -dst:# (dest start: [integer])\n" +
" -dln:# (dest length (max size): [integer])\n" +
" -sst:# (source start: [integer])\n" +
" -sln:# (source length: [integer])\n" +
" -tes:[cp|ip|st] (test type: copy, in place, string)\n" +
" -help (print this help message)\n" +
" text can contain unicode escape values in the format '\\uXXXX' only\n";
private static String escapedText(char[] text, int start, int length) {
StringBuffer buf = new StringBuffer();
for (int i = start, e = start + length; i < e; ++i) {
char ch = text[i];
if (ch < 0x20 || ch > 0x7e) {
buf.append("\\u");
if (ch < 0x1000) {
buf.append('0');
}
if (ch < 0x100) {
buf.append('0');
}
if (ch < 0x10) {
buf.append('0');
}
buf.append(Integer.toHexString(ch));
} else {
buf.append(ch);
}
}
return buf.toString();
}
private static String parseText(String text) {
// process unicode escapes (only)
StringBuffer buf = new StringBuffer();
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; ++i) {
char ch = chars[i];
if (ch == '\\') {
if ((i < chars.length - 1) &&
(chars[i+1] == 'u')) {
int val = Integer.parseInt(text.substring(i+2, i+6), 16);
buf.append((char)val);
i += 5;
} else {
buf.append('\\');
}
} else {
buf.append(ch);
}
}
return buf.toString();
}
}

View File

@ -1,269 +0,0 @@
/**
*******************************************************************************
* Copyright (C) 1996-2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.test.text;
import com.ibm.text.UScript;
import com.ibm.test.TestFmwk;
import java.util.Locale;
public class TestUScript extends TestFmwk{
/**
* Constructor
*/
public TestUScript()
{
}
public static void main(String[] args) throws Exception {
new TestUScript().run(args);
}
public void TestLocaleGetCode(){
final Locale[] testNames={
/* test locale */
new Locale("en",""), new Locale("en","US"),
new Locale("sr",""), new Locale("ta","") ,
new Locale("te","IN"),
new Locale("hi",""),
new Locale("he",""), new Locale("ar",""),
new Locale("abcde",""),
new Locale("abcde","cdef")
};
final int[] expected ={
/* locales should return */
UScript.LATIN, UScript.LATIN,
UScript.CYRILLIC, UScript.TAMIL,
UScript.TELUGU,UScript.DEVANAGARI,
UScript.HEBREW, UScript.ARABIC,
UScript.INVALID_CODE,UScript.INVALID_CODE
};
int i =0;
int numErrors =0;
for( ; i<testNames.length; i++){
int[] code = UScript.getCode(testNames[i]);
if((code!=null) && (code[0] != expected[i])){
logln("Error getting script code Got: " +code[0] + " Expected: " +expected[i] +" for name "+testNames[i]);
numErrors++;
}
}
if(numErrors >0 ){
errln("Number of Errors in UScript.getCode() : " + numErrors);
}
}
public void TestMultipleCode(){
final String[] testNames = { "ja" ,"ko_KR","zh","zh_TW"};
final int[][] expected = {
{UScript.KATAKANA,UScript.HIRAGANA,UScript.HAN},
{UScript.HANGUL, UScript.HAN},
{UScript.HAN},
{UScript.HAN,UScript.BOPOMOFO}
};
for(int i=0; i<testNames.length;i++){
int[] code = UScript.getCode(testNames[i]);
int[] expt = (int[]) expected[i];
for(int j =0; j< code.length;j++){
if(code[j]!=expt[j]){
logln("Error getting script code Got: " +code[j] + " Expected: " +expt[j] +" for name "+testNames[i]);
}
}
}
}
public void TestGetCode(){
final String[] testNames={
/* test locale */
"en", "en_US", "sr", "ta" , "te_IN",
"hi", "he", "ar",
/* test abbr */
"Hani", "Hang","Hebr","Hira",
"Knda","Kana","Khmr","Lao",
"Latn",/*"Latf","Latg",*/
"Mlym", "Mong",
/* test names */
"CYRILLIC","DESERET","DEVANAGARI","ETHIOPIC","GEORGIAN",
"GOTHIC", "GREEK", "GUJARATI", "COMMON", "INHERITED",
/* test lower case names */
"malayalam", "mongolian", "myanmar", "ogham", "old-italic",
"oriya", "runic", "sinhala", "syriac","tamil",
"telugu", "thaana", "thai", "tibetan",
/* test the bounds*/
"ucas", "arabic",
};
final int[] expected ={
/* locales should return */
UScript.LATIN, UScript.LATIN,
UScript.CYRILLIC, UScript.TAMIL,
UScript.TELUGU,UScript.DEVANAGARI,
UScript.HEBREW, UScript.ARABIC,
/* abbr should return */
UScript.HAN, UScript.HANGUL, UScript.HEBREW, UScript.HIRAGANA,
UScript.KANNADA, UScript.KATAKANA, UScript.KHMER, UScript.LAO,
UScript.LATIN,/* UScript.LATIN, UScript.LATIN,*/
UScript.MALAYALAM, UScript.MONGOLIAN,
/* names should return */
UScript.CYRILLIC, UScript.DESERET, UScript.DEVANAGARI, UScript.ETHIOPIC, UScript.GEORGIAN,
UScript.GOTHIC, UScript.GREEK, UScript.GUJARATI, UScript.COMMON, UScript.INHERITED,
/* lower case names should return */
UScript.MALAYALAM, UScript.MONGOLIAN, UScript.MYANMAR, UScript.OGHAM, UScript.OLD_ITALIC,
UScript.ORIYA, UScript.RUNIC, UScript.SINHALA, UScript.SYRIAC, UScript.TAMIL,
UScript.TELUGU, UScript.THAANA, UScript.THAI, UScript.TIBETAN,
/* bounds */
UScript.UCAS, UScript.ARABIC,
};
int i =0;
int numErrors =0;
for( ; i<testNames.length; i++){
int[] code = UScript.getCode(testNames[i]);
if((code!=null) && (code[0] != expected[i])){
logln("Error getting script code Got: " +code[0] + " Expected: " +expected[i] +" for name "+testNames[i]);
numErrors++;
}
}
if(numErrors >0 ){
errln("Number of Errors in UScript.getCode() : " + numErrors);
}
}
public void TestGetName(){
final int[] testCodes={
/* names should return */
UScript.CYRILLIC, UScript.DESERET, UScript.DEVANAGARI, UScript.ETHIOPIC, UScript.GEORGIAN,
UScript.GOTHIC, UScript.GREEK, UScript.GUJARATI,
};
final String[] expectedNames={
/* test names */
"CYRILLIC","DESERET","DEVANAGARI","ETHIOPIC","GEORGIAN",
"GOTHIC", "GREEK", "GUJARATI",
};
int i =0;
while(i< testCodes.length){
String scriptName = UScript.getName(testCodes[i]);
int numErrors=0;
if(!expectedNames[i].equals(scriptName)){
logln("Error getting abbreviations Got: " +scriptName +" Expected: "+expectedNames[i]);
numErrors++;
}
if(numErrors > 0){
if(numErrors >0 ){
errln("Errors UScript.getShorName() : " + numErrors);
}
}
i++;
}
}
public void TestGetShortName(){
final int[] testCodes={
/* abbr should return */
UScript.HAN, UScript.HANGUL, UScript.HEBREW, UScript.HIRAGANA,
UScript.KANNADA, UScript.KATAKANA, UScript.KHMER, UScript.LAO,
UScript.LATIN,
UScript.MALAYALAM, UScript.MONGOLIAN,
};
final String[] expectedAbbr={
/* test abbr */
"Hani", "Hang","Hebr","Hira",
"Knda","Kana","Khmr","Lao",
"Latn",
"Mlym", "Mong",
};
int i=0;
while(i<testCodes.length){
String shortName = UScript.getShortName(testCodes[i]);
int numErrors=0;
if(!expectedAbbr[i].equals(shortName)){
logln("Error getting abbreviations Got: " +shortName+ " Expected: " +expectedAbbr[i]);
numErrors++;
}
if(numErrors > 0){
if(numErrors >0 ){
errln("Errors UChar.getScriptAbbr() : "+numErrors);
}
}
i++;
}
}
public void TestGetScript(){
int codepoints[] = {
0x0000FF9D,
0x0000FFBE,
0x0000FFC7,
0x0000FFCF,
0x0000FFD7,
0x0000FFDC,
0x00010300,
0x00010330,
0x0001034A,
0x00010400,
0x00010428,
0x0001D167,
0x0001D17B,
0x0001D185,
0x0001D1AA,
0x00020000,
0x00000D02,
0x00000D00,
0x00000000,
0x0001D169,
0x0001D182,
0x0001D18B,
0x0001D1AD,
};
int expected[] = {
UScript.KATAKANA ,
UScript.HANGUL ,
UScript.HANGUL ,
UScript.HANGUL ,
UScript.HANGUL ,
UScript.HANGUL ,
UScript.OLD_ITALIC,
UScript.GOTHIC ,
UScript.GOTHIC ,
UScript.DESERET ,
UScript.DESERET ,
UScript.INHERITED,
UScript.INHERITED,
UScript.INHERITED,
UScript.INHERITED,
UScript.HAN ,
UScript.MALAYALAM,
UScript.INVALID_CODE,
UScript.COMMON,
UScript.INHERITED ,
UScript.INHERITED ,
UScript.INHERITED ,
UScript.INHERITED ,
};
int i =0;
int code = UScript.INVALID_CODE;
boolean passed = true;
while(i< codepoints.length){
code = UScript.getScript(codepoints[i]);
if(code != expected[i]){
logln("UScript.getScript for codepoint 0x"+ hex(codepoints[i])+" failed\n");
passed = false;
}
i++;
}
if(!passed){
errln("UScript.getScript failed.");
}
}
}

View File

@ -1,313 +0,0 @@
/**
*******************************************************************************
* Copyright (C) 1996-2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/text/Attic/UCharacterCompare.java,v $
* $Date: 2001/03/23 19:52:03 $
* $Revision: 1.6 $
*
*******************************************************************************
*/
package com.ibm.icu.test.text;
import com.ibm.text.UCharacter;
import com.ibm.text.UCharacterCategory;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.Enumeration;
/**
* A class to compare the difference in methods between java.lang.Character and
* UCharacter
* @author Syn Wee Quek
* @since oct 06 2000
* @see com.ibm.text.UCharacter
*/
public final class UCharacterCompare
{
// private variables ================================================
private static Hashtable m_hashtable_ = new Hashtable();
// public methods ======================================================
/**
* Main testing method
*/
public static void main(String arg[])
{
try
{
FileWriter f;
if (arg.length == 0)
f = new FileWriter("compare.txt");
else
f = new FileWriter(arg[0]);
PrintWriter p = new PrintWriter(f);
p.print("char character name ");
p.println("method name ucharacter character");
for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i ++)
{
if (UCharacter.isDefined(i) != Character.isDefined(i))
trackDifference(p, i, "isDefined()", "" + UCharacter.isDefined(i),
"" + Character.isDefined(i));
else
{
if (UCharacter.digit(i, 10) != Character.digit(i, 10))
trackDifference(p, i, "digit()", "" + UCharacter.digit(i, 10),
"" + Character.digit(i, 10));
if (UCharacter.getNumericValue(i) != Character.getNumericValue(i))
trackDifference(p, i, "getNumericValue()",
"" + UCharacter.getNumericValue(i),
"" + Character.getNumericValue(i));
if (!compareType(UCharacter.getType(i), Character.getType(i)))
trackDifference(p, i, "getType()", "" + UCharacter.getType(i),
"" + Character.getType(i));
if (UCharacter.isDigit(i) != Character.isDigit(i))
trackDifference(p, i, "isDigit()",
"" + UCharacter.isDigit(i),
"" + Character.isDigit(i));
if (UCharacter.isISOControl(i) != Character.isISOControl(i))
trackDifference(p, i, "isISOControl()",
"" + UCharacter.isISOControl(i),
"" + Character.isISOControl(i));
if (UCharacter.isLetter(i) != Character.isLetter(i))
trackDifference(p, i, "isLetter()", "" + UCharacter.isLetter(i),
"" + Character.isLetter(i));
if (UCharacter.isLetterOrDigit(i) != Character.isLetterOrDigit(i))
trackDifference(p, i, "isLetterOrDigit()",
"" + UCharacter.isLetterOrDigit(i),
"" + Character.isLetterOrDigit(i));
if (UCharacter.isLowerCase(i) != Character.isLowerCase(i))
trackDifference(p, i, "isLowerCase()",
"" + UCharacter.isLowerCase(i),
"" + Character.isLowerCase(i));
if (UCharacter.isWhitespace(i) != Character.isWhitespace(i))
trackDifference(p, i, "isWhitespace()",
"" + UCharacter.isWhitespace(i),
"" + Character.isWhitespace(i));
if (UCharacter.isSpaceChar(i) != Character.isSpaceChar(i))
trackDifference(p, i, "isSpaceChar()",
"" + UCharacter.isSpaceChar(i),
"" + Character.isSpaceChar(i));
if (UCharacter.isTitleCase(i) != Character.isTitleCase(i))
trackDifference(p, i, "isTitleChar()",
"" + UCharacter.isTitleCase(i),
"" + Character.isTitleCase(i));
if (UCharacter.isUnicodeIdentifierPart(i) !=
Character.isUnicodeIdentifierPart(i))
trackDifference(p, i, "isUnicodeIdentifierPart()",
"" + UCharacter.isUnicodeIdentifierPart(i),
"" + Character.isUnicodeIdentifierPart(i));
if (UCharacter.isUnicodeIdentifierStart(i) !=
Character.isUnicodeIdentifierStart(i))
trackDifference(p, i, "isUnicodeIdentifierStart()",
"" + UCharacter.isUnicodeIdentifierStart(i),
"" + Character.isUnicodeIdentifierStart(i));
if (UCharacter.isIdentifierIgnorable(i) !=
Character.isIdentifierIgnorable(i))
trackDifference(p, i, "isIdentifierIgnorable()",
"" + UCharacter.isIdentifierIgnorable(i),
"" + Character.isIdentifierIgnorable(i));
if (UCharacter.isUpperCase(i) != Character.isUpperCase(i))
trackDifference(p, i, "isUpperCase()",
"" + UCharacter.isUpperCase(i),
"" + Character.isUpperCase(i));
if (UCharacter.toLowerCase(i) != Character.toLowerCase(i))
trackDifference(p, i, "toLowerCase()",
Integer.toHexString(UCharacter.toLowerCase(i)),
Integer.toHexString(Character.toLowerCase(i)));
if (!UCharacter.toString(i).equals(new Character(i).toString()))
trackDifference(p, i, "toString()",
UCharacter.toString(i),
new Character(i).toString());
if (UCharacter.toTitleCase(i) != Character.toTitleCase(i))
trackDifference(p, i, "toTitleCase()",
Integer.toHexString(UCharacter.toTitleCase(i)),
Integer.toHexString(Character.toTitleCase(i)));
if (UCharacter.toUpperCase(i) != Character.toUpperCase(i))
trackDifference(p, i, "toUpperCase()",
Integer.toHexString(UCharacter.toUpperCase(i)),
Integer.toHexString(Character.toUpperCase(i)));
}
}
summary(p);
p.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
// private methods ===================================================
/**
* Comparing types
* @param uchartype UCharacter type
* @param jchartype java.lang.Character type
*/
private static boolean compareType(int uchartype, int jchartype)
{
if (uchartype == UCharacterCategory.UNASSIGNED &&
jchartype == Character.UNASSIGNED)
return true;
if (uchartype == UCharacterCategory.UPPERCASE_LETTER &&
jchartype == Character.UPPERCASE_LETTER)
return true;
if (uchartype == UCharacterCategory.LOWERCASE_LETTER &&
jchartype == Character.LOWERCASE_LETTER)
return true;
if (uchartype == UCharacterCategory.TITLECASE_LETTER &&
jchartype == Character.TITLECASE_LETTER)
return true;
if (uchartype == UCharacterCategory.MODIFIER_LETTER &&
jchartype == Character.MODIFIER_LETTER)
return true;
if (uchartype == UCharacterCategory.OTHER_LETTER &&
jchartype == Character.OTHER_LETTER)
return true;
if (uchartype == UCharacterCategory.NON_SPACING_MARK &&
jchartype == Character.NON_SPACING_MARK)
return true;
if (uchartype == UCharacterCategory.ENCLOSING_MARK &&
jchartype == Character.ENCLOSING_MARK)
return true;
if (uchartype == UCharacterCategory.COMBINING_SPACING_MARK &&
jchartype == Character.COMBINING_SPACING_MARK)
return true;
if (uchartype == UCharacterCategory.DECIMAL_DIGIT_NUMBER &&
jchartype == Character.DECIMAL_DIGIT_NUMBER)
return true;
if (uchartype == UCharacterCategory.LETTER_NUMBER &&
jchartype == Character.LETTER_NUMBER)
return true;
if (uchartype == UCharacterCategory.OTHER_NUMBER &&
jchartype == Character.OTHER_NUMBER)
return true;
if (uchartype == UCharacterCategory.SPACE_SEPARATOR &&
jchartype == Character.SPACE_SEPARATOR)
return true;
if (uchartype == UCharacterCategory.LINE_SEPARATOR &&
jchartype == Character.LINE_SEPARATOR)
return true;
if (uchartype == UCharacterCategory.PARAGRAPH_SEPARATOR &&
jchartype == Character.PARAGRAPH_SEPARATOR)
return true;
if (uchartype == UCharacterCategory.CONTROL &&
jchartype == Character.CONTROL)
return true;
if (uchartype == UCharacterCategory.FORMAT &&
jchartype == Character.FORMAT)
return true;
if (uchartype == UCharacterCategory.PRIVATE_USE &&
jchartype == Character.PRIVATE_USE)
return true;
if (uchartype == UCharacterCategory.SURROGATE &&
jchartype == Character.SURROGATE)
return true;
if (uchartype == UCharacterCategory.DASH_PUNCTUATION &&
jchartype == Character.DASH_PUNCTUATION)
return true;
if (uchartype == UCharacterCategory.START_PUNCTUATION &&
jchartype == Character.START_PUNCTUATION)
return true;
if (uchartype == UCharacterCategory.END_PUNCTUATION &&
jchartype == Character.END_PUNCTUATION)
return true;
if (uchartype == UCharacterCategory.CONNECTOR_PUNCTUATION &&
jchartype == Character.CONNECTOR_PUNCTUATION)
return true;
if (uchartype == UCharacterCategory.OTHER_PUNCTUATION &&
jchartype == Character.OTHER_PUNCTUATION)
return true;
if (uchartype == UCharacterCategory.MATH_SYMBOL &&
jchartype == Character.MATH_SYMBOL)
return true;
if (uchartype == UCharacterCategory.CURRENCY_SYMBOL &&
jchartype == Character.CURRENCY_SYMBOL)
return true;
if (uchartype == UCharacterCategory.MODIFIER_SYMBOL &&
jchartype == Character.MODIFIER_SYMBOL)
return true;
if (uchartype == UCharacterCategory.OTHER_SYMBOL &&
jchartype == Character.OTHER_SYMBOL)
return true;
if (uchartype == UCharacterCategory.INITIAL_PUNCTUATION &&
jchartype == Character.START_PUNCTUATION)
return true;
if (uchartype == UCharacterCategory.FINAL_PUNCTUATION &&
jchartype == Character.END_PUNCTUATION)
return true;
/*if (uchartype == UCharacterCategory.GENERAL_OTHER_TYPES &&
jchartype == Character.GENERAL_OTHER_TYPES)
return true;*/
return false;
}
/**
* Difference writing to file
* @param f file outputstream
* @param ch code point
* @param method for testing
* @param ucharval UCharacter value after running method
* @param charval Character value after running method
* @exception thrown when error occur in writing to file
*/
private static void trackDifference(PrintWriter f, int ch, String method,
String ucharval, String charval)
throws Exception
{
if (m_hashtable_.containsKey(method))
{
Integer value = (Integer)m_hashtable_.get(method);
m_hashtable_.put(method, new Integer(value.intValue() + 1));
}
else
m_hashtable_.put(method, new Integer(1));
String temp = Integer.toHexString(ch);
StringBuffer s = new StringBuffer(temp);
for (int i = 0; i < 6 - temp.length(); i ++)
s.append(' ');
temp = UCharacter.getName(ch);
if (temp == null)
temp = " ";
s.append(temp);
for (int i = 0; i < 73 - temp.length(); i ++)
s.append(' ');
s.append(method);
for (int i = 0; i < 27 - method.length(); i ++)
s.append(' ');
s.append(ucharval);
for (int i = 0; i < 11 - ucharval.length(); i ++)
s.append(' ');
s.append(charval);
f.println(s.toString());
}
/**
* Does up a summary of the differences
* @param f file outputstream
*/
private static void summary(PrintWriter f)
{
f.println("==================================================");
f.println("Summary of differences");
for (Enumeration e = m_hashtable_.keys() ; e.hasMoreElements() ;)
{
StringBuffer method = new StringBuffer((String)e.nextElement());
int count = ((Integer)m_hashtable_.get(method.toString())).intValue();
for (int i = 30 - method.length(); i > 0; i --)
method.append(' ');
f.println(method + " " + count);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,653 +0,0 @@
/**
*******************************************************************************
* Copyright (C) 1996-2002, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/util/Attic/TrieTest.java,v $
* $Date: 2002/02/08 01:31:18 $
* $Revision: 1.1 $
*
*******************************************************************************
*/
package com.ibm.icu.test.util;
import com.ibm.test.TestFmwk;
import com.ibm.icu.internal.util.Trie;
import com.ibm.icu.util.IntTrie;
import com.ibm.text.UTF16;
import com.ibm.text.UCharacter;
import java.io.ByteArrayInputStream;
/**
* Testing class for Trie
* @author Syn Wee Quek
* @since release 2.1 Jan 01 2002
*/
public final class TrieTest extends TestFmwk
{
// constructor ---------------------------------------------------
/**
* Constructor
*/
public TrieTest()
{
}
// public methods -----------------------------------------------
public static void main(String arg[])
{
TrieTest test = new TrieTest();
test.TestValues();
}
public void TestValues()
{
byte array[] = new byte[TRIE_1_DATA_.length << 1];
for (int i = 0; i < TRIE_1_DATA_.length; i ++) {
array[i << 1] = (byte)((TRIE_1_DATA_[i] >> 8) & 0xFF);
array[(i << 1) + 1] = (byte)(TRIE_1_DATA_[i] & 0xFF);
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(array);
IntTrie trie = null;
try {
trie = new IntTrie(inputStream, new IntDataManipulate());
} catch (Exception e) {
errln("Failed reading trie data");
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < STRING_1_.length; i ++) {
UTF16.append(buffer, STRING_1_[i]);
}
String str = buffer.toString();
int values[] = VALUE_1_;
internalTestValues(trie, str, values);
// testing invalid codepoints
int result = 0;
result = trie.getCodePointValue(0x110000);
if (result != 0) {
errln("Error: Expected value for illegal codepoint should be 0");
}
}
// private class ------------------------------------------------
private static class IntDataManipulate implements Trie.DataManipulate
{
public int getFoldingOffset(int data)
{
return data >> 16;
}
}
// private data members -----------------------------------------
// trie data, generated from icu4c
private final char TRIE_1_DATA_[] = {
0x5472, 0x6965, 0x0, 0x125, 0x0, 0x8c0, 0x0, 0x18c, 0x0, 0x8, 0x8, 0x8,
0x8, 0xf, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x1e, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4d, 0x4f, 0x4f, 0x4f,
0x4f, 0x4f, 0x53, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x29, 0x29, 0x29, 0x29, 0x29,
0x5b, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x2e,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29, 0x29,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
0x32, 0x32, 0x32, 0x32, 0x36, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
0x17, 0x17, 0x3d, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x45, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1234, 0x0, 0x1234,
0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234,
0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234,
0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234,
0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234,
0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234,
0x0, 0x1234, 0x0, 0x1234, 0x0, 0x1234, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1,
0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1,
0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1,
0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1,
0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1,
0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1, 0x0, 0x1,
0x0, 0x1, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162,
0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x6162, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf,
0x0, 0x10, 0x0, 0x10, 0x0, 0x11, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12,
0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12,
0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12,
0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12,
0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x0, 0x12, 0x820, 0x1, 0x820, 0x1,
0x820, 0x1, 0x820, 0x1, 0x840, 0x6163, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162,
0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162,
0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162,
0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162,
0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162,
0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162,
0x860, 0x6162, 0x860, 0x6162, 0x860, 0x6162, 0x880, 0x6162, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132, 0x0, 0x3132,
0x8a0, 0x1f, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27, 0x0, 0x27,
0x0, 0x27, 0x0, 0x27, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
};
private final int STRING_1_[] = {0, 0x20, 0xa7, 0x3400, 0x9fa6, 0xdada,
0xeeee, 0x11111, 0x44444, 0xf0003,
0xf0004, 0xf0006, 0xf0007, 0xf0020};
private final int VALUE_1_[] = {0, 0x1234, 0, 0x6162, 0x3132, 0x27, 1,
0x6162, 0, 0xf, 0x10, 0x11, 0x12, 0};
// private methods ----------------------------------------------
private void internalTestValues(IntTrie trie, String str, int values[])
{
// try forward
int count = 0;
int valueindex = 0;
while (count < str.length()) {
int value;
char c = str.charAt(count ++);
char c2 = UTF16.isLeadSurrogate(c) && count < str.length() &&
UTF16.isTrailSurrogate(str.charAt(count))
? str.charAt(count ++) : 0;
if (c2 != 0) {
value = trie.getSurrogateValue(c, c2);
}
else {
value = trie.getBMPValue(c);
}
if (value != values[valueindex]) {
errln("Error: Expected value should be " + values[valueindex] +
" not " + value);
}
value = trie.getLeadValue(c);
if (c2 != 0) {
value = trie.getTrailValue(value, c2);
}
if (value != values[valueindex]) {
errln("Error: Expected value should be " + values[valueindex] +
" not " + value);
}
if (c2!=0) {
int codepoint = UCharacter.getCodePoint(c, c2);
value = trie.getCodePointValue(codepoint);
}
else {
value = trie.getBMPValue(c);
}
if (value != values[valueindex]) {
errln("Error: Expected value should be " + values[valueindex] +
" not " + value);
}
valueindex ++;
}
}
}

View File

@ -1,216 +0,0 @@
/*
******************************************************************************
* Copyright (C) 1996-2002, International Business Machines Corporation and *
* others. All Rights Reserved. *
******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/util/Attic/CharTrie.java,v $
* $Date: 2002/02/08 01:08:38 $
* $Revision: 1.1 $
*
******************************************************************************
*/
package com.ibm.icu.util;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.IOException;
import com.ibm.icu.internal.util.Trie;
/**
* Trie implementation which stores data in char, 16 bits.
* @author synwee
* @see com.ibm.icu.util.Trie
* @since release 2.1, Jan 01 2002
*/
// note that i need to handle the block calculations later, since chartrie
// in icu4c uses the same index array.
public class CharTrie extends Trie
{
// public constructors ---------------------------------------------
/**
* <p>Creates a new Trie with the settings for the trie data.</p>
* <p>Unserialize the 32-bit-aligned input stream and use the data for the
* trie.</p>
* @param inputStream file input stream to a ICU data file, containing
* the trie
* @param dataManipulate, object which provides methods to parse the char
* data
* @exception IOException thrown when data reading fails
* @draft 2.1
*/
public CharTrie(InputStream inputStream,
DataManipulate dataManipulate) throws IOException
{
super(inputStream, dataManipulate);
if (!isCharTrie()) {
throw new IllegalArgumentException(
"Data given does not belong to a char trie.");
}
}
// public methods --------------------------------------------------
/**
* Gets the value associated with the codepoint.
* If no value is associated with the codepoint, a default value will be
* returned.
* @param ch codepoint
* @return offset to data
* @draft 2.1
*/
public final char getCodePointValue(int ch)
{
int offset = getCodePointOffset(ch);
if (offset > 0) {
return m_data_[offset];
}
return m_initialValue_;
}
/**
* Gets the value to the data which this lead surrogate character points
* to.
* Returned data may contain folding offset information for the next
* trailing surrogate character.
* This method does not guarantee correct results for trail surrogates.
* @param ch lead surrogate character
* @return data value
* @draft 2.1
*/
public final char getLeadValue(char ch)
{
return m_data_[getLeadOffset(ch)];
}
/**
* Get the value associated with the BMP code point.
* Lead surrogate code points are treated as normal code points, with
* unfolded values that may differ from getLeadValue() results.
* @param ch the input BMP code point
* @return trie data value associated with the BMP codepoint
* @draft 2.1
*/
public final char getBMPValue(char ch)
{
return m_data_[getBMPOffset(ch)];
}
/**
* Get the value associated with a pair of surrogates.
* @param lead a lead surrogate
* @param trail a trail surrogate
* @param trie data value associated with the surrogate characters
* @draft 2.1
*/
public final char getSurrogateValue(char lead, char trail)
{
return m_data_[getSurrogateOffset(lead, trail)];
}
/**
* Get a value from a folding offset (from the value of a lead surrogate)
* and a trail surrogate.
* @param leadvalue value associated with the lead surrogate which contains
* the folding offset
* @param trail surrogate
* @return trie data value associated with the trail character
* @draft 2.1
*/
public final char getTrailValue(int leadvalue, char trail)
{
if (m_dataManipulate_ == null) {
throw new NullPointerException(
"The field DataManipulate in this Trie is null");
}
return m_data_[getRawOffset(
m_dataManipulate_.getFoldingOffset(leadvalue),
(char)(trail & SURROGATE_MASK_))];
}
// protected methods -----------------------------------------------
/**
* <p>Parses the input stream and stores its trie content into a index and
* data array</p>
* @param inputStream data input stream containing trie data
* @exception IOException thrown when data reading fails
*/
protected final void unserialize(InputStream inputStream)
throws IOException
{
DataInputStream input = new DataInputStream(inputStream);
int indexDataLength = m_dataOffset_ + m_dataLength_;
m_index_ = new char[indexDataLength];
for (int i = 0; i < indexDataLength; i ++) {
m_index_[i] = input.readChar();
}
m_data_ = m_index_;
m_initialValue_ = m_data_[m_dataOffset_];
}
/**
* Gets the offset to the data which the surrogate pair points to.
* @param lead lead surrogate
* @param trail trailing surrogate
* @return offset to data
* @draft 2.1
*/
protected final int getSurrogateOffset(char lead, char trail)
{
if (m_dataManipulate_ == null) {
throw new NullPointerException(
"The field DataManipulate in this Trie is null");
}
// get fold position for the next trail surrogate
int offset = m_dataManipulate_.getFoldingOffset(getLeadValue(lead));
// get the real data from the folded lead/trail units
if (offset > 0) {
return getRawOffset(offset, (char)(trail & SURROGATE_MASK_));
}
// return -1 if there is an error, in this case we return the default
// value: m_initialValue_
return -1;
}
/**
* Gets the value at the argument index.
* For use internally in com.ibm.icu.util.TrieEnumeration.
* @param index value at index will be retrieved
* @return 32 bit value
* @see com.ibm.icu.util.TrieEnumeration
* @draft 2.1
*/
protected final int getValue(int index)
{
return m_data_[index];
}
/**
* Gets the default initial value
* @return 32 bit value
* @draft 2.1
*/
protected final int getInitialValue()
{
return m_initialValue_;
}
// private data members --------------------------------------------
/**
* Default value
*/
private char m_initialValue_;
/**
* Array of char data
*/
protected char m_data_[];
}

View File

@ -1,246 +0,0 @@
/*
******************************************************************************
* Copyright (C) 1996-2002, International Business Machines Corporation and *
* others. All Rights Reserved. *
******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/util/Attic/IntTrie.java,v $
* $Date: 2002/02/08 01:08:38 $
* $Revision: 1.1 $
*
******************************************************************************
*/
package com.ibm.icu.util;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.IOException;
import com.ibm.text.UTF16;
import com.ibm.icu.internal.util.Trie;
/**
* Trie implementation which stores data in int, 32 bits.
* @author synwee
* @see com.ibm.icu.util.Trie
* @since release 2.1, Jan 01 2002
*/
public class IntTrie extends Trie
{
// public constructors ---------------------------------------------
/**
* <p>Creates a new Trie with the settings for the trie data.</p>
* <p>Unserialize the 32-bit-aligned input stream and use the data for the
* trie.</p>
* @param inputStream file input stream to a ICU data file, containing
* the trie
* @param dataManipulate, object which provides methods to parse the char
* data
* @exception IOException thrown when data reading fails
* @draft 2.1
*/
public IntTrie(InputStream inputStream, DataManipulate datamanipulate)
throws IOException
{
super(inputStream, datamanipulate);
if (!isIntTrie()) {
throw new IllegalArgumentException(
"Data given does not belong to a int trie.");
}
}
// public methods --------------------------------------------------
// to be removed
public String toString()
{
StringBuffer result = new StringBuffer(super.toString());
result.append("\ndata length ");
int length = m_data_.length;
result.append(length);
result.append("\ndata-------------------\n");
for (int i = 0; i < length;) {
result.append("0x");
result.append(Integer.toHexString(m_data_[i]));
result.append(", ");
i ++;
if ((i % 15) == 0) {
result.append("\n");
}
}
return result.toString();
}
/**
* Gets the value associated with the codepoint.
* If no value is associated with the codepoint, a default value will be
* returned.
* @param ch codepoint
* @return offset to data
* @draft 2.1
*/
public final int getCodePointValue(int ch)
{
int offset = getCodePointOffset(ch);
if (offset > 0) {
return m_data_[offset];
}
return m_initialValue_;
}
/**
* Gets the value to the data which this lead surrogate character points
* to.
* Returned data may contain folding offset information for the next
* trailing surrogate character.
* This method does not guarantee correct results for trail surrogates.
* @param ch lead surrogate character
* @return data value
* @draft 2.1
*/
public final int getLeadValue(char ch)
{
return m_data_[getLeadOffset(ch)];
}
/**
* Get the value associated with the BMP code point.
* Lead surrogate code points are treated as normal code points, with
* unfolded values that may differ from getLeadValue() results.
* @param ch the input BMP code point
* @return trie data value associated with the BMP codepoint
* @draft 2.1
*/
public final int getBMPValue(char ch)
{
return m_data_[getBMPOffset(ch)];
}
/**
* Get the value associated with a pair of surrogates.
* @param lead a lead surrogate
* @param trail a trail surrogate
* @param trie data value associated with the surrogate characters
* @draft 2.1
*/
public final int getSurrogateValue(char lead, char trail)
{
if (!UTF16.isLeadSurrogate(lead) || !UTF16.isTrailSurrogate(trail)) {
throw new IllegalArgumentException(
"Argument characters do not form a supplementary character");
}
// get fold position for the next trail surrogate
int offset = getSurrogateOffset(lead, trail);
// get the real data from the folded lead/trail units
if (offset > 0) {
return m_data_[offset];
}
// return m_initialValue_ if there is an error
return m_initialValue_;
}
/**
* Get a value from a folding offset (from the value of a lead surrogate)
* and a trail surrogate.
* @param leadvalue the value of a lead surrogate that contains the
* folding offset
* @param trail surrogate
* @return trie data value associated with the trail character
* @draft 2.1
*/
public final int getTrailValue(int leadvalue, char trail)
{
if (m_dataManipulate_ == null) {
throw new NullPointerException(
"The field DataManipulate in this Trie is null");
}
return m_data_[getRawOffset(
m_dataManipulate_.getFoldingOffset(leadvalue),
(char)(trail & SURROGATE_MASK_))];
}
// protected methods -----------------------------------------------
/**
* <p>Parses the input stream and stores its trie content into a index and
* data array</p>
* @param inputStream data input stream containing trie data
* @exception IOException thrown when data reading fails
*/
protected final void unserialize(InputStream inputStream)
throws IOException
{
super.unserialize(inputStream);
// one used for initial value
m_data_ = new int[m_dataLength_];
DataInputStream input = new DataInputStream(inputStream);
for (int i = 0; i < m_dataLength_; i ++) {
m_data_[i] = input.readInt();
}
m_initialValue_ = m_data_[0];
}
/**
* Gets the offset to the data which the surrogate pair points to.
* @param lead lead surrogate
* @param trail trailing surrogate
* @return offset to data
* @draft 2.1
*/
protected final int getSurrogateOffset(char lead, char trail)
{
if (m_dataManipulate_ == null) {
throw new NullPointerException(
"The field DataManipulate in this Trie is null");
}
// get fold position for the next trail surrogate
int offset = m_dataManipulate_.getFoldingOffset(getLeadValue(lead));
// get the real data from the folded lead/trail units
if (offset > 0) {
return getRawOffset(offset, (char)(trail & SURROGATE_MASK_));
}
// return -1 if there is an error, in this case we return the default
// value: m_initialValue_
return -1;
}
/**
* Gets the value at the argument index.
* For use internally in com.ibm.icu.util.TrieEnumeration.
* @param index value at index will be retrieved
* @return 32 bit value
* @see com.ibm.icu.util.TrieEnumeration
* @draft 2.1
*/
protected final int getValue(int index)
{
return m_data_[index];
}
/**
* Gets the default initial value
* @return 32 bit value
* @draft 2.1
*/
protected final int getInitialValue()
{
return m_initialValue_;
}
// private data members --------------------------------------------
/**
* Default value
*/
private int m_initialValue_;
/**
* Array of char data
*/
private int m_data_[];
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,582 +0,0 @@
/* Generated from 'MathContext.nrx' 8 Sep 2000 11:07:48 [v2.00] */
/* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */
package com.ibm.math;
/* ------------------------------------------------------------------ */
/* MathContext -- Math context settings */
/* ------------------------------------------------------------------ */
/* Copyright IBM Corporation, 1997, 2000. All Rights Reserved. */
/* */
/* The MathContext object encapsulates the settings used by the */
/* BigDecimal class; it could also be used by other arithmetics. */
/* ------------------------------------------------------------------ */
/* Notes: */
/* */
/* 1. The properties are checked for validity on construction, so */
/* the BigDecimal class may assume that they are correct. */
/* ------------------------------------------------------------------ */
/* Author: Mike Cowlishaw */
/* 1997.09.03 Initial version (edited from netrexx.lang.RexxSet) */
/* 1997.09.12 Add lostDigits property */
/* 1998.05.02 Make the class immutable and final; drop set methods */
/* 1998.06.05 Add Round (rounding modes) property */
/* 1998.06.25 Rename from DecimalContext; allow digits=0 */
/* 1998.10.12 change to com.ibm.math package */
/* 1999.02.06 add javadoc comments */
/* 1999.03.05 simplify; changes from discussion with J. Bloch */
/* 1999.03.13 1.00 release to IBM Centre for Java Technology */
/* 1999.07.10 1.04 flag serialization unused */
/* 2000.01.01 1.06 copyright update */
/* ------------------------------------------------------------------ */
/**
* The <code>MathContext</code> immutable class encapsulates the
* settings understood by the operator methods of the {@link BigDecimal}
* class (and potentially other classes). Operator methods are those
* that effect an operation on a number or a pair of numbers.
* <p>
* The settings, which are not base-dependent, comprise:
* <ol>
* <li><code>digits</code>:
* the number of digits (precision) to be used for an operation
* <li><code>form</code>:
* the form of any exponent that results from the operation
* <li><code>lostDigits</code>:
* whether checking for lost digits is enabled
* <li><code>roundingMode</code>:
* the algorithm to be used for rounding.
* </ol>
* <p>
* When provided, a <code>MathContext</code> object supplies the
* settings for an operation directly.
* <p>
* When <code>MathContext.DEFAULT</code> is provided for a
* <code>MathContext</code> parameter then the default settings are used
* (<code>9, SCIENTIFIC, false, ROUND_HALF_UP</code>).
* <p>
* In the <code>BigDecimal</code> class, all methods which accept a
* <code>MathContext</code> object defaults) also have a version of the
* method which does not accept a MathContext parameter. These versions
* carry out unlimited precision fixed point arithmetic (as though the
* settings were (<code>0, PLAIN, false, ROUND_HALF_UP</code>).
* <p>
* The instance variables are shared with default access (so they are
* directly accessible to the <code>BigDecimal</code> class), but must
* never be changed.
* <p>
* The rounding mode constants have the same names and values as the
* constants of the same name in <code>java.math.BigDecimal</code>, to
* maintain compatibility with earlier versions of
* <code>BigDecimal</code>.
*
* @see BigDecimal
* @version 1.08 2000.06.18
* @author Mike Cowlishaw
*/
public final class MathContext implements java.io.Serializable{
private static final java.lang.String $0="MathContext.nrx";
/* ----- Properties ----- */
/* properties public constant */
/**
* Plain (fixed point) notation, without any exponent.
* Used as a setting to control the form of the result of a
* <code>BigDecimal</code> operation.
* A zero result in plain form may have a decimal part of one or
* more zeros.
*
* @see #ENGINEERING
* @see #SCIENTIFIC
*/
public static final int PLAIN=0; // [no exponent]
/**
* Standard floating point notation (with scientific exponential
* format, where there is one digit before any decimal point).
* Used as a setting to control the form of the result of a
* <code>BigDecimal</code> operation.
* A zero result in plain form may have a decimal part of one or
* more zeros.
*
* @see #ENGINEERING
* @see #PLAIN
*/
public static final int SCIENTIFIC=1; // 1 digit before .
/**
* Standard floating point notation (with engineering exponential
* format, where the power of ten is a multiple of 3).
* Used as a setting to control the form of the result of a
* <code>BigDecimal</code> operation.
* A zero result in plain form may have a decimal part of one or
* more zeros.
*
* @see #PLAIN
* @see #SCIENTIFIC
*/
public static final int ENGINEERING=2; // 1-3 digits before .
// The rounding modes match the original BigDecimal class values
/**
* Rounding mode to round to a more positive number.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If any of the discarded digits are non-zero then the result
* should be rounded towards the next more positive digit.
*/
public static final int ROUND_CEILING=2;
/**
* Rounding mode to round towards zero.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* All discarded digits are ignored (truncated). The result is
* neither incremented nor decremented.
*/
public static final int ROUND_DOWN=1;
/**
* Rounding mode to round to a more negative number.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If any of the discarded digits are non-zero then the result
* should be rounded towards the next more negative digit.
*/
public static final int ROUND_FLOOR=3;
/**
* Rounding mode to round to nearest neighbor, where an equidistant
* value is rounded down.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If the discarded digits represent greater than half (0.5 times)
* the value of a one in the next position then the result should be
* rounded up (away from zero). Otherwise the discarded digits are
* ignored.
*/
public static final int ROUND_HALF_DOWN=5;
/**
* Rounding mode to round to nearest neighbor, where an equidistant
* value is rounded to the nearest even neighbor.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If the discarded digits represent greater than half (0.5 times)
* the value of a one in the next position then the result should be
* rounded up (away from zero). If they represent less than half,
* then the result should be rounded down.
* <p>
* Otherwise (they represent exactly half) the result is rounded
* down if its rightmost digit is even, or rounded up if its
* rightmost digit is odd (to make an even digit).
*/
public static final int ROUND_HALF_EVEN=6;
/**
* Rounding mode to round to nearest neighbor, where an equidistant
* value is rounded up.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If the discarded digits represent greater than or equal to half
* (0.5 times) the value of a one in the next position then the result
* should be rounded up (away from zero). Otherwise the discarded
* digits are ignored.
*/
public static final int ROUND_HALF_UP=4;
/**
* Rounding mode to assert that no rounding is necessary.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* Rounding (potential loss of information) is not permitted.
* If any of the discarded digits are non-zero then an
* <code>ArithmeticException</code> should be thrown.
*/
public static final int ROUND_UNNECESSARY=7;
/**
* Rounding mode to round away from zero.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If any of the discarded digits are non-zero then the result will
* be rounded up (away from zero).
*/
public static final int ROUND_UP=0;
/* properties shared */
/**
* The number of digits (precision) to be used for an operation.
* A value of 0 indicates that unlimited precision (as many digits
* as are required) will be used.
* <p>
* The {@link BigDecimal} operator methods use this value to
* determine the precision of results.
* Note that leading zeros (in the integer part of a number) are
* never significant.
* <p>
* <code>digits</code> will always be non-negative.
*
* @serial
*/
int digits;
/**
* The form of results from an operation.
* <p>
* The {@link BigDecimal} operator methods use this value to
* determine the form of results, in particular whether and how
* exponential notation should be used.
*
* @see #ENGINEERING
* @see #PLAIN
* @see #SCIENTIFIC
* @serial
*/
int form; // values for this must fit in a byte
/**
* Controls whether lost digits checking is enabled for an
* operation.
* Set to <code>true</code> to enable checking, or
* to <code>false</code> to disable checking.
* <p>
* When enabled, the {@link BigDecimal} operator methods check
* the precision of their operand or operands, and throw an
* <code>ArithmeticException</code> if an operand is more precise
* than the digits setting (that is, digits would be lost).
* When disabled, operands are rounded to the specified digits.
*
* @serial
*/
boolean lostDigits;
/**
* The rounding algorithm to be used for an operation.
* <p>
* The {@link BigDecimal} operator methods use this value to
* determine the algorithm to be used when non-zero digits have to
* be discarded in order to reduce the precision of a result.
* The value must be one of the public constants whose name starts
* with <code>ROUND_</code>.
*
* @see #ROUND_CEILING
* @see #ROUND_DOWN
* @see #ROUND_FLOOR
* @see #ROUND_HALF_DOWN
* @see #ROUND_HALF_EVEN
* @see #ROUND_HALF_UP
* @see #ROUND_UNNECESSARY
* @see #ROUND_UP
* @serial
*/
int roundingMode;
/* properties private constant */
// default settings
private static final int DEFAULT_FORM=SCIENTIFIC;
private static final int DEFAULT_DIGITS=9;
private static final boolean DEFAULT_LOSTDIGITS=false;
private static final int DEFAULT_ROUNDINGMODE=ROUND_HALF_UP;
/* properties private constant */
private static final int MIN_DIGITS=0; // smallest value for DIGITS.
private static final int MAX_DIGITS=999999999; // largest value for DIGITS. If increased,
// the BigDecimal class may need update.
// list of valid rounding mode values, most common two first
private static final int ROUNDS[]=new int[]{ROUND_HALF_UP,ROUND_UNNECESSARY,ROUND_CEILING,ROUND_DOWN,ROUND_FLOOR,ROUND_HALF_DOWN,ROUND_HALF_EVEN,ROUND_UP};
private static final java.lang.String ROUNDWORDS[]=new java.lang.String[]{"ROUND_HALF_UP","ROUND_UNNECESSARY","ROUND_CEILING","ROUND_DOWN","ROUND_FLOOR","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_UP"}; // matching names of the ROUNDS values
/* properties private constant unused */
// Serialization version
private static final long serialVersionUID=7163376998892515376L;
/* properties public constant */
/**
* A <code>MathContext</code> object initialized to the default
* settings for general-purpose arithmetic. That is,
* <code>digits=9 form=SCIENTIFIC lostDigits=false
* roundingMode=ROUND_HALF_UP</code>.
*
* @see #SCIENTIFIC
* @see #ROUND_HALF_UP
*/
public static final com.ibm.math.MathContext DEFAULT=new com.ibm.math.MathContext(DEFAULT_DIGITS,DEFAULT_FORM,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
/* ----- Constructors ----- */
/**
* Constructs a new <code>MathContext</code> with a specified
* precision.
* The other settings are set to the default values
* (see {@link #DEFAULT}).
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (&lt;0 or &gt;999999999).
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
*/
public MathContext(int setdigits){
this(setdigits,DEFAULT_FORM,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
return;}
/**
* Constructs a new <code>MathContext</code> with a specified
* precision and form.
* The other settings are set to the default values
* (see {@link #DEFAULT}).
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (&lt;0 or &gt;999999999), or if the value given for the
* <code>setform</code> parameter is not one of the appropriate
* constants.
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @param setform The <code>int</code> form setting
* for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
*/
public MathContext(int setdigits,int setform){
this(setdigits,setform,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
return;}
/**
* Constructs a new <code>MathContext</code> with a specified
* precision, form, and lostDigits setting.
* The roundingMode setting is set to its default value
* (see {@link #DEFAULT}).
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (&lt;0 or &gt;999999999), or if the value given for the
* <code>setform</code> parameter is not one of the appropriate
* constants.
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @param setform The <code>int</code> form setting
* for this <code>MathContext</code>.
* @param setlostdigits The <code>boolean</code> lostDigits
* setting for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
*/
public MathContext(int setdigits,int setform,boolean setlostdigits){
this(setdigits,setform,setlostdigits,DEFAULT_ROUNDINGMODE);
return;}
/**
* Constructs a new <code>MathContext</code> with a specified
* precision, form, lostDigits, and roundingMode setting.
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (&lt;0 or &gt;999999999), or if the value given for the
* <code>setform</code> or <code>setroundingmode</code> parameters is
* not one of the appropriate constants.
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @param setform The <code>int</code> form setting
* for this <code>MathContext</code>.
* @param setlostdigits The <code>boolean</code> lostDigits
* setting for this <code>MathContext</code>.
* @param setroundingmode The <code>int</code> roundingMode setting
* for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
*/
public MathContext(int setdigits,int setform,boolean setlostdigits,int setroundingmode){super();
// set values, after checking
if (setdigits!=DEFAULT_DIGITS)
{
if (setdigits<MIN_DIGITS)
throw new java.lang.IllegalArgumentException("Digits too small:"+" "+setdigits);
if (setdigits>MAX_DIGITS)
throw new java.lang.IllegalArgumentException("Digits too large:"+" "+setdigits);
}
{/*select*/
if (setform==SCIENTIFIC)
; // [most common]
else if (setform==ENGINEERING)
;
else if (setform==PLAIN)
;
else{
throw new java.lang.IllegalArgumentException("Bad form value:"+" "+setform);
}
}
if ((!(isValidRound(setroundingmode))))
throw new java.lang.IllegalArgumentException("Bad roundingMode value:"+" "+setroundingmode);
digits=setdigits;
form=setform;
lostDigits=setlostdigits; // [no bad value possible]
roundingMode=setroundingmode;
return;}
/**
* Returns the digits setting.
* This value is always non-negative.
*
* @return an <code>int</code> which is the value of the digits
* setting
*/
public int getDigits(){
return digits;
}
/**
* Returns the form setting.
* This will be one of
* {@link #ENGINEERING},
* {@link #PLAIN}, or
* {@link #SCIENTIFIC}.
*
* @return an <code>int</code> which is the value of the form setting
*/
public int getForm(){
return form;
}
/**
* Returns the lostDigits setting.
* This will be either <code>true</code> (enabled) or
* <code>false</code> (disabled).
*
* @return a <code>boolean</code> which is the value of the lostDigits
* setting
*/
public boolean getLostDigits(){
return lostDigits;
}
/**
* Returns the roundingMode setting.
* This will be one of
* {@link #ROUND_CEILING},
* {@link #ROUND_DOWN},
* {@link #ROUND_FLOOR},
* {@link #ROUND_HALF_DOWN},
* {@link #ROUND_HALF_EVEN},
* {@link #ROUND_HALF_UP},
* {@link #ROUND_UNNECESSARY}, or
* {@link #ROUND_UP}.
*
* @return an <code>int</code> which is the value of the roundingMode
* setting
*/
public int getRoundingMode(){
return roundingMode;
}
/** Returns the <code>MathContext</code> as a readable string.
* The <code>String</code> returned represents the settings of the
* <code>MathContext</code> object as four blank-delimited words
* separated by a single blank and with no leading or trailing blanks,
* as follows:
* <ol>
* <li>
* <code>digits=</code>, immediately followed by
* the value of the digits setting as a numeric word.
* <li>
* <code>form=</code>, immediately followed by
* the value of the form setting as an uppercase word
* (one of <code>SCIENTIFIC</code>, <code>PLAIN</code>, or
* <code>ENGINEERING</code>).
* <li>
* <code>lostDigits=</code>, immediately followed by
* the value of the lostDigits setting
* (<code>1</code> if enabled, <code>0</code> if disabled).
* <li>
* <code>roundingMode=</code>, immediately followed by
* the value of the roundingMode setting as a word.
* This word will be the same as the name of the corresponding public
* constant.
* </ol>
* <p>
* For example:
* <br><code>
* digits=9 form=SCIENTIFIC lostDigits=0 roundingMode=ROUND_HALF_UP
* </code>
* <p>
* Additional words may be appended to the result of
* <code>toString</code> in the future if more properties are added
* to the class.
*
* @return a <code>String</code> representing the context settings.
*/
public java.lang.String toString(){
java.lang.String formstr=null;
int r=0;
java.lang.String roundword=null;
{/*select*/
if (form==SCIENTIFIC)
formstr="SCIENTIFIC";
else if (form==ENGINEERING)
formstr="ENGINEERING";
else{
formstr="PLAIN";/* form=PLAIN */
}
}
{int $1=ROUNDS.length;r=0;r:for(;$1>0;$1--,r++){
if (roundingMode==ROUNDS[r])
{
roundword=ROUNDWORDS[r];
break r;
}
}
}/*r*/
return "digits="+digits+" "+"form="+formstr+" "+"lostDigits="+(lostDigits?"1":"0")+" "+"roundingMode="+roundword;
}
/* <sgml> Test whether round is valid. </sgml> */
// This could be made shared for use by BigDecimal for setScale.
private static boolean isValidRound(int testround){
int r=0;
{int $2=ROUNDS.length;r=0;r:for(;$2>0;$2--,r++){
if (testround==ROUNDS[r])
return true;
}
}/*r*/
return false;
}
}

View File

@ -1,19 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head><!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/math/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/04/05 18:05:11 $
-->
<title>C:\cvs\icu4j\src\com\ibm\demo\package.html</title>
</head>
<body bgcolor="white">
<p>IBM BigDecimal support.</p>
</body>
</html>

View File

@ -1,44 +0,0 @@
/*
* @(#)$RCSfile: Declaration.java,v $ $Revision: 1.1 $ $Date: 2000/04/20 17:46:57 $
*
* (C) Copyright IBM Corp. 1998-1999. All Rights Reserved.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/
package com.ibm.richtext.tests;
import com.ibm.richtext.styledtext.MConstText;
import com.ibm.richtext.styledtext.StyledText;
import com.ibm.textlayout.attributes.AttributeMap;
/**
* This class contains the first four paragraphs of the Declaration
* of Independence, as both styled and unstyled text. The views
* expressed therein are not necessarily those of the programmer or of
* his/her employer. No criticism of any monarchy, oligarchy, dictatorship,
* autocracy, plutocracy, theocracy, anarchist territory, colonial power,
* or any other nondemocratic form of government is intended. This document
* is provided "as-is" without any warranty expressed or implied.
*/
public final class Declaration {
static final String COPYRIGHT =
"(C) Copyright IBM Corp. 1998-1999 - All Rights Reserved";
public static final String fgDeclarationStr = "In Congress, July 4, 1776, THE UNANIMOUS DECLARATION OF THE THIRTEEN UNITED STATES OF AMERICA\n" +
"\n" +
"When in the Course of human Events, it becomes necessary for one People to dissolve the Political Bands which have connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the Laws of Nature and of Nature's God entitle them, a decent Respect to the Opinions of Mankind requires that they should declare the causes which impel them to the Separation.\n" +
"\n" +
"We hold these Truths to be self-evident, that all Men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the Pursuit of Happiness.\n" +
"\n" +
"That to secure these Rights, Governments are instituted among Men, deriving their just Powers from the Consent of the Governed, that whenever any Form of Government becomes destructive of these Ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its Foundation on such Principles, and organizing its Powers in such Form, as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments long established should not be changed for light and transient Causes; and accordingly all Experience hath shewn, that Mankind are more disposed to suffer, while Evils are sufferable, than to right themselves by abolishing the Forms to which they are accustomed. But when a long Train of Abuses and Usurpations, pursuing invariably the same Object, evinces a Design to reduce them under absolute Despotism, it is their Right, it is their Duty, to throw off such Government, and to provide new Guards for their future Security.\n" +
"\n";
public static final MConstText fgDeclaration = new StyledText(fgDeclarationStr, AttributeMap.EMPTY_ATTRIBUTE_MAP);
}

View File

@ -1,214 +0,0 @@
/*
* @(#)$RCSfile: ITestTextPanel.java,v $ $Revision: 1.2 $ $Date: 2000/04/22 03:31:34 $
*
* (C) Copyright IBM Corp. 1998-1999. All Rights Reserved.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/
package com.ibm.richtext.tests;
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.util.Date;
import java.text.DateFormat;
import com.ibm.richtext.textpanel.MTextPanel;
import com.ibm.richtext.textpanel.TextPanel;
import com.ibm.richtext.awtui.TextFrame;
public class ITestTextPanel extends Frame implements ActionListener {
static final String COPYRIGHT =
"(C) Copyright IBM Corp. 1998-1999 - All Rights Reserved";
private static long fgOpCount = 0;
private TestTextPanel fTest;
private MTextPanel fTextPanel;
private Frame fTextFrame;
private Clipboard fClipboard;
private Button fExersize, fStressTest, fResize;
public static void main(String[] args) {
Date startDate = new Date();
try {
Clipboard clipboard = new Clipboard("ITextTestPanel");
TextFrame frame = new TextFrame(null, "Interactive Test", clipboard);
MTextPanel panel = frame.getTextPanel();
new ITestTextPanel(panel, frame, clipboard).show();
}
finally {
DateFormat df = DateFormat.getDateTimeInstance();
System.out.println("Start time: " + df.format(startDate));
System.out.println("End Time: " + df.format(new Date()));
System.out.println("Op count: " + fgOpCount);
}
}
public ITestTextPanel(MTextPanel panel,
Frame frame,
Clipboard clipboard) {
fTextPanel = panel;
fTest = new TestTextPanel(fTextPanel);
fClipboard = clipboard;
setLayout(new GridLayout(0, 1));
fTextFrame = frame;
fTextFrame.setSize(350, 500);
fTextFrame.show();
// initialize UI:
fExersize = new Button("Exercise");
fExersize.addActionListener(this);
add(fExersize);
fStressTest = new Button("Stress Test");
fStressTest.addActionListener(this);
add(fStressTest);
pack();
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
//activateTextFrame();
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setSize(280, 150);
}
private void activateTextFrame() {
fTextFrame.toFront();
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
activateTextFrame();
Date startDate = new Date();
boolean exitedNormally = false;
try {
if (source == fExersize) {
fTest.incRandSeed();
for (int i=0; i < 100; i++) {
selectOperation(fTextFrame, fClipboard);
}
}
else if (source == fStressTest) {
fTest.incRandSeed();
while (true) {
selectOperation(fTextFrame, fClipboard);
}
}
exitedNormally = true;
}
finally {
if (!exitedNormally) {
DateFormat df = DateFormat.getDateTimeInstance();
System.out.println("Start time: " + df.format(startDate));
System.out.println("End Time: " + df.format(new Date()));
System.out.println("Rand seed: " + fTest.getRandSeed());
System.out.println("Op count: " + fgOpCount);
}
}
}
/**
* Perform a random operation on the MTextPanel. Frame can
* be null.
*/
private static final int OP_COUNT = 15;
public void selectOperation(Frame frame,
Clipboard fClipboard) {
int op = fTest.randInt(OP_COUNT);
switch (op) {
case 0:
fTest._testSetSelection();
break;
case 1:
fTest._testModifications(fTest.MOD_TEXT,
true);
break;
case 2:
fTest._testEditMenuOperations(fClipboard);
break;
case 3:
fTest._testModFlag(fTextPanel.getCommandLogSize());
break;
case 4:
fTest.applyCharacterStyle();
break;
case 5:
fTest.applyParagraphStyle();
break;
case 6:
case 7:
case 8:
case 9:
fTest.typeKeys();
break;
case 10:
fTest.selectText();
break;
case 11:
fTest.undoRedo();
break;
case 12:
//if (frame != null) {
// fTest.resizeFrame(frame);
// break;
//}
case 13:
fTest.applyKeyRemap();
break;
case 14:
fTest._testCommandLogControl();
break;
default:
throw new Error("OP_COUNT is incorrect");
}
fgOpCount++;
}
}

View File

@ -1,846 +0,0 @@
/*
* @(#)$RCSfile: TestTextPanel.java,v $ $Revision: 1.7 $ $Date: 2000/04/24 21:11:45 $
*
* (C) Copyright IBM Corp. 1998-1999. All Rights Reserved.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/
package com.ibm.richtext.tests;
import java.util.Random;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import com.ibm.richtext.textpanel.KeyRemap;
import com.ibm.richtext.textpanel.KeyEventForwarder;
import com.ibm.richtext.textpanel.MTextPanel;
import com.ibm.richtext.textpanel.TextPanel;
import com.ibm.richtext.textpanel.TextPanelEvent;
import com.ibm.richtext.textpanel.TextPanelListener;
import com.ibm.richtext.styledtext.MConstText;
import com.ibm.richtext.styledtext.StyledText;
import com.ibm.textlayout.attributes.TextAttribute;
import com.ibm.textlayout.attributes.AttributeMap;
import com.ibm.richtext.styledtext.StyleModifier;
import com.ibm.textlayout.attributes.AttributeSet;
import com.ibm.textlayout.attributes.TextAttribute;
import com.ibm.textlayout.attributes.AttributeMap;
// Note: this used to be a TestFmwk test. If you add
// more tests to it, be sure to add them to
// com.ibm.test.richtext.FmwkTestTextPanel.test() -
// otherwise they won't get run!
public class TestTextPanel /*extends TestFmwk*/ {
private final class TestListener implements TextPanelListener {
private int NO_WAY = 0;
private int DEFINITELY = 1;
private int MAYBE = 2;
private final int[] status;
TestListener(MTextPanel textPanel) {
int length = TextPanelEvent.TEXT_PANEL_LAST -
TextPanelEvent.TEXT_PANEL_FIRST + 1;
status = new int[length];
textPanel.addListener(this);
allowAll();
}
void refuseAll() {
for (int i=0; i < status.length; i++) {
status[i] = NO_WAY;
}
}
void allowAll() {
for (int i=0; i < status.length; i++) {
status[i] = MAYBE;
}
}
void expectEvent(int type) {
int index = type - TextPanelEvent.TEXT_PANEL_FIRST;
status[index] = DEFINITELY;
}
void allowEvent(int type) {
int index = type - TextPanelEvent.TEXT_PANEL_FIRST;
status[index] = MAYBE;
}
void assertNotExpectingEvents() {
assertNotExpectingEvents(false, 0, false);
}
void assertNotExpectingEvents(int iterationCount, boolean exp) {
assertNotExpectingEvents(true, iterationCount, exp);
}
private void assertNotExpectingEvents(boolean logDetails, int iterationCount, boolean exp) {
boolean e = false;
for (int i=0; i < status.length; i++) {
if (status[i] == DEFINITELY) {
if (logDetails) {
logMessage("Expecting event " +
(i+TextPanelEvent.TEXT_PANEL_FIRST));
logMessage("iterationCount="+iterationCount+"; expexting="+exp);
}
e = true;
}
}
if (e) {
reportError("Some events pending");
}
}
public void textEventOccurred(TextPanelEvent event) {
int index = event.getID() - TextPanelEvent.TEXT_PANEL_FIRST;
if (status[index] == NO_WAY) {
reportError("Unexpected event: " + event);
}
else if (status[index] == DEFINITELY) {
status[index] = NO_WAY;
}
}
public boolean respondsToEventType(int type) {
return true;
}
}
static final String COPYRIGHT =
"(C) Copyright IBM Corp. 1998-1999 - All Rights Reserved";
private static final String STRING_CONTENT = "Some content";
private static final int TEST_ITERS = 2;
public static final MConstText MOD_TEXT =
new StyledText("Styled", AttributeMap.EMPTY_ATTRIBUTE_MAP);
private Clipboard fClipboard;
private MTextPanel fTextPanel = null;
private TestListener fListener = null;
private int fRandSeed = 0;
private Random rand;
private static final int BIG_COMMAND_LOG_SIZE = 40;
private static final int SMALL_COMMAND_LOG_SIZE = 8;
private static final StyleModifier[] paraMods = {
StyleModifier.createAddModifier(
new AttributeMap(TextAttribute.LINE_FLUSH,
TextAttribute.FLUSH_LEADING)),
StyleModifier.createAddModifier(TextAttribute.LINE_FLUSH,
TextAttribute.FLUSH_CENTER),
StyleModifier.createAddModifier(TextAttribute.LINE_FLUSH,
TextAttribute.FLUSH_TRAILING),
StyleModifier.createAddModifier(TextAttribute.LINE_FLUSH,
TextAttribute.FULLY_JUSTIFIED),
StyleModifier.createAddModifier(TextAttribute.RUN_DIRECTION,
TextAttribute.RUN_DIRECTION_RTL),
StyleModifier.createAddModifier(TextAttribute.RUN_DIRECTION,
TextAttribute.RUN_DIRECTION_LTR),
StyleModifier.createRemoveModifier(
new AttributeSet(TextAttribute.LINE_FLUSH)),
StyleModifier.createRemoveModifier(
new AttributeSet(TextAttribute.RUN_DIRECTION))
};
private static final int SELECT = 0;
private static final int SET_CARET_POS = 1;
private static final int SET_START = 2;
private static final int SET_END = 3;
// using both styles of add modifier: AttributeMap and
// key-value, just for variety...
private static final StyleModifier[] charMods = {
StyleModifier.createAddModifier(
new AttributeMap(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD)),
StyleModifier.createAddModifier(TextAttribute.FOREGROUND,
Color.green),
StyleModifier.createAddModifier(
new AttributeMap(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON).addAttributes(
new AttributeMap(TextAttribute.SIZE, new Float(6)))),
StyleModifier.createReplaceModifier(
new AttributeMap(TextAttribute.FAMILY, "Dialog")),
StyleModifier.createRemoveModifier(
new AttributeSet(
new Object[] { TextAttribute.WEIGHT,
TextAttribute.POSTURE,
TextAttribute.UNDERLINE,
TextAttribute.STRIKETHROUGH,
TextAttribute.SUPERSCRIPT })),
StyleModifier.IDENTITY
};
private static final char[] TYPED_CHARS = new char[128 - ' ' + 3];
static {
TYPED_CHARS[0] = 8; // backspace
TYPED_CHARS[1] = '\t';
TYPED_CHARS[2] = '\n';
for (int i=3; i < TYPED_CHARS.length; i++) {
TYPED_CHARS[i] = (char) (' ' + i - 3);
}
}
public TestTextPanel() {
fClipboard = new Clipboard("TestTextPanel");
incRandSeed();
}
protected void reportError(String message) {
System.err.println(message);
throw new RuntimeException(message);
//super.errln(message);
}
protected void logMessage(String message) {
System.err.println(message);
//super.logMessage(message);
}
public TestTextPanel(MTextPanel panel) {
this();
setTextPanel(panel);
}
void incRandSeed() {
rand = new Random(++fRandSeed);
}
int getRandSeed() {
return fRandSeed;
}
int randInt(int limit) {
return randInt(0, limit);
}
int randInt(int start, int limit) {
if (start > limit) {
throw new IllegalArgumentException("Range is 0-length.");
}
else if (start == limit) {
return start;
}
return start + (Math.abs(rand.nextInt())%(limit-start)) ;
}
public void test() {
AttributeMap bold = new AttributeMap(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD);
MConstText text1 = new StyledText("Test contents. 1234\nHow about it?",
AttributeMap.EMPTY_ATTRIBUTE_MAP);
MConstText text2 = new StyledText("Another test string.", bold);
_testWithText(text1);
_testWithText(text2);
_testWithText(new StyledText());
StyledText big1 = new StyledText();
for (int i=0; i < 50; i++) {
big1.append(text1);
}
_testWithText(big1);
StyledText big2 = new StyledText(text1);
for (int i=0; i < 80; i++) {
big2.append(text2);
}
_testWithText(big2);
}
private void setTextPanel(MTextPanel panel) {
fTextPanel = panel;
fListener = new TestListener(panel);
}
private void _testWithText(MConstText text) {
setTextPanel(new TextPanel(text, fClipboard));
for (int i=0; i < TEST_ITERS; i++) {
_testSetSelection();
_testModifications(MOD_TEXT, true);
_testEditMenuOperations(fClipboard);
_testModFlag(fTextPanel.getCommandLogSize());
_testCommandLogControl();
}
}
private void _testSelection(int function,
final int aStart,
final int aLimit) {
int oldStart = fTextPanel.getSelectionStart();
int oldLimit = fTextPanel.getSelectionEnd();
final int length = fTextPanel.getTextLength();
int start = aStart;
int limit = aLimit;
if (start < 0) {
start = 0;
}
else if (start > length) {
start = length;
}
if (limit < start) {
limit = start;
}
else if (limit > length) {
limit = length;
}
fListener.refuseAll();
if (oldStart != start || oldLimit != limit) {
fListener.expectEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
fListener.allowEvent(TextPanelEvent.SELECTION_STYLES_CHANGED);
}
if ((oldStart==oldLimit) != (start==limit)) {
fListener.expectEvent(TextPanelEvent.SELECTION_EMPTY_CHANGED);
}
if (oldStart==oldLimit) {
fListener.allowEvent(TextPanelEvent.UNDO_STATE_CHANGED);
}
switch(function) {
case SELECT:
fTextPanel.select(aStart, aLimit);
break;
case SET_CARET_POS:
fTextPanel.setCaretPosition(aStart);
break;
case SET_START:
fTextPanel.setSelectionStart(aStart);
break;
case SET_END:
fTextPanel.setSelectionEnd(aLimit);
break;
default:
throw new IllegalArgumentException("Invalid function");
}
if (fTextPanel.getSelectionStart() != start) {
reportError("getSelectionStart is incorrect after set");
}
if (fTextPanel.getSelectionEnd() != limit) {
reportError("getSelectionEnd is incorrect after set");
}
fListener.assertNotExpectingEvents();
fListener.allowAll();
}
private void setAndTestSelection(int start, int limit) {
_testSelection(SELECT, start, limit);
}
private void setAndTestCaret(int caretPos) {
_testSelection(SET_CARET_POS, caretPos, caretPos);
}
private void setAndTestSelectionStart(int selStart) {
int limit = fTextPanel.getSelectionEnd();
_testSelection(SET_START, selStart, limit);
}
private void setAndTestSelectionEnd(int selEnd) {
int start = fTextPanel.getSelectionStart();
_testSelection(SET_END, start, selEnd);
}
public void _testSetSelection() {
int textLength = fTextPanel.getTextLength();
if (textLength != fTextPanel.getText().length()) {
reportError("Text panel length is not correct");
}
setAndTestSelection(0, textLength / 2);
setAndTestSelection(textLength / 2, textLength);
setAndTestSelection(0, textLength);
setAndTestSelection(-1, textLength+1);
if (textLength > 0) {
setAndTestSelection(0, textLength - 1);
setAndTestSelection(0, 1);
}
final int incAmount = Math.max(1, textLength/5);
for (int index = 0; index <= textLength; index += incAmount) {
setAndTestCaret(index);
setAndTestSelectionStart(textLength-index);
setAndTestSelectionEnd(textLength);
setAndTestSelectionStart(0);
setAndTestSelectionEnd(textLength-index);
}
}
/**
* Text must be editable to pass this test.
*/
public void _testModifications(MConstText insertionText,
boolean restoreOldText) {
MConstText oldText = new StyledText(fTextPanel.getText());
final int insLength = insertionText.length();
fListener.allowAll();
fListener.expectEvent(TextPanelEvent.TEXT_CHANGED);
fListener.expectEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
fTextPanel.append(insertionText);
fListener.assertNotExpectingEvents();
if (fTextPanel.getSelectionStart() != oldText.length() + insLength) {
reportError("Append didn't result in correct selection");
}
fListener.expectEvent(TextPanelEvent.TEXT_CHANGED);
fListener.expectEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
fTextPanel.insert(insertionText, 0);
fListener.assertNotExpectingEvents();
fListener.allowAll();
if (fTextPanel.getSelectionStart() != insLength) {
reportError("Insert didn't result in correct selection");
}
fTextPanel.replaceRange(insertionText, insLength, insLength+oldText.length());
if (fTextPanel.getSelectionStart() != insLength*2) {
reportError("Replace didn't result in correct selection");
}
if (fTextPanel.getSelectionEnd() != insLength*2) {
reportError("Replace didn't result in correct selection");
}
if (fTextPanel.getTextLength() != insLength*3) {
reportError("textLength is incorrect");
}
if (restoreOldText) {
fTextPanel.setText(oldText);
if (fTextPanel.getSelectionStart() != oldText.length()) {
reportError("setText didn't result in correct selection");
}
if (fTextPanel.getTextLength() != oldText.length()) {
reportError("length incorrect after setText");
}
}
fListener.allowAll();
}
private static int iterationCount = 0;
public void _testCommandLogControl() {
fListener.refuseAll();
iterationCount++;
boolean exp = false;
if (fTextPanel.canRedo() || BIG_COMMAND_LOG_SIZE==0) {
fListener.expectEvent(TextPanelEvent.UNDO_STATE_CHANGED);
exp = true;
}
//try {
fTextPanel.setCommandLogSize(BIG_COMMAND_LOG_SIZE);
if (fTextPanel.canRedo()) {
reportError("canRedo after setCommandLogSize");
}
fListener.assertNotExpectingEvents(iterationCount, exp);
//}
//catch(Error e) {
// logMessage("iterationCount="+iterationCount+"; expexting="+exp);
// throw e;
//}
MConstText insText = new StyledText("7",
AttributeMap.EMPTY_ATTRIBUTE_MAP);
final int origLength = fTextPanel.getTextLength();
int start = origLength / 3;
fListener.allowEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
fListener.allowEvent(TextPanelEvent.SELECTION_STYLES_CHANGED);
for (int i=start; i < BIG_COMMAND_LOG_SIZE+start; i++) {
fListener.expectEvent(TextPanelEvent.UNDO_STATE_CHANGED);
fListener.expectEvent(TextPanelEvent.TEXT_CHANGED);
if (fTextPanel.getSelectionStart() != fTextPanel.getSelectionEnd()) {
fListener.expectEvent(TextPanelEvent.SELECTION_EMPTY_CHANGED);
}
fTextPanel.insert(insText, i);
fListener.assertNotExpectingEvents();
}
fListener.allowEvent(TextPanelEvent.SELECTION_EMPTY_CHANGED);
for (int i=0; i < BIG_COMMAND_LOG_SIZE-1; i++) {
fListener.expectEvent(TextPanelEvent.UNDO_STATE_CHANGED);
fListener.expectEvent(TextPanelEvent.TEXT_CHANGED);
fTextPanel.undo();
fListener.assertNotExpectingEvents();
}
if (!fTextPanel.canUndo()) {
reportError("Command log is too small");
}
fListener.allowAll();
fTextPanel.undo();
if (fTextPanel.canUndo()) {
reportError("Command log is too large");
}
if (fTextPanel.getTextLength() != origLength * insText.length()) {
reportError("Text length was not restored");
}
for (int i=0; i < BIG_COMMAND_LOG_SIZE; i++) {
fTextPanel.redo();
}
if (fTextPanel.getTextLength() != origLength+BIG_COMMAND_LOG_SIZE) {
reportError("Text length was not restored after redo");
}
if (fTextPanel.canRedo()) {
reportError("Should not be able to redo");
}
fTextPanel.undo();
fTextPanel.setCommandLogSize(SMALL_COMMAND_LOG_SIZE);
if (fTextPanel.canRedo()) {
reportError("canRedo after setCommandLogSize(small)");
}
for (int i=0; i < SMALL_COMMAND_LOG_SIZE; i++) {
if (!fTextPanel.canUndo()) {
reportError("should be able to undo");
}
fTextPanel.undo();
}
if (fTextPanel.canUndo()) {
reportError("should not be able to undo after setCommandLogSize(small)");
}
if (!fTextPanel.canRedo()) {
reportError("why can't this redo???");
}
fTextPanel.redo();
fTextPanel.clearCommandLog();
if (fTextPanel.canUndo() || fTextPanel.canRedo()) {
reportError("Command log wasn't cleared");
}
}
/**
* Test cut, copy, paste, undo, redo, clear, canUndo, canRedo.
* Text must be editable to pass this test.
*/
public void _testEditMenuOperations(Clipboard clipboard) {
if (clipboard != null) {
// test paste and undo / redo
Transferable tr = new StringSelection(STRING_CONTENT);
clipboard.setContents(tr, new ClipboardOwner() {
public void lostOwnership(Clipboard c, Transferable t) {
}
});
if (!fTextPanel.clipboardNotEmpty()) {
reportError("MTextPanel doesn't recognize string content.");
}
fTextPanel.setCaretPosition(fTextPanel.getSelectionStart());
int oldLength = fTextPanel.getTextLength();
fTextPanel.paste();
if (fTextPanel.getTextLength() != oldLength + STRING_CONTENT.length()) {
reportError("Text length is wrong after paste.");
}
if (!fTextPanel.canUndo()) {
reportError("canUndo should be true");
}
fTextPanel.undo();
if (fTextPanel.getTextLength() != oldLength) {
reportError("Length is wrong after undo");
}
if (!fTextPanel.canRedo()) {
reportError("canRedo should be true");
}
fTextPanel.redo();
if (fTextPanel.getTextLength() != oldLength + STRING_CONTENT.length()) {
reportError("Text length is wrong after redo.");
}
}
int origLength = fTextPanel.getTextLength();
fTextPanel.selectAll();
fTextPanel.clear();
if (fTextPanel.getTextLength() != 0) {
reportError("Length is nonzero after clear");
}
if (!fTextPanel.canUndo()) {
reportError("canUndo should be true");
}
fTextPanel.undo();
if (fTextPanel.getTextLength() != origLength) {
reportError("Old text not restored");
}
if (origLength > 0) {
fTextPanel.select(0, 1);
fTextPanel.cut();
if (fTextPanel.getTextLength() != origLength-1) {
reportError("Length wrong after cut");
}
fTextPanel.paste();
if (fTextPanel.getTextLength() != origLength) {
reportError("Length wrong after paste");
}
fTextPanel.select(0, origLength);
fTextPanel.copy();
fTextPanel.setCaretPosition(0);
fTextPanel.paste();
if (fTextPanel.getTextLength() != 2*origLength) {
reportError("Length wrong after paste");
}
fTextPanel.undo();
if (fTextPanel.getTextLength() != origLength) {
reportError("Length wrong after undo");
}
}
}
private void setAndTestModFlag(final int depth,
boolean modified) {
fTextPanel.setModified(modified);
for (int i=0; i < depth; i++) {
if (!fTextPanel.canUndo()) {
reportError("Panel cannot undo at valid depth. Depth=" + i);
}
fTextPanel.undo();
fTextPanel.setModified(modified);
}
// check that all mod flags are false:
if (fTextPanel.isModified() != modified) {
reportError("isModified is not correct");
}
for (int i=0; i < depth; i++) {
fTextPanel.redo();
if (fTextPanel.isModified() != modified) {
reportError("isModified is not correct");
}
}
}
/**
* Make <code>depth</code> modifications to the text in textfTextPanel.
* Set the modified flag on each operation, and then retrieve its
* value. Finally, undo the modifications.
*/
public void _testModFlag(final int depth) {
final int oldLength = fTextPanel.getTextLength();
for (int i=0; i < depth; i++) {
fTextPanel.insert(MOD_TEXT, 0);
}
setAndTestModFlag(depth, false);
setAndTestModFlag(depth, true);
for (int i=0; i < depth; i++) {
fTextPanel.undo();
}
if (fTextPanel.getTextLength() != oldLength) {
reportError("Undo did not restore old text.");
}
}
void applyCharacterStyle() {
StyleModifier stMod = charMods[randInt(charMods.length)];
fListener.refuseAll();
fListener.expectEvent(TextPanelEvent.SELECTION_STYLES_CHANGED);
if (fTextPanel.getSelectionStart() != fTextPanel.getSelectionEnd()) {
fListener.expectEvent(TextPanelEvent.TEXT_CHANGED);
fListener.allowEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
}
fListener.allowEvent(TextPanelEvent.UNDO_STATE_CHANGED);
fTextPanel.modifyCharacterStyleOnSelection(stMod);
fListener.assertNotExpectingEvents();
fListener.allowAll();
}
void applyParagraphStyle() {
fListener.refuseAll();
fListener.expectEvent(TextPanelEvent.SELECTION_STYLES_CHANGED);
fListener.expectEvent(TextPanelEvent.TEXT_CHANGED);
fListener.allowEvent(TextPanelEvent.UNDO_STATE_CHANGED);
fListener.allowEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
StyleModifier stMod = paraMods[randInt(paraMods.length)];
fTextPanel.modifyParagraphStyleOnSelection(stMod);
fListener.assertNotExpectingEvents();
fListener.allowAll();
}
void applyKeyRemap() {
fListener.refuseAll();
fListener.expectEvent(TextPanelEvent.KEYREMAP_CHANGED);
int op = randInt(5);
switch (op) {
case 0:
fTextPanel.setKeyRemap(KeyRemap.getIdentityRemap());
break;
case 1:
fTextPanel.setKeyRemap(KeyRemap.getArabicTransliteration());
break;
case 2:
fTextPanel.setKeyRemap(KeyRemap.getHebrewTransliteration());
break;
case 3:
fTextPanel.setKeyRemap(KeyRemap.getIsraelNikud());
break;
case 4:
//fTextPanel.setKeyRemap(KeyRemap.getThaiKetmanee());
fTextPanel.setKeyRemap(KeyRemap.getIsraelNikud());
break;
default:
reportError("Invalid operation!");
}
fListener.assertNotExpectingEvents();
fListener.allowAll();
}
void resizeFrame(Frame frame) {
fListener.refuseAll();
fListener.allowEvent(TextPanelEvent.FORMAT_WIDTH_CHANGED);
int wd = randInt(50, 1000);
int ht = randInt(20, 800);
frame.setSize(wd, ht);
fListener.allowAll();
}
void selectText() {
int selStart = randInt(-10, fTextPanel.getTextLength());
int selLimit = randInt(0, fTextPanel.getTextLength() + 10);
_testSelection(SELECT, selStart, selLimit);
}
void undoRedo() {
final int opCount = randInt(-10, 15);
for (int i=opCount; i <= 0; i++) {
fTextPanel.redo();
}
for (int i=0; i < opCount; i++) {
fTextPanel.undo();
}
}
void typeKeys() {
final int keyCount = randInt(1, 100);
TextPanel textPanel = (TextPanel) fTextPanel;
KeyEventForwarder forwarder = new KeyEventForwarder(textPanel);
fListener.refuseAll();
fListener.allowEvent(TextPanelEvent.UNDO_STATE_CHANGED);
if (fTextPanel.getSelectionStart() != fTextPanel.getSelectionEnd()) {
fListener.expectEvent(TextPanelEvent.SELECTION_EMPTY_CHANGED);
}
for (int i=0; i < keyCount; i++) {
char typedChar = TYPED_CHARS[randInt(TYPED_CHARS.length)];
KeyEvent event = new KeyEvent(textPanel,
KeyEvent.KEY_TYPED,
0,
0,
KeyEvent.VK_UNDEFINED,
typedChar);
if (typedChar == 8 || typedChar == 0x7f) {
fListener.allowEvent(TextPanelEvent.TEXT_CHANGED);
fListener.allowEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
}
else {
fListener.expectEvent(TextPanelEvent.TEXT_CHANGED);
fListener.expectEvent(TextPanelEvent.SELECTION_RANGE_CHANGED);
}
forwarder.handleKeyEvent(event);
//try {
fListener.assertNotExpectingEvents(i, false);
//}
//catch(Error e) {
// logMessage("i="+i+"; typedChar="+Integer.toHexString(typedChar));
// throw e;
//}
}
fListener.allowAll();
}
}

View File

@ -1,242 +0,0 @@
/*
* @(#)$RCSfile: TypingPerfTest.java,v $ $Revision: 1.3 $ $Date: 2001/09/08 01:14:52 $
*
* (C) Copyright IBM Corp. 1998-1999. All Rights Reserved.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/
package com.ibm.richtext.tests;
import java.awt.Button;
import java.awt.GridLayout;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import com.ibm.richtext.textpanel.KeyEventForwarder;
import com.ibm.richtext.textpanel.TextPanel;
import com.ibm.richtext.awtui.TextFrame;
import com.ibm.richtext.styledtext.MConstText;
import com.ibm.richtext.demo.EditDemo;
import com.ibm.richtext.demo.TextDocument;
public class TypingPerfTest implements ActionListener {
static final String COPYRIGHT =
"(C) Copyright IBM Corp. 1998-1999 - All Rights Reserved";
private TextFrame fTextFrame;
private KeyEventForwarder fKeyEventForwarder;
private PrintWriter fOut;
private static final String fgAtStartCommand = "Insert at start";
private static final String fgAtEndCommand = "Insert at end";
private static final String fgFwdDelete = "Forward delete";
private static final String fgBackspace = "Backspace";
private static final String fgAtCurrentPosCommand = "Insert at current position";
private static final String fgLotsOfTextCommand = "Insert a lot of text";
private static final String USAGE = "Usage: java com.ibm.richtext.tests.TypingPerfTest [file] [-insertionText text]";
private char[] fInsText;
public static void main(String[] args) throws IOException {
// not used OutputStream outStream = null;
PrintWriter writer = new PrintWriter(System.out);
MConstText text = Declaration.fgDeclaration;
char[] insText = "The quick brown fox jumps over the lazy dog. The end. ".toCharArray();
int index = 0;
while (index < args.length) {
if (args[index].equals("-insertionText")) {
if (args.length == ++index) {
throw new Error(USAGE);
}
insText = args[index++].toCharArray();
}
else {
// This will try MConstText first, then plain text.
TextDocument doc = EditDemo.getDocumentFromFile(new File(args[index++]));
if (doc == null) {
throw new Error("Couldn't open file "+args[index-1]);
}
text = doc.getText();
}
}
if (index != args.length) {
throw new Error(USAGE);
}
new TypingPerfTest(writer, text, insText);
}
public TypingPerfTest(PrintWriter out, MConstText text, char[] insText) throws IOException {
fInsText = insText;
fTextFrame = new TextFrame(text, "", null);
TextPanel textPanel = (TextPanel) fTextFrame.getTextPanel();
fKeyEventForwarder = new KeyEventForwarder(textPanel);
fOut = out;
DateFormat df = DateFormat.getDateTimeInstance();
out.println("Test date: " + df.format(new Date()));
fTextFrame.setSize(500, 700);
fTextFrame.show();
Frame f = new Frame("Typing Perf Test");
f.setLayout(new GridLayout(0, 1));
Button b;
/*
b = new Button(fgAtStartCmd);
b.addActionListener(this);
f.add(b);
b = new Button(fgAtEndCmd);
b.addActionListener(this);
f.add(b);
*/
b = new Button(fgAtCurrentPosCommand);
b.addActionListener(this);
f.add(b);
b = new Button(fgLotsOfTextCommand);
b.addActionListener(this);
f.add(b);
b = new Button(fgFwdDelete);
b.addActionListener(this);
f.add(b);
b = new Button(fgBackspace);
b.addActionListener(this);
f.add(b);
f.doLayout();
WindowAdapter closer = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
fOut.close();
System.exit(0);
}
};
f.addWindowListener(closer);
fTextFrame.addWindowListener(closer);
f.setSize(200, 80);
f.show();
}
public void actionPerformed(ActionEvent evt) {
try {
if (evt.getActionCommand().equals(fgAtCurrentPosCommand)) {
insertAtCurrentPos(1);
}
else if (evt.getActionCommand().equals(fgLotsOfTextCommand)) {
insertAtCurrentPos(8);
}
else if (evt.getActionCommand().equals(fgFwdDelete)) {
forwardDelete(1);
}
else if (evt.getActionCommand().equals(fgBackspace)) {
backspace(1);
}
}
catch(IOException e) {
System.out.println("Caught exception: " + e);
}
}
private void insertAtCurrentPos(final int times) throws IOException {
fTextFrame.toFront();
System.gc();
long startTime = System.currentTimeMillis();
for (int t=0; t < times; t++) {
for (int i=0; i < fInsText.length; i++) {
KeyEvent event = new KeyEvent(fTextFrame, KeyEvent.KEY_TYPED, 0, 0, 0, fInsText[i]);
fKeyEventForwarder.handleKeyEvent(event);
}
}
long time = System.currentTimeMillis() - startTime;
fOut.println("Total time: " + time);
fOut.println("Millis per character: " + (time / (fInsText.length*times)));
fOut.flush();
}
private void forwardDelete(final int times) throws IOException {
System.gc();
long startTime = System.currentTimeMillis();
for (int t=0; t < times; t++) {
for (int i=0; i < fInsText.length; i++) {
KeyEvent event = new KeyEvent(fTextFrame, 0, 0, 0, KeyEvent.VK_DELETE, '\u00FF');
fKeyEventForwarder.handleKeyEvent(event);
}
}
long time = System.currentTimeMillis() - startTime;
fOut.println("Total time: " + time);
fOut.println("Millis per character: " + (time / (fInsText.length*times)));
fOut.flush();
}
private void backspace(final int times) throws IOException {
System.gc();
long startTime = System.currentTimeMillis();
for (int t=0; t < times; t++) {
for (int i=0; i < fInsText.length; i++) {
KeyEvent event = new KeyEvent(fTextFrame, 0, 0, 0, KeyEvent.VK_BACK_SPACE, '\u0010');
fKeyEventForwarder.handleKeyEvent(event);
}
}
long time = System.currentTimeMillis() - startTime;
fOut.println("Total time: " + time);
fOut.println("Millis per character: " + (time / (fInsText.length*times)));
fOut.flush();
}
}

View File

@ -1,158 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/Attic/TestAll.java,v $
* $Date: 2002/02/08 01:12:45 $
* $Revision: 1.19 $
*
*****************************************************************************************
*/
package com.ibm.test;
import com.ibm.test.TestFmwk;
import java.text.*;
import java.util.*;
/**
* Top level test used to run all other tests as a batch.
*/
public class TestAll extends TestFmwk {
public static void main(String[] args) throws Exception {
new TestAll().run(args);
}
public void TestBigNumberFormat() throws Exception{
run(new com.ibm.test.bnf.BigNumberFormatTest());
}
public void TestCompression() throws Exception{
run(new TestFmwk[] {
new com.ibm.test.compression.DecompressionTest(),
new com.ibm.test.compression.ExhaustiveTest()
});
}
public void TestNormalizer() throws Exception{
run(new TestFmwk[] {
new com.ibm.test.normalizer.BasicTest(),
new com.ibm.test.normalizer.ExhaustiveTest(),
new com.ibm.test.normalizer.ConformanceTest(),
});
}
public void TestRuleBasedNumberFormat() throws Exception {
run(new TestFmwk[] {
new com.ibm.test.rbnf.RbnfTest(),
new com.ibm.test.rbnf.RbnfRoundTripTest()
});
}
public void TestRuleBasedBreakIterator() throws Exception {
run(new TestFmwk[] {
new com.ibm.test.rbbi.SimpleBITest(),
new com.ibm.test.rbbi.BreakIteratorTest(),
new com.ibm.test.rbbi.RBBITest(),
new com.ibm.test.rbbi.RBBIAPITest()
});
}
public void TestTranslit() throws Exception {
run(new TestFmwk[] {
new com.ibm.test.translit.TransliteratorTest(),
new com.ibm.test.translit.UnicodeSetTest(),
new com.ibm.test.translit.UnicodeFilterLogicTest(),
new com.ibm.test.translit.CompoundTransliteratorTest(),
new com.ibm.test.translit.UnicodeToHexTransliteratorTest(),
new com.ibm.test.translit.HexToUnicodeTransliteratorTest(),
new com.ibm.test.translit.JamoTest(),
new com.ibm.test.translit.ErrorTest(),
new com.ibm.test.translit.RoundTripTest(),
new com.ibm.test.translit.ReplaceableTest()
});
}
public void TestSearch() throws Exception {
run(new com.ibm.test.search.SearchTest());
}
public void TestRichEdit() throws Exception {
run(new com.ibm.test.richtext.TestAll());
}
public void TestArabicShaping() throws Exception {
run(new com.ibm.icu.test.text.ArabicShapingRegTest());
}
public void TestCalendar() throws Exception {
run(new TestFmwk[] {
new com.ibm.test.calendar.AstroTest(),
new com.ibm.test.calendar.CalendarRegression(),
new com.ibm.test.calendar.CompatibilityTest(),
new com.ibm.test.calendar.HebrewTest(),
new com.ibm.test.calendar.IBMCalendarTest(),
new com.ibm.test.calendar.IslamicTest(),
new com.ibm.test.calendar.ChineseTest()
});
}
public void TestTimeZone() throws Exception {
run(new TestFmwk[] {
new com.ibm.test.timezone.TimeZoneTest(),
new com.ibm.test.timezone.TimeZoneRegression(),
new com.ibm.test.timezone.TimeZoneBoundaryTest()
});
}
public void TestCharacter() throws Exception {
run(new TestFmwk[] {
new com.ibm.icu.test.text.UCharacterTest(),
new com.ibm.icu.test.text.UTF16Test()
});
}
public void TestTrie() throws Exception {
run(new TestFmwk[] {
new com.ibm.icu.test.util.TrieTest()
});
}
public void TestUScript() throws Exception {
run( new TestFmwk[] {
new com.ibm.icu.test.text.TestUScript(),
});
}
public void TestNumberFormat() throws Exception {
run(new TestFmwk[] {
new com.ibm.icu.test.format.IntlTestNumberFormat(),
new com.ibm.icu.test.format.IntlTestNumberFormatAPI(),
new com.ibm.icu.test.format.NumberFormatTest(),
new com.ibm.icu.test.format.NumberFormatRoundTripTest(),
new com.ibm.icu.test.format.NumberRegression(),
new com.ibm.icu.test.format.NumberFormatRegressionTest(),
new com.ibm.icu.test.format.IntlTestDecimalFormatAPI(),
new com.ibm.icu.test.format.IntlTestDecimalFormatAPIC(),
new com.ibm.icu.test.format.IntlTestDecimalFormatSymbols(),
new com.ibm.icu.test.format.IntlTestDecimalFormatSymbolsC()
});
}
public void TestDateFormat() throws Exception {
run(new TestFmwk[] {
new com.ibm.icu.test.format.DateFormatMiscTests(),
new com.ibm.icu.test.format.DateFormatRegressionTest(),
new com.ibm.icu.test.format.DateFormatRoundTripTest(),
new com.ibm.icu.test.format.DateFormatTest(),
new com.ibm.icu.test.format.IntlTestDateFormat(),
new com.ibm.icu.test.format.IntlTestDateFormatAPI(),
new com.ibm.icu.test.format.IntlTestDateFormatAPIC(),
new com.ibm.icu.test.format.IntlTestDateFormatSymbols(),
new com.ibm.icu.test.format.IntlTestSimpleDateFormatAPI(),
new com.ibm.icu.test.format.DateFormatRegressionTestJ()
});
}
}

View File

@ -1,428 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/Attic/TestFmwk.java,v $
* $Date: 2001/12/03 21:48:07 $
* $Revision: 1.26 $
*
*****************************************************************************************
*/
package com.ibm.test;
import java.lang.reflect.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Comparator;
import java.io.*;
import java.text.*;
import com.ibm.text.UTF16;
import com.ibm.util.Utility;
import com.ibm.text.UnicodeSet;
/**
* TestFmwk is a base class for tests that can be run conveniently from
* the command line as well as under the Java test harness.
* <p>
* Sub-classes implement a set of methods named Test<something>. Each
* of these methods performs some test. Test methods should indicate
* errors by calling either err or errln. This will increment the
* errorCount field and may optionally print a message to the log.
* Debugging information may also be added to the log via the log
* and logln methods. These methods will add their arguments to the
* log only if the test is being run in verbose mode.
*/
public class TestFmwk implements TestLog {
/**
* Puts a copyright in the .class file
*/
private static final String copyrightNotice
= "Copyright \u00a91997-1998 IBM Corp. All rights reserved.";
//------------------------------------------------------------------------
// Everything below here is boilerplate code that makes it possible
// to add a new test by simply adding a function to an existing class
//------------------------------------------------------------------------
protected TestFmwk() {
// Create a hashtable containing all the test methods.
testMethods = new Hashtable();
Method[] methods = getClass().getDeclaredMethods();
for( int i=0; i<methods.length; i++ ) {
if( methods[i].getName().startsWith("Test")
|| methods[i].getName().startsWith("test")) {
testMethods.put( methods[i].getName(), methods[i] );
}
}
}
private void _run() throws Exception {
writeTestName(getClass().getName());
params.indentLevel++;
Enumeration methodsToRun;
if (testsToRun != null && testsToRun.size() >= 1) {
methodsToRun = testsToRun.elements();
} else {
methodsToRun = testMethods.elements();
}
methodsToRun = new SortedEnumeration(methodsToRun,
new Comparator() {
public int compare(Object a, Object b) {
return ((Method)a).getName().compareToIgnoreCase(
((Method)b).getName());
}
public boolean equals(Object o) {
return false;
}
});
int oldClassCount = params.errorCount;
// Run the list of tests given in the test arguments
while (methodsToRun.hasMoreElements()) {
int oldCount = params.errorCount;
Method testMethod = (Method)methodsToRun.nextElement();
writeTestName(testMethod.getName());
try {
testMethod.invoke(this, new Object[0]);
} catch( IllegalAccessException e ) {
errln("Can't access test method " + testMethod.getName());
} catch( InvocationTargetException e ) {
errln("Uncaught exception \""+e+"\" thrown in test method "
+ testMethod.getName());
e.getTargetException().printStackTrace(this.params.log);
}
writeTestResult(params.errorCount - oldCount);
}
params.indentLevel--;
writeTestResult(params.errorCount - oldClassCount);
}
public void run(String[] args) throws Exception {
if (params == null) params = new TestParams();
// Parse the test arguments. They can be either the flag
// "-verbose" or names of test methods. Create a list of
// tests to be run.
testsToRun = new Vector(args.length);
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-verbose") || args[i].equals("-v")) {
params.verbose = true;
}
else if (args[i].equals("-prompt")) {
params.prompt = true;
} else if (args[i].equals("-nothrow")) {
params.nothrow = true;
} else if (args[i].startsWith("-e")) {
params.inclusion = (args[i].length() == 2) ? 5 : Integer.parseInt(args[i].substring(2));
} else if (args[i].toLowerCase().startsWith("-filter:")) {
params.filter = args[i].substring(8);
} else {
Object m = testMethods.get(args[i]);
if (m != null) {
testsToRun.addElement(m);
} else {
usage();
return;
}
}
}
if (params == null) params = new TestParams();
_run();
if (params.prompt) {
System.out.println("Hit RETURN to exit...");
try {
System.in.read();
} catch (IOException e) {
System.out.println("Exception: " + e.toString() + e.getMessage());
}
}
if (params.nothrow) {
System.exit(params.errorCount);
}
}
protected void run(TestFmwk childTest) throws Exception {
run(new TestFmwk[] { childTest });
}
protected void run(TestFmwk[] tests) throws Exception {
for (int i=0; i<tests.length; ++i) {
tests[i].params = this.params;
params.indentLevel++;
tests[i]._run();
params.indentLevel--;
}
}
protected boolean isVerbose() {
return params.verbose;
}
/**
* 0 = fewest tests, 5 is normal build, 10 is most tests
*/
public int getInclusion() {
return params.inclusion;
}
public boolean isQuick() {
return params.inclusion == 0;
}
public String getFilter() {
return params.filter;
}
/**
* Adds given string to the log if we are in verbose mode.
*/
public void log( String message ) {
log(message, true, false);
}
public void logln( String message ) {
log(message + System.getProperty("line.separator"), true, false);
}
/**
* Add a given string to the log.
* @param message text to add
* @param pass if true and if in verbose mode, or if false, then add
* the text; otherwise suppress it
* @param incrementCount if pass if false and incrementCount is true,
* then increment the failure count; if pass is true, then this param
* is ignored
*/
public void log( String message, boolean pass, boolean incrementCount ) {
if (!pass && incrementCount) {
params.errorCount++;
}
if (!pass || params.verbose) {
indent(params.indentLevel + 1);
params.log.print( message );
params.log.flush();
}
if (!pass && !params.nothrow) {
throw new RuntimeException(message);
}
}
public void logln( String message, boolean pass, boolean incrementCount ) {
log(message + System.getProperty("line.separator"), pass, incrementCount);
}
/**
* Convenience overloads
*/
public void log( String message, boolean pass ) {
log(message, pass, true);
}
public void logln( String message, boolean pass ) {
logln(message, pass, true);
}
/**
* Report an error
*/
public void err( String message ) {
log(message, false, true);
}
public void errln( String message ) {
logln(message, false, true);
}
protected int getErrorCount() {
return params.errorCount;
}
protected void writeTestName(String testName) {
indent(params.indentLevel);
params.log.print(testName);
params.log.flush();
params.needLineFeed = true;
}
protected void writeTestResult(int count) {
if (!params.needLineFeed) {
indent(params.indentLevel);
params.log.print("}");
}
params.needLineFeed = false;
if (count != 0) {
params.log.println(" FAILED (" + count + " failures)");
} else {
params.log.println(" Passed");
}
}
private final void indent(int distance) {
if (params.needLineFeed) {
params.log.println(" {");
params.needLineFeed = false;
}
params.log.print(spaces.substring(0, distance * 2));
}
/**
* Print a usage message for this test class.
*/
void usage() {
System.out.println(getClass().getName() +
": [-verbose] [-nothrow] [-prompt] [test names]");
System.out.println("test names:");
Enumeration methodNames = new SortedEnumeration(testMethods.keys(),
new Comparator() {
public int compare(Object a, Object b) {
return ((String)a).compareToIgnoreCase(
((String)b));
}
public boolean equals(Object o) {
return false;
}
});
while( methodNames.hasMoreElements() ) {
System.out.println("\t" + methodNames.nextElement() );
}
}
public static String hex(char ch) {
StringBuffer result = new StringBuffer();
String foo = Integer.toString(ch,16).toUpperCase();
for (int i = foo.length(); i < 4; ++i) {
result.append('0');
}
return result + foo;
}
public static String hex(int ch) {
StringBuffer result = new StringBuffer();
String foo = Integer.toString(ch,16).toUpperCase();
for (int i = foo.length(); i < 4; ++i) {
result.append('0');
}
return result + foo;
}
public static String hex(String s) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < s.length(); ++i) {
if (i != 0) result.append(',');
result.append(hex(s.charAt(i)));
}
return result.toString();
}
public static String hex(StringBuffer s) {
return hex(s.toString());
}
private static class ASCIIWriter extends PrintWriter {
private Writer w;
private StringBuffer buffer = new StringBuffer();
// Characters that we think are printable but that escapeUnprintable
// doesn't
private static final UnicodeSet S =
new UnicodeSet("[\\u0009\\u000A\\u000D]");
public ASCIIWriter(Writer w, boolean autoFlush) {
super(w, autoFlush);
}
public ASCIIWriter(OutputStream os, boolean autoFlush) {
super(os, autoFlush);
}
public void write(int c) {
synchronized(lock) {
buffer.setLength(0);
if (!S.contains(c) && Utility.escapeUnprintable(buffer, c)) {
super.write(buffer.toString());
} else {
super.write(c);
}
}
}
public void write(char[] buf, int off, int len) {
synchronized (lock) {
buffer.setLength(0);
int limit = off + len;
while (off < limit) {
int c = UTF16.charAt(buf, 0, buf.length, off);
off += UTF16.getCharCount(c);
if (!S.contains(c) && Utility.escapeUnprintable(buffer, c)) {
super.write(buffer.toString());
buffer.setLength(0);
} else {
super.write(c);
}
}
}
}
public void write(String s, int off, int len) {
write(s.substring(off, off + len).toCharArray(), 0, len);
}
}
private static class TestParams {
public boolean prompt = false;
public boolean nothrow = false;
public boolean verbose = false;
public int inclusion = 0;
public String filter = null;
public PrintWriter log = new ASCIIWriter(System.out, true);
public int indentLevel = 0;
public boolean needLineFeed = false;
public int errorCount = 0;
}
private static class SortedEnumeration implements Enumeration {
private Object[] sorted;
private int pos;
public SortedEnumeration(Enumeration unsorted, Comparator c) {
Vector v = new Vector();
while (unsorted.hasMoreElements()) {
v.addElement(unsorted.nextElement());
}
sorted = new Object[v.size()];
v.copyInto(sorted);
java.util.Arrays.sort(sorted, c);
pos = 0;
}
public boolean hasMoreElements() {
return pos < sorted.length;
}
public Object nextElement() {
return pos < sorted.length ? sorted[pos++] : null;
}
}
private TestParams params = null;
private Hashtable testMethods;
private Vector testsToRun;
private final String spaces = " ";
}

View File

@ -1,18 +0,0 @@
package com.ibm.test;
public interface TestLog {
/**
* Adds given string to the log if we are in verbose mode.
*/
void log(String message);
void logln(String message);
/**
* Report an error
*/
void err(String message);
void errln(String message);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,426 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/bnf/Attic/BigNumberFormatTest.java,v $
* $Date: 2001/10/19 12:47:42 $
* $Revision: 1.11 $
*
*****************************************************************************************
*/
package com.ibm.test.bnf;
import com.ibm.test.*;
import com.ibm.text.*;
import java.text.ParseException;
import java.util.*;
import java.math.BigInteger;
import com.ibm.util.Utility;
/**
* @test
* General test of Big NumberFormat
*/
public class BigNumberFormatTest extends TestFmwk {
static final int ILLEGAL = -1;
public static void main(String[] args) throws Exception {
new BigNumberFormatTest().run(args);
}
public void TestExponent() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt1 = new DecimalFormat("0.###E0", US);
DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US);
Number n = new Long(1234);
expect(fmt1, n, "1.234E3");
expect(fmt2, n, "1.234E+3");
expect(fmt1, "1.234E3", n);
expect(fmt1, "1.234E+3", n); // Either format should parse "E+3"
expect(fmt2, "1.234E+3", n);
}
/**
* Test the functioning of the secondary grouping value.
*/
public void TestSecondaryGrouping() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat f = new DecimalFormat("#,##,###", US);
expect(f, new Long(123456789), "12,34,56,789");
expectPat(f, "#,##,###");
f.applyPattern("#,###");
f.setSecondaryGroupingSize(4);
expect(f, new Long(123456789), "12,3456,789");
expectPat(f, "#,####,###");
// On Sun JDK 1.2-1.3, the hi_IN locale uses '0' for a zero digit,
// but on IBM JDK 1.2-1.3, the locale uses U+0966.
f = (DecimalFormat) NumberFormat.getInstance(new Locale("hi", "IN"));
String str = transmute("1,87,65,43,210",
f.getDecimalFormatSymbols().getZeroDigit());
expect(f, new Long(1876543210), str);
}
private void expectPad(DecimalFormat fmt, String pat, int pos) {
expectPad(fmt, pat, pos, 0, (char)0);
}
private void expectPad(DecimalFormat fmt, String pat,
int pos, int width, char pad) {
int apos = 0, awidth = 0;
char apad = 0;
try {
fmt.applyPattern(pat);
apos = fmt.getPadPosition();
awidth = fmt.getFormatWidth();
apad = fmt.getPadCharacter();
} catch (IllegalArgumentException e) {
apos = -1;
awidth = width;
apad = pad;
}
if (apos == pos && awidth == width && apad == pad) {
logln("Ok \"" + pat + "\" pos=" + apos +
((pos == -1) ? "" : " width=" + awidth + " pad=" + apad));
} else {
logln("FAIL \"" + pat + "\" pos=" + apos +
" width=" + awidth + " pad=" + apad +
", expected " + pos + " " + width + " " + pad);
}
}
/**
*/
public void TestPatterns() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt = new DecimalFormat("#", US);
expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, '^');
expectPad(fmt, "$*^#", DecimalFormat.PAD_AFTER_PREFIX, 2, '^');
expectPad(fmt, "#*^", DecimalFormat.PAD_BEFORE_SUFFIX, 1, '^');
expectPad(fmt, "#$*^", DecimalFormat.PAD_AFTER_SUFFIX, 2, '^');
expectPad(fmt, "$*^$#", ILLEGAL);
expectPad(fmt, "#$*^$", ILLEGAL);
expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat.PAD_BEFORE_SUFFIX,
12, 'x');
expectPad(fmt, "''#0*x", DecimalFormat.PAD_BEFORE_SUFFIX,
3, 'x');
expectPad(fmt, "'I''ll'*a###.##", DecimalFormat.PAD_AFTER_PREFIX,
10, 'a');
fmt.applyPattern("AA#,##0.00ZZ");
fmt.setPadCharacter('^');
fmt.setFormatWidth(10);
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_PREFIX);
expectPat(fmt, "*^AA#,##0.00ZZ");
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_SUFFIX);
expectPat(fmt, "AA#,##0.00*^ZZ");
fmt.setPadPosition(DecimalFormat.PAD_AFTER_SUFFIX);
expectPat(fmt, "AA#,##0.00ZZ*^");
// 12 3456789012
String exp = "AA*^#,##0.00ZZ";
fmt.setFormatWidth(12);
fmt.setPadPosition(DecimalFormat.PAD_AFTER_PREFIX);
expectPat(fmt, exp);
fmt.setFormatWidth(13);
// 12 34567890123
expectPat(fmt, "AA*^##,##0.00ZZ");
fmt.setFormatWidth(14);
// 12 345678901234
expectPat(fmt, "AA*^###,##0.00ZZ");
fmt.setFormatWidth(15);
// 12 3456789012345
expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case
fmt.setFormatWidth(16);
// 12 34567890123456
expectPat(fmt, "AA*^#,###,##0.00ZZ");
}
private void expectPat(DecimalFormat fmt, String exp) {
String pat = fmt.toPattern();
if (pat.equals(exp)) {
logln("Ok \"" + pat + '"');
} else {
errln("FAIL \"" + pat + "\", expected \"" + exp + '"');
}
}
/**
* Test the handling of the AlphaWorks BigDecimal
*/
public void TestAlphaBigDecimal() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
/*For ICU compatibility [Richard/GCL]*/
expect(NumberFormat.getScientificInstance(Locale.US),
new Number[] { new com.ibm.math.BigDecimal("12345.678901"),
},
"1.2345678901E4");
expect(new DecimalFormat("##0.####E0", US),
new Number[] { new com.ibm.math.BigDecimal("12345.4999"),
new com.ibm.math.BigDecimal("12344.5001"),
},
"12.345E3");
expect(new DecimalFormat("##0.####E0", US),
new Number[] { new com.ibm.math.BigDecimal("12345.5000"),
new com.ibm.math.BigDecimal("12346.5000"),
},
"12.346E3");
}
/**
*/
public void TestScientific() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
/*For ICU compatibility [Richard/GCL]*/
expect(NumberFormat.getScientificInstance(Locale.US),
new Number[] { new Double(12345.678901),
new java.math.BigDecimal("12345.678901"),
},
"1.2345678901E4");
expect(new DecimalFormat("##0.###E0", US),
new Double(12345),
"12.34E3");
expect(new DecimalFormat("##0.###E0", US),
new Double(12345.00001),
"12.35E3");
expect(new DecimalFormat("##0.####E0", US),
new Number[] { new Integer(12345),
new Long(12345),
new java.math.BigDecimal("12345.4999"),
new java.math.BigDecimal("12344.5001"),
},
"12.345E3");
expect(new DecimalFormat("##0.####E0", US),
new Number[] { new java.math.BigDecimal("12345.5000"),
new java.math.BigDecimal("12346.5000"),
},
"12.346E3");
/*For ICU compatibility [Richard/GCL]*/
expect(NumberFormat.getScientificInstance(Locale.FRANCE),
new Double(12345.678901),
"1,2345678901E4");
expect(new DecimalFormat("##0.####E0", US),
new Double(789.12345e-9),
"789.12E-9");
expect(new DecimalFormat("##0.####E0", US),
new Double(780.e-9),
"780E-9");
expect(new DecimalFormat(".###E0", US),
new Double(45678),
".457E5");
expect(new DecimalFormat(".###E0", US),
new Long(0),
".0E0");
expect(new DecimalFormat[] { new DecimalFormat("#E0", US),
new DecimalFormat("##E0", US),
new DecimalFormat("####E0", US),
new DecimalFormat("0E0", US),
new DecimalFormat("00E0", US),
new DecimalFormat("000E0", US),
},
new Long(45678000),
new String[] { "4.5678E7",
"45.678E6",
"4567.8E4",
"5E7",
"46E6",
"457E5",
}
);
expect(new DecimalFormat("###E0", US),
new Object[] { new Double(0.0000123), "12.3E-6",
new Double(0.000123), "123E-6",
new java.math.BigDecimal("0.00123"), "1.23E-3", // Cafe VM messes up Double(0.00123)
new Double(0.0123), "12.3E-3",
new Double(0.123), "123E-3",
new Double(1.23), "1.23E0",
new Double(12.3), "12.3E0",
new Double(123), "123E0",
new Double(1230), "1.23E3",
});
expect(new DecimalFormat("0.#E+00", US),
new Object[] { new Double(0.00012), "1.2E-04",
new Long(12000), "1.2E+04",
});
}
/**
*/
public void TestPad() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
expect(new DecimalFormat("*^##.##", US),
new Object[] { new Long(0), "^^^^0",
new Double(-1.3), "^-1.3",
}
);
expect(new DecimalFormat("##0.0####E0*_ g-m/s^2", US),
new Object[] { new Long(0), "0.0E0______ g-m/s^2",
new Double(1.0/3), "333.333E-3_ g-m/s^2",
}
);
expect(new DecimalFormat("##0.0####*_ g-m/s^2", US),
new Object[] { new Long(0), "0.0______ g-m/s^2",
new Double(1.0/3), "0.33333__ g-m/s^2",
}
);
expect(new DecimalFormat("*x#,###,###,##0.00;*x(#,###,###,##0.00)", US),
new Object[] {
new Long(-100), "xxxxxxxx(100.00)",
new Long(-1000), "xxxxxx(1,000.00)",
new Long(-1000000), "xx(1,000,000.00)",
new Long(-1000000000), "(1,000,000,000.00)",
});
}
private void expect(NumberFormat fmt, Object[] data) {
for (int i=0; i<data.length; i+=2) {
expect(fmt, (Number) data[i], (String) data[i+1]);
}
}
private void expect(Object fmto, Object numo, Object expo) {
NumberFormat fmt = null, fmts[] = null;
Number num = null, nums[] = null;
String exp = null, exps[] = null;
if (fmto instanceof NumberFormat[]) {
fmts = (NumberFormat[]) fmto;
} else {
fmt = (NumberFormat) fmto;
}
if (numo instanceof Number[]) {
nums = (Number[]) numo;
} else {
num = (Number) numo;
}
if (expo instanceof String[]) {
exps = (String[]) expo;
} else {
exp = (String) expo;
}
int n = 1;
if (fmts != null) {
n = Math.max(n, fmts.length);
}
if (nums != null) {
n = Math.max(n, nums.length);
}
if (exps != null) {
n = Math.max(n, exps.length);
}
for (int i=0; i<n; ++i) {
expect(fmts == null ? fmt : fmts[i],
nums == null ? num : nums[i],
exps == null ? exp : exps[i]);
}
}
private static String showNumber(Number n) {
String cls = n.getClass().getName();
if (!(n instanceof com.ibm.math.BigDecimal
|| n instanceof java.math.BigDecimal)) {
int i = cls.lastIndexOf('.');
cls = cls.substring(i+1);
}
return n.toString() + " (" + cls + ')';
}
private void expect(NumberFormat fmt, Number n, String exp) {
String saw = fmt.format(n);
String pat = ((DecimalFormat) fmt).toPattern();
if (saw.equals(exp)) {
logln("Ok " + showNumber(n) + " x " +
pat + " = " +
Utility.escape(saw));
} else {
errln("FAIL " + showNumber(n) + " x " +
pat + " = \"" +
Utility.escape(saw) + ", expected " + Utility.escape(exp));
}
}
private void expect(NumberFormat fmt, String str, Number exp) {
Number saw = null;
try {
saw = fmt.parse(str);
} catch (ParseException e) {
saw = null;
}
String pat = ((DecimalFormat) fmt).toPattern();
if (saw.equals(exp)) {
logln("Ok \"" + str + "\" x " +
pat + " = " +
showNumber(saw));
} else {
errln("FAIL \"" + str + "\" x " +
pat + " = " +
showNumber(saw) + ", expected " + showNumber(exp));
}
}
/**
* Given a string composed of [0-9] and other chars, convert the
* [0-9] chars to be offsets 0..9 from 'zero'.
*/
private static String transmute(String str, char zero) {
StringBuffer buf = new StringBuffer();
for (int i=0; i<str.length(); ++i) {
char c = str.charAt(i);
if (c >= '0' && c <= '9') {
c = (char) (c - '0' + zero);
}
buf.append(c);
}
return buf.toString();
}
public void Test4161100() {
NumberFormat f = NumberFormat.getInstance();
f.setMinimumFractionDigits(1);
f.setMaximumFractionDigits(1);
double a = -0.09;
String s = f.format(a);
logln(a + " x " +
((DecimalFormat) f).toPattern() + " = " +
s);
if (!s.equals("-0.1")) {
errln("FAIL");
}
}
public void TestBigDecimalJ28() {
String[] DATA = {
"1", "1E0",
"-1", "-1E0",
"0", "0E0",
"12e34", "1.2E35",
"-12.3e-45", "-1.23E-44",
"0.73e-7", "7.3E-8",
};
NumberFormat fmt = NumberFormat.getScientificInstance(Locale.US);
logln("Pattern: " + ((DecimalFormat)fmt).toPattern());
for (int i=0; i<DATA.length; i+=2) {
String input = DATA[i];
String exp = DATA[i+1];
com.ibm.math.BigDecimal bd = new com.ibm.math.BigDecimal(input);
String output = fmt.format(bd);
if (output.equals(exp)) {
logln("input=" + input + " num=" + bd + " output=" + output);
} else {
errln("FAIL: input=" + input + " num=" + bd + " output=" + output +
" expected=" + exp);
}
}
}
}

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/bnf/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 21:35:48 $
-->
</head>
<body bgcolor="white">
BigNumberFormat tests.
</body>
</html>

View File

@ -1,75 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/AstroTest.java,v $
* $Date: 2001/09/08 01:15:15 $
* $Revision: 1.5 $
*
*****************************************************************************************
*/
package com.ibm.test.calendar;
// AstroTest
import com.ibm.test.*;
import com.ibm.util.*;
import com.ibm.util.CalendarAstronomer.*;
// TODO: try finding next new moon after 07/28/1984 16:00 GMT
public class AstroTest extends TestFmwk {
public static void main(String[] args) throws Exception {
new AstroTest().run(args);
}
static final double PI = Math.PI;
static GregorianCalendar gc = new GregorianCalendar(new SimpleTimeZone(0, "UTC"));
static CalendarAstronomer astro = new CalendarAstronomer();
public void TestSolarLongitude() {
final double tests[][] = {
{ 1980, 7, 27, 00, 00, 124.114347 },
{ 1988, 7, 27, 00, 00, 124.187732 },
};
logln("");
for (int i = 0; i < tests.length; i++) {
gc.clear();
gc.set((int)tests[i][0], (int)tests[i][1]-1, (int)tests[i][2], (int)tests[i][3], (int) tests[i][4]);
astro.setDate(gc.getTime());
double longitude = astro.getSunLongitude();
longitude = 0;
Equatorial result = astro.getSunPosition();
result = null;
}
}
public void TestLunarPosition() {
final double tests[][] = {
{ 1979, 2, 26, 16, 00, 0, 0 },
};
logln("");
for (int i = 0; i < tests.length; i++) {
gc.clear();
gc.set((int)tests[i][0], (int)tests[i][1]-1, (int)tests[i][2], (int)tests[i][3], (int) tests[i][4]);
astro.setDate(gc.getTime());
Equatorial result = astro.getMoonPosition();
result = null;
}
}
public void TestCoordinates() {
Equatorial result = astro.eclipticToEquatorial(139.686111 * PI/ 180.0, 4.875278* PI / 180.0);
logln("result is " + result + "; " + result.toHmsString());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,360 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/CalendarTest.java,v $
* $Date: 2000/11/30 21:54:34 $
* $Revision: 1.11 $
*
*****************************************************************************************
*/
package com.ibm.test.calendar;
import com.ibm.test.*;
import com.ibm.text.DateFormat;
import com.ibm.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Hashtable;
import java.util.Enumeration;
import com.ibm.util.*;
/**
* A base class for classes that test individual Calendar subclasses.
* Defines various useful utility methods and constants
*/
public class CalendarTest extends TestFmwk {
// Constants for use by subclasses, solely to save typing
public final static int SUN = Calendar.SUNDAY;
public final static int MON = Calendar.MONDAY;
public final static int TUE = Calendar.TUESDAY;
public final static int WED = Calendar.WEDNESDAY;
public final static int THU = Calendar.THURSDAY;
public final static int FRI = Calendar.FRIDAY;
public final static int SAT = Calendar.SATURDAY;
public final static int ERA = Calendar.ERA;
public final static int YEAR = Calendar.YEAR;
public final static int MONTH = Calendar.MONTH;
public final static int DATE = Calendar.DATE;
public final static int HOUR = Calendar.HOUR;
public final static int MINUTE = Calendar.MINUTE;
public final static int SECOND = Calendar.SECOND;
public final static int DOY = Calendar.DAY_OF_YEAR;
public final static int WOY = Calendar.WEEK_OF_YEAR;
public final static int WOM = Calendar.WEEK_OF_MONTH;
public final static int DOW = Calendar.DAY_OF_WEEK;
public final static int DOWM = Calendar.DAY_OF_WEEK_IN_MONTH;
public final static SimpleTimeZone UTC = new SimpleTimeZone(0, "GMT");
private static final String[] FIELD_NAME = {
"ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH",
"DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK",
"DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", "HOUR_OF_DAY",
"MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET",
"DST_OFFSET", "YEAR_WOY", "DOW_LOCAL", "EXTENDED_YEAR",
"JULIAN_DAY", "MILLISECONDS_IN_DAY",
"IS_LEAP_MONTH" // (ChineseCalendar only)
};
public static final String fieldName(int f) {
return (f>=0 && f<FIELD_NAME.length) ?
FIELD_NAME[f] : ("<Field " + f + ">");
}
/**
* Iterates through a list of calendar <code>TestCase</code> objects and
* makes sure that the time-to-fields and fields-to-time calculations work
* correnctly for the values in each test case.
*/
public void doTestCases(TestCase[] cases, Calendar cal)
{
cal.setTimeZone(UTC);
// Get a format to use for printing dates in the calendar system we're testing
DateFormat format = DateFormat.getDateTimeInstance(cal, DateFormat.SHORT, -1, Locale.getDefault());
final String pattern = (cal instanceof ChineseCalendar) ?
"E MMl/dd/y G HH:mm:ss.S z" :
"E, MM/dd/yyyy G HH:mm:ss.S z";
((SimpleDateFormat)format).applyPattern(pattern);
// This format is used for printing Gregorian dates.
DateFormat gregFormat = new SimpleDateFormat(pattern);
gregFormat.setTimeZone(UTC);
GregorianCalendar pureGreg = new GregorianCalendar(UTC);
pureGreg.setGregorianChange(new Date(Long.MIN_VALUE));
DateFormat pureGregFmt = new SimpleDateFormat("E M/d/yyyy G");
pureGregFmt.setCalendar(pureGreg);
// Now iterate through the test cases and see what happens
for (int i = 0; i < cases.length; i++)
{
TestCase test = cases[i];
//
// First we want to make sure that the millis -> fields calculation works
// test.applyTime will call setTime() on the calendar object, and
// test.fieldsEqual will retrieve all of the field values and make sure
// that they're the same as the ones in the testcase
//
test.applyTime(cal);
if (!test.fieldsEqual(cal, this)) {
errln("Fail: (millis=>fields) " +
gregFormat.format(test.getTime()) + " => " +
format.format(cal.getTime()) +
", expected " + test);
}
//
// If that was OK, check the fields -> millis calculation
// test.applyFields will set all of the calendar's fields to
// match those in the test case.
//
cal.clear();
test.applyFields(cal);
if (!test.equals(cal)) {
errln("Fail: (fields=>millis) " + test + " => " +
pureGregFmt.format(cal.getTime()) +
", expected " + pureGregFmt.format(test.getTime()));
}
}
}
static public final boolean ROLL = true;
static public final boolean ADD = false;
/**
* Process test cases for <code>add</code> and <code>roll</code> methods.
* Each test case is an array of integers, as follows:
* <ul>
* <li>0: input year
* <li>1: month (zero-based)
* <li>2: day
* <li>3: field to roll or add to
* <li>4: amount to roll or add
* <li>5: result year
* <li>6: month (zero-based)
* <li>7: day
* </ul>
* For example:
* <pre>
* // input add by output
* // year month day field amount year month day
* { 5759, HESHVAN, 2, MONTH, 1, 5759, KISLEV, 2 },
* </pre>
*
* @param roll <code>true</code> or <code>ROLL</code> to test the <code>roll</code> method;
* <code>false</code> or <code>ADD</code> to test the <code>add</code method
*/
public void doRollAdd(boolean roll, Calendar cal, int[][] tests)
{
String name = roll ? "rolling" : "adding";
for (int i = 0; i < tests.length; i++) {
int[] test = tests[i];
cal.clear();
if (cal instanceof ChineseCalendar) {
cal.set(Calendar.EXTENDED_YEAR, test[0]);
cal.set(Calendar.MONTH, test[1]);
cal.set(Calendar.DAY_OF_MONTH, test[2]);
} else {
cal.set(test[0], test[1], test[2]);
}
if (roll) {
cal.roll(test[3], test[4]);
} else {
cal.add(test[3], test[4]);
}
int y = cal.get(cal instanceof ChineseCalendar ?
Calendar.EXTENDED_YEAR : YEAR);
if (y != test[5] || cal.get(MONTH) != test[6]
|| cal.get(DATE) != test[7])
{
errln("Fail: " + name + " "+ ymdToString(test[0], test[1], test[2])
+ " " + FIELD_NAME[test[3]] + " by " + test[4]
+ ": expected " + ymdToString(test[5], test[6], test[7])
+ ", got " + ymdToString(cal));
} else if (isVerbose()) {
logln("OK: " + name + " "+ ymdToString(test[0], test[1], test[2])
+ " " + FIELD_NAME[test[3]] + " by " + test[4]
+ ": got " + ymdToString(cal));
}
}
}
/**
* Test the functions getXxxMinimum() and getXxxMaximum() by marching a
* test calendar 'cal' through 'numberOfDays' sequential days starting
* with 'startDate'. For each date, read a field value along with its
* reported actual minimum and actual maximum. These values are
* checked against one another as well as against getMinimum(),
* getGreatestMinimum(), getLeastMaximum(), and getMaximum(). We
* expect to see:
*
* 1. minimum <= actualMinimum <= greatestMinimum <=
* leastMaximum <= actualMaximum <= maximum
*
* 2. actualMinimum <= value <= actualMaximum
*
* Note: In addition to outright failures, this test reports some
* results as warnings. These are not generally of concern, but they
* should be evaluated by a human. To see these, run this test in
* verbose mode.
* @param cal the calendar to be tested
* @param fieldsToTest an array of field values to be tested, e.g., new
* int[] { Calendar.MONTH, Calendar.DAY_OF_MONTH }. It only makes
* sense to test the day fields; the time fields are not tested by this
* method. If null, then test all standard fields.
* @param startDate the first date to test
* @param testDuration if positive, the number of days to be tested.
* If negative, the number of seconds to run the test.
*/
protected void doLimitsTest(Calendar cal, int[] fieldsToTest,
Date startDate, int testDuration) {
GregorianCalendar greg = new GregorianCalendar();
greg.setTime(startDate);
logln("Start: " + startDate);
if (fieldsToTest == null) {
fieldsToTest = new int[] {
Calendar.ERA, Calendar.YEAR, Calendar.MONTH,
Calendar.WEEK_OF_YEAR, Calendar.WEEK_OF_MONTH,
Calendar.DAY_OF_MONTH, Calendar.DAY_OF_YEAR,
Calendar.DAY_OF_WEEK_IN_MONTH, Calendar.YEAR_WOY,
Calendar.EXTENDED_YEAR
};
}
// Keep a record of minima and maxima that we actually see.
// These are kept in an array of arrays of hashes.
Hashtable[][] limits = new Hashtable[fieldsToTest.length][2];
Object nub = new Object(); // Meaningless placeholder
// This test can run for a long time; show progress.
long millis = System.currentTimeMillis();
long mark = millis + 5000; // 5 sec
millis -= testDuration * 1000; // stop time if testDuration<0
for (int i=0;
testDuration>0 ? i<testDuration
: System.currentTimeMillis()<millis;
++i) {
if (System.currentTimeMillis() >= mark) {
logln("(" + i + " days)");
mark += 5000; // 5 sec
}
cal.setTimeInMillis(greg.getTimeInMillis());
for (int j=0; j<fieldsToTest.length; ++j) {
int f = fieldsToTest[j];
int v = cal.get(f);
int minActual = cal.getActualMinimum(f);
int maxActual = cal.getActualMaximum(f);
int minLow = cal.getMinimum(f);
int minHigh = cal.getGreatestMinimum(f);
int maxLow = cal.getLeastMaximum(f);
int maxHigh = cal.getMaximum(f);
// Fetch the hash for this field and keep track of the
// minima and maxima.
Hashtable[] h = limits[j];
if (h[0] == null) {
h[0] = new Hashtable();
h[1] = new Hashtable();
}
h[0].put(new Integer(minActual), nub);
h[1].put(new Integer(maxActual), nub);
if (minActual < minLow || minActual > minHigh) {
errln("Fail: " + ymdToString(cal) +
" Range for min of " + FIELD_NAME[f] +
"=" + minLow + ".." + minHigh +
", actual_min=" + minActual);
}
if (maxActual < maxLow || maxActual > maxHigh) {
errln("Fail: " + ymdToString(cal) +
" Range for max of " + FIELD_NAME[f] +
"=" + maxLow + ".." + maxHigh +
", actual_max=" + maxActual);
}
if (v < minActual || v > maxActual) {
errln("Fail: " + ymdToString(cal) +
" " + FIELD_NAME[f] + "=" + v +
", actual range=" + minActual + ".." + maxActual +
", allowed=(" + minLow + ".." + minHigh + ")..(" +
maxLow + ".." + maxHigh + ")");
}
}
greg.add(Calendar.DAY_OF_YEAR, 1);
}
// Check actual maxima and minima seen against ranges returned
// by API.
StringBuffer buf = new StringBuffer();
for (int j=0; j<fieldsToTest.length; ++j) {
int f = fieldsToTest[j];
buf.setLength(0);
buf.append(FIELD_NAME[f]);
Hashtable[] h = limits[j];
boolean fullRangeSeen = true;
for (int k=0; k<2; ++k) {
int rangeLow = (k==0) ?
cal.getMinimum(f) : cal.getLeastMaximum(f);
int rangeHigh = (k==0) ?
cal.getGreatestMinimum(f) : cal.getMaximum(f);
// If either the top of the range or the bottom was never
// seen, then there may be a problem.
if (h[k].get(new Integer(rangeLow)) == null ||
h[k].get(new Integer(rangeHigh)) == null) {
fullRangeSeen = false;
}
buf.append(k==0 ? " minima seen=(" : "; maxima seen=(");
for (Enumeration e=h[k].keys(); e.hasMoreElements(); ) {
int v = ((Integer) e.nextElement()).intValue();
buf.append(" " + v);
}
buf.append(") range=" + rangeLow + ".." + rangeHigh);
}
if (fullRangeSeen) {
logln("OK: " + buf.toString());
} else {
// This may or may not be an error -- if the range of dates
// we scan over doesn't happen to contain a minimum or
// maximum, it doesn't mean some other range won't.
logln("Warning: " + buf.toString());
}
}
logln("End: " + greg.getTime());
}
/**
* Convert year,month,day values to the form "year/month/day".
* On input the month value is zero-based, but in the result string it is one-based.
*/
static public String ymdToString(int year, int month, int day) {
return "" + year + "/" + (month+1) + "/" + day;
}
/**
* Convert year,month,day values to the form "year/month/day".
*/
static public String ymdToString(Calendar cal) {
if (cal instanceof ChineseCalendar) {
return "" + cal.get(Calendar.EXTENDED_YEAR) + "/" +
(cal.get(Calendar.MONTH)+1) +
(cal.get(ChineseCalendar.IS_LEAP_MONTH)==1?"(leap)":"") + "/" +
cal.get(Calendar.DATE);
}
return ymdToString(cal.get(Calendar.EXTENDED_YEAR),
cal.get(MONTH), cal.get(DATE));
}
}

View File

@ -1,525 +0,0 @@
/*********************************************************************
* Copyright (C) 2000, International Business Machines Corporation and
* others. All Rights Reserved.
*********************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/ChineseTest.java,v $
* $Date: 2001/10/31 19:06:15 $
* $Revision: 1.8 $
*/
package com.ibm.test.calendar;
import com.ibm.util.*;
import com.ibm.text.*;
import java.util.Date;
import java.util.Locale;
/**
* Test of ChineseCalendar.
*
* Leap months in this century:
* Wed May 23 2001 = 4638-04*-01, Year 18, Cycle 78
* Sun Mar 21 2004 = 4641-02*-01, Year 21, Cycle 78
* Thu Aug 24 2006 = 4643-07*-01, Year 23, Cycle 78
* Tue Jun 23 2009 = 4646-05*-01, Year 26, Cycle 78
* Mon May 21 2012 = 4649-04*-01, Year 29, Cycle 78
* Fri Oct 24 2014 = 4651-09*-01, Year 31, Cycle 78
* Sun Jul 23 2017 = 4654-06*-01, Year 34, Cycle 78
* Sat May 23 2020 = 4657-04*-01, Year 37, Cycle 78
* Wed Mar 22 2023 = 4660-02*-01, Year 40, Cycle 78
* Fri Jul 25 2025 = 4662-06*-01, Year 42, Cycle 78
* Fri Jun 23 2028 = 4665-05*-01, Year 45, Cycle 78
* Tue Apr 22 2031 = 4668-03*-01, Year 48, Cycle 78
* Thu Dec 22 2033 = 4670-11*-01, Year 50, Cycle 78
* Wed Jul 23 2036 = 4673-06*-01, Year 53, Cycle 78
* Wed Jun 22 2039 = 4676-05*-01, Year 56, Cycle 78
* Sat Mar 22 2042 = 4679-02*-01, Year 59, Cycle 78
* Tue Aug 23 2044 = 4681-07*-01, Year 01, Cycle 79
* Sun Jun 23 2047 = 4684-05*-01, Year 04, Cycle 79
* Thu Apr 21 2050 = 4687-03*-01, Year 07, Cycle 79
* Mon Sep 23 2052 = 4689-08*-01, Year 09, Cycle 79
* Sat Jul 24 2055 = 4692-06*-01, Year 12, Cycle 79
* Wed May 22 2058 = 4695-04*-01, Year 15, Cycle 79
* Wed Apr 20 2061 = 4698-03*-01, Year 18, Cycle 79
* Fri Aug 24 2063 = 4700-07*-01, Year 20, Cycle 79
* Wed Jun 23 2066 = 4703-05*-01, Year 23, Cycle 79
* Tue May 21 2069 = 4706-04*-01, Year 26, Cycle 79
* Thu Sep 24 2071 = 4708-08*-01, Year 28, Cycle 79
* Tue Jul 24 2074 = 4711-06*-01, Year 31, Cycle 79
* Sat May 22 2077 = 4714-04*-01, Year 34, Cycle 79
* Sat Apr 20 2080 = 4717-03*-01, Year 37, Cycle 79
* Mon Aug 24 2082 = 4719-07*-01, Year 39, Cycle 79
* Fri Jun 22 2085 = 4722-05*-01, Year 42, Cycle 79
* Fri May 21 2088 = 4725-04*-01, Year 45, Cycle 79
* Sun Sep 24 2090 = 4727-08*-01, Year 47, Cycle 79
* Thu Jul 23 2093 = 4730-06*-01, Year 50, Cycle 79
* Tue May 22 2096 = 4733-04*-01, Year 53, Cycle 79
* Sun Mar 22 2099 = 4736-02*-01, Year 56, Cycle 79
*/
public class ChineseTest extends CalendarTest {
public static void main(String args[]) throws Exception {
new ChineseTest().run(args);
}
/**
* Test basic mapping to and from Gregorian.
*/
public void TestMapping() {
final int[] DATA = {
// (Note: months are 1-based)
// Gregorian Chinese
1964, 9, 4, 4601, 7,0, 28,
1964, 9, 5, 4601, 7,0, 29,
1964, 9, 6, 4601, 8,0, 1,
1964, 9, 7, 4601, 8,0, 2,
1961, 12, 25, 4598, 11,0, 18,
1999, 6, 4, 4636, 4,0, 21,
1990, 5, 23, 4627, 4,0, 29,
1990, 5, 24, 4627, 5,0, 1,
1990, 6, 22, 4627, 5,0, 30,
1990, 6, 23, 4627, 5,1, 1,
1990, 7, 20, 4627, 5,1, 28,
1990, 7, 21, 4627, 5,1, 29,
1990, 7, 22, 4627, 6,0, 1,
};
ChineseCalendar cal = new ChineseCalendar();
StringBuffer buf = new StringBuffer();
logln("Gregorian -> Chinese");
java.util.Calendar tempcal = java.util.Calendar.getInstance();
tempcal.clear();
for (int i=0; i<DATA.length; ) {
tempcal.set(DATA[i++], DATA[i++]-1, DATA[i++]);
Date date = tempcal.getTime();
cal.setTime(date);
int y = cal.get(Calendar.EXTENDED_YEAR);
int m = cal.get(Calendar.MONTH)+1; // 0-based -> 1-based
int L = cal.get(ChineseCalendar.IS_LEAP_MONTH);
int d = cal.get(Calendar.DAY_OF_MONTH);
int yE = DATA[i++]; // Expected y, m, isLeapMonth, d
int mE = DATA[i++]; // 1-based
int LE = DATA[i++];
int dE = DATA[i++];
buf.setLength(0);
buf.append(date + " -> ");
buf.append(y + "/" + m + (L==1?"(leap)":"") + "/" + d);
if (y == yE && m == mE && L == LE && d == dE) {
logln("OK: " + buf.toString());
} else {
errln("Fail: " + buf.toString() + ", expected " +
yE + "/" + mE + (LE==1?"(leap)":"") + "/" + dE);
}
}
logln("Chinese -> Gregorian");
for (int i=0; i<DATA.length; ) {
tempcal.set(DATA[i++], DATA[i++]-1, DATA[i++]);
Date dexp = tempcal.getTime();
int cyear = DATA[i++];
int cmonth = DATA[i++];
int cisleapmonth = DATA[i++];
int cdayofmonth = DATA[i++];
cal.clear();
cal.set(Calendar.EXTENDED_YEAR, cyear);
cal.set(Calendar.MONTH, cmonth-1);
cal.set(ChineseCalendar.IS_LEAP_MONTH, cisleapmonth);
cal.set(Calendar.DAY_OF_MONTH, cdayofmonth);
Date date = cal.getTime();
buf.setLength(0);
buf.append(cyear + "/" + cmonth +
(cisleapmonth==1?"(leap)":"") + "/" + cdayofmonth);
buf.append(" -> " + date);
if (date.equals(dexp)) {
logln("OK: " + buf.toString());
} else {
errln("Fail: " + buf.toString() + ", expected " + dexp);
}
}
}
/**
* Make sure no Gregorian dates map to Chinese 1-based day of
* month zero. This was a problem with some of the astronomical
* new moon determinations.
*/
public void TestZeroDOM() {
ChineseCalendar cal = new ChineseCalendar();
GregorianCalendar greg = new GregorianCalendar(1989, Calendar.SEPTEMBER, 1);
logln("Start: " + greg.getTime());
for (int i=0; i<1000; ++i) {
cal.setTimeInMillis(greg.getTimeInMillis());
if (cal.get(Calendar.DAY_OF_MONTH) == 0) {
errln("Fail: " + greg.getTime() + " -> " +
cal.get(Calendar.EXTENDED_YEAR) + "/" +
cal.get(Calendar.MONTH) +
(cal.get(ChineseCalendar.IS_LEAP_MONTH)==1?"(leap)":"") +
"/" + cal.get(Calendar.DAY_OF_MONTH));
}
greg.add(Calendar.DAY_OF_YEAR, 1);
}
logln("End: " + greg.getTime());
}
/**
* Test minimum and maximum functions.
*/
public void TestLimits() {
// The number of days and the start date can be adjusted
// arbitrarily to either speed up the test or make it more
// thorough, but try to test at least a full year, preferably a
// full non-leap and a full leap year.
// Final parameter is either number of days, if > 0, or test
// duration in seconds, if < 0.
java.util.Calendar tempcal = java.util.Calendar.getInstance();
tempcal.clear();
tempcal.set(1989, Calendar.NOVEMBER, 1);
doLimitsTest(new ChineseCalendar(), null, tempcal.getTime(), -10);
}
/**
* Run through several standard tests from Dershowitz & Reingold.
*/
public void TestJulianDayMapping() {
final TestCase[] tests = {
//
// From Dershowitz & Reingold, "Calendrical Calculations".
//
// The months in this table are 1-based rather than 0-based.
//
// * Failing fields->millis
// ** Millis->fields gives 0-based month -1
// These failures were fixed by changing the start search date
// for the winter solstice from Dec 15 to Dec 1.
//
// Julian Day Era Year Month Leap DOM WkDay
new ChineseTestCase(1507231.5, 35, 11, 6, false, 12, SUN),
new ChineseTestCase(1660037.5, 42, 9, 10, false, 27, WED),
new ChineseTestCase(1746893.5, 46, 7, 8, false, 4, WED),
new ChineseTestCase(1770641.5, 47, 12, 8, false, 9, SUN),
new ChineseTestCase(1892731.5, 52, 46, 11, false, 20, WED),
new ChineseTestCase(1931579.5, 54, 33, 4, false, 5, MON),
new ChineseTestCase(1974851.5, 56, 31, 10, false, 15, SAT),
new ChineseTestCase(2091164.5, 61, 50, 3, false, 7, SUN),
new ChineseTestCase(2121509.5, 63, 13, 4, false, 24, SUN),
new ChineseTestCase(2155779.5, 64, 47, 2, false, 9, FRI),
new ChineseTestCase(2174029.5, 65, 37, 2, false, 9, SAT),
new ChineseTestCase(2191584.5, 66, 25, 2, false, 23, FRI),
new ChineseTestCase(2195261.5, 66, 35, 3, false, 9, SUN), //*
new ChineseTestCase(2229274.5, 68, 8, 5, false, 2, SUN), //*
new ChineseTestCase(2245580.5, 68, 53, 1, false, 8, WED), //**
new ChineseTestCase(2266100.5, 69, 49, 3, false, 4, SAT),
new ChineseTestCase(2288542.5, 70, 50, 8, false, 2, SAT), //*
new ChineseTestCase(2290901.5, 70, 57, 1, false, 29, SAT), //*
new ChineseTestCase(2323140.5, 72, 25, 4, true, 20, WED), //*
new ChineseTestCase(2334848.5, 72, 57, 6, false, 5, SUN),
new ChineseTestCase(2348020.5, 73, 33, 6, false, 6, FRI),
new ChineseTestCase(2366978.5, 74, 25, 5, false, 5, SUN),
new ChineseTestCase(2385648.5, 75, 16, 6, false, 12, MON),
new ChineseTestCase(2392825.5, 75, 36, 2, false, 13, WED),
new ChineseTestCase(2416223.5, 76, 40, 3, false, 22, SUN),
new ChineseTestCase(2425848.5, 77, 6, 7, false, 21, SUN),
new ChineseTestCase(2430266.5, 77, 18, 8, false, 9, MON),
new ChineseTestCase(2430833.5, 77, 20, 3, false, 15, MON),
new ChineseTestCase(2431004.5, 77, 20, 9, false, 9, THU),
new ChineseTestCase(2448698.5, 78, 9, 2, false, 14, TUE),
new ChineseTestCase(2450138.5, 78, 13, 1, false, 7, SUN),
new ChineseTestCase(2465737.5, 78, 55, 10, false, 14, WED),
new ChineseTestCase(2486076.5, 79, 51, 6, false, 7, SUN),
// Additional tests not from D&R
new ChineseTestCase(2467496.5, 78, 60, 8, false, 2, FRI), // year 60
};
ChineseCalendar cal = new ChineseCalendar();
cal.setLenient(true);
doTestCases(tests, cal);
}
/**
* Test formatting.
*/
public void TestFormat() {
ChineseCalendar cal = new ChineseCalendar();
DateFormat fmt = DateFormat.getDateTimeInstance(cal,
DateFormat.DEFAULT, DateFormat.DEFAULT);
java.util.Calendar tempcal = java.util.Calendar.getInstance();
tempcal.clear();
Date[] DATA = new Date[2];
tempcal.set(2001, Calendar.MAY, 22);
DATA[0] = tempcal.getTime();
tempcal.set(2001, Calendar.MAY, 23);
DATA[1] = tempcal.getTime();
// Wed May 23 2001 = Month 4(leap), Day 1, Year 18, Cycle 78
for (int i=0; i<DATA.length; ++i) {
String s = fmt.format(DATA[i]);
try {
Date e = fmt.parse(s);
if (e.equals(DATA[i])) {
logln("Ok: " + DATA[i] + " -> " + s + " -> " + e);
} else {
errln("FAIL: " + DATA[i] + " -> " + s + " -> " + e);
}
} catch (java.text.ParseException e) {
errln("Fail: " + s + " -> parse failure at " + e.getErrorOffset());
errln(e.toString());
}
}
}
/**
* Make sure IS_LEAP_MONTH participates in field resolution.
*/
public void TestResolution() {
ChineseCalendar cal = new ChineseCalendar();
DateFormat fmt = DateFormat.getDateInstance(cal, DateFormat.DEFAULT);
// May 22 2001 = y4638 m4 d30 doy119
// May 23 2001 = y4638 m4* d1 doy120
final int THE_YEAR = 4638;
final int END = -1;
int[] DATA = {
// Format:
// (field, value)+, END, exp.month, exp.isLeapMonth, exp.DOM
// Note: exp.month is ONE-BASED
// If we set DAY_OF_YEAR only, that should be used
Calendar.DAY_OF_YEAR, 1,
END,
1,0,1, // Expect 1-1
// If we set MONTH only, that should be used
ChineseCalendar.IS_LEAP_MONTH, 1,
Calendar.DAY_OF_MONTH, 1,
Calendar.MONTH, 3,
END,
4,1,1, // Expect 4*-1
// If we set the DOY last, that should take precedence
Calendar.MONTH, 1, // Should ignore
ChineseCalendar.IS_LEAP_MONTH, 1, // Should ignore
Calendar.DAY_OF_MONTH, 1, // Should ignore
Calendar.DAY_OF_YEAR, 121,
END,
4,1,2, // Expect 4*-2
// I've disabled this test because it doesn't work this way,
// not even with a GregorianCalendar! MONTH alone isn't enough
// to supersede DAY_OF_YEAR. Some other month-related field is
// also required. - Liu 11/28/00
//! // If we set MONTH last, that should take precedence
//! ChineseCalendar.IS_LEAP_MONTH, 1,
//! Calendar.DAY_OF_MONTH, 1,
//! Calendar.DAY_OF_YEAR, 5, // Should ignore
//! Calendar.MONTH, 3,
//! END,
//! 4,1,1, // Expect 4*-1
// If we set IS_LEAP_MONTH last, that should take precedence
Calendar.MONTH, 3,
Calendar.DAY_OF_MONTH, 1,
Calendar.DAY_OF_YEAR, 5, // Should ignore
ChineseCalendar.IS_LEAP_MONTH, 1,
END,
4,1,1, // Expect 4*-1
};
StringBuffer buf = new StringBuffer();
for (int i=0; i<DATA.length; ) {
cal.clear();
cal.set(Calendar.EXTENDED_YEAR, THE_YEAR);
buf.setLength(0);
buf.append("EXTENDED_YEAR=" + THE_YEAR);
while (DATA[i] != END) {
cal.set(DATA[i++], DATA[i++]);
buf.append(" " + fieldName(DATA[i-2]) + "=" + DATA[i-1]);
}
++i; // Skip over END mark
int expMonth = DATA[i++]-1;
int expIsLeapMonth = DATA[i++];
int expDOM = DATA[i++];
int month = cal.get(Calendar.MONTH);
int isLeapMonth = cal.get(ChineseCalendar.IS_LEAP_MONTH);
int dom = cal.get(Calendar.DAY_OF_MONTH);
if (expMonth == month && expIsLeapMonth == isLeapMonth &&
dom == expDOM) {
logln("OK: " + buf + " => " + fmt.format(cal.getTime()));
} else {
String s = fmt.format(cal.getTime());
cal.clear();
cal.set(Calendar.EXTENDED_YEAR, THE_YEAR);
cal.set(Calendar.MONTH, expMonth);
cal.set(ChineseCalendar.IS_LEAP_MONTH, expIsLeapMonth);
cal.set(Calendar.DAY_OF_MONTH, expDOM);
errln("Fail: " + buf + " => " + s +
"=" + (month+1) + "," + isLeapMonth + "," + dom +
", expected " + fmt.format(cal.getTime()) +
"=" + (expMonth+1) + "," + expIsLeapMonth + "," + expDOM);
}
}
}
/**
* Test the behavior of fields that are out of range.
*/
public void TestOutOfRange() {
int[] DATA = new int[] {
// Input Output
4638, 13, 1, 4639, 1, 1,
4638, 18, 1, 4639, 6, 1,
4639, 0, 1, 4638, 12, 1,
4639, -6, 1, 4638, 6, 1,
4638, 1, 32, 4638, 2, 2, // 1-4638 has 30 days
4638, 2, -1, 4638, 1, 29,
};
ChineseCalendar cal = new ChineseCalendar();
for (int i=0; i<DATA.length; ) {
int y1 = DATA[i++];
int m1 = DATA[i++]-1;
int d1 = DATA[i++];
int y2 = DATA[i++];
int m2 = DATA[i++]-1;
int d2 = DATA[i++];
cal.clear();
cal.set(Calendar.EXTENDED_YEAR, y1);
cal.set(MONTH, m1);
cal.set(DATE, d1);
int y = cal.get(Calendar.EXTENDED_YEAR);
int m = cal.get(MONTH);
int d = cal.get(DATE);
if (y!=y2 || m!=m2 || d!=d2) {
errln("Fail: " + y1 + "/" + (m1+1) + "/" + d1 + " resolves to " +
y + "/" + (m+1) + "/" + d + ", expected " +
y2 + "/" + (m2+1) + "/" + d2);
} else if (isVerbose()) {
logln("OK: " + y1 + "/" + (m1+1) + "/" + d1 + " resolves to " +
y + "/" + (m+1) + "/" + d);
}
}
}
/**
* Test the behavior of ChineseCalendar.add(). The only real
* nastiness with roll is the MONTH field around leap months.
*/
public void TestAdd() {
int[][] tests = new int[][] {
// MONTHS ARE 1-BASED HERE
// input add output
// year mon day field amount year mon day
{ 4642, 3,0, 15, MONTH, 3, 4642, 6,0, 15 }, // normal
{ 4639, 12,0, 15, MONTH, 1, 4640, 1,0, 15 }, // across year
{ 4640, 1,0, 15, MONTH, -1, 4639, 12,0, 15 }, // across year
{ 4638, 3,0, 15, MONTH, 3, 4638, 5,0, 15 }, // 4=leap
{ 4638, 3,0, 15, MONTH, 2, 4638, 4,1, 15 }, // 4=leap
{ 4638, 4,0, 15, MONTH, 1, 4638, 4,1, 15 }, // 4=leap
{ 4638, 4,1, 15, MONTH, 1, 4638, 5,0, 15 }, // 4=leap
{ 4638, 4,0, 30, MONTH, 1, 4638, 4,1, 29 }, // dom should pin
{ 4638, 4,0, 30, MONTH, 2, 4638, 5,0, 30 }, // no dom pin
{ 4638, 4,0, 30, MONTH, 3, 4638, 6,0, 29 }, // dom should pin
};
ChineseCalendar cal = new ChineseCalendar();
doRollAdd(ADD, cal, tests);
}
/**
* Test the behavior of ChineseCalendar.roll(). The only real
* nastiness with roll is the MONTH field around leap months.
*/
public void TestRoll() {
int[][] tests = new int[][] {
// MONTHS ARE 1-BASED HERE
// input add output
// year mon day field amount year mon day
{ 4642, 3,0, 15, MONTH, 3, 4642, 6,0, 15 }, // normal
{ 4642, 3,0, 15, MONTH, 11, 4642, 2,0, 15 }, // normal
{ 4639, 12,0, 15, MONTH, 1, 4639, 1,0, 15 }, // across year
{ 4640, 1,0, 15, MONTH, -1, 4640, 12,0, 15 }, // across year
{ 4638, 3,0, 15, MONTH, 3, 4638, 5,0, 15 }, // 4=leap
{ 4638, 3,0, 15, MONTH, 16, 4638, 5,0, 15 }, // 4=leap
{ 4638, 3,0, 15, MONTH, 2, 4638, 4,1, 15 }, // 4=leap
{ 4638, 3,0, 15, MONTH, 28, 4638, 4,1, 15 }, // 4=leap
{ 4638, 4,0, 15, MONTH, 1, 4638, 4,1, 15 }, // 4=leap
{ 4638, 4,0, 15, MONTH, -12, 4638, 4,1, 15 }, // 4=leap
{ 4638, 4,1, 15, MONTH, 1, 4638, 5,0, 15 }, // 4=leap
{ 4638, 4,1, 15, MONTH, -25, 4638, 5,0, 15 }, // 4=leap
{ 4638, 4,0, 30, MONTH, 1, 4638, 4,1, 29 }, // dom should pin
{ 4638, 4,0, 30, MONTH, 14, 4638, 4,1, 29 }, // dom should pin
{ 4638, 4,0, 30, MONTH, 15, 4638, 5,0, 30 }, // no dom pin
{ 4638, 4,0, 30, MONTH, -10, 4638, 6,0, 29 }, // dom should pin
};
ChineseCalendar cal = new ChineseCalendar();
doRollAdd(ROLL, cal, tests);
}
void doRollAdd(boolean roll, ChineseCalendar cal, int[][] tests) {
String name = roll ? "rolling" : "adding";
for (int i = 0; i < tests.length; i++) {
int[] test = tests[i];
cal.clear();
cal.set(Calendar.EXTENDED_YEAR, test[0]);
cal.set(Calendar.MONTH, test[1]-1);
cal.set(ChineseCalendar.IS_LEAP_MONTH, test[2]);
cal.set(Calendar.DAY_OF_MONTH, test[3]);
if (roll) {
cal.roll(test[4], test[5]);
} else {
cal.add(test[4], test[5]);
}
if (cal.get(Calendar.EXTENDED_YEAR) != test[6] ||
cal.get(MONTH) != (test[7]-1) ||
cal.get(ChineseCalendar.IS_LEAP_MONTH) != test[8] ||
cal.get(DATE) != test[9]) {
errln("Fail: " + name + " " +
ymdToString(test[0], test[1]-1, test[2], test[3])
+ " " + fieldName(test[4]) + " by " + test[5]
+ ": expected " +
ymdToString(test[6], test[7]-1, test[8], test[9])
+ ", got " + ymdToString(cal));
} else if (isVerbose()) {
logln("OK: " + name + " " +
ymdToString(test[0], test[1]-1, test[2], test[3])
+ " " + fieldName(test[4]) + " by " + test[5]
+ ": got " + ymdToString(cal));
}
}
}
/**
* Convert year,month,day values to the form "year/month/day".
* On input the month value is zero-based, but in the result string it is one-based.
*/
static public String ymdToString(int year, int month, int isLeapMonth, int day) {
return "" + year + "/" + (month+1) +
((isLeapMonth!=0)?"(leap)":"") +
"/" + day;
}
// public void TestFindLeapMonths() {
// ChineseCalendar cal = new ChineseCalendar();
// cal.setTime(new Date(2000-1900, Calendar.JANUARY, 1));
// long end = new Date(2100-1900, Calendar.JANUARY, 1).getTime();
// ChineseDateFormat fmt = (ChineseDateFormat) DateFormat.getInstance(cal);
// fmt.applyPattern("u-MMl-dd, 'Year' y, 'Cycle' G");
// while (cal.getTimeInMillis() < end) {
// if (cal.get(ChineseCalendar.IS_LEAP_MONTH) != 0) {
// cal.set(Calendar.DAY_OF_MONTH, 1);
// logln(cal.getTime() + " = " + fmt.format(cal.getTime()));
// cal.set(Calendar.DAY_OF_MONTH, 29);
// }
// cal.add(Calendar.DAY_OF_YEAR, 25);
// }
// }
}

View File

@ -1,48 +0,0 @@
package com.ibm.test.calendar;
import com.ibm.util.*;
import java.util.Date;
public class ChineseTestCase extends TestCase {
/**
* Initialize an object using a Julian day number and
* the corresponding fields for the calendar being tested.
*
* @param era the ERA field of tested calendar on the given Julian
* day
* @param year the YEAR field of tested calendar on the given
* Julian day
* @param month the MONTH (1-based) field of tested calendar on
* the given Julian day
* @param isLeapMonth if true, treat month as a leap month
* @param dayOfMonth the DAY_OF_MONTH field of tested calendar on the
* given Julian day
* @param dayOfWeek the DAY_OF_WEEK field of tested calendar on given
* Julian day
*/
public ChineseTestCase(double julian,
int era, int year, int month,
boolean isLeapMonth, int dayOfMonth, int dayOfWeek) {
setTime(new Date(JULIAN_EPOCH + (long)(ONE_DAY * julian)));
set(Calendar.ERA, era);
set(Calendar.YEAR, year);
set(Calendar.MONTH, month - 1);
set(ChineseCalendar.IS_LEAP_MONTH, isLeapMonth?1:0);
set(Calendar.DAY_OF_MONTH, dayOfMonth);
set(Calendar.DAY_OF_WEEK, dayOfWeek);
}
/**
* Return a String representation of this test case's time.
*/
public String toString() {
return dowToString(get(Calendar.DAY_OF_WEEK)) +
get(Calendar.YEAR) + "of" + get(Calendar.ERA) +
"/" + (get(Calendar.MONTH)+1) +
(get(ChineseCalendar.IS_LEAP_MONTH)==1?"(leap)":"") + "/" +
get(Calendar.DAY_OF_MONTH);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,314 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/HebrewTest.java,v $
* $Date: 2000/11/18 00:17:58 $
* $Revision: 1.3 $
*
*****************************************************************************************
*/
package com.ibm.test.calendar;
import com.ibm.test.*;
import com.ibm.util.*;
import java.util.Locale;
/**
* Tests for the <code>HebrewCalendar</code> class.
*/
public class HebrewTest extends CalendarTest {
public static void main(String args[]) throws Exception {
new HebrewTest().run(args);
}
// Constants to save typing.
public static final int TISHRI = HebrewCalendar.TISHRI;
public static final int HESHVAN = HebrewCalendar.HESHVAN;
public static final int KISLEV = HebrewCalendar.KISLEV;
public static final int TEVET = HebrewCalendar.TEVET;
public static final int SHEVAT = HebrewCalendar.SHEVAT;
public static final int ADAR_1 = HebrewCalendar.ADAR_1;
public static final int ADAR = HebrewCalendar.ADAR;
public static final int NISAN = HebrewCalendar.NISAN;
public static final int IYAR = HebrewCalendar.IYAR;
public static final int SIVAN = HebrewCalendar.SIVAN;
public static final int TAMUZ = HebrewCalendar.TAMUZ;
public static final int AV = HebrewCalendar.AV;
public static final int ELUL = HebrewCalendar.ELUL;
/**
* Test the behavior of HebrewCalendar.roll
* The only real nastiness with roll is the MONTH field, since a year can
* have a variable number of months.
*/
public void TestRoll() {
int[][] tests = new int[][] {
// input roll by output
// year month day field amount year month day
{ 5759, HESHVAN, 2, MONTH, 1, 5759, KISLEV, 2 }, // non-leap years
{ 5759, SHEVAT, 2, MONTH, 1, 5759, ADAR, 2 },
{ 5759, SHEVAT, 2, MONTH, 2, 5759, NISAN, 2 },
{ 5759, SHEVAT, 2, MONTH, 12, 5759, SHEVAT, 2 },
{ 5759, AV, 1, MONTH, 12, 5759, AV, 1 }, // Alan
{ 5757, HESHVAN, 2, MONTH, 1, 5757, KISLEV, 2 }, // leap years
{ 5757, SHEVAT, 2, MONTH, 1, 5757, ADAR_1, 2 },
{ 5757, SHEVAT, 2, MONTH, 2, 5757, ADAR, 2 },
{ 5757, SHEVAT, 2, MONTH, 3, 5757, NISAN, 2 },
{ 5757, SHEVAT, 2, MONTH, 12, 5757, TEVET, 2 },
{ 5757, SHEVAT, 2, MONTH, 13, 5757, SHEVAT, 2 },
{ 5757, AV, 1, MONTH, 12, 5757, TAMUZ, 1 }, // Alan
{ 5757, KISLEV, 1, DATE, 30, 5757, KISLEV, 2 }, // 29-day month
{ 5758, KISLEV, 1, DATE, 31, 5758, KISLEV, 2 }, // 30-day month
// Try some other fields too
{ 5757, TISHRI, 1, YEAR, 1, 5758, TISHRI, 1 },
// Try some rolls that require other fields to be adjusted
{ 5757, TISHRI, 30, MONTH, 1, 5757, HESHVAN, 29 },
{ 5758, KISLEV, 30, YEAR, -1, 5757, KISLEV, 29 },
};
HebrewCalendar cal = new HebrewCalendar(UTC, Locale.getDefault());
doRollAdd(ROLL, cal, tests);
}
/**
* Test the behavior of HebrewCalendar.roll
* The only real nastiness with roll is the MONTH field, since a year can
* have a variable number of months.
*/
public void TestAdd() {
int[][] tests = new int[][] {
// input add by output
// year month day field amount year month day
{ 5759, HESHVAN, 2, MONTH, 1, 5759, KISLEV, 2 }, // non-leap years
{ 5759, SHEVAT, 2, MONTH, 1, 5759, ADAR, 2 },
{ 5759, SHEVAT, 2, MONTH, 2, 5759, NISAN, 2 },
{ 5759, SHEVAT, 2, MONTH, 12, 5760, SHEVAT, 2 },
{ 5757, HESHVAN, 2, MONTH, 1, 5757, KISLEV, 2 }, // leap years
{ 5757, SHEVAT, 2, MONTH, 1, 5757, ADAR_1, 2 },
{ 5757, SHEVAT, 2, MONTH, 2, 5757, ADAR, 2 },
{ 5757, SHEVAT, 2, MONTH, 3, 5757, NISAN, 2 },
{ 5757, SHEVAT, 2, MONTH, 12, 5758, TEVET, 2 },
{ 5757, SHEVAT, 2, MONTH, 13, 5758, SHEVAT, 2 },
{ 5757, KISLEV, 1, DATE, 30, 5757, TEVET, 2 }, // 29-day month
{ 5758, KISLEV, 1, DATE, 31, 5758, TEVET, 2 }, // 30-day month
};
HebrewCalendar cal = new HebrewCalendar(UTC, Locale.getDefault());
doRollAdd(ADD, cal, tests);
}
/**
* A huge list of test cases to make sure that computeTime and computeFields
* work properly for a wide range of data.
*/
public void TestCases() {
doTestCases(testCases, new HebrewCalendar());
}
static final TestCase[] testCases = {
//
// Most of these test cases were taken from the back of
// "Calendrical Calculations", with some extras added to help
// debug a few of the problems that cropped up in development.
//
// The months in this table are 1-based rather than 0-based,
// because it's easier to edit that way.
//
// Julian Day Era Year Month Day WkDay Hour Min Sec
new TestCase(1507231.5, 0, 3174, 12, 10, SUN, 0, 0, 0),
new TestCase(1660037.5, 0, 3593, 3, 25, WED, 0, 0, 0),
new TestCase(1746893.5, 0, 3831, 1, 3, WED, 0, 0, 0),
new TestCase(1770641.5, 0, 3896, 1, 9, SUN, 0, 0, 0),
new TestCase(1892731.5, 0, 4230, 4, 18, WED, 0, 0, 0),
new TestCase(1931579.5, 0, 4336, 10, 4, MON, 0, 0, 0),
new TestCase(1974851.5, 0, 4455, 2, 13, SAT, 0, 0, 0),
new TestCase(2091164.5, 0, 4773, 9, 6, SUN, 0, 0, 0),
new TestCase(2121509.5, 0, 4856, 9, 23, SUN, 0, 0, 0),
new TestCase(2155779.5, 0, 4950, 8, 7, FRI, 0, 0, 0),
new TestCase(2174029.5, 0, 5000, 7, 8, SAT, 0, 0, 0),
new TestCase(2191584.5, 0, 5048, 8, 21, FRI, 0, 0, 0),
new TestCase(2195261.5, 0, 5058, 9, 7, SUN, 0, 0, 0),
new TestCase(2229274.5, 0, 5151, 11, 1, SUN, 0, 0, 0),
new TestCase(2245580.5, 0, 5196, 5, 7, WED, 0, 0, 0),
new TestCase(2266100.5, 0, 5252, 8, 3, SAT, 0, 0, 0),
new TestCase(2288542.5, 0, 5314, 1, 1, SAT, 0, 0, 0),
new TestCase(2290901.5, 0, 5320, 6, 27, SAT, 0, 0, 0),
new TestCase(2323140.5, 0, 5408, 10, 20, WED, 0, 0, 0),
new TestCase(2334551.5, 0, 5440, 1, 1, THU, 0, 0, 0),
new TestCase(2334581.5, 0, 5440, 2, 1, SAT, 0, 0, 0),
new TestCase(2334610.5, 0, 5440, 3, 1, SUN, 0, 0, 0),
new TestCase(2334639.5, 0, 5440, 4, 1, MON, 0, 0, 0),
new TestCase(2334668.5, 0, 5440, 5, 1, TUE, 0, 0, 0),
new TestCase(2334698.5, 0, 5440, 6, 1, THU, 0, 0, 0),
new TestCase(2334728.5, 0, 5440, 7, 1, SAT, 0, 0, 0),
new TestCase(2334757.5, 0, 5440, 8, 1, SUN, 0, 0, 0),
new TestCase(2334787.5, 0, 5440, 9, 1, TUE, 0, 0, 0),
new TestCase(2334816.5, 0, 5440, 10, 1, WED, 0, 0, 0),
new TestCase(2334846.5, 0, 5440, 11, 1, FRI, 0, 0, 0),
new TestCase(2334848.5, 0, 5440, 11, 3, SUN, 0, 0, 0),
new TestCase(2334934.5, 0, 5441, 1, 1, TUE, 0, 0, 0),
new TestCase(2348020.5, 0, 5476, 12, 5, FRI, 0, 0, 0),
new TestCase(2366978.5, 0, 5528, 11, 4, SUN, 0, 0, 0),
new TestCase(2385648.5, 0, 5579, 12, 11, MON, 0, 0, 0),
new TestCase(2392825.5, 0, 5599, 8, 12, WED, 0, 0, 0),
new TestCase(2416223.5, 0, 5663, 8, 22, SUN, 0, 0, 0),
new TestCase(2425848.5, 0, 5689, 12, 19, SUN, 0, 0, 0),
new TestCase(2430266.5, 0, 5702, 1, 8, MON, 0, 0, 0),
new TestCase(2430833.5, 0, 5703, 8, 14, MON, 0, 0, 0),
new TestCase(2431004.5, 0, 5704, 1, 8, THU, 0, 0, 0),
new TestCase(2448698.5, 0, 5752, 7, 12, TUE, 0, 0, 0),
new TestCase(2450138.5, 0, 5756, 7, 5, SUN, 0, 0, 0),
new TestCase(2465737.5, 0, 5799, 2, 12, WED, 0, 0, 0),
new TestCase(2486076.5, 0, 5854, 12, 5, SUN, 0, 0, 0),
// Additional test cases for bugs found during development
// G.YY/MM/DD Era Year Month Day WkDay Hour Min Sec
new TestCase(1013, 9, 8, 0, 4774, 1, 1, TUE, 0, 0, 0),
new TestCase(1239, 9, 1, 0, 5000, 1, 1, THU, 0, 0, 0),
new TestCase(1240, 9,18, 0, 5001, 1, 1, TUE, 0, 0, 0),
// Test cases taken from a table of 14 "year types" in the Help file
// of the application "Hebrew Calendar"
new TestCase(2456187.5, 0, 5773, 1, 1, MON, 0, 0, 0),
new TestCase(2459111.5, 0, 5781, 1, 1, SAT, 0, 0, 0),
new TestCase(2453647.5, 0, 5766, 1, 1, TUE, 0, 0, 0),
new TestCase(2462035.5, 0, 5789, 1, 1, THU, 0, 0, 0),
new TestCase(2458756.5, 0, 5780, 1, 1, MON, 0, 0, 0),
new TestCase(2460586.5, 0, 5785, 1, 1, THU, 0, 0, 0),
new TestCase(2463864.5, 0, 5794, 1, 1, SAT, 0, 0, 0),
new TestCase(2463481.5, 0, 5793, 1, 1, MON, 0, 0, 0),
new TestCase(2470421.5, 0, 5812, 1, 1, THU, 0, 0, 0),
new TestCase(2460203.5, 0, 5784, 1, 1, SAT, 0, 0, 0),
new TestCase(2459464.5, 0, 5782, 1, 1, TUE, 0, 0, 0),
new TestCase(2467142.5, 0, 5803, 1, 1, MON, 0, 0, 0),
new TestCase(2455448.5, 0, 5771, 1, 1, THU, 0, 0, 0),
new TestCase(2487223.5, 0, 5858, 1, 1, SAT, 0, 0, 0),
};
/**
* Problem reported by Armand Bendanan in which setting of the MONTH
* field in a Hebrew calendar causes the time fields to go negative.
*/
public void TestTimeFields() {
HebrewCalendar calendar = new HebrewCalendar(5761, 0, 11, 12, 28, 15);
calendar.set(Calendar.YEAR, 5717);
calendar.set(Calendar.MONTH, 2);
calendar.set(Calendar.DAY_OF_MONTH, 23);
if (calendar.get(Calendar.HOUR_OF_DAY) != 12) {
errln("Fail: HebrewCalendar HOUR_OF_DAY = " + calendar.get(Calendar.HOUR_OF_DAY));
}
}
/**
* Test of the behavior of the month field. This requires special
* handling in the Hebrew calendar because of the pattern of leap
* years.
*/
public void TestMonthMovement() {
HebrewCalendar cal = new HebrewCalendar();
// Leap years are:
// 3 6 8 11 14 17 19 (and so on - 19-year cycle)
// We can't test complete() on some lines below because of ADAR_1 -- if
// the calendar is set to ADAR_1 on a non-leap year, the result is undefined.
int[] DATA = {
// c - test complete() or not
// m/y - before and after month/year
// delta - amount to add to month field
//c m1 y1 delta m2 y2
1, 10, 2, +24, 9, 4, // (year 2, month 10) + 24 months -> (y 4, m 9)
1, 10, 2, +60, 8, 7, // (y 2, m 10) + 60 months -> (y 7, m 8)
1, 1, 2, +12, 1, 3, // (y 2, m 1) + 12 months -> (y 3, m 1)
1, 3, 18, -24, 4, 16, // (y 18, m 3) - 24 months -> (y 16, m 4)
1, 1, 6, -24, 1, 4,
1, 4, 3, +2, 6, 3, // Leap year - no skip 4,5,6,7,8
1, 8, 3, -2, 6, 3, // Leap year - no skip
0, 4, 2, +2, 7, 2, // Skip over leap month 4,5,(6),7,8
0, 8, 2, -2, 5, 2, // Skip over leap month going backward
};
for (int i=0; i<DATA.length; ) {
boolean testComplete = DATA[i++] != 0;
int m = DATA[i++], y = DATA[i++];
int monthDelta = DATA[i++];
int m2 = DATA[i++], y2 = DATA[i++];
int mact, yact;
cal.clear();
cal.set(Calendar.YEAR, y);
cal.set(Calendar.MONTH, m-1);
cal.add(Calendar.MONTH, monthDelta);
yact = cal.get(Calendar.YEAR); mact = cal.get(Calendar.MONTH) + 1;
if (y2 != yact || m2 != mact) {
errln("Fail: " + m + "/" + y +
" -> add(MONTH, " + monthDelta + ") -> " +
mact + "/" + yact + ", expected " +
m2 + "/" + y2);
cal.clear();
cal.set(Calendar.YEAR, y);
cal.set(Calendar.MONTH, m-1);
logln("Start: " + m + "/" + y);
int delta = monthDelta > 0 ? 1 : -1;
for (int c=0; c!=monthDelta; c+=delta) {
cal.add(Calendar.MONTH, delta);
logln("+ " + delta + " MONTH -> " +
(cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR));
}
}
if (testComplete) {
cal.clear();
cal.set(Calendar.YEAR, y);
cal.set(Calendar.MONTH, m + monthDelta - 1);
yact = cal.get(Calendar.YEAR); mact = cal.get(Calendar.MONTH) + 1;
if (y2 != yact || m2 != mact) {
errln("Fail: " + (m+monthDelta) + "/" + y +
" -> complete() -> " +
mact + "/" + yact + ", expected " +
m2 + "/" + y2);
}
}
}
}
/**
* Test handling of ADAR_1.
*/
/*
public void TestAdar1() {
HebrewCalendar cal = new HebrewCalendar();
cal.clear();
cal.set(Calendar.YEAR, 1903); // leap
cal.set(Calendar.MONTH, HebrewCalendar.ADAR_1);
logln("1903(leap)/ADAR_1 => " +
cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH)+1));
cal.clear();
cal.set(Calendar.YEAR, 1904); // non-leap
cal.set(Calendar.MONTH, HebrewCalendar.ADAR_1);
logln("1904(non-leap)/ADAR_1 => " +
cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH)+1));
}
*/
/**
* With no fields set, the calendar should use default values.
*/
public void TestDefaultFieldValues() {
HebrewCalendar cal = new HebrewCalendar();
cal.clear();
logln("cal.clear() -> " + cal.getTime());
}
};

View File

@ -1,218 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 2000, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/IBMCalendarTest.java,v $
* $Date: 2001/10/30 02:42:49 $
* $Revision: 1.5 $
*******************************************************************************
*/
package com.ibm.test.calendar;
import com.ibm.test.TestFmwk;
import com.ibm.util.*;
import java.text.*;
import java.util.Date;
import java.util.Locale;
/**
* @test
* @summary Tests of new functionality in IBMCalendar
*/
public class IBMCalendarTest extends CalendarTest {
public static void main(String[] args) throws Exception {
new IBMCalendarTest().run(args);
}
/**
* Test weekend support in IBMCalendar.
*
* NOTE: This test will have to be updated when the isWeekend() etc.
* API is finalized later.
*
* In particular, the test will have to be rewritten to instantiate
* a Calendar in the given locale (using getInstance()) and call
* that Calendar's isWeekend() etc. methods.
*/
public void TestWeekend() {
SimpleDateFormat fmt = new SimpleDateFormat("EEE MMM dd yyyy G HH:mm:ss.SSS");
// NOTE
// This test tests for specific locale data. This is probably okay
// as far as US data is concerned, but if the Arabic/Bahrain data
// changes, this test will have to be updated.
// Test specific days
Object[] DATA1 = {
Locale.US, new int[] { // Saturday:Sunday
2000, Calendar.MARCH, 17, 23, 0, 0, // Fri 23:00
2000, Calendar.MARCH, 18, 0, -1, 0, // Fri 23:59:59.999
2000, Calendar.MARCH, 18, 0, 0, 1, // Sat 00:00
2000, Calendar.MARCH, 18, 15, 0, 1, // Sat 15:00
2000, Calendar.MARCH, 19, 23, 0, 1, // Sun 23:00
2000, Calendar.MARCH, 20, 0, -1, 1, // Sun 23:59:59.999
2000, Calendar.MARCH, 20, 0, 0, 0, // Mon 00:00
2000, Calendar.MARCH, 20, 8, 0, 0, // Mon 08:00
},
new Locale("ar", "BH"), new int[] { // Thursday:Friday
2000, Calendar.MARCH, 15, 23, 0, 0, // Wed 23:00
2000, Calendar.MARCH, 16, 0, -1, 0, // Wed 23:59:59.999
2000, Calendar.MARCH, 16, 0, 0, 1, // Thu 00:00
2000, Calendar.MARCH, 16, 15, 0, 1, // Thu 15:00
2000, Calendar.MARCH, 17, 23, 0, 1, // Fri 23:00
2000, Calendar.MARCH, 18, 0, -1, 1, // Fri 23:59:59.999
2000, Calendar.MARCH, 18, 0, 0, 0, // Sat 00:00
2000, Calendar.MARCH, 18, 8, 0, 0, // Sat 08:00
},
};
// Test days of the week
Object[] DATA2 = {
Locale.US, new int[] {
Calendar.MONDAY, Calendar.WEEKDAY,
Calendar.FRIDAY, Calendar.WEEKDAY,
Calendar.SATURDAY, Calendar.WEEKEND,
Calendar.SUNDAY, Calendar.WEEKEND,
},
new Locale("ar", "BH"), new int[] { // Thursday:Friday
Calendar.WEDNESDAY,Calendar.WEEKDAY,
Calendar.SATURDAY, Calendar.WEEKDAY,
Calendar.THURSDAY, Calendar.WEEKEND,
Calendar.FRIDAY, Calendar.WEEKEND,
},
};
// We only test the getDayOfWeekType() and isWeekend() APIs.
// The getWeekendTransition() API is tested indirectly via the
// isWeekend() API, which calls it.
for (int i1=0; i1<DATA1.length; i1+=2) {
Locale loc = (Locale)DATA1[i1];
int[] data = (int[]) DATA1[i1+1];
Calendar cal = Calendar.getInstance(loc);
logln("Locale: " + loc);
for (int i=0; i<data.length; i+=6) {
cal.clear();
cal.set(data[i], data[i+1], data[i+2], data[i+3], 0, 0);
if (data[i+4] != 0) {
cal.setTime(new Date(cal.getTime().getTime() + data[i+4]));
}
boolean isWeekend = cal.isWeekend();
boolean ok = isWeekend == (data[i+5] != 0);
if (ok) {
logln("Ok: " + fmt.format(cal.getTime()) + " isWeekend=" + isWeekend);
} else {
errln("FAIL: " + fmt.format(cal.getTime()) + " isWeekend=" + isWeekend +
", expected=" + (!isWeekend));
}
}
}
for (int i2=0; i2<DATA2.length; i2+=2) {
Locale loc = (Locale)DATA2[i2];
int[] data = (int[]) DATA2[i2+1];
logln("Locale: " + loc);
Calendar cal = Calendar.getInstance(loc);
for (int i=0; i<data.length; i+=2) {
int type = cal.getDayOfWeekType(data[i]);
int exp = data[i+1];
if (type == exp) {
logln("Ok: DOW " + data[i] + " type=" + type);
} else {
errln("FAIL: DOW " + data[i] + " type=" + type +
", expected=" + exp);
}
}
}
}
/**
* Run a test of a quasi-Gregorian calendar. This is a calendar
* that behaves like a Gregorian but has different year/era mappings.
* The int[] data array should have the format:
*
* { era, year, gregorianYear, month, dayOfMonth, ... }
*/
void quasiGregorianTest(Calendar cal, int[] data) {
for (int i=0; i<data.length; ) {
int era = data[i++];
int year = data[i++];
int gregorianYear = data[i++];
int month = data[i++];
int dayOfMonth = data[i++];
java.util.Calendar tempcal = java.util.Calendar.getInstance();
tempcal.clear();
tempcal.set(gregorianYear, month, dayOfMonth);
Date D = tempcal.getTime();
cal.clear();
cal.set(Calendar.ERA, era);
cal.set(year, month, dayOfMonth);
Date d = cal.getTime();
if (d.equals(D)) {
logln("OK: " + era + ":" + year + "/" + (month+1) + "/" + dayOfMonth +
" => " + d);
} else {
errln("Fail: " + era + ":" + year + "/" + (month+1) + "/" + dayOfMonth +
" => " + d + ", expected " + D);
}
cal.clear();
cal.setTime(D);
int e = cal.get(Calendar.ERA);
int y = cal.get(Calendar.YEAR);
if (y == year && e == era) {
logln("OK: " + D + " => " + cal.get(Calendar.ERA) + ":" +
cal.get(Calendar.YEAR) + "/" +
(cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.DATE));
} else {
logln("Fail: " + D + " => " + cal.get(Calendar.ERA) + ":" +
cal.get(Calendar.YEAR) + "/" +
(cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.DATE) +
", expected " + era + ":" + year + "/" + (month+1) + "/" +
dayOfMonth);
}
}
}
/**
* Verify that BuddhistCalendar shifts years to Buddhist Era but otherwise
* behaves like GregorianCalendar.
*/
public void TestBuddhist() {
quasiGregorianTest(new BuddhistCalendar(),
new int[] {
// BE 2542 == 1999 CE
0, 2542, 1999, Calendar.JUNE, 4
});
}
/**
* Verify that JapaneseCalendar shifts years to Buddhist Era but otherwise
* behaves like GregorianCalendar.
*/
public void TestJapanese() {
int[] data = {
JapaneseCalendar.MEIJI, 1, 1868, Calendar.SEPTEMBER, 8,
JapaneseCalendar.MEIJI, 1, 1868, Calendar.SEPTEMBER, 9,
JapaneseCalendar.MEIJI, 2, 1869, Calendar.JUNE, 4,
JapaneseCalendar.MEIJI, 45, 1912, Calendar.JULY, 29,
JapaneseCalendar.TAISHO, 1, 1912, Calendar.JULY, 30,
JapaneseCalendar.TAISHO, 1, 1912, Calendar.AUGUST, 1,
};
quasiGregorianTest(new JapaneseCalendar(), data);
}
/**
* Test limits of the Gregorian calendar.
*/
public void TestGregorianLimits() {
// Final parameter is either number of days, if > 0, or test
// duration in seconds, if < 0.
Calendar cal = Calendar.getInstance();
cal.set(2004, Calendar.JANUARY, 1);
doLimitsTest(new GregorianCalendar(), null, cal.getTime(), -10);
}
}

View File

@ -1,144 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/IslamicTest.java,v $
* $Date: 2000/11/18 00:17:58 $
* $Revision: 1.3 $
*
*****************************************************************************************
*/
package com.ibm.test.calendar;
import com.ibm.test.*;
import java.util.*;
import java.text.*;
import com.ibm.util.*;
/**
* Tests for the <code>IslamicCalendar</code> class.
*/
public class IslamicTest extends CalendarTest {
public static void main(String args[]) throws Exception {
new IslamicTest().run(args);
}
/** Constants to save typing. */
public static final int MUHARRAM = IslamicCalendar.MUHARRAM;
public static final int SAFAR = IslamicCalendar.SAFAR;
public static final int RABI_1 = IslamicCalendar.RABI_1;
public static final int RABI_2 = IslamicCalendar.RABI_2;
public static final int JUMADA_1 = IslamicCalendar.JUMADA_1;
public static final int JUMADA_2 = IslamicCalendar.JUMADA_2;
public static final int RAJAB = IslamicCalendar.RAJAB;
public static final int SHABAN = IslamicCalendar.SHABAN;
public static final int RAMADAN = IslamicCalendar.RAMADAN;
public static final int SHAWWAL = IslamicCalendar.SHAWWAL;
public static final int QIDAH = IslamicCalendar.DHU_AL_QIDAH;
public static final int HIJJAH = IslamicCalendar.DHU_AL_HIJJAH;
public void TestRoll() {
int[][] tests = new int[][] {
// input roll by output
// year month day field amount year month day
{ 0001, QIDAH, 2, MONTH, 1, 0001, HIJJAH, 2 }, // non-leap years
{ 0001, QIDAH, 2, MONTH, 2, 0001, MUHARRAM, 2 },
{ 0001, QIDAH, 2, MONTH, -1, 0001, SHAWWAL, 2 },
{ 0001, MUHARRAM, 2, MONTH, 12, 0001, MUHARRAM, 2 },
{ 0001, MUHARRAM, 2, MONTH, 13, 0001, SAFAR, 2 },
{ 0001, HIJJAH, 1, DATE, 30, 0001, HIJJAH, 2 }, // 29-day month
{ 0002, HIJJAH, 1, DATE, 31, 0002, HIJJAH, 2 }, // 30-day month
// Try some rolls that require other fields to be adjusted
{ 0001, MUHARRAM, 30, MONTH, 1, 0001, SAFAR, 29 },
{ 0002, HIJJAH, 30, YEAR, -1, 0001, HIJJAH, 29 },
};
IslamicCalendar cal = newCivil();
doRollAdd(ROLL, cal, tests);
}
/**
* A huge list of test cases to make sure that computeTime and computeFields
* work properly for a wide range of data in the civil calendar.
*/
public void TestCivilCases()
{
final TestCase[] tests = {
//
// Most of these test cases were taken from the back of
// "Calendrical Calculations", with some extras added to help
// debug a few of the problems that cropped up in development.
//
// The months in this table are 1-based rather than 0-based,
// because it's easier to edit that way.
// Islamic
// Julian Day Era Year Month Day WkDay Hour Min Sec
new TestCase(1507231.5, 0, -1245, 12, 9, SUN, 0, 0, 0),
new TestCase(1660037.5, 0, -813, 2, 23, WED, 0, 0, 0),
new TestCase(1746893.5, 0, -568, 4, 1, WED, 0, 0, 0),
new TestCase(1770641.5, 0, -501, 4, 6, SUN, 0, 0, 0),
new TestCase(1892731.5, 0, -157, 10, 17, WED, 0, 0, 0),
new TestCase(1931579.5, 0, -47, 6, 3, MON, 0, 0, 0),
new TestCase(1974851.5, 0, 75, 7, 13, SAT, 0, 0, 0),
new TestCase(2091164.5, 0, 403, 10, 5, SUN, 0, 0, 0),
new TestCase(2121509.5, 0, 489, 5, 22, SUN, 0, 0, 0),
new TestCase(2155779.5, 0, 586, 2, 7, FRI, 0, 0, 0),
new TestCase(2174029.5, 0, 637, 8, 7, SAT, 0, 0, 0),
new TestCase(2191584.5, 0, 687, 2, 20, FRI, 0, 0, 0),
new TestCase(2195261.5, 0, 697, 7, 7, SUN, 0, 0, 0),
new TestCase(2229274.5, 0, 793, 7, 1, SUN, 0, 0, 0),
new TestCase(2245580.5, 0, 839, 7, 6, WED, 0, 0, 0),
new TestCase(2266100.5, 0, 897, 6, 1, SAT, 0, 0, 0),
new TestCase(2288542.5, 0, 960, 9, 30, SAT, 0, 0, 0),
new TestCase(2290901.5, 0, 967, 5, 27, SAT, 0, 0, 0),
new TestCase(2323140.5, 0, 1058, 5, 18, WED, 0, 0, 0),
new TestCase(2334848.5, 0, 1091, 6, 2, SUN, 0, 0, 0),
new TestCase(2348020.5, 0, 1128, 8, 4, FRI, 0, 0, 0),
new TestCase(2366978.5, 0, 1182, 2, 3, SUN, 0, 0, 0),
new TestCase(2385648.5, 0, 1234, 10, 10, MON, 0, 0, 0),
new TestCase(2392825.5, 0, 1255, 1, 11, WED, 0, 0, 0),
new TestCase(2416223.5, 0, 1321, 1, 21, SUN, 0, 0, 0),
new TestCase(2425848.5, 0, 1348, 3, 19, SUN, 0, 0, 0),
new TestCase(2430266.5, 0, 1360, 9, 8, MON, 0, 0, 0),
new TestCase(2430833.5, 0, 1362, 4, 13, MON, 0, 0, 0),
new TestCase(2431004.5, 0, 1362, 10, 7, THU, 0, 0, 0),
new TestCase(2448698.5, 0, 1412, 9, 13, TUE, 0, 0, 0),
new TestCase(2450138.5, 0, 1416, 10, 5, SUN, 0, 0, 0),
new TestCase(2465737.5, 0, 1460, 10, 12, WED, 0, 0, 0),
new TestCase(2486076.5, 0, 1518, 3, 5, SUN, 0, 0, 0),
};
IslamicCalendar civilCalendar = newCivil();
civilCalendar.setLenient(true);
doTestCases(tests, civilCalendar);
}
public void TestBasic() {
IslamicCalendar cal = newCivil();
cal.clear();
cal.set(1000, 0, 30);
logln("1000/0/30 -> " +
cal.get(YEAR) + "/" +
cal.get(MONTH) + "/" +
cal.get(DATE));
cal.clear();
cal.set(1, 0, 30);
logln("1/0/30 -> " +
cal.get(YEAR) + "/" +
cal.get(MONTH) + "/" +
cal.get(DATE));
}
private static IslamicCalendar newCivil() {
IslamicCalendar civilCalendar = new IslamicCalendar();
civilCalendar.setCivil(true);
return civilCalendar;
}
};

View File

@ -1,245 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/TestCase.java,v $
* $Date: 2000/11/18 00:17:58 $
* $Revision: 1.6 $
*
*****************************************************************************************
*/
package com.ibm.test.calendar;
import com.ibm.test.*;
import com.ibm.util.Calendar;
import com.ibm.util.GregorianCalendar;
import java.util.Date;
import com.ibm.util.SimpleTimeZone;
import java.util.Locale;
/**
* A pseudo <code>Calendar</code> that is useful for testing
* new calendars. A <code>TestCase</code> object is used to hold the
* field and millisecond values that the calendar should have at one
* particular instant in time. The applyFields and applyTime
* methods are used to apply these settings to the calendar object being
* tested, and the equals and fieldsEqual methods are used to ensure
* that the calendar has ended up in the right state.
*/
public class TestCase {
//------------------------------------------------------------------
// Pseudo-Calendar fields and methods
//------------------------------------------------------------------
protected int[] fields = new int[32];
protected boolean[] isSet = new boolean[32];
protected long time;
protected void set(int field, int value) {
fields[field] = value;
isSet[field] = true;
}
protected int get(int field) {
return fields[field];
}
protected boolean isSet(int field) {
return isSet[field];
}
protected void setTime(Date d) {
time = d.getTime();
}
public Date getTime() {
return new Date(time);
}
/**
* Return a String representation of this test case's time.
*/
public String toString() {
return dowToString(get(Calendar.DAY_OF_WEEK)) +
get(Calendar.YEAR) + "/" + (get(Calendar.MONTH)+1) + "/" +
get(Calendar.DATE);
}
private static final String[] DOW_NAMES = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
public static String dowToString(int dow) {
--dow;
return (dow < 0 || dow > 6) ?
("<DOW " + dow + ">") : DOW_NAMES[dow];
}
/**
* Initialize a TestCase object using a julian day number and
* the corresponding fields for the calendar being tested.
*
* @param era The ERA field of tested calendar on the given julian day
* @param year The YEAR field of tested calendar on the given julian day
* @param month The MONTH (1-based) field of tested calendar on the given julian day
* @param day The DAY_OF_MONTH field of tested calendar on the given julian day
* @param dayOfWeek The DAY_OF_WEEK field of tested calendar on the given julian day
* @param hour The HOUR field of tested calendar on the given julian day
* @param min The MINUTE field of tested calendar on the given julian day
* @param sec The SECOND field of tested calendar on the given julian day
*/
public TestCase(double julian,
int era, int year, int month, int day,
int dayOfWeek,
int hour, int min, int sec)
{
setTime(new Date(JULIAN_EPOCH + (long)(ONE_DAY * julian)));
set(Calendar.ERA, era);
set(Calendar.YEAR, year);
set(Calendar.MONTH, month - 1);
set(Calendar.DATE, day);
set(Calendar.DAY_OF_WEEK, dayOfWeek);
set(Calendar.HOUR, hour);
set(Calendar.MINUTE, min);
set(Calendar.SECOND, sec);
}
/**
* Initialize a TestCase object using a Gregorian year/month/day and
* the corresponding fields for the calendar being tested.
*
* @param gregYear The Gregorian year of the date to be tested
* @param gregMonth The Gregorian month of the date to be tested
* @param gregDay The Gregorian day of the month of the date to be tested
*
* @param era The ERA field of tested calendar on the given gregorian date
* @param year The YEAR field of tested calendar on the given gregorian date
* @param month The MONTH (0-based) field of tested calendar on the given gregorian date
* @param day The DAY_OF_MONTH field of tested calendar on the given gregorian date
* @param dayOfWeek The DAY_OF_WEEK field of tested calendar on the given gregorian date
* @param hour The HOUR field of tested calendar on the given gregorian date
* @param min The MINUTE field of tested calendar on the given gregorian date
* @param sec The SECOND field of tested calendar on the given gregorian date
*/
public TestCase(int gregYear, int gregMonth, int gregDay,
int era, int year, int month, int day,
int dayOfWeek,
int hour, int min, int sec)
{
GregorianCalendar greg = new GregorianCalendar(UTC, Locale.getDefault());
greg.clear();
greg.set(gregYear, gregMonth-1, gregDay);
setTime(greg.getTime());
set(Calendar.ERA, era);
set(Calendar.YEAR, year);
set(Calendar.MONTH, month - 1);
set(Calendar.DATE, day);
set(Calendar.DAY_OF_WEEK, dayOfWeek);
set(Calendar.HOUR, hour);
set(Calendar.MINUTE, min);
set(Calendar.SECOND, sec);
}
/**
* For subclasses.
*/
protected TestCase() {}
/**
* Apply this test case's field values to another calendar
* by calling its set method for each field. This is useful in combination
* with the equal method.
*
* @see #equal
*/
public void applyFields(Calendar c) {
for (int i=0; i < c.getFieldCount(); i++) {
if (isSet(i)) {
c.set(i, get(i));
}
}
}
/**
* Apply this test case's time in milliseconds to another calendar
* by calling its setTime method. This is useful in combination
* with fieldsEqual
*
* @see #fieldsEqual
*/
public void applyTime(Calendar c) {
c.setTime(new Date(time));
}
/**
* Determine whether the fields of this calendar
* are the same as that of the other calendar. This method is useful
* for determining whether the other calendar's computeFields method
* works properly. For example:
* <pre>
* Calendar testCalendar = ...
* TestCase case = ...
* case.applyTime(testCalendar);
* if (!case.fieldsEqual(testCalendar)) {
* // Error!
* }
* </pre>
*
* @see #applyTime
*/
public boolean fieldsEqual(Calendar c, TestLog log) {
for (int i=0; i < c.getFieldCount(); i++) {
if (isSet(i) && get(i) != c.get(i)) {
log.errln("Fail: " + CalendarTest.fieldName(i) + " = " + c.get(i) +
", expected " + get(i));
for (int j=0; j<c.getFieldCount(); ++j) {
if (isSet(j)) {
if (get(j) == c.get(j)) {
log.errln(" OK: " + CalendarTest.fieldName(j) + " = " +
c.get(j));
} else {
log.errln(" Fail: " + CalendarTest.fieldName(j) + " = " +
c.get(j) + ", expected " + get(j));
}
}
}
return false;
}
}
return true;
}
/**
* Determine whether time in milliseconds of this calendar
* is the same as that of the other calendar. This method is useful
* for determining whether the other calendar's computeTime method
* works properly. For example:
* <pre>
* Calendar testCalendar = ...
* TestCase case = ...
* case.applyFields(testCalendar);
* if (!case.equals(testCalendar)) {
* // Error!
* }
* </pre>
*
* @see #applyFields
*/
public boolean equals(Object obj) {
return time == ((Calendar)obj).getTime().getTime();
}
protected static final int ONE_SECOND = 1000;
protected static final int ONE_MINUTE = 60*ONE_SECOND;
protected static final int ONE_HOUR = 60*ONE_MINUTE;
protected static final long ONE_DAY = 24*ONE_HOUR;
protected static final long JULIAN_EPOCH = -210866760000000L; // 1/1/4713 BC 12:00
public final static SimpleTimeZone UTC = new SimpleTimeZone(0, "GMT");
}

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/calendar/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 21:35:49 $
-->
</head>
<body bgcolor="white">
Tests for the calendar classes.
</body>
</html>

View File

@ -1,130 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/compression/Attic/DecompressionTest.java,v $
* $Date: 2000/03/10 03:47:45 $
* $Revision: 1.2 $
*
*****************************************************************************************
*/
package com.ibm.test.compression;
import com.ibm.text.UnicodeCompressor;
import com.ibm.text.UnicodeDecompressor;
import com.ibm.test.TestFmwk;
public class DecompressionTest extends TestFmwk {
public static void main(String[] args) throws Exception {
new DecompressionTest().run(args);
}
/** Print out a segment of a character array, if in verbose mode */
private void log(char [] chars, int start, int count) {
log("|");
for(int i = start; i < start + count; ++i) {
log(String.valueOf(chars[i]));
}
log("|");
}
/** Print out a segment of a character array, followed by a newline */
private void logln(char [] chars, int start, int count)
{
log(chars, start, count);
logln("");
}
/** Decompress the two segments */
private String decompressTest(byte [] segment1, byte [] segment2) {
StringBuffer s = new StringBuffer();
UnicodeDecompressor myDecompressor = new UnicodeDecompressor();
int [] bytesRead = new int[1];
char [] charBuffer = new char [2*(segment1.length + segment2.length)];
int count1 = 0, count2 = 0;
count1 = myDecompressor.decompress(segment1, 0, segment1.length,
bytesRead,
charBuffer, 0, charBuffer.length);
logln("Segment 1 (" + segment1.length + " bytes) " +
"decompressed into " + count1 + " chars");
logln("Bytes consumed: " + bytesRead[0]);
logln("Got chars: ");
logln(charBuffer, 0, count1);
s.append(charBuffer, 0, count1);
count2 = myDecompressor.decompress(segment2, 0, segment2.length,
bytesRead,
charBuffer, count1,
charBuffer.length);
logln("Segment 2 (" + segment2.length + " bytes) " +
"decompressed into " + count2 + " chars");
logln("Bytes consumed: " + bytesRead[0]);
logln("Got chars: ");
logln(charBuffer, count1, count2);
s.append(charBuffer, count1, count2);
logln("Result: ");
logln(charBuffer, 0, count1 + count2);
logln("====================");
return s.toString();
}
public void testDecompression() throws Exception {
String result;
// compressed segment breaking on a define window sequence
/* B o o t h SD1 */
byte [] segment1 = { 0x42, 0x6f, 0x6f, 0x74, 0x68, 0x19 };
// continuation
/* IDX , S . */
byte [] segment2 = { 0x01, 0x2c, 0x20, 0x53, 0x2e };
result = decompressTest(segment1, segment2);
if(! result.equals("Booth, S.")) {
errln("Decompression test failed");
return;
}
// compressed segment breaking on a quote unicode sequence
/* B o o t SQU */
byte [] segment3 = { 0x42, 0x6f, 0x6f, 0x74, 0x0e, 0x00 };
// continuation
/* h , S . */
byte [] segment4 = { 0x68, 0x2c, 0x20, 0x53, 0x2e };
result = decompressTest(segment3, segment4);
if(! result.equals("Booth, S.")) {
errln("Decompression test failed");
return;
}
// compressed segment breaking on a quote unicode sequence
/* SCU UQU */
byte [] segment5 = { 0x0f, (byte)0xf0, 0x00 };
// continuation
/* B */
byte [] segment6 = { 0x42 };
result = decompressTest(segment5, segment6);
if(! result.equals("B")) {
errln("Decompression test failed");
return;
}
}
};

View File

@ -1,529 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/compression/Attic/ExhaustiveTest.java,v $
* $Date: 2001/09/08 01:16:25 $
* $Revision: 1.4 $
*
*****************************************************************************************
*/
package com.ibm.test.compression;
import com.ibm.text.UnicodeCompressor;
import com.ibm.text.UnicodeDecompressor;
import java.util.Random;
import com.ibm.test.TestFmwk;
public class ExhaustiveTest extends TestFmwk {
public static void main(String args[]) throws Exception {
new ExhaustiveTest().run(args);
}
/** Test simple compress/decompress API, returning # of errors */
public void testSimple() throws Exception {
for(int i = 0; i < fTestCases.length; i++) {
simpleTest(fTestCases[i]);
}
}
private void simpleTest(String s) throws Exception {
byte [] compressed = UnicodeCompressor.compress(s);
String res = UnicodeDecompressor.decompress(compressed);
if (logDiffs(s.toCharArray(), s.length(),
res.toCharArray(), res.length()) == false) {
logln(s.length() + " chars ===> "
+ compressed.length + " bytes ===> "
+ res.length() + " chars");
} else {
logln("Compressed:");
printBytes(compressed, compressed.length);
errln("testSimple did not compress correctly");
}
}
/** Test iterative compress/decompress API, returning # of errors */
public void testIterative() throws Exception {
for(int i = 0; i < fTestCases.length; i++) {
myTest(fTestCases[i].toCharArray(), fTestCases[i].length());
}
}
private void myTest(char[] chars, int len) {
UnicodeCompressor myCompressor = new UnicodeCompressor();
UnicodeDecompressor myDecompressor = new UnicodeDecompressor();
// variables for my compressor
int myByteCount = 0;
int myCharCount = 0;
int myCompressedSize = Math.max(512, 3*len);
byte[] myCompressed = new byte[myCompressedSize];
int myDecompressedSize = Math.max(2, 2 * len);
char[] myDecompressed = new char[myDecompressedSize];
int[] unicharsRead = new int[1];
int[] bytesRead = new int[1];
myByteCount = myCompressor.compress(chars, 0, len, unicharsRead,
myCompressed, 0, myCompressedSize);
myCharCount = myDecompressor.decompress(myCompressed, 0, myByteCount,
bytesRead, myDecompressed, 0, myDecompressedSize);
if (logDiffs(chars, len, myDecompressed, myCharCount) == false) {
logln(len + " chars ===> "
+ myByteCount + " bytes ===> "
+ myCharCount + " chars");
} else {
logln("Compressed:");
printBytes(myCompressed, myByteCount);
errln("Iterative test failed");
}
}
/** Test iterative compress/decompress API */
public void testMultipass() throws Exception {
for(int i = 0; i < fTestCases.length; i++) {
myMultipassTest(fTestCases[i].toCharArray(), fTestCases[i].length());
}
}
private void myMultipassTest(char [] chars, int len) throws Exception {
UnicodeCompressor myCompressor = new UnicodeCompressor();
UnicodeDecompressor myDecompressor = new UnicodeDecompressor();
// variables for my compressor
// for looping
int byteBufferSize = 4;//Math.max(4, len / 4);
byte[] byteBuffer = new byte [byteBufferSize];
// real target
int compressedSize = Math.max(512, 3 * len);
byte[] compressed = new byte[compressedSize];
// for looping
int unicharBufferSize = 2;//byteBufferSize;
char[] unicharBuffer = new char[unicharBufferSize];
// real target
int decompressedSize = Math.max(2, 2 * len);
char[] decompressed = new char[decompressedSize];
int bytesWritten = 0;
int unicharsWritten = 0;
int[] unicharsRead = new int[1];
int[] bytesRead = new int[1];
int totalCharsCompressed = 0;
int totalBytesWritten = 0;
int totalBytesDecompressed = 0;
int totalCharsWritten = 0;
// not used boolean err = false;
// perform the compression in a loop
do {
// do the compression
bytesWritten = myCompressor.compress(chars, totalCharsCompressed,
len, unicharsRead, byteBuffer, 0, byteBufferSize);
// copy the current set of bytes into the target buffer
System.arraycopy(byteBuffer, 0, compressed,
totalBytesWritten, bytesWritten);
// update the no. of characters compressed
totalCharsCompressed += unicharsRead[0];
// update the no. of bytes written
totalBytesWritten += bytesWritten;
/*System.out.logln("Compression pass complete. Compressed "
+ unicharsRead[0] + " chars into "
+ bytesWritten + " bytes.");*/
} while(totalCharsCompressed < len);
if (totalCharsCompressed != len) {
errln("ERROR: Number of characters compressed("
+ totalCharsCompressed + ") != len(" + len + ")");
} else {
logln("MP: " + len + " chars ===> " + totalBytesWritten + " bytes.");
}
// perform the decompression in a loop
do {
// do the decompression
unicharsWritten = myDecompressor.decompress(compressed,
totalBytesDecompressed, totalBytesWritten,
bytesRead, unicharBuffer, 0, unicharBufferSize);
// copy the current set of chars into the target buffer
System.arraycopy(unicharBuffer, 0, decompressed,
totalCharsWritten, unicharsWritten);
// update the no. of bytes decompressed
totalBytesDecompressed += bytesRead[0];
// update the no. of chars written
totalCharsWritten += unicharsWritten;
/*System.out.logln("Decompression pass complete. Decompressed "
+ bytesRead[0] + " bytes into "
+ unicharsWritten + " chars.");*/
} while (totalBytesDecompressed < totalBytesWritten);
if (totalBytesDecompressed != totalBytesWritten) {
errln("ERROR: Number of bytes decompressed("
+ totalBytesDecompressed
+ ") != totalBytesWritten("
+ totalBytesWritten + ")");
} else {
logln("MP: " + totalBytesWritten
+ " bytes ===> " + totalCharsWritten + " chars.");
}
if (logDiffs(chars, len, decompressed, totalCharsWritten)) {
errln("ERROR: buffer contents incorrect");
}
}
/** Print differences between two character buffers */
private boolean logDiffs(char[] s1, int s1len, char[] s2, int s2len) {
boolean result = false;
if(s1len != s2len) {
logln("====================");
logln("Length doesn't match: expected " + s1len
+ ", got " + s2len);
logln("Expected:");
printChars(s1, s1len);
logln("Got:");
printChars(s2, s2len);
result = true;
}
int len = Math.min(s1len, s2len);
for(int i = 0; i < len; ++i) {
if(s1[i] != s2[i]) {
if(result == false) {
logln("====================");
}
logln("First difference at char " + i);
logln("Exp. char: " + Integer.toHexString(s1[i]));
logln("Got char : " + Integer.toHexString(s2[i]));
logln("Expected:");
printChars(s1, s1len);
logln("Got:");
printChars(s2, s2len);
result = true;
break;
}
}
return result;
}
// generate a string of characters, with simulated runs of characters
private static char[] randomChars(int len, Random random) {
char[] result = new char [len];
int runLen = 0;
int used = 0;
while(used < len) {
runLen = (int) (30 * random.nextDouble());
if(used + runLen >= len) {
runLen = len - used;
}
randomRun(result, used, runLen, random);
used += runLen;
}
return result;
}
// generate a run of characters in a "window"
private static void randomRun(char[] target, int pos, int len, Random random) {
int offset = (int) (0xFFFF * random.nextDouble());
// don't overflow 16 bits
if(offset > 0xFF80) {
offset = 0xFF80;
}
for(int i = pos; i < pos + len; i++) {
target[i] = (char)(offset + (0x7F * random.nextDouble()));
}
}
private static final String [] fTestCases = {
"Hello \u9292 \u9192 World!",
"Hell\u0429o \u9292 \u9192 W\u0084rld!",
"Hell\u0429o \u9292 \u9292W\u0084rld!",
"\u0648\u06c8", // catch missing reset
"\u0648\u06c8",
"\u4444\uE001", // lowest quotable
"\u4444\uf2FF", // highest quotable
"\u4444\uf188\u4444",
"\u4444\uf188\uf288",
"\u4444\uf188abc\0429\uf288",
"\u9292\u2222",
"Hell\u0429\u04230o \u9292 \u9292W\u0084\u0192rld!",
"Hell\u0429o \u9292 \u9292W\u0084rld!",
"Hello World!123456",
"Hello W\u0081\u011f\u0082!", // Latin 1 run
"abc\u0301\u0302", // uses SQn for u301 u302
"abc\u4411d", // uses SQU
"abc\u4411\u4412d",// uses SCU
"abc\u0401\u0402\u047f\u00a5\u0405", // uses SQn for ua5
"\u9191\u9191\u3041\u9191\u3041\u3041\u3000", // SJIS like data
"\u9292\u2222",
"\u9191\u9191\u3041\u9191\u3041\u3041\u3000",
"\u9999\u3051\u300c\u9999\u9999\u3060\u9999\u3065\u3065\u3065\u300c",
"\u3000\u266a\u30ea\u30f3\u30b4\u53ef\u611b\u3044\u3084\u53ef\u611b\u3044\u3084\u30ea\u30f3\u30b4\u3002",
"", // empty input
"\u0000", // smallest BMP character
"\uFFFF", // largest BMP character
"\ud800\udc00", // smallest surrogate
"\ud8ff\udcff", // largest surrogate pair
// regression tests
"\u6441\ub413\ua733\uf8fe\ueedb\u587f\u195f\u4899\uf23d\u49fd\u0aac\u5792\ufc22\ufc3c\ufc46\u00aa",
"\u30f9\u8321\u05e5\u181c\ud72b\u2019\u99c9\u2f2f\uc10c\u82e1\u2c4d\u1ebc\u6013\u66dc\ubbde\u94a5\u4726\u74af\u3083\u55b9\u000c",
"\u0041\u00df\u0401\u015f",
"\u9066\u2123abc",
"\ud266\u43d7\\\ue386\uc9c0\u4a6b\u9222\u901f\u7410\ua63f\u539b\u9596\u482e\u9d47\ucfe4\u7b71\uc280\uf26a\u982f\u862a\u4edd\uf513\ufda6\u869d\u2ee0\ua216\u3ff6\u3c70\u89c0\u9576\ud5ec\ubfda\u6cca\u5bb3\ubcea\u554c\u914e\ufa4a\uede3\u2990\ud2f5\u2729\u5141\u0f26\uccd8\u5413\ud196\ubbe2\u51b9\u9b48\u0dc8\u2195\u21a2\u21e9\u00e4\u9d92\u0bc0\u06c5",
"\uf95b\u2458\u2468\u0e20\uf51b\ue36e\ubfc1\u0080\u02dd\uf1b5\u0cf3\u6059\u7489"
};
//==========================
// Compression modes
//==========================
private final static int SINGLEBYTEMODE = 0;
private final static int UNICODEMODE = 1;
//==========================
// Single-byte mode tags
//==========================
private final static int SDEFINEX = 0x0B;
private final static int SRESERVED = 0x0C; // this is a reserved value
private final static int SQUOTEU = 0x0E;
private final static int SSWITCHU = 0x0F;
private final static int SQUOTE0 = 0x01;
private final static int SQUOTE1 = 0x02;
private final static int SQUOTE2 = 0x03;
private final static int SQUOTE3 = 0x04;
private final static int SQUOTE4 = 0x05;
private final static int SQUOTE5 = 0x06;
private final static int SQUOTE6 = 0x07;
private final static int SQUOTE7 = 0x08;
private final static int SSWITCH0 = 0x10;
private final static int SSWITCH1 = 0x11;
private final static int SSWITCH2 = 0x12;
private final static int SSWITCH3 = 0x13;
private final static int SSWITCH4 = 0x14;
private final static int SSWITCH5 = 0x15;
private final static int SSWITCH6 = 0x16;
private final static int SSWITCH7 = 0x17;
private final static int SDEFINE0 = 0x18;
private final static int SDEFINE1 = 0x19;
private final static int SDEFINE2 = 0x1A;
private final static int SDEFINE3 = 0x1B;
private final static int SDEFINE4 = 0x1C;
private final static int SDEFINE5 = 0x1D;
private final static int SDEFINE6 = 0x1E;
private final static int SDEFINE7 = 0x1F;
//==========================
// Unicode mode tags
//==========================
private final static int USWITCH0 = 0xE0;
private final static int USWITCH1 = 0xE1;
private final static int USWITCH2 = 0xE2;
private final static int USWITCH3 = 0xE3;
private final static int USWITCH4 = 0xE4;
private final static int USWITCH5 = 0xE5;
private final static int USWITCH6 = 0xE6;
private final static int USWITCH7 = 0xE7;
private final static int UDEFINE0 = 0xE8;
private final static int UDEFINE1 = 0xE9;
private final static int UDEFINE2 = 0xEA;
private final static int UDEFINE3 = 0xEB;
private final static int UDEFINE4 = 0xEC;
private final static int UDEFINE5 = 0xED;
private final static int UDEFINE6 = 0xEE;
private final static int UDEFINE7 = 0xEF;
private final static int UQUOTEU = 0xF0;
private final static int UDEFINEX = 0xF1;
private final static int URESERVED = 0xF2; // this is a reserved value
/* Print out an array of characters, with non-printables (for me)
displayed as hex values */
private void printChars(char[] chars, int len) {
for(int i = 0; i < len; i++) {
int c = (int)chars[i];
if(c < 0x0020 || c >= 0x7f) {
log("[0x");
log(Integer.toHexString(c));
log("]");
} else {
log(String.valueOf((char)c));
}
}
logln("");
}
private void printBytes(byte[] byteBuffer, int len) {
int curByteIndex = 0;
int byteBufferLimit = len;
int mode = SINGLEBYTEMODE;
int aByte = 0x00;
if(len > byteBuffer.length) {
logln("Warning: printBytes called with length too large. Truncating");
byteBufferLimit = byteBuffer.length;;
}
while(curByteIndex < byteBufferLimit) {
switch(mode) {
case SINGLEBYTEMODE:
while(curByteIndex < byteBufferLimit
&& mode == SINGLEBYTEMODE) {
aByte = ((int)byteBuffer[curByteIndex++]) & 0xFF;
switch(aByte) {
default:
log(Integer.toHexString(((int) aByte) & 0xFF) + " ");
break;
// quote unicode
case SQUOTEU:
log("SQUOTEU ");
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
break;
// switch to Unicode mode
case SSWITCHU:
log("SSWITCHU ");
mode = UNICODEMODE;
break;
// handle all quote tags
case SQUOTE0: case SQUOTE1: case SQUOTE2: case SQUOTE3:
case SQUOTE4: case SQUOTE5: case SQUOTE6: case SQUOTE7:
log("SQUOTE" + (aByte - SQUOTE0) + " ");
if(curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
break;
// handle all switch tags
case SSWITCH0: case SSWITCH1: case SSWITCH2: case SSWITCH3:
case SSWITCH4: case SSWITCH5: case SSWITCH6: case SSWITCH7:
log("SSWITCH" + (aByte - SSWITCH0) + " ");
break;
// handle all define tags
case SDEFINE0: case SDEFINE1: case SDEFINE2: case SDEFINE3:
case SDEFINE4: case SDEFINE5: case SDEFINE6: case SDEFINE7:
log("SDEFINE" + (aByte - SDEFINE0) + " ");
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
break;
// handle define extended tag
case SDEFINEX:
log("SDEFINEX ");
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
break;
} // end switch
} // end while
break;
case UNICODEMODE:
while(curByteIndex < byteBufferLimit && mode == UNICODEMODE) {
aByte = ((int)byteBuffer[curByteIndex++]) & 0xFF;
switch(aByte) {
// handle all define tags
case UDEFINE0: case UDEFINE1: case UDEFINE2: case UDEFINE3:
case UDEFINE4: case UDEFINE5: case UDEFINE6: case UDEFINE7:
log("UDEFINE" + (aByte - UDEFINE0) + " ");
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
mode = SINGLEBYTEMODE;
break;
// handle define extended tag
case UDEFINEX:
log("UDEFINEX ");
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
break;
// handle all switch tags
case USWITCH0: case USWITCH1: case USWITCH2: case USWITCH3:
case USWITCH4: case USWITCH5: case USWITCH6: case USWITCH7:
log("USWITCH" + (aByte - USWITCH0) + " ");
mode = SINGLEBYTEMODE;
break;
// quote unicode
case UQUOTEU:
log("UQUOTEU ");
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
break;
default:
log(Integer.toHexString(((int) aByte) & 0xFF) + " ");
if (curByteIndex < byteBufferLimit) {
log(Integer.toHexString(((int) byteBuffer[curByteIndex++]) & 0xFF) + " ");
}
break;
} // end switch
} // end while
break;
} // end switch( mode )
} // end while
logln("");
}
}

View File

@ -1,15 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!-- Copyright (C) 2000, International Business Machines Corporation and
others. All Rights Reserved.
$Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/compression/Attic/package.html,v $
$Revision: 1.1 $
$Date: 2000/03/15 21:35:49 $
-->
</head>
<body bgcolor="white">
Tests for the compression classes.
</body>
</html>

View File

@ -1,491 +0,0 @@
/*
*******************************************************************************
* Copyright (C) 1996-2000, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/test/normalizer/Attic/BasicTest.java,v $
* $Date: 2001/04/02 19:21:06 $
* $Revision: 1.8 $
*
*****************************************************************************************
*/
package com.ibm.test.normalizer;
import com.ibm.test.*;
import com.ibm.text.*;
import com.ibm.util.Utility;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class BasicTest extends TestFmwk {
public static void main(String[] args) throws Exception {
new BasicTest().run(args);
}
String[][] canonTests = {
// Input Decomposed Composed
{ "cat", "cat", "cat" },
{ "\u00e0ardvark", "a\u0300ardvark", "\u00e0ardvark", },
{ "\u1e0a", "D\u0307", "\u1e0a" }, // D-dot_above
{ "D\u0307", "D\u0307", "\u1e0a" }, // D dot_above
{ "\u1e0c\u0307", "D\u0323\u0307", "\u1e0c\u0307" }, // D-dot_below dot_above
{ "\u1e0a\u0323", "D\u0323\u0307", "\u1e0c\u0307" }, // D-dot_above dot_below
{ "D\u0307\u0323", "D\u0323\u0307", "\u1e0c\u0307" }, // D dot_below dot_above
{ "\u1e10\u0307\u0323", "D\u0327\u0323\u0307", "\u1e10\u0323\u0307"}, // D dot_below cedilla dot_above
{ "D\u0307\u0328\u0323","D\u0328\u0323\u0307", "\u1e0c\u0328\u0307"}, // D dot_above ogonek dot_below
{ "\u1E14", "E\u0304\u0300", "\u1E14" }, // E-macron-grave
{ "\u0112\u0300", "E\u0304\u0300", "\u1E14" }, // E-macron + grave
{ "\u00c8\u0304", "E\u0300\u0304", "\u00c8\u0304" }, // E-grave + macron
{ "\u212b", "A\u030a", "\u00c5" }, // angstrom_sign
{ "\u00c5", "A\u030a", "\u00c5" }, // A-ring
// { "\u00fdffin", "A\u0308ffin", "\u00fdffin" },
{ "\u00fdffin", "y\u0301ffin", "\u00fdffin" }, //updated with 3.0
// { "\u00fd\uFB03n", "A\u0308\uFB03n", "\u00fd\uFB03n" },
{ "\u00fd\uFB03n", "y\u0301\uFB03n", "\u00fd\uFB03n" }, //updated with 3.0
{ "Henry IV", "Henry IV", "Henry IV" },
{ "Henry \u2163", "Henry \u2163", "Henry \u2163" },
{ "\u30AC", "\u30AB\u3099", "\u30AC" }, // ga (Katakana)
{ "\u30AB\u3099", "\u30AB\u3099", "\u30AC" }, // ka + ten
{ "\uFF76\uFF9E", "\uFF76\uFF9E", "\uFF76\uFF9E" }, // hw_ka + hw_ten
{ "\u30AB\uFF9E", "\u30AB\uFF9E", "\u30AB\uFF9E" }, // ka + hw_ten
{ "\uFF76\u3099", "\uFF76\u3099", "\uFF76\u3099" }, // hw_ka + ten
{ "A\u0300\u0316", "A\u0316\u0300", "\u00C0\u0316" },
};
String[][] compatTests = {
// Input Decomposed Composed
{ "\uFB4f", "\u05D0\u05DC", "\u05D0\u05DC", }, // Alef-Lamed vs. Alef, Lamed
// { "\u00fdffin", "A\u0308ffin", "\u00fdffin" },
// { "\u00fd\uFB03n", "A\u0308ffin", "\u00fdffin" }, // ffi ligature -> f + f + i
{ "\u00fdffin", "y\u0301ffin", "\u00fdffin" }, //updated for 3.0
{ "\u00fd\uFB03n", "y\u0301ffin", "\u00fdffin" }, // ffi ligature -> f + f + i
{ "Henry IV", "Henry IV", "Henry IV" },
{ "Henry \u2163", "Henry IV", "Henry IV" },
{ "\u30AC", "\u30AB\u3099", "\u30AC" }, // ga (Katakana)
{ "\u30AB\u3099", "\u30AB\u3099", "\u30AC" }, // ka + ten
{ "\uFF76\u3099", "\u30AB\u3099", "\u30AC" }, // hw_ka + ten
/* These two are broken in Unicode 2.1.2 but fixed in 2.1.5 and later
{ "\uFF76\uFF9E", "\u30AB\u3099", "\u30AC" }, // hw_ka + hw_ten
{ "\u30AB\uFF9E", "\u30AB\u3099", "\u30AC" }, // ka + hw_ten
*/
};
// With Canonical decomposition, Hangul syllables should get decomposed
// into Jamo, but Jamo characters should not be decomposed into
// conjoining Jamo
String[][] hangulCanon = {
// Input Decomposed Composed
{ "\ud4db", "\u1111\u1171\u11b6", "\ud4db" },
{ "\u1111\u1171\u11b6", "\u1111\u1171\u11b6", "\ud4db" },
};
// With compatibility decomposition turned on,
// it should go all the way down to conjoining Jamo characters.
// THIS IS NO LONGER TRUE IN UNICODE v2.1.8, SO THIS TEST IS OBSOLETE
String[][] hangulCompat = {
// Input Decomposed Composed
// { "\ud4db", "\u1111\u116e\u1175\u11af\u11c2", "\ud478\u1175\u11af\u11c2" },
};
public void TestHangulCompose() {
// Make sure that the static composition methods work
logln("Canonical composition...");
staticTest(Normalizer.COMPOSE, 0, hangulCanon, 2);
logln("Compatibility composition...");
staticTest(Normalizer.COMPOSE_COMPAT, 0, hangulCompat, 2);
// Now try iterative composition....
logln("Static composition...");
Normalizer norm = new Normalizer("", Normalizer.COMPOSE, 0);
iterateTest(norm, hangulCanon, 2);
norm.setMode(Normalizer.COMPOSE_COMPAT);
iterateTest(norm, hangulCompat, 2);
// And finally, make sure you can do it in reverse too
logln("Reverse iteration...");
norm.setMode(Normalizer.COMPOSE);
backAndForth(norm, hangulCanon);
}
public void TestHangulDecomp() {
// Make sure that the static decomposition methods work
logln("Canonical decomposition...");
staticTest(Normalizer.DECOMP, 0, hangulCanon, 1);
logln("Compatibility decomposition...");
staticTest(Normalizer.DECOMP_COMPAT, 0, hangulCompat, 1);
// Now the iterative decomposition methods...
logln("Iterative decomposition...");
Normalizer norm = new Normalizer("", Normalizer.DECOMP, 0);
iterateTest(norm, hangulCanon, 1);
norm.setMode(Normalizer.DECOMP_COMPAT);
iterateTest(norm, hangulCompat, 1);
// And finally, make sure you can do it in reverse too
logln("Reverse iteration...");
norm.setMode(Normalizer.DECOMP);
backAndForth(norm, hangulCanon);
}
public void TestPrevious() {
Normalizer norm = new Normalizer("", Normalizer.DECOMP, 0);
logln("testing decomp...");
backAndForth(norm, canonTests);
logln("testing compose...");
norm.setMode(Normalizer.COMPOSE);
backAndForth(norm, canonTests);
}
public void TestDecomp() {
Normalizer norm = new Normalizer("", Normalizer.DECOMP, 0);
iterateTest(norm, canonTests, 1);
staticTest(Normalizer.DECOMP, 0, canonTests, 1);
}
public void TestCompatDecomp() {
Normalizer norm = new Normalizer("", Normalizer.DECOMP_COMPAT, 0);
iterateTest(norm, compatTests, 1);
staticTest(Normalizer.DECOMP_COMPAT, 0, compatTests, 1);
}
public void TestCanonCompose() {
Normalizer norm = new Normalizer("", Normalizer.COMPOSE, 0);
iterateTest(norm, canonTests, 2);
staticTest(Normalizer.COMPOSE, 0, canonTests, 2);
}
public void TestCompatCompose() {
Normalizer norm = new Normalizer("", Normalizer.COMPOSE_COMPAT, 0);
iterateTest(norm, compatTests, 2);
staticTest(Normalizer.COMPOSE_COMPAT, 0, compatTests, 2);
}
public void TestExplodingBase() {
// \u017f - Latin small letter long s
// \u0307 - combining dot above
// \u1e61 - Latin small letter s with dot above
// \u1e9b - Latin small letter long s with dot above
String[][] canon = {
// Input Decomposed Composed
{ "Tschu\u017f", "Tschu\u017f", "Tschu\u017f" },
{ "Tschu\u1e9b", "Tschu\u017f\u0307", "Tschu\u1e9b" },
};
String[][] compat = {
// Input Decomposed Composed
{ "\u017f", "s", "s" },
{ "\u1e9b", "s\u0307", "\u1e61" },
};
staticTest(Normalizer.DECOMP, 0, canon, 1);
staticTest(Normalizer.COMPOSE, 0, canon, 2);
staticTest(Normalizer.DECOMP_COMPAT, 0, compat, 1);
staticTest(Normalizer.COMPOSE_COMPAT, 0, compat, 2);
Normalizer norm = new Normalizer("", Normalizer.DECOMP_COMPAT);
iterateTest(norm, compat, 1);
backAndForth(norm, compat);
norm.setMode(Normalizer.COMPOSE_COMPAT);
iterateTest(norm, compat, 2);
backAndForth(norm, compat);
}
/**
* The Tibetan vowel sign AA, 0f71, was messed up prior to Unicode version 2.1.9.
* Once 2.1.9 or 3.0 is released, uncomment this test.
*/
public void TestTibetan() {
String[][] decomp = {
{ "\u0f77", "\u0f77", "\u0fb2\u0f71\u0f80" }
};
String[][] compose = {
{ "\u0fb2\u0f71\u0f80", "\u0fb2\u0f71\u0f80", "\u0fb2\u0f71\u0f80" }
};
staticTest(Normalizer.DECOMP, 0, decomp, 1);
staticTest(Normalizer.DECOMP_COMPAT, 0, decomp, 2);
staticTest(Normalizer.COMPOSE, 0, compose, 1);
staticTest(Normalizer.COMPOSE_COMPAT, 0, compose, 2);
}
/**
* Make sure characters in the CompositionExclusion.txt list do not get
* composed to.
*/
public void TestCompositionExclusion() {
// This list is generated from CompositionExclusion.txt.
// Update whenever the normalizer tables are updated. Note
// that we test all characters listed, even those that can be
// derived from the Unicode DB and are therefore commented
// out.
String EXCLUDED =
"\u0340\u0341\u0343\u0344\u0374\u037E\u0387\u0958" +
"\u0959\u095A\u095B\u095C\u095D\u095E\u095F\u09DC" +
"\u09DD\u09DF\u0A33\u0A36\u0A59\u0A5A\u0A5B\u0A5E" +
"\u0B5C\u0B5D\u0F43\u0F4D\u0F52\u0F57\u0F5C\u0F69" +
"\u0F73\u0F75\u0F76\u0F78\u0F81\u0F93\u0F9D\u0FA2" +
"\u0FA7\u0FAC\u0FB9\u1F71\u1F73\u1F75\u1F77\u1F79" +
"\u1F7B\u1F7D\u1FBB\u1FBE\u1FC9\u1FCB\u1FD3\u1FDB" +
"\u1FE3\u1FEB\u1FEE\u1FEF\u1FF9\u1FFB\u1FFD\u2000" +
"\u2001\u2126\u212A\u212B\u2329\u232A\uF900\uFA10" +
"\uFA12\uFA15\uFA20\uFA22\uFA25\uFA26\uFA2A\uFB1F" +
"\uFB2A\uFB2B\uFB2C\uFB2D\uFB2E\uFB2F\uFB30\uFB31" +
"\uFB32\uFB33\uFB34\uFB35\uFB36\uFB38\uFB39\uFB3A" +
"\uFB3B\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46" +
"\uFB47\uFB48\uFB49\uFB4A\uFB4B\uFB4C\uFB4D\uFB4E";
for (int i=0; i<EXCLUDED.length(); ++i) {
String a = String.valueOf(EXCLUDED.charAt(i));
String b = Normalizer.normalize(a, Normalizer.DECOMP_COMPAT, 0);
String c = Normalizer.normalize(b, Normalizer.COMPOSE, 0);
if (c.equals(a)) {
errln("FAIL: " + hex(a) + " x DECOMP_COMPAT => " +
hex(b) + " x COMPOSE => " +
hex(c));
} else if (isVerbose()) {
logln("Ok: " + hex(a) + " x DECOMP_COMPAT => " +
hex(b) + " x COMPOSE => " +
hex(c));
}
}
// The following method works too, but it is somewhat
// incestuous. It uses UInfo, which is the same database that
// NormalizerBuilder uses, so if something is wrong with
// UInfo, the following test won't show it. All it will show
// is that NormalizerBuilder has been run with whatever the
// current UInfo is.
//
// We comment this out in favor of the test above, which
// provides independent verification (but also requires
// independent updating).
// logln("---");
// UInfo uinfo = new UInfo();
// for (int i=0; i<=0xFFFF; ++i) {
// if (!uinfo.isExcludedComposition((char)i) ||
// (!uinfo.hasCanonicalDecomposition((char)i) &&
// !uinfo.hasCompatibilityDecomposition((char)i))) continue;
// String a = String.valueOf((char)i);
// String b = Normalizer.normalize(a, Normalizer.DECOMP_COMPAT, 0);
// String c = Normalizer.normalize(b, Normalizer.COMPOSE, 0);
// if (c.equals(a)) {
// errln("FAIL: " + hex(a) + " x DECOMP_COMPAT => " +
// hex(b) + " x COMPOSE => " +
// hex(c));
// } else if (isVerbose()) {
// logln("Ok: " + hex(a) + " x DECOMP_COMPAT => " +
// hex(b) + " x COMPOSE => " +
// hex(c));
// }
// }
}
/**
* Test for a problem that showed up just before ICU 1.6 release
* having to do with combining characters with an index of zero.
* Such characters do not participate in any canonical
* decompositions. However, having an index of zero means that
* they all share one typeMask[] entry, that is, they all have to
* map to the same canonical class, which is not the case, in
* reality.
*/
public void TestZeroIndex() {
String[] DATA = {
// Expect col1 x COMPOSE_COMPAT => col2
// Expect col2 x DECOMP => col3
"A\u0316\u0300", "\u00C0\u0316", "A\u0316\u0300",
"A\u0300\u0316", "\u00C0\u0316", "A\u0316\u0300",
"A\u0327\u0300", "\u00C0\u0327", "A\u0327\u0300",
"c\u0321\u0327", "c\u0321\u0327", "c\u0321\u0327",
"c\u0327\u0321", "\u00E7\u0321", "c\u0327\u0321",
};
for (int i=0; i<DATA.length; i+=3) {
String a = DATA[i];
String b = Normalizer.normalize(a, Normalizer.COMPOSE_COMPAT, 0);
String exp = DATA[i+1];
if (b.equals(exp)) {
logln("Ok: " + hex(a) + " x COMPOSE_COMPAT => " + hex(b));
} else {
errln("FAIL: " + hex(a) + " x COMPOSE_COMPAT => " + hex(b) +
", expect " + hex(exp));
}
a = Normalizer.normalize(b, Normalizer.DECOMP, 0);
exp = DATA[i+2];
if (a.equals(exp)) {
logln("Ok: " + hex(b) + " x DECOMP => " + hex(a));
} else {
errln("FAIL: " + hex(b) + " x DECOMP => " + hex(a) +
", expect " + hex(exp));
}
}
}
/**
* Test for a problem found by Verisign. Problem is that
* characters at the start of a string are not put in canonical
* order correctly by compose() if there is no starter.
*/
public void TestVerisign() {
String[] inputs = {
"\u05b8\u05b9\u05b1\u0591\u05c3\u05b0\u05ac\u059f",
"\u0592\u05b7\u05bc\u05a5\u05b0\u05c0\u05c4\u05ad"
};
String[] outputs = {
"\u05b1\u05b8\u05b9\u0591\u05c3\u05b0\u05ac\u059f",
"\u05b0\u05b7\u05bc\u05a5\u0592\u05c0\u05ad\u05c4"
};
for (int i = 0; i < inputs.length; ++i) {
String input = inputs[i];
String output = outputs[i];
String result = Normalizer.decompose(input, false, 0);
if (!result.equals(output)) {
errln("FAIL input: " + Utility.escape(input));
errln(" decompose: " + Utility.escape(result));
errln(" expected: " + Utility.escape(output));
}
result = Normalizer.compose(input, false, 0);
if (!result.equals(output)) {
errln("FAIL input: " + Utility.escape(input));
errln(" compose: " + Utility.escape(result));
errln(" expected: " + Utility.escape(output));
}
}
}
//------------------------------------------------------------------------
// Internal utilities
//
private void backAndForth(Normalizer iter, String input)
{
iter.setText(input);
// Run through the iterator forwards and stick it into a StringBuffer
StringBuffer forward = new StringBuffer();
for (char ch = iter.first(); ch != iter.DONE; ch = iter.next()) {
forward.append(ch);
}
// Now do it backwards
StringBuffer reverse = new StringBuffer();
for (char ch = iter.last(); ch != iter.DONE; ch = iter.previous()) {
reverse.insert(0, ch);
}
if (!forward.toString().equals(reverse.toString())) {
errln("FAIL: Forward/reverse mismatch for input " + hex(input)
+ ", forward: " + hex(forward) + ", backward: " + hex(reverse));
} else if (isVerbose()) {
logln("Ok: Forward/reverse for input " + hex(input)
+ ", forward: " + hex(forward) + ", backward: " + hex(reverse));
}
}
private void backAndForth(Normalizer iter, String[][] tests)
{
for (int i = 0; i < tests.length; i++)
{
iter.setText(tests[i][0]);
// Run through the iterator forwards and stick it into a StringBuffer
StringBuffer forward = new StringBuffer();
for (char ch = iter.first(); ch != iter.DONE; ch = iter.next()) {
forward.append(ch);
}
// Now do it backwards
StringBuffer reverse = new StringBuffer();
for (char ch = iter.last(); ch != iter.DONE; ch = iter.previous()) {
reverse.insert(0, ch);
}
if (!forward.toString().equals(reverse.toString())) {
errln("FAIL: Forward/reverse mismatch for input " + hex(tests[i][0])
+ ", forward: " + hex(forward) + ", backward: " + hex(reverse));
} else if (isVerbose()) {
logln("Ok: Forward/reverse for input " + hex(tests[i][0])
+ ", forward: " + hex(forward) + ", backward: " + hex(reverse));
}
}
}
private void staticTest(Normalizer.Mode mode, int options, String[][] tests, int outCol)
{
for (int i = 0; i < tests.length; i++)
{
String input = tests[i][0];
String expect = tests[i][outCol];
logln("Normalizing '" + input + "' (" + hex(input) + ")" );
String output = Normalizer.normalize(input, mode, options);
if (!output.equals(expect)) {
errln("FAIL: case " + i
+ " expected '" + expect + "' (" + hex(expect) + ")"
+ " but got '" + output + "' (" + hex(output) + ")" );
}
}
}
private void iterateTest(Normalizer iter, String[][] tests, int outCol)
{
for (int i = 0; i < tests.length; i++)
{
String input = tests[i][0];
String expect = tests[i][outCol];
logln("Normalizing '" + input + "' (" + hex(input) + ")" );
iter.setText(input);
assertEqual(expect, iter, "case " + i + " ");
}
}
private void assertEqual(String expected, Normalizer iter, String msg)
{
int index = 0;
for (char ch = iter.first(); ch != iter.DONE; ch = iter.next())
{
if (index >= expected.length()) {
errln("FAIL: " + msg + "Unexpected character '" + ch + "' (" + hex(ch) + ")"
+ " at index " + index);
break;
}
char want = expected.charAt(index);
if (ch != want) {
errln("FAIL: " + msg + "got '" + ch + "' (" + hex(ch) + ")"
+ " but expected '" + want + "' (" + hex(want) + ")"
+ " at index " + index);
}
index++;
}
if (index < expected.length()) {
errln("FAIL: " + msg + "Only got " + index + " chars, expected " + expected.length());
}
}
}

View File

@ -1,250 +0,0 @@
/*
************************************************************************
* Copyright (c) 1997-2000, International Business Machines
* Corporation and others. All Rights Reserved.
************************************************************************
*/
package com.ibm.test.normalizer;
import java.io.*;
import com.ibm.test.*;
import com.ibm.text.*;
import com.ibm.util.Utility;
public class ConformanceTest extends TestFmwk {
Normalizer normalizer;
static final String TEST_SUITE_FILE =
"src/data/unicode/Draft-TestSuite.txt";
public static void main(String[] args) throws Exception {
new ConformanceTest().run(args);
}
public ConformanceTest() {
// Doesn't matter what the string and mode are; we'll change
// them later as needed.
normalizer = new Normalizer("", Normalizer.COMPOSE);
}
/**
* Test the conformance of Normalizer to
* http://www.unicode.org/unicode/reports/tr15/conformance/Draft-TestSuite.txt.
* This file must be located at the path specified as TEST_SUITE_FILE.
*/
public void TestConformance() {
BufferedReader input = null;
String line = null;
String[] fields = new String[5];
StringBuffer buf = new StringBuffer();
int passCount = 0;
int failCount = 0;
try {
input = new BufferedReader(new FileReader(TEST_SUITE_FILE),64*1024);
for (int count = 0;;++count) {
line = input.readLine();
if (line == null) break;
if (line.length() == 0) continue;
// Expect 5 columns of this format:
// 1E0C;1E0C;0044 0323;1E0C;0044 0323; # <comments>
// Skip comments
if (line.charAt(0) == '#') continue;
// Parse out the fields
hexsplit(line, ';', fields, buf);
if (checkConformance(fields, line)) {
++passCount;
} else {
++failCount;
}
if ((count % 1000) == 999) {
logln("Line " + (count+1));
}
}
} catch (IOException ex) {
try {
input.close();
} catch (Exception ex2) {
System.out.print("");
}
ex.printStackTrace();
throw new IllegalArgumentException("Couldn't read file "
+ ex.getClass().getName() + " " + ex.getMessage()
+ " line = " + line
);
}
if (failCount != 0) {
errln("Total: " + failCount + " lines failed, " +
passCount + " lines passed");
} else {
logln("Total: " + passCount + " lines passed");
}
}
/**
* Verify the conformance of the given line of the Unicode
* normalization (UTR 15) test suite file. For each line,
* there are five columns, corresponding to field[0]..field[4].
*
* The following invariants must be true for all conformant implementations
* c2 == NFC(c1) == NFC(c2) == NFC(c3)
* c3 == NFD(c1) == NFD(c2) == NFD(c3)
* c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5)
* c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5)
*
* @param field the 5 columns
* @param line the source line from the test suite file
* @return true if the test passes
*/
private boolean checkConformance(String[] field, String line) {
boolean pass = true;
StringBuffer buf = new StringBuffer(); // scratch
String out;
for (int i=0; i<5; ++i) {
if (i<3) {
out = Normalizer.normalize(field[i], Normalizer.COMPOSE, 0);
pass &= assertEqual("C", field[i], out, field[1], "c2!=C(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.COMPOSE, buf, +1);
pass &= assertEqual("C(+1)", field[i], out, field[1], "c2!=C(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.COMPOSE, buf, -1);
pass &= assertEqual("C(-1)", field[i], out, field[1], "c2!=C(c" + (i+1));
out = Normalizer.normalize(field[i], Normalizer.DECOMP, 0);
pass &= assertEqual("D", field[i], out, field[2], "c3!=D(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.DECOMP, buf, +1);
pass &= assertEqual("D(+1)", field[i], out, field[2], "c3!=D(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.DECOMP, buf, -1);
pass &= assertEqual("D(-1)", field[i], out, field[2], "c3!=D(c" + (i+1));
}
out = Normalizer.normalize(field[i], Normalizer.COMPOSE_COMPAT, 0);
pass &= assertEqual("KC", field[i], out, field[3], "c4!=KC(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.COMPOSE_COMPAT, buf, +1);
pass &= assertEqual("KD(+1)", field[i], out, field[3], "c4!=KC(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.COMPOSE_COMPAT, buf, -1);
pass &= assertEqual("KD(-1)", field[i], out, field[3], "c4!=KC(c" + (i+1));
out = Normalizer.normalize(field[i], Normalizer.DECOMP_COMPAT, 0);
pass &= assertEqual("KD", field[i], out, field[4], "c5!=KD(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.DECOMP_COMPAT, buf, +1);
pass &= assertEqual("KD(+1)", field[i], out, field[4], "c5!=KD(c" + (i+1));
out = iterativeNorm(field[i], Normalizer.DECOMP_COMPAT, buf, -1);
pass &= assertEqual("KD(-1)", field[i], out, field[4], "c5!=KD(c" + (i+1));
}
if (!pass) {
errln("FAIL: " + line);
}
return pass;
}
/**
* Do a normalization using the iterative API in the given direction.
* @param buf scratch buffer
* @param dir either +1 or -1
*/
private String iterativeNorm(String str, Normalizer.Mode mode,
StringBuffer buf, int dir) {
normalizer.setText(str);
normalizer.setMode(mode);
buf.setLength(0);
char ch;
if (dir > 0) {
for (ch = normalizer.first(); ch != Normalizer.DONE;
ch = normalizer.next()) {
buf.append(ch);
}
} else {
for (ch = normalizer.last(); ch != Normalizer.DONE;
ch = normalizer.previous()) {
buf.insert(0, ch);
}
}
return buf.toString();
}
/**
* @param op name of normalization form, e.g., "KC"
* @param s string being normalized
* @param got value received
* @param exp expected value
* @param msg description of this test
* @param return true if got == exp
*/
private boolean assertEqual(String op, String s, String got,
String exp, String msg) {
if (exp.equals(got)) {
return true;
}
errln(Utility.escape(" " + msg + ") " + op + "(" + s + ")=" + got +
", exp. " + exp));
return false;
}
/**
* Split a string into pieces based on the given delimiter
* character. Then, parse the resultant fields from hex into
* characters. That is, "0040 0400;0C00;0899" -> new String[] {
* "\u0040\u0400", "\u0C00", "\u0899" }. The output is assumed to
* be of the proper length already, and exactly output.length
* fields are parsed. If there are too few an exception is
* thrown. If there are too many the extras are ignored.
*
* @param buf scratch buffer
*/
private static void hexsplit(String s, char delimiter,
String[] output, StringBuffer buf) {
int i;
int pos = 0;
for (i=0; i<output.length; ++i) {
int delim = s.indexOf(delimiter, pos);
if (delim < 0) {
throw new IllegalArgumentException("Missing field in " + s);
}
// Our field is from pos..delim-1.
buf.setLength(0);
while (pos < delim) {
if (s.charAt(pos) == ' ') {
++pos;
} else if (pos+4 > delim) {
throw new IllegalArgumentException("Premature eol in " + s);
} else {
int hex = Integer.parseInt(s.substring(pos, pos+4), 16);
if (hex < 0 || hex > 0xFFFF) {
throw new IllegalArgumentException("Out of range hex " +
hex + " in " + s);
}
buf.append((char) hex);
pos += 4;
}
}
if (buf.length() < 1) {
throw new IllegalArgumentException("Empty field " + i + " in " + s);
}
output[i] = buf.toString();
++pos; // Skip over delim
}
}
// Specific tests for debugging. These are generally failures
// taken from the conformance file, but culled out to make
// debugging easier. These can be eliminated without affecting
// coverage.
public void _hideTestCase6() {
_testOneLine("0385;0385;00A8 0301;0020 0308 0301;0020 0308 0301;");
}
public void _testOneLine(String line) {
String[] fields = new String[5];
StringBuffer buf = new StringBuffer();
// Parse out the fields
hexsplit(line, ';', fields, buf);
checkConformance(fields, line);
}
}

Some files were not shown because too many files have changed in this diff Show More