You can subscribe to this list here.
| 2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(97) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2007 |
Jan
(127) |
Feb
(34) |
Mar
(16) |
Apr
(26) |
May
(55) |
Jun
(107) |
Jul
(36) |
Aug
(72) |
Sep
(90) |
Oct
(41) |
Nov
(27) |
Dec
(13) |
| 2008 |
Jan
(37) |
Feb
(39) |
Mar
(98) |
Apr
(115) |
May
(134) |
Jun
(120) |
Jul
(86) |
Aug
(149) |
Sep
(68) |
Oct
(66) |
Nov
(104) |
Dec
(49) |
| 2009 |
Jan
(131) |
Feb
(132) |
Mar
(125) |
Apr
(172) |
May
(161) |
Jun
(43) |
Jul
(47) |
Aug
(38) |
Sep
(18) |
Oct
(6) |
Nov
(1) |
Dec
(15) |
| 2010 |
Jan
(21) |
Feb
(8) |
Mar
(10) |
Apr
(4) |
May
(9) |
Jun
|
Jul
(1) |
Aug
|
Sep
|
Oct
(2) |
Nov
|
Dec
(4) |
| 2011 |
Jan
(23) |
Feb
(10) |
Mar
(13) |
Apr
(3) |
May
|
Jun
(19) |
Jul
(11) |
Aug
(22) |
Sep
|
Oct
(4) |
Nov
(2) |
Dec
(12) |
| 2012 |
Jan
(3) |
Feb
(4) |
Mar
(7) |
Apr
(3) |
May
|
Jun
(1) |
Jul
(1) |
Aug
(30) |
Sep
(3) |
Oct
(2) |
Nov
|
Dec
(8) |
| 2013 |
Jan
(3) |
Feb
(40) |
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(12) |
Dec
|
| 2021 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(2) |
Oct
|
Nov
|
Dec
|
|
From: <ls...@us...> - 2007-06-23 05:03:36
|
Revision: 3294
http://jnode.svn.sourceforge.net/jnode/?rev=3294&view=rev
Author: lsantha
Date: 2007-06-22 22:03:35 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Modified Paths:
--------------
trunk/core/src/classpath/java/java/lang/InheritableThreadLocal.java
Modified: trunk/core/src/classpath/java/java/lang/InheritableThreadLocal.java
===================================================================
--- trunk/core/src/classpath/java/java/lang/InheritableThreadLocal.java 2007-06-23 05:02:44 UTC (rev 3293)
+++ trunk/core/src/classpath/java/java/lang/InheritableThreadLocal.java 2007-06-23 05:03:35 UTC (rev 3294)
@@ -59,7 +59,7 @@
* @since 1.2
* @status updated to 1.4
*/
-public class InheritableThreadLocal extends ThreadLocal
+public class InheritableThreadLocal<T> extends ThreadLocal<T>
{
/**
@@ -101,7 +101,7 @@
Iterator keys = parentThread.locals.keySet().iterator();
while (keys.hasNext())
{
- Key key = (Key)keys.next();
+ ThreadLocal.Key key = (ThreadLocal.Key)keys.next();
if (key.get() instanceof InheritableThreadLocal)
{
InheritableThreadLocal local = (InheritableThreadLocal)key.get();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-23 05:02:45
|
Revision: 3293
http://jnode.svn.sourceforge.net/jnode/?rev=3293&view=rev
Author: lsantha
Date: 2007-06-22 22:02:44 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Removed Paths:
-------------
trunk/core/src/classpath/java/java/io/IOException.java
Deleted: trunk/core/src/classpath/java/java/io/IOException.java
===================================================================
--- trunk/core/src/classpath/java/java/io/IOException.java 2007-06-23 05:02:03 UTC (rev 3292)
+++ trunk/core/src/classpath/java/java/io/IOException.java 2007-06-23 05:02:44 UTC (rev 3293)
@@ -1,74 +0,0 @@
-/* IOException.java -- Generic input/output exception
- Copyright (C) 1998, 1999, 2001, 2002, 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package java.io;
-
-/**
- * This exception is thrown to indicate an I/O problem of some sort
- * occurred. Since this is a fairly generic exception, often a subclass
- * of IOException will actually be thrown in order to provide a more
- * detailed indication of what happened.
- *
- * @author Aaron M. Renn (ar...@ur...)
- * @author Tom Tromey (tr...@cy...)
- * @status updated to 1.4
- */
-public class IOException extends Exception
-{
- /**
- * Compatible with JDK 1.0+.
- */
- private static final long serialVersionUID = 7818375828146090155L;
-
- /**
- * Create an exception without a descriptive error message.
- */
- public IOException()
- {
- }
-
- /**
- * Create an exception with a descriptive error message.
- *
- * @param message the descriptive error message
- */
- public IOException(String message)
- {
- super(message);
- }
-} // class IOException
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-23 05:02:05
|
Revision: 3292
http://jnode.svn.sourceforge.net/jnode/?rev=3292&view=rev
Author: lsantha
Date: 2007-06-22 22:02:03 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/sun/sun/util/calendar/
trunk/core/src/openjdk/sun/sun/util/calendar/AbstractCalendar.java
trunk/core/src/openjdk/sun/sun/util/calendar/BaseCalendar.java
trunk/core/src/openjdk/sun/sun/util/calendar/CalendarDate.java
trunk/core/src/openjdk/sun/sun/util/calendar/CalendarSystem.java
trunk/core/src/openjdk/sun/sun/util/calendar/CalendarUtils.java
trunk/core/src/openjdk/sun/sun/util/calendar/Era.java
trunk/core/src/openjdk/sun/sun/util/calendar/Gregorian.java
trunk/core/src/openjdk/sun/sun/util/calendar/ImmutableGregorianDate.java
trunk/core/src/openjdk/sun/sun/util/calendar/JulianCalendar.java
trunk/core/src/openjdk/sun/sun/util/calendar/LocalGregorianCalendar.java
trunk/core/src/openjdk/sun/sun/util/calendar/ZoneInfo.java
trunk/core/src/openjdk/sun/sun/util/calendar/ZoneInfoFile.java
Added: trunk/core/src/openjdk/sun/sun/util/calendar/AbstractCalendar.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/util/calendar/AbstractCalendar.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/util/calendar/AbstractCalendar.java 2007-06-23 05:02:03 UTC (rev 3292)
@@ -0,0 +1,398 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.util.calendar;
+
+import java.util.Locale;
+import java.util.TimeZone;
+
+/**
+ * The <code>AbstractCalendar</code> class provides a framework for
+ * implementing a concrete calendar system.
+ *
+ * <p><a name="fixed_date"></a><B>Fixed Date</B><br>
+ *
+ * For implementing a concrete calendar system, each calendar must
+ * have the common date numbering, starting from midnight the onset of
+ * Monday, January 1, 1 (Gregorian). It is called a <I>fixed date</I>
+ * in this class. January 1, 1 (Gregorian) is fixed date 1. (See
+ * Nachum Dershowitz and Edward M. Reingold, <I>CALENDRICAL
+ * CALCULATION The Millennium Edition</I>, Section 1.2 for details.)
+ *
+ * @author Masayoshi Okutsu
+ * @since 1.5
+ */
+
+public abstract class AbstractCalendar extends CalendarSystem {
+
+ // The constants assume no leap seconds support.
+ static final int SECOND_IN_MILLIS = 1000;
+ static final int MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
+ static final int HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
+ static final int DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
+
+ // The number of days between January 1, 1 and January 1, 1970 (Gregorian)
+ static final int EPOCH_OFFSET = 719163;
+
+ private Era[] eras;
+
+ protected AbstractCalendar() {
+ }
+
+ public Era getEra(String eraName) {
+ if (eras != null) {
+ for (int i = 0; i < eras.length; i++) {
+ if (eras[i].equals(eraName)) {
+ return eras[i];
+ }
+ }
+ }
+ return null;
+ }
+
+ public Era[] getEras() {
+ Era[] e = null;
+ if (eras != null) {
+ e = new Era[eras.length];
+ System.arraycopy(eras, 0, e, 0, eras.length);
+ }
+ return e;
+ }
+
+ public void setEra(CalendarDate date, String eraName) {
+ if (eras == null) {
+ return; // should report an error???
+ }
+ for (int i = 0; i < eras.length; i++) {
+ Era e = eras[i];
+ if (e != null && e.getName().equals(eraName)) {
+ date.setEra(e);
+ return;
+ }
+ }
+ throw new IllegalArgumentException("unknown era name: " + eraName);
+ }
+
+ protected void setEras(Era[] eras) {
+ this.eras = eras;
+ }
+
+ public CalendarDate getCalendarDate() {
+ return getCalendarDate(System.currentTimeMillis(), newCalendarDate());
+ }
+
+ public CalendarDate getCalendarDate(long millis) {
+ return getCalendarDate(millis, newCalendarDate());
+ }
+
+ public CalendarDate getCalendarDate(long millis, TimeZone zone) {
+ CalendarDate date = newCalendarDate(zone);
+ return getCalendarDate(millis, date);
+ }
+
+ public CalendarDate getCalendarDate(long millis, CalendarDate date) {
+ int ms = 0; // time of day
+ int zoneOffset = 0;
+ int saving = 0;
+ long days = 0; // fixed date
+
+ // adjust to local time if `date' has time zone.
+ TimeZone zi = date.getZone();
+ if (zi != null) {
+ int[] offsets = new int[2];
+ if (zi instanceof ZoneInfo) {
+ zoneOffset = ((ZoneInfo)zi).getOffsets(millis, offsets);
+ } else {
+ zoneOffset = zi.getOffset(millis);
+ offsets[0] = zi.getRawOffset();
+ offsets[1] = zoneOffset - offsets[0];
+ }
+
+ // We need to calculate the given millis and time zone
+ // offset separately for java.util.GregorianCalendar
+ // compatibility. (i.e., millis + zoneOffset could cause
+ // overflow or underflow, which must be avoided.) Usually
+ // days should be 0 and ms is in the range of -13:00 to
+ // +14:00. However, we need to deal with extreme cases.
+ days = zoneOffset / DAY_IN_MILLIS;
+ ms = zoneOffset % DAY_IN_MILLIS;
+ saving = offsets[1];
+ }
+ date.setZoneOffset(zoneOffset);
+ date.setDaylightSaving(saving);
+
+ days += millis / DAY_IN_MILLIS;
+ ms += (int) (millis % DAY_IN_MILLIS);
+ if (ms >= DAY_IN_MILLIS) {
+ // at most ms is (DAY_IN_MILLIS - 1) * 2.
+ ms -= DAY_IN_MILLIS;
+ ++days;
+ } else {
+ // at most ms is (1 - DAY_IN_MILLIS) * 2. Adding one
+ // DAY_IN_MILLIS results in still negative.
+ while (ms < 0) {
+ ms += DAY_IN_MILLIS;
+ --days;
+ }
+ }
+
+ // convert to fixed date (offset from Jan. 1, 1 (Gregorian))
+ days += EPOCH_OFFSET;
+
+ // calculate date fields from the fixed date
+ getCalendarDateFromFixedDate(date, days);
+
+ // calculate time fields from the time of day
+ setTimeOfDay(date, ms);
+ date.setLeapYear(isLeapYear(date));
+ date.setNormalized(true);
+ return date;
+ }
+
+ public long getTime(CalendarDate date) {
+ long gd = getFixedDate(date);
+ long ms = (gd - EPOCH_OFFSET) * DAY_IN_MILLIS + getTimeOfDay(date);
+ int zoneOffset = 0;
+ TimeZone zi = date.getZone();
+ if (zi != null) {
+ if (date.isNormalized()) {
+ return ms - date.getZoneOffset();
+ }
+ // adjust time zone and daylight saving
+ int[] offsets = new int[2];
+ if (date.isStandardTime()) {
+ // 1) 2:30am during starting-DST transition is
+ // intrepreted as 2:30am ST
+ // 2) 5:00pm during DST is still interpreted as 5:00pm ST
+ // 3) 1:30am during ending-DST transition is interpreted
+ // as 1:30am ST (after transition)
+ if (zi instanceof ZoneInfo) {
+ ((ZoneInfo)zi).getOffsetsByStandard(ms, offsets);
+ zoneOffset = offsets[0];
+ } else {
+ zoneOffset = zi.getOffset(ms - zi.getRawOffset());
+ }
+ } else {
+ // 1) 2:30am during starting-DST transition is
+ // intrepreted as 3:30am DT
+ // 2) 5:00pm during DST is intrepreted as 5:00pm DT
+ // 3) 1:30am during ending-DST transition is interpreted
+ // as 1:30am DT/0:30am ST (before transition)
+ if (zi instanceof ZoneInfo) {
+ zoneOffset = ((ZoneInfo)zi).getOffsetsByWall(ms, offsets);
+ } else {
+ zoneOffset = zi.getOffset(ms - zi.getRawOffset());
+ }
+ }
+ }
+ ms -= zoneOffset;
+ getCalendarDate(ms, date);
+ return ms;
+ }
+
+ protected long getTimeOfDay(CalendarDate date) {
+ long fraction = date.getTimeOfDay();
+ if (fraction != CalendarDate.TIME_UNDEFINED) {
+ return fraction;
+ }
+ fraction = getTimeOfDayValue(date);
+ date.setTimeOfDay(fraction);
+ return fraction;
+ }
+
+ public long getTimeOfDayValue(CalendarDate date) {
+ long fraction = date.getHours();
+ fraction *= 60;
+ fraction += date.getMinutes();
+ fraction *= 60;
+ fraction += date.getSeconds();
+ fraction *= 1000;
+ fraction += date.getMillis();
+ return fraction;
+ }
+
+ public CalendarDate setTimeOfDay(CalendarDate cdate, int fraction) {
+ if (fraction < 0) {
+ throw new IllegalArgumentException();
+ }
+ boolean normalizedState = cdate.isNormalized();
+ int time = fraction;
+ int hours = time / HOUR_IN_MILLIS;
+ time %= HOUR_IN_MILLIS;
+ int minutes = time / MINUTE_IN_MILLIS;
+ time %= MINUTE_IN_MILLIS;
+ int seconds = time / SECOND_IN_MILLIS;
+ time %= SECOND_IN_MILLIS;
+ cdate.setHours(hours);
+ cdate.setMinutes(minutes);
+ cdate.setSeconds(seconds);
+ cdate.setMillis(time);
+ cdate.setTimeOfDay(fraction);
+ if (hours < 24 && normalizedState) {
+ // If this time of day setting doesn't affect the date,
+ // then restore the normalized state.
+ cdate.setNormalized(normalizedState);
+ }
+ return cdate;
+ }
+
+ /**
+ * Returns 7 in this default implementation.
+ *
+ * @return 7
+ */
+ public int getWeekLength() {
+ return 7;
+ }
+
+ protected abstract boolean isLeapYear(CalendarDate date);
+
+ public CalendarDate getNthDayOfWeek(int nth, int dayOfWeek, CalendarDate date) {
+ CalendarDate ndate = (CalendarDate) date.clone();
+ normalize(ndate);
+ long fd = getFixedDate(ndate);
+ long nfd;
+ if (nth > 0) {
+ nfd = 7 * nth + getDayOfWeekDateBefore(fd, dayOfWeek);
+ } else {
+ nfd = 7 * nth + getDayOfWeekDateAfter(fd, dayOfWeek);
+ }
+ getCalendarDateFromFixedDate(ndate, nfd);
+ return ndate;
+ }
+
+ /**
+ * Returns a date of the given day of week before the given fixed
+ * date.
+ *
+ * @param fixedDate the fixed date
+ * @param dayOfWeek the day of week
+ * @return the calculated date
+ */
+ static long getDayOfWeekDateBefore(long fixedDate, int dayOfWeek) {
+ return getDayOfWeekDateOnOrBefore(fixedDate - 1, dayOfWeek);
+ }
+
+ /**
+ * Returns a date of the given day of week that is closest to and
+ * after the given fixed date.
+ *
+ * @param fixedDate the fixed date
+ * @param dayOfWeek the day of week
+ * @return the calculated date
+ */
+ static long getDayOfWeekDateAfter(long fixedDate, int dayOfWeek) {
+ return getDayOfWeekDateOnOrBefore(fixedDate + 7, dayOfWeek);
+ }
+
+ /**
+ * Returns a date of the given day of week on or before the given fixed
+ * date.
+ *
+ * @param fixedDate the fixed date
+ * @param dayOfWeek the day of week
+ * @return the calculated date
+ */
+ // public for java.util.GregorianCalendar
+ public static long getDayOfWeekDateOnOrBefore(long fixedDate, int dayOfWeek) {
+ long fd = fixedDate - (dayOfWeek - 1);
+ if (fd >= 0) {
+ return fixedDate - (fd % 7);
+ }
+ return fixedDate - CalendarUtils.mod(fd, 7);
+ }
+
+ /**
+ * Returns the fixed date calculated with the specified calendar
+ * date. If the specified date is not normalized, its date fields
+ * are normalized.
+ *
+ * @param date a <code>CalendarDate</code> with which the fixed
+ * date is calculated
+ * @return the calculated fixed date
+ * @see AbstractCalendar.html#fixed_date
+ */
+ protected abstract long getFixedDate(CalendarDate date);
+
+ /**
+ * Calculates calendar fields from the specified fixed date. This
+ * method stores the calculated calendar field values in the specified
+ * <code>CalendarDate</code>.
+ *
+ * @param date a <code>CalendarDate</code> to stored the
+ * calculated calendar fields.
+ * @param fixedDate a fixed date to calculate calendar fields
+ * @see AbstractCalendar.html#fixed_date
+ */
+ protected abstract void getCalendarDateFromFixedDate(CalendarDate date,
+ long fixedDate);
+
+ public boolean validateTime(CalendarDate date) {
+ int t = date.getHours();
+ if (t < 0 || t >= 24) {
+ return false;
+ }
+ t = date.getMinutes();
+ if (t < 0 || t >= 60) {
+ return false;
+ }
+ t = date.getSeconds();
+ // TODO: Leap second support.
+ if (t < 0 || t >= 60) {
+ return false;
+ }
+ t = date.getMillis();
+ if (t < 0 || t >= 1000) {
+ return false;
+ }
+ return true;
+ }
+
+
+ int normalizeTime(CalendarDate date) {
+ long fraction = getTimeOfDay(date);
+ long days = 0;
+
+ if (fraction >= DAY_IN_MILLIS) {
+ days = fraction / DAY_IN_MILLIS;
+ fraction %= DAY_IN_MILLIS;
+ } else if (fraction < 0) {
+ days = CalendarUtils.floorDivide(fraction, DAY_IN_MILLIS);
+ if (days != 0) {
+ fraction -= DAY_IN_MILLIS * days; // mod(fraction, DAY_IN_MILLIS)
+ }
+ }
+ if (days != 0) {
+ date.setTimeOfDay(fraction);
+ }
+ date.setMillis((int)(fraction % 1000));
+ fraction /= 1000;
+ date.setSeconds((int)(fraction % 60));
+ fraction /= 60;
+ date.setMinutes((int)(fraction % 60));
+ date.setHours((int)(fraction / 60));
+ return (int)days;
+ }
+}
Added: trunk/core/src/openjdk/sun/sun/util/calendar/BaseCalendar.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/util/calendar/BaseCalendar.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/util/calendar/BaseCalendar.java 2007-06-23 05:02:03 UTC (rev 3292)
@@ -0,0 +1,538 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.util.calendar;
+
+import java.util.Locale;
+import java.util.TimeZone;
+
+/**
+ * The <code>BaseCalendar</code> provides basic calendar calculation
+ * functions to support the Julian, Gregorian, and Gregorian-based
+ * calendar systems.
+ *
+ * @author Masayoshi Okutsu
+ * @since 1.5
+ */
+
+public abstract class BaseCalendar extends AbstractCalendar {
+
+ public static final int JANUARY = 1;
+ public static final int FEBRUARY = 2;
+ public static final int MARCH = 3;
+ public static final int APRIL = 4;
+ public static final int MAY = 5;
+ public static final int JUNE = 6;
+ public static final int JULY = 7;
+ public static final int AUGUST = 8;
+ public static final int SEPTEMBER = 9;
+ public static final int OCTOBER = 10;
+ public static final int NOVEMBER = 11;
+ public static final int DECEMBER = 12;
+
+ // day of week constants
+ public static final int SUNDAY = 1;
+ public static final int MONDAY = 2;
+ public static final int TUESDAY = 3;
+ public static final int WEDNESDAY = 4;
+ public static final int THURSDAY = 5;
+ public static final int FRIDAY = 6;
+ public static final int SATURDAY = 7;
+
+ // The base Gregorian year of FIXED_DATES[]
+ private static final int BASE_YEAR = 1970;
+
+ // Pre-calculated fixed dates of January 1 from BASE_YEAR
+ // (Gregorian). This table covers all the years that can be
+ // supported by the POSIX time_t (32-bit) after the Epoch. Note
+ // that the data type is int[].
+ private static final int[] FIXED_DATES = {
+ 719163, // 1970
+ 719528, // 1971
+ 719893, // 1972
+ 720259, // 1973
+ 720624, // 1974
+ 720989, // 1975
+ 721354, // 1976
+ 721720, // 1977
+ 722085, // 1978
+ 722450, // 1979
+ 722815, // 1980
+ 723181, // 1981
+ 723546, // 1982
+ 723911, // 1983
+ 724276, // 1984
+ 724642, // 1985
+ 725007, // 1986
+ 725372, // 1987
+ 725737, // 1988
+ 726103, // 1989
+ 726468, // 1990
+ 726833, // 1991
+ 727198, // 1992
+ 727564, // 1993
+ 727929, // 1994
+ 728294, // 1995
+ 728659, // 1996
+ 729025, // 1997
+ 729390, // 1998
+ 729755, // 1999
+ 730120, // 2000
+ 730486, // 2001
+ 730851, // 2002
+ 731216, // 2003
+ 731581, // 2004
+ 731947, // 2005
+ 732312, // 2006
+ 732677, // 2007
+ 733042, // 2008
+ 733408, // 2009
+ 733773, // 2010
+ 734138, // 2011
+ 734503, // 2012
+ 734869, // 2013
+ 735234, // 2014
+ 735599, // 2015
+ 735964, // 2016
+ 736330, // 2017
+ 736695, // 2018
+ 737060, // 2019
+ 737425, // 2020
+ 737791, // 2021
+ 738156, // 2022
+ 738521, // 2023
+ 738886, // 2024
+ 739252, // 2025
+ 739617, // 2026
+ 739982, // 2027
+ 740347, // 2028
+ 740713, // 2029
+ 741078, // 2030
+ 741443, // 2031
+ 741808, // 2032
+ 742174, // 2033
+ 742539, // 2034
+ 742904, // 2035
+ 743269, // 2036
+ 743635, // 2037
+ 744000, // 2038
+ 744365, // 2039
+ };
+
+ public abstract static class Date extends CalendarDate {
+ protected Date() {
+ super();
+ }
+ protected Date(TimeZone zone) {
+ super(zone);
+ }
+
+ public Date setNormalizedDate(int normalizedYear, int month, int dayOfMonth) {
+ setNormalizedYear(normalizedYear);
+ setMonth(month).setDayOfMonth(dayOfMonth);
+ return this;
+ }
+
+ public abstract int getNormalizedYear();
+
+ public abstract void setNormalizedYear(int normalizedYear);
+
+ // Cache for the fixed date of January 1 and year length of the
+ // cachedYear. A simple benchmark showed 7% performance
+ // improvement with >90% cache hit. The initial values are for Gregorian.
+ int cachedYear = 2004;
+ long cachedFixedDateJan1 = 731581L;
+ long cachedFixedDateNextJan1 = cachedFixedDateJan1 + 366;
+
+ protected final boolean hit(int year) {
+ return year == cachedYear;
+ }
+
+ protected final boolean hit(long fixedDate) {
+ return (fixedDate >= cachedFixedDateJan1 &&
+ fixedDate < cachedFixedDateNextJan1);
+ }
+ protected int getCachedYear() {
+ return cachedYear;
+ }
+
+ protected long getCachedJan1() {
+ return cachedFixedDateJan1;
+ }
+
+ protected void setCache(int year, long jan1, int len) {
+ cachedYear = year;
+ cachedFixedDateJan1 = jan1;
+ cachedFixedDateNextJan1 = jan1 + len;
+ }
+ }
+
+ public boolean validate(CalendarDate date) {
+ Date bdate = (Date) date;
+ if (bdate.isNormalized()) {
+ return true;
+ }
+ int month = bdate.getMonth();
+ if (month < JANUARY || month > DECEMBER) {
+ return false;
+ }
+ int d = bdate.getDayOfMonth();
+ if (d <= 0 || d > getMonthLength(bdate.getNormalizedYear(), month)) {
+ return false;
+ }
+ int dow = bdate.getDayOfWeek();
+ if (dow != bdate.FIELD_UNDEFINED && dow != getDayOfWeek(bdate)) {
+ return false;
+ }
+
+ if (!validateTime(date)) {
+ return false;
+ }
+
+ bdate.setNormalized(true);
+ return true;
+ }
+
+ public boolean normalize(CalendarDate date) {
+ if (date.isNormalized()) {
+ return true;
+ }
+
+ Date bdate = (Date) date;
+ TimeZone zi = bdate.getZone();
+
+ // If the date has a time zone, then we need to recalculate
+ // the calendar fields. Let getTime() do it.
+ if (zi != null) {
+ getTime(date);
+ return true;
+ }
+
+ int days = normalizeTime(bdate);
+ normalizeMonth(bdate);
+ long d = (long)bdate.getDayOfMonth() + days;
+ int m = bdate.getMonth();
+ int y = bdate.getNormalizedYear();
+ int ml = getMonthLength(y, m);
+
+ if (!(d > 0 && d <= ml)) {
+ if (d <= 0 && d > -28) {
+ ml = getMonthLength(y, --m);
+ d += ml;
+ bdate.setDayOfMonth((int) d);
+ if (m == 0) {
+ m = DECEMBER;
+ bdate.setNormalizedYear(y - 1);
+ }
+ bdate.setMonth(m);
+ } else if (d > ml && d < (ml + 28)) {
+ d -= ml;
+ ++m;
+ bdate.setDayOfMonth((int)d);
+ if (m > DECEMBER) {
+ bdate.setNormalizedYear(y + 1);
+ m = JANUARY;
+ }
+ bdate.setMonth(m);
+ } else {
+ long fixedDate = d + getFixedDate(y, m, 1, bdate) - 1L;
+ getCalendarDateFromFixedDate(bdate, fixedDate);
+ }
+ } else {
+ bdate.setDayOfWeek(getDayOfWeek(bdate));
+ }
+ date.setLeapYear(isLeapYear(bdate.getNormalizedYear()));
+ date.setZoneOffset(0);
+ date.setDaylightSaving(0);
+ bdate.setNormalized(true);
+ return true;
+ }
+
+ void normalizeMonth(CalendarDate date) {
+ Date bdate = (Date) date;
+ int year = bdate.getNormalizedYear();
+ long month = bdate.getMonth();
+ if (month <= 0) {
+ long xm = 1L - month;
+ year -= (int)((xm / 12) + 1);
+ month = 13 - (xm % 12);
+ bdate.setNormalizedYear(year);
+ bdate.setMonth((int) month);
+ } else if (month > DECEMBER) {
+ year += (int)((month - 1) / 12);
+ month = ((month - 1)) % 12 + 1;
+ bdate.setNormalizedYear(year);
+ bdate.setMonth((int) month);
+ }
+ }
+
+ /**
+ * Returns 366 if the specified date is in a leap year, or 365
+ * otherwise This method does not perform the normalization with
+ * the specified <code>CalendarDate</code>. The
+ * <code>CalendarDate</code> must be normalized to get a correct
+ * value.
+ *
+ * @param a <code>CalendarDate</code>
+ * @return a year length in days
+ * @throws ClassCastException if the specified date is not a
+ * {@link BaseCalendar.Date}
+ */
+ public int getYearLength(CalendarDate date) {
+ return isLeapYear(((Date)date).getNormalizedYear()) ? 366 : 365;
+ }
+
+ public int getYearLengthInMonths(CalendarDate date) {
+ return 12;
+ }
+
+ static final int[] DAYS_IN_MONTH
+ // 12 1 2 3 4 5 6 7 8 9 10 11 12
+ = { 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
+ static final int[] ACCUMULATED_DAYS_IN_MONTH
+ // 12/1 1/1 2/1 3/1 4/1 5/1 6/1 7/1 8/1 9/1 10/1 11/1 12/1
+ = { -30, 0, 31, 59, 90,120,151,181,212,243, 273, 304, 334};
+
+ static final int[] ACCUMULATED_DAYS_IN_MONTH_LEAP
+ // 12/1 1/1 2/1 3/1 4/1 5/1 6/1 7/1 8/1 9/1 10/1 11/1 12/1
+ = { -30, 0, 31, 59+1, 90+1,120+1,151+1,181+1,212+1,243+1, 273+1, 304+1, 334+1};
+
+ public int getMonthLength(CalendarDate date) {
+ Date gdate = (Date) date;
+ int month = gdate.getMonth();
+ if (month < JANUARY || month > DECEMBER) {
+ throw new IllegalArgumentException("Illegal month value: " + month);
+ }
+ return getMonthLength(gdate.getNormalizedYear(), month);
+ }
+
+ // accepts 0 (December in the previous year) to 12.
+ private final int getMonthLength(int year, int month) {
+ int days = DAYS_IN_MONTH[month];
+ if (month == FEBRUARY && isLeapYear(year)) {
+ days++;
+ }
+ return days;
+ }
+
+ public long getDayOfYear(CalendarDate date) {
+ return getDayOfYear(((Date)date).getNormalizedYear(),
+ date.getMonth(),
+ date.getDayOfMonth());
+ }
+
+ final long getDayOfYear(int year, int month, int dayOfMonth) {
+ return (long) dayOfMonth
+ + (isLeapYear(year) ?
+ ACCUMULATED_DAYS_IN_MONTH_LEAP[month] : ACCUMULATED_DAYS_IN_MONTH[month]);
+ }
+
+ // protected
+ public long getFixedDate(CalendarDate date) {
+ if (!date.isNormalized()) {
+ normalizeMonth(date);
+ }
+ return getFixedDate(((Date)date).getNormalizedYear(),
+ date.getMonth(),
+ date.getDayOfMonth(),
+ (BaseCalendar.Date) date);
+ }
+
+ // public for java.util.GregorianCalendar
+ public long getFixedDate(int year, int month, int dayOfMonth, BaseCalendar.Date cache) {
+ boolean isJan1 = month == JANUARY && dayOfMonth == 1;
+
+ // Look up the one year cache
+ if (cache != null && cache.hit(year)) {
+ if (isJan1) {
+ return cache.getCachedJan1();
+ }
+ return cache.getCachedJan1() + getDayOfYear(year, month, dayOfMonth) - 1;
+ }
+
+ // Look up the pre-calculated fixed date table
+ int n = year - BASE_YEAR;
+ if (n >= 0 && n < FIXED_DATES.length) {
+ long jan1 = FIXED_DATES[n];
+ if (cache != null) {
+ cache.setCache(year, jan1, isLeapYear(year) ? 366 : 365);
+ }
+ return isJan1 ? jan1 : jan1 + getDayOfYear(year, month, dayOfMonth) - 1;
+ }
+
+ long prevyear = (long)year - 1;
+ long days = dayOfMonth;
+
+ if (prevyear >= 0) {
+ days += (365 * prevyear)
+ + (prevyear / 4)
+ - (prevyear / 100)
+ + (prevyear / 400)
+ + ((367 * month - 362) / 12);
+ } else {
+ days += (365 * prevyear)
+ + CalendarUtils.floorDivide(prevyear, 4)
+ - CalendarUtils.floorDivide(prevyear, 100)
+ + CalendarUtils.floorDivide(prevyear, 400)
+ + CalendarUtils.floorDivide((367 * month - 362), 12);
+ }
+
+ if (month > FEBRUARY) {
+ days -= isLeapYear(year) ? 1 : 2;
+ }
+
+ // If it's January 1, update the cache.
+ if (cache != null && isJan1) {
+ cache.setCache(year, days, isLeapYear(year) ? 366 : 365);
+ }
+
+ return days;
+ }
+
+ /**
+ * Calculates calendar fields and store them in the specified
+ * <code>CalendarDate</code>.
+ */
+ // should be 'protected'
+ public void getCalendarDateFromFixedDate(CalendarDate date,
+ long fixedDate) {
+ Date gdate = (Date) date;
+ int year;
+ long jan1;
+ boolean isLeap;
+ if (gdate.hit(fixedDate)) {
+ year = gdate.getCachedYear();
+ jan1 = gdate.getCachedJan1();
+ isLeap = isLeapYear(year);
+ } else {
+ // Looking up FIXED_DATES[] here didn't improve performance
+ // much. So we calculate year and jan1. getFixedDate()
+ // will look up FIXED_DATES[] actually.
+ year = getGregorianYearFromFixedDate(fixedDate);
+ jan1 = getFixedDate(year, JANUARY, 1, null);
+ isLeap = isLeapYear(year);
+ // Update the cache data
+ gdate.setCache (year, jan1, isLeap ? 366 : 365);
+ }
+
+ int priorDays = (int)(fixedDate - jan1);
+ long mar1 = jan1 + 31 + 28;
+ if (isLeap) {
+ ++mar1;
+ }
+ if (fixedDate >= mar1) {
+ priorDays += isLeap ? 1 : 2;
+ }
+ int month = 12 * priorDays + 373;
+ if (month > 0) {
+ month /= 367;
+ } else {
+ month = CalendarUtils.floorDivide(month, 367);
+ }
+ long month1 = jan1 + ACCUMULATED_DAYS_IN_MONTH[month];
+ if (isLeap && month >= MARCH) {
+ ++month1;
+ }
+ int dayOfMonth = (int)(fixedDate - month1) + 1;
+ int dayOfWeek = getDayOfWeekFromFixedDate(fixedDate);
+ assert dayOfWeek > 0 : "negative day of week " + dayOfWeek;
+ gdate.setNormalizedYear(year);
+ gdate.setMonth(month);
+ gdate.setDayOfMonth(dayOfMonth);
+ gdate.setDayOfWeek(dayOfWeek);
+ gdate.setLeapYear(isLeap);
+ gdate.setNormalized(true);
+ }
+
+ /**
+ * Returns the day of week of the given Gregorian date.
+ */
+ public int getDayOfWeek(CalendarDate date) {
+ long fixedDate = getFixedDate(date);
+ return getDayOfWeekFromFixedDate(fixedDate);
+ }
+
+ public static final int getDayOfWeekFromFixedDate(long fixedDate) {
+ // The fixed day 1 (January 1, 1 Gregorian) is Monday.
+ if (fixedDate >= 0) {
+ return (int)(fixedDate % 7) + SUNDAY;
+ }
+ return (int)CalendarUtils.mod(fixedDate, 7) + SUNDAY;
+ }
+
+ public int getYearFromFixedDate(long fixedDate) {
+ return getGregorianYearFromFixedDate(fixedDate);
+ }
+
+ /**
+ * Returns the Gregorian year number of the given fixed date.
+ */
+ final int getGregorianYearFromFixedDate(long fixedDate) {
+ long d0;
+ int d1, d2, d3, d4;
+ int n400, n100, n4, n1;
+ int year;
+
+ if (fixedDate > 0) {
+ d0 = fixedDate - 1;
+ n400 = (int)(d0 / 146097);
+ d1 = (int)(d0 % 146097);
+ n100 = d1 / 36524;
+ d2 = d1 % 36524;
+ n4 = d2 / 1461;
+ d3 = d2 % 1461;
+ n1 = d3 / 365;
+ d4 = (d3 % 365) + 1;
+ } else {
+ d0 = fixedDate - 1;
+ n400 = (int)CalendarUtils.floorDivide(d0, 146097L);
+ d1 = (int)CalendarUtils.mod(d0, 146097L);
+ n100 = CalendarUtils.floorDivide(d1, 36524);
+ d2 = CalendarUtils.mod(d1, 36524);
+ n4 = CalendarUtils.floorDivide(d2, 1461);
+ d3 = CalendarUtils.mod(d2, 1461);
+ n1 = CalendarUtils.floorDivide(d3, 365);
+ d4 = CalendarUtils.mod(d3, 365) + 1;
+ }
+ year = 400 * n400 + 100 * n100 + 4 * n4 + n1;
+ if (!(n100 == 4 || n1 == 4)) {
+ ++year;
+ }
+ return year;
+ }
+
+ /**
+ * @return true if the specified year is a Gregorian leap year, or
+ * false otherwise.
+ * @see BaseCalendar#isGregorianLeapYear
+ */
+ protected boolean isLeapYear(CalendarDate date) {
+ return isLeapYear(((Date)date).getNormalizedYear());
+ }
+
+ boolean isLeapYear(int normalizedYear) {
+ return CalendarUtils.isGregorianLeapYear(normalizedYear);
+ }
+}
Added: trunk/core/src/openjdk/sun/sun/util/calendar/CalendarDate.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/util/calendar/CalendarDate.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/util/calendar/CalendarDate.java 2007-06-23 05:02:03 UTC (rev 3292)
@@ -0,0 +1,505 @@
+/*
+ * Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.util.calendar;
+
+import java.lang.Cloneable;
+import java.util.Locale;
+import java.util.TimeZone;
+
+/**
+ * The <code>CalendarDate</code> class represents a specific instant
+ * in time by calendar date and time fields that are multiple cycles
+ * in different time unites. The semantics of each calendar field is
+ * given by a concrete calendar system rather than this
+ * <code>CalendarDate</code> class that holds calendar field values
+ * without interpreting them. Therefore, this class can be used to
+ * represent an amount of time, such as 2 years and 3 months.
+ *
+ * <p>A <code>CalendarDate</code> instance can be created by calling
+ * the <code>newCalendarDate</code> or <code>getCalendarDate</code>
+ * methods in <code>CalendarSystem</code>. A
+ * <code>CalendarSystem</code> instance is obtained by calling one of
+ * the factory methods in <code>CalendarSystem</code>. Manipulations
+ * of calendar dates must be handled by the calendar system by which
+ * <code>CalendarDate</code> instances have been created.
+ *
+ * <p>Some calendar fields can be modified through method calls. Any
+ * modification of a calendar field brings the state of a
+ * <code>CalendarDate</code> to <I>not normalized</I>. The
+ * normalization must be performed to make all the calendar fields
+ * consistent with a calendar system.
+ *
+ * <p>The <code>protected</code> methods are intended to be used for
+ * implementing a concrete calendar system, not for general use as an
+ * API.
+ *
+ * @see CalendarSystem
+ * @author Masayoshi Okutsu
+ * @since 1.5
+ */
+public abstract class CalendarDate implements Cloneable {
+ public static final int FIELD_UNDEFINED = Integer.MIN_VALUE;
+ public static final long TIME_UNDEFINED = Long.MIN_VALUE;
+
+ private Era era;
+ private int year;
+ private int month;
+ private int dayOfMonth;
+ private int dayOfWeek = FIELD_UNDEFINED;
+ private boolean leapYear;
+
+ private int hours;
+ private int minutes;
+ private int seconds;
+ private int millis; // fractional part of the second
+ private long fraction; // time of day value in millisecond
+
+ private boolean normalized;
+
+ private TimeZone zoneinfo;
+ private int zoneOffset;
+ private int daylightSaving;
+ private boolean forceStandardTime;
+
+ private Locale locale;
+
+ protected CalendarDate() {
+ this(TimeZone.getDefault());
+ }
+
+ protected CalendarDate(TimeZone zone) {
+ zoneinfo = zone;
+ }
+
+ public Era getEra() {
+ return era;
+ }
+
+ /**
+ * Sets the era of the date to the specified era. The default
+ * implementation of this method accepts any Era value, including
+ * <code>null</code>.
+ *
+ * @exception NullPointerException if the calendar system for this
+ * <code>CalendarDate</code> requires eras and the specified era
+ * is null.
+ * @exception IllegalArgumentException if the specified
+ * <code>era</code> is unknown to the calendar
+ * system for this <code>CalendarDate</code>.
+ */
+ public CalendarDate setEra(Era era) {
+ if (this.era == era) {
+ return this;
+ }
+ this.era = era;
+ normalized = false;
+ return this;
+ }
+
+ public int getYear() {
+ return year;
+ }
+
+ public CalendarDate setYear(int year) {
+ if (this.year != year) {
+ this.year = year;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public CalendarDate addYear(int n) {
+ if (n != 0) {
+ year += n;
+ normalized = false;
+ }
+ return this;
+ }
+
+ /**
+ * Returns whether the year represented by this
+ * <code>CalendarDate</code> is a leap year. If leap years are
+ * not applicable to the calendar system, this method always
+ * returns <code>false</code>.
+ *
+ * <p>If this <code>CalendarDate</code> hasn't been normalized,
+ * <code>false</code> is returned. The normalization must be
+ * performed to retrieve the correct leap year information.
+ *
+ * @return <code>true</code> if this <code>CalendarDate</code> is
+ * normalized and the year of this <code>CalendarDate</code> is a
+ * leap year, or <code>false</code> otherwise.
+ * @see BaseCalendar#isGregorianLeapYear
+ */
+ public boolean isLeapYear() {
+ return leapYear;
+ }
+
+ void setLeapYear(boolean leapYear) {
+ this.leapYear = leapYear;
+ }
+
+ public int getMonth() {
+ return month;
+ }
+
+ public CalendarDate setMonth(int month) {
+ if (this.month != month) {
+ this.month = month;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public CalendarDate addMonth(int n) {
+ if (n != 0) {
+ month += n;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public int getDayOfMonth() {
+ return dayOfMonth;
+ }
+
+ public CalendarDate setDayOfMonth(int date) {
+ if (dayOfMonth != date) {
+ dayOfMonth = date;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public CalendarDate addDayOfMonth(int n) {
+ if (n != 0) {
+ dayOfMonth += n;
+ normalized = false;
+ }
+ return this;
+ }
+
+ /**
+ * Returns the day of week value. If this CalendarDate is not
+ * normalized, {@link #FIELD_UNDEFINED} is returned.
+ *
+ * @return day of week or {@link #FIELD_UNDEFINED}
+ */
+ public int getDayOfWeek() {
+ if (!isNormalized()) {
+ dayOfWeek = FIELD_UNDEFINED;
+ }
+ return dayOfWeek;
+ }
+
+ public int getHours() {
+ return hours;
+ }
+
+ public CalendarDate setHours(int hours) {
+ if (this.hours != hours) {
+ this.hours = hours;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public CalendarDate addHours(int n) {
+ if (n != 0) {
+ hours += n;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public int getMinutes() {
+ return minutes;
+ }
+
+ public CalendarDate setMinutes(int minutes) {
+ if (this.minutes != minutes) {
+ this.minutes = minutes;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public CalendarDate addMinutes(int n) {
+ if (n != 0) {
+ minutes += n;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public int getSeconds() {
+ return seconds;
+ }
+
+ public CalendarDate setSeconds(int seconds) {
+ if (this.seconds != seconds) {
+ this.seconds = seconds;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public CalendarDate addSeconds(int n) {
+ if (n != 0) {
+ seconds += n;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public int getMillis() {
+ return millis;
+ }
+
+ public CalendarDate setMillis(int millis) {
+ if (this.millis != millis) {
+ this.millis = millis;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public CalendarDate addMillis(int n) {
+ if (n != 0) {
+ millis += n;
+ normalized = false;
+ }
+ return this;
+ }
+
+ public long getTimeOfDay() {
+ if (!isNormalized()) {
+ return fraction = TIME_UNDEFINED;
+ }
+ return fraction;
+ }
+
+ public CalendarDate setDate(int year, int month, int dayOfMonth) {
+ setYear(year);
+ setMonth(month);
+ setDayOfMonth(dayOfMonth);
+ return this;
+ }
+
+ public CalendarDate addDate(int year, int month, int dayOfMonth) {
+ addYear(year);
+ addMonth(month);
+ addDayOfMonth(dayOfMonth);
+ return this;
+ }
+
+ public CalendarDate setTimeOfDay(int hours, int minutes, int seconds, int millis) {
+ setHours(hours);
+ setMinutes(minutes);
+ setSeconds(seconds);
+ setMillis(millis);
+ return this;
+ }
+
+ public CalendarDate addTimeOfDay(int hours, int minutes, int seconds, int millis) {
+ addHours(hours);
+ addMinutes(minutes);
+ addSeconds(seconds);
+ addMillis(millis);
+ return this;
+ }
+
+ protected void setTimeOfDay(long fraction) {
+ this.fraction = fraction;
+ }
+
+ public boolean isNormalized() {
+ return normalized;
+ }
+
+
+ public boolean isStandardTime() {
+ return forceStandardTime;
+ }
+
+ public void setStandardTime(boolean standardTime) {
+ forceStandardTime = standardTime;
+ }
+
+ public boolean isDaylightTime() {
+ if (isStandardTime()) {
+ return false;
+ }
+ return daylightSaving != 0;
+ }
+
+ protected void setLocale(Locale loc) {
+ locale = loc;
+ }
+
+ public TimeZone getZone() {
+ return zoneinfo;
+ }
+
+ public CalendarDate setZone(TimeZone zoneinfo) {
+ this.zoneinfo = zoneinfo;
+ return this;
+ }
+
+ /**
+ * Returns whether the specified date is the same date of this
+ * <code>CalendarDate</code>. The time of the day fields are
+ * ignored for the comparison.
+ */
+ public boolean isSameDate(CalendarDate date) {
+ return getDayOfWeek() == date.getDayOfWeek()
+ && getMonth() == date.getMonth()
+ && getYear() == date.getYear()
+ && getEra() == date.getEra();
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof CalendarDate)) {
+ return false;
+ }
+ CalendarDate that = (CalendarDate) obj;
+ if (isNormalized() != that.isNormalized()) {
+ return false;
+ }
+ boolean hasZone = zoneinfo != null;
+ boolean thatHasZone = that.zoneinfo != null;
+ if (hasZone != thatHasZone) {
+ return false;
+ }
+ if (hasZone && !zoneinfo.equals(that.zoneinfo)) {
+ return false;
+ }
+ return (getEra() == that.getEra()
+ && year == that.year
+ && month == that.month
+ && dayOfMonth == that.dayOfMonth
+ && hours == that.hours
+ && minutes == that.minutes
+ && seconds == that.seconds
+ && millis == that.millis
+ && zoneOffset == that.zoneOffset);
+ }
+
+ public int hashCode() {
+ // a pseudo (local standard) time stamp value in milliseconds
+ // from the Epoch, assuming Gregorian calendar fields.
+ long hash = ((((((long)year - 1970) * 12) + (month - 1)) * 30) + dayOfMonth) * 24;
+ hash = ((((((hash + hours) * 60) + minutes) * 60) + seconds) * 1000) + millis;
+ hash -= zoneOffset;
+ int normalized = isNormalized() ? 1 : 0;
+ int era = 0;
+ Era e = getEra();
+ if (e != null) {
+ era = e.hashCode();
+ }
+ int zone = zoneinfo != null ? zoneinfo.hashCode() : 0;
+ return (int) hash * (int)(hash >> 32) ^ era ^ normalized ^ zone;
+ }
+
+ /**
+ * Returns a copy of this <code>CalendarDate</code>. The
+ * <code>TimeZone</code> object, if any, is not cloned.
+ *
+ * @return a copy of this <code>CalendarDate</code>
+ */
+ public Object clone() {
+ try {
+ return super.clone();
+ } catch (CloneNotSupportedException e) {
+ // this shouldn't happen
+ throw new InternalError();
+ }
+ }
+
+ /**
+ * Converts calendar date values to a <code>String</code> in the
+ * following format.
+ * <pre>
+ * yyyy-MM-dd'T'HH:mm:ss.SSSz
+ * </pre>
+ *
+ * @see java.text.SimpleDateFormat
+ */
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ CalendarUtils.sprintf0d(sb, year, 4).append('-');
+ CalendarUtils.sprintf0d(sb, month, 2).append('-');
+ CalendarUtils.sprintf0d(sb, dayOfMonth, 2).append('T');
+ CalendarUtils.sprintf0d(sb, hours, 2).append(':');
+ CalendarUtils.sprintf0d(sb, minutes, 2).append(':');
+ CalendarUtils.sprintf0d(sb, seconds, 2).append('.');
+ CalendarUtils.sprintf0d(sb, millis, 3);
+ if (zoneOffset == 0) {
+ sb.append('Z');
+ } else if (zoneOffset != FIELD_UNDEFINED) {
+ int offset;
+ char sign;
+ if (zoneOffset > 0) {
+ offset = zoneOffset;
+ sign = '+';
+ } else {
+ offset = -zoneOffset;
+ sign = '-';
+ }
+ offset /= 60000;
+ sb.append(sign);
+ CalendarUtils.sprintf0d(sb, offset / 60, 2);
+ CalendarUtils.sprintf0d(sb, offset % 60, 2);
+ } else {
+ sb.append(" local time");
+ }
+ return sb.toString();
+ }
+
+ protected void setDayOfWeek(int dayOfWeek) {
+ this.dayOfWeek = dayOfWeek;
+ }
+
+ protected void setNormalized(boolean normalized) {
+ this.normalized = normalized;
+ }
+
+ public int getZoneOffset() {
+ return zoneOffset;
+ }
+
+ protected void setZoneOffset(int offset) {
+ zoneOffset = offset;
+ }
+
+ public int getDaylightSaving() {
+ return daylightSaving;
+ }
+
+ protected void setDaylightSaving(int daylightSaving) {
+ this.daylightSaving = daylightSaving;
+ }
+}
Added: trunk/core/src/openjdk/sun/sun/util/calendar/CalendarSystem.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/util/calendar/CalendarSystem.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/util/calendar/CalendarSystem.java 2007-06-23 05:02:03 UTC (rev 3292)
@@ -0,0 +1,357 @@
+/*
+ * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.util.calendar;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.Set;
+import java.util.TimeZone;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * <code>CalendarSystem</code> is an abstract class that defines the
+ * programming interface to deal with calendar date and time.
+ *
+ * <p><code>CalendarSystem</code> instances are singletons. For
+ * example, there exists only one Gregorian calendar instance in the
+ * Java runtime environment. A singleton instance can be obtained
+ * calling one of the static factory methods.
+ *
+ * <h4>CalendarDate</h4>
+ *
+ * <p>For the methods in a <code>CalendarSystem</code> that manipulate
+ * a <code>CalendarDate</code>, <code>CalendarDate</code>s that have
+ * been created by the <code>CalendarSystem</code> must be
+ * specified. Otherwise, the methods throw an exception. This is
+ * because, for example, a Chinese calendar date can't be understood
+ * by the Hebrew calendar system.
+ *
+ * <h4>Calendar names</h4>
+ *
+ * Each calendar system has a unique name to be identified. The Java
+ * runtime in this release supports the following calendar systems.
+ *
+ * <pre>
+ * Name Calendar System
+ * ---------------------------------------
+ * gregorian Gregorian Calendar
+ * julian Julian Calendar
+ * japanese Japanese Imperial Calendar
+ * </pre>
+ *
+ * @see CalendarDate
+ * @author Masayoshi Okutsu
+ * @since 1.5
+ */
+
+public abstract class CalendarSystem {
+
+ /////////////////////// Calendar Factory Methods /////////////////////////
+
+ private volatile static boolean initialized = false;
+
+ // Map of calendar names and calendar class names
+ private static ConcurrentMap<String, String> names;
+
+ // Map of calendar names and CalendarSystem instances
+ private static ConcurrentMap<String,CalendarSystem> calendars;
+
+ private static final String PACKAGE_NAME = "sun.util.calendar.";
+
+ private static final String[] namePairs = {
+ "gregorian", "Gregorian",
+ "japanese", "LocalGregorianCalendar",
+ "julian", "JulianCalendar",
+ /*
+ "hebrew", "HebrewCalendar",
+ "iso8601", "ISOCalendar",
+ "taiwanese", "LocalGregorianCalendar",
+ "thaibuddhist", "LocalGregorianCalendar",
+ */
+ };
+
+ private static void initNames() {
+ ConcurrentMap<String,String> nameMap = new ConcurrentHashMap<String,String>();
+
+ // Associate a calendar name with its class name and the
+ // calendar class name with its date class name.
+ StringBuilder clName = new StringBuilder();
+ for (int i = 0; i < namePairs.length; i += 2) {
+ clName.setLength(0);
+ String cl = clName.append(PACKAGE_NAME).append(namePairs[i+1]).toString();
+ nameMap.put(namePairs[i], cl);
+ }
+ synchronized (CalendarSystem.class) {
+ if (!initialized) {
+ names = nameMap;
+ calendars = new ConcurrentHashMap<String,CalendarSystem>();
+ initialized = true;
+ }
+ }
+ }
+
+ private final static Gregorian GREGORIAN_INSTANCE = new Gregorian();
+
+ /**
+ * Returns the singleton instance of the <code>Gregorian</code>
+ * calendar system.
+ *
+ * @return the <code>Gregorian</code> instance
+ */
+ public static Gregorian getGregorianCalendar() {
+ return GREGORIAN_INSTANCE;
+ }
+
+ /**
+ * Returns a <code>CalendarSystem</code> specified by the calendar
+ * name. The calendar name has to be one of the supported calendar
+ * names.
+ *
+ * @param calendarName the calendar name
+ * @return the <code>CalendarSystem</code> specified by
+ * <code>calendarName</code>, or null if there is no
+ * <code>CalendarSystem</code> associated with the given calendar name.
+ */
+ public static CalendarSystem forName(String calendarName) {
+ if ("gregorian".equals(calendarName)) {
+ return GREGORIAN_INSTANCE;
+ }
+
+ if (!initialized) {
+ initNames();
+ }
+
+ CalendarSystem cal = calendars.get(calendarName);
+ if (cal != null) {
+ return cal;
+ }
+
+ String className = names.get(calendarName);
+ if (className == null) {
+ return null; // Unknown calendar name
+ }
+
+ if (className.endsWith("LocalGregorianCalendar")) {
+ // Create the specific kind of local Gregorian calendar system
+ cal = LocalGregorianCalendar.getLocalGregorianCalendar(calendarName);
+ } else {
+ try {
+ Class cl = Class.forName(className);
+ cal = (CalendarSystem) cl.newInstance();
+ } catch (Exception e) {
+ throw new RuntimeException("internal error", e);
+ }
+ }
+ if (cal == null) {
+ return null;
+ }
+ CalendarSystem cs = calendars.putIfAbsent(calendarName, cal);
+ return (cs == null) ? cal : cs;
+ }
+
+ //////////////////////////////// Calendar API //////////////////////////////////
+
+ /**
+ * Returns the name of this calendar system.
+ */
+ public abstract String getName();
+
+ public abstract CalendarDate getCalendarDate();
+
+ /**
+ * Calculates calendar fields from the specified number of
+ * milliseconds since the Epoch, January 1, 1970 00:00:00 UTC
+ * (Gregorian). This method doesn't check overflow or underflow
+ * when adjusting the millisecond value (representing UTC) with
+ * the time zone offsets (i.e., the GMT offset and amount of
+ * daylight saving).
+ *
+ * @param millis the offset value in milliseconds from January 1,
+ * 1970 00:00:00 UTC (Gregorian).
+ * @return a <code>CalendarDate</code> instance that contains the
+ * calculated calendar field values.
+ */
+ public abstract CalendarDate getCalendarDate(long millis);
+
+ public abstract CalendarDate getCalendarDate(long millis, CalendarDate date);
+
+ public abstract CalendarDate getCalendarDate(long millis, TimeZone zone);
+
+ /**
+ * Constructs a <code>CalendarDate</code> that is specific to this
+ * calendar system. All calendar fields have their initial
+ * values. The {@link TimeZone#getDefault() default time zone} is
+ * set to the instance.
+ *
+ * @return a <code>CalendarDate</code> instance that contains the initial
+ * calendar field values.
+ */
+ public abstract CalendarDate newCalendarDate();
+
+ public abstract CalendarDate newCalendarDate(TimeZone zone);
+
+ /**
+ * Returns the number of milliseconds since the Epoch, January 1,
+ * 1970 00:00:00 UTC (Gregorian), represented by the specified
+ * <code>CalendarDate</code>.
+ *
+ * @param date the <code>CalendarDate</code> from which the time
+ * value is calculated
+ * @return the number of milliseconds since the Epoch.
+ */
+ public abstract long getTime(CalendarDate date);
+
+ /**
+ * Returns the length in days of the specified year by
+ * <code>date</code>. This method does not perform the
+ * normalization with the specified <code>CalendarDate</code>. The
+ * <code>CalendarDate</code> must be normalized to get a correct
+ * value.
+ */
+ public abstract int getYearLength(CalendarDate date);
+
+ /**
+ * Returns the number of months of the specified year. This method
+ * does not perform the normalization with the specified
+ * <code>CalendarDate</code>. The <code>CalendarDate</code> must
+ * be normalized to get a correct value.
+ */
+ public abstract int getYearLengthInMonths(CalendarDate date);
+
+ /**
+ * Returns the length in days of the month specified by the calendar
+ * date. This method does not perform the normalization with the
+ * specified calendar date. The <code>CalendarDate</code> must
+ * be normalized to get a correct value.
+ *
+ * @param date the date from which the month value is obtained
+ * @return the number of days in the month
+ * @exception IllegalArgumentException if the specified calendar date
+ * doesn't have a valid month value in this calendar system.
+ */
+ public abstract int getMonthLength(CalendarDate date); // no setter
+
+ /**
+ * Returns the length in days of a week in this calendar
+ * system. If this calendar system has multiple radix weeks, this
+ * method returns only one of them.
+ */
+ public abstract int getWeekLength();
+
+ /**
+ * Returns the <code>Era</code> designated by the era name that
+ * has to be known to this calendar system. If no Era is
+ * applicable to this calendar system, null is returned.
+ *
+ * @param eraName the name of the era
+ * @return the <code>Era</code> designated by
+ * <code>eraName</code>, or <code>null</code> if no Era is
+ * applicable to this calendar system or the specified era name is
+ * not known to this calendar system.
+ */
+ public abstract Era getEra(String eraName);
+
+ /**
+ * Returns valid <code>Era</code>s of this calendar system. The
+ * return value is sorted in the descendant order. (i.e., the first
+ * element of the returned array is the oldest era.) If no era is
+ * applicable to this calendar system, <code>null</code> is returned.
+ *
+ * @return an array of valid <code>Era</code>s, or
+ * <code>null</code> if no era is applicable to this calendar
+ * system.
+ */
+ public abstract Era[] getEras();
+
+ /**
+ * @throws IllegalArgumentException if the specified era name is
+ * unknown to this calendar system.
+ * @see Era
+ */
+ public abstract void setEra(CalendarDate date, String eraName);
+
+ /**
+ * Returns a <code>CalendarDate</code> of the n-th day of week
+ * which is on, after or before the specified date. For example, the
+ * first Sunday in April 2002 (Gregorian) can be obtained as
+ * below:
+ *
+ * <pre><code>
+ * Gregorian cal = CalendarSystem.getGregorianCalendar();
+ * CalendarDate date = cal.newCalendarDate();
+ * date.setDate(2004, cal.APRIL, 1);
+ * CalendarDate firstSun = cal.getNthDayOfWeek(1, cal.SUNDAY, date);
+ * // firstSun represents April 4, 2004.
+ * </code></pre>
+ *
+ * This method returns a new <code>CalendarDate</code> instance
+ * and doesn't modify the original date.
+ *
+ * @param nth specifies the n-th one. A positive number specifies
+ * <em>on or after</em> the <code>date</code>. A non-positive number
+ * specifies <em>on or before</em> the <code>date</code>.
+ * @param dayOfWeek the day of week
+ * @param date the date
+ * @return the date of the nth <code>dayOfWeek</code> after
+ * or before the specified <code>CalendarDate</code>
+ */
+ public abstract CalendarDate getNthDayOfWeek(int nth, int dayOfWeek,
+ CalendarDate date);
+
+ public abstract CalendarDate setTimeOfDay(CalendarDate date, int timeOfDay);
+
+ /**
+ * Checks whether the calendar fields specified by <code>date</code>
+ * represents a valid date and time in this calendar system. If the
+ * given date is valid, <code>date</code> is marked as <em>normalized</em>.
+ *
+ * @param date the <code>CalendarDate</code> to be validated
+ * @return <code>true</code> if all the calendar fields are consistent,
+ * otherwise, <code>false</code> is returned.
+ * @exception NullPointerException if the specified
+ * <code>date</code> is <code>null</code>
+ */
+ public abstract boolean validate(CalendarDate date);
+
+ /**
+ * Normalizes calendar fields in the specified
+ * <code>date</code>. Also all {@link CalendarDate#FIELD_UNDEFINED
+ * undefined} fields are set to correct values. The actual
+ * normalization process is calendar system dependent.
+ *
+ * @param date the calendar date to be validated
+ * @return <code>true</code> if all fields have been normalized;
+ * <code>false</code> otherwise.
+ * @exception NullPointerException if the specified
+ * <code>date</code> is <code>null</code>
+ */
+ public abstract boolean normalize(CalendarDate date);
+}
Added: trunk/core/src/openjdk/sun/sun/util/calendar/CalendarUtils.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/util/calendar/CalendarUtils.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/util/calendar/CalendarUtils.java 2007-06-23 05:02:03 UTC (rev 3292)
@@ -0,0 +1,193 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.util.calendar;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class CalendarUtils {
+
+ /**
+ * Returns whether the specified year is a leap year in the Gregorian
+ * calendar system.
+ *
+ * @param gregorianYear a Gregorian calendar year
+ * @return true if the given year is a leap year in the Gregorian
+ * calendar system.
+ * @see CalendarDate#isLeapYear
+ */
+ public static final boolean isGregorianLeapYear(int gregorianYear) {
+ return (((gregorianYear % 4) == 0)
+ && (((gregorianYear % 100) != 0) || ((gregorianYear % 400) == 0)));
+ }
+
+ /**
+ * Returns whether the specified year is a leap year in the Julian
+ * calendar system. The year number must be a normalized one
+ * (e.g., 45 B.C.E. is 1-45).
+ *
+ * @param normalizedJulianYear a normalized Julian calendar year
+ * @return true if the given year is a leap year in the Julian
+ * calendar system.
+ * @see CalendarDate#isLeapYear
+ */
+ public static final boolean isJulianLeapYear(int normalizedJulianYear) {
+ return (normalizedJulianYear % 4) == 0;
+ }
+
+ /**
+ * Divides two integers and returns the floor of the quotient.
+ * For example, <code>floorDivide(-1, 4)</code> returns -1 while
+ * -1/4 is 0.
+ *
+ * @param n the numerator
+ * @param d a divisor that must be greater than 0
+ * @return the floor of the quotient
+ */
+ public static final long floorDivide(long n, long d) {
+ return ((n >= 0) ?
+ (n / d) : (((n + 1L) / d) - 1L));
+ }
+
+ /**
+ * Divides two integers and returns the floor of the quotient.
+ * For example, <code>floorDivide(-1, 4)</code> returns -1 while
+ * -1/4 is 0.
+ *
+ * @param n the numerator
+ * @param d a divisor that must be greater than 0
+ * @return the floor of the quotient
+ */
+ public static final int floorDivide(int n, int d) {
+ return...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-23 05:00:56
|
Revision: 3291
http://jnode.svn.sourceforge.net/jnode/?rev=3291&view=rev
Author: lsantha
Date: 2007-06-22 22:00:54 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/sun/sun/net/dns/
trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfiguration.java
trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfigurationImpl.java
trunk/core/src/openjdk/sun/sun/net/util/
trunk/core/src/openjdk/sun/sun/net/util/IPAddressUtil.java
trunk/core/src/openjdk/sun/sun/security/ec/
trunk/core/src/openjdk/sun/sun/security/ec/ECKeyFactory.java
trunk/core/src/openjdk/sun/sun/security/ec/ECParameters.java
trunk/core/src/openjdk/sun/sun/security/ec/ECPrivateKeyImpl.java
trunk/core/src/openjdk/sun/sun/security/ec/ECPublicKeyImpl.java
trunk/core/src/openjdk/sun/sun/security/ec/NamedCurve.java
trunk/core/src/openjdk/sun/sun/security/jca/
trunk/core/src/openjdk/sun/sun/security/jca/GetInstance.java
trunk/core/src/openjdk/sun/sun/security/jca/JCAUtil.java
trunk/core/src/openjdk/sun/sun/security/jca/ProviderConfig.java
trunk/core/src/openjdk/sun/sun/security/jca/ProviderList.java
trunk/core/src/openjdk/sun/sun/security/jca/Providers.java
trunk/core/src/openjdk/sun/sun/security/jca/ServiceId.java
trunk/core/src/openjdk/sun/sun/security/krb5/
trunk/core/src/openjdk/sun/sun/security/krb5/Asn1Exception.java
trunk/core/src/openjdk/sun/sun/security/krb5/Checksum.java
trunk/core/src/openjdk/sun/sun/security/krb5/Config.java
trunk/core/src/openjdk/sun/sun/security/krb5/Confounder.java
trunk/core/src/openjdk/sun/sun/security/krb5/Credentials.java
trunk/core/src/openjdk/sun/sun/security/krb5/EncryptedData.java
trunk/core/src/openjdk/sun/sun/security/krb5/EncryptionKey.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbApRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbApReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbAppMessage.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbAsRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbAsReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbCred.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbCryptoException.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbException.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbKdcRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbKdcReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbPriv.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbSafe.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbServiceLocator.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbTgsRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/KrbTgsReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/PrincipalName.java
trunk/core/src/openjdk/sun/sun/security/krb5/Realm.java
trunk/core/src/openjdk/sun/sun/security/krb5/RealmException.java
trunk/core/src/openjdk/sun/sun/security/krb5/ServiceName.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/
trunk/core/src/openjdk/sun/sun/security/krb5/internal/APOptions.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/APRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/APReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ASRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ASReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/AuthContext.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/Authenticator.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/AuthorizationData.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/AuthorizationDataEntry.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/CredentialsUtil.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ETypeInfo.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ETypeInfo2.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/EncAPRepPart.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/EncASRepPart.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/EncKDCRepPart.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/EncKrbCredPart.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/EncKrbPrivPart.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/EncTGSRepPart.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/EncTicketPart.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/HostAddress.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/HostAddresses.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KDCOptions.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KDCRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KDCReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KDCReqBody.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KRBCred.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KRBError.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KRBPriv.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KRBSafe.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KRBSafeBody.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KdcErrException.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KerberosTime.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/Krb5.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KrbApErrException.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KrbCredInfo.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/KrbErrException.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/LastReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/LastReqEntry.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/LocalSeqNumber.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/LoginOptions.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/MethodData.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/PAData.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/PAEncTSEnc.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/SeqNumber.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/TCPClient.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/TGSRep.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/TGSReq.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/Ticket.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/TicketFlags.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/TransitedEncoding.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/UDPClient.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/CCacheInputStream.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/CCacheOutputStream.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/Credentials.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/CredentialsCache.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/FileCCacheConstants.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/FileCredentialsCache.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/MemoryCredentialsCache.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ccache/Tag.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Aes128.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Aes128CtsHmacSha1EType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Aes256.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Aes256CtsHmacSha1EType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/ArcFourHmac.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/ArcFourHmacEType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/CksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Crc32CksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Des.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Des3.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Des3CbcHmacSha1KdEType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/DesCbcCrcEType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/DesCbcEType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/DesCbcMd5EType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/DesMacCksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/DesMacKCksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/EType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/HmacMd5ArcFourCksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/HmacSha1Aes128CksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/HmacSha1Aes256CksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/HmacSha1Des3KdCksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/KeyUsage.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/Nonce.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/NullEType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/RsaMd5CksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/RsaMd5DesCksumType.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/crc32.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/dk/
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/dk/AesDkCrypto.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/dk/ArcFourCrypto.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/dk/Des3DkCrypto.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/crypto/dk/DkCrypto.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ktab/
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ktab/KeyTab.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ktab/KeyTabConstants.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ktab/KeyTabEntry.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ktab/KeyTabInputStream.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/ktab/KeyTabOutputStream.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/rcache/
trunk/core/src/openjdk/sun/sun/security/krb5/internal/rcache/AuthTime.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/rcache/CacheTable.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/rcache/ReplayCache.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/util/
trunk/core/src/openjdk/sun/sun/security/krb5/internal/util/KerberosFlags.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/util/KrbDataInputStream.java
trunk/core/src/openjdk/sun/sun/security/krb5/internal/util/KrbDataOutputStream.java
trunk/core/src/openjdk/sun/sun/security/pkcs/
trunk/core/src/openjdk/sun/sun/security/pkcs/ContentInfo.java
trunk/core/src/openjdk/sun/sun/security/pkcs/EncodingException.java
trunk/core/src/openjdk/sun/sun/security/pkcs/EncryptedPrivateKeyInfo.java
trunk/core/src/openjdk/sun/sun/security/pkcs/PKCS10.java
trunk/core/src/openjdk/sun/sun/security/pkcs/PKCS10Attribute.java
trunk/core/src/openjdk/sun/sun/security/pkcs/PKCS10Attributes.java
trunk/core/src/openjdk/sun/sun/security/pkcs/PKCS7.java
trunk/core/src/openjdk/sun/sun/security/pkcs/PKCS8Key.java
trunk/core/src/openjdk/sun/sun/security/pkcs/PKCS9Attribute.java
trunk/core/src/openjdk/sun/sun/security/pkcs/PKCS9Attributes.java
trunk/core/src/openjdk/sun/sun/security/pkcs/ParsingException.java
trunk/core/src/openjdk/sun/sun/security/pkcs/SignerInfo.java
trunk/core/src/openjdk/sun/sun/security/pkcs/SigningCertificateInfo.java
trunk/core/src/openjdk/sun/sun/security/provider/
trunk/core/src/openjdk/sun/sun/security/provider/ByteArrayAccess.java
trunk/core/src/openjdk/sun/sun/security/provider/DSA.java
trunk/core/src/openjdk/sun/sun/security/provider/DSAKeyFactory.java
trunk/core/src/openjdk/sun/sun/security/provider/DSAKeyPairGenerator.java
trunk/core/src/openjdk/sun/sun/security/provider/DSAParameterGenerator.java
trunk/core/src/openjdk/sun/sun/security/provider/DSAParameters.java
trunk/core/src/openjdk/sun/sun/security/provider/DSAPrivateKey.java
trunk/core/src/openjdk/sun/sun/security/provider/DSAPublicKey.java
trunk/core/src/openjdk/sun/sun/security/provider/DSAPublicKeyImpl.java
trunk/core/src/openjdk/sun/sun/security/provider/DigestBase.java
trunk/core/src/openjdk/sun/sun/security/provider/IdentityDatabase.java
trunk/core/src/openjdk/sun/sun/security/provider/JavaKeyStore.java
trunk/core/src/openjdk/sun/sun/security/provider/KeyProtector.java
trunk/core/src/openjdk/sun/sun/security/provider/MD2.java
trunk/core/src/openjdk/sun/sun/security/provider/MD4.java
trunk/core/src/openjdk/sun/sun/security/provider/MD5.java
trunk/core/src/openjdk/sun/sun/security/provider/ParameterCache.java
trunk/core/src/openjdk/sun/sun/security/provider/PolicyParser.java
trunk/core/src/openjdk/sun/sun/security/provider/SHA.java
trunk/core/src/openjdk/sun/sun/security/provider/SHA2.java
trunk/core/src/openjdk/sun/sun/security/provider/SHA5.java
trunk/core/src/openjdk/sun/sun/security/provider/SystemIdentity.java
trunk/core/src/openjdk/sun/sun/security/provider/SystemSigner.java
trunk/core/src/openjdk/sun/sun/security/provider/X509Factory.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/
trunk/core/src/openjdk/sun/sun/security/provider/certpath/AdjacencyList.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/BasicChecker.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/BuildStep.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/Builder.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/CertId.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/CertPathHelper.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/CollectionCertStore.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/ConstraintsChecker.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/CrlRevocationChecker.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/DistributionPointFetcher.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/ForwardBuilder.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/ForwardState.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/IndexedCollectionCertStore.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/KeyChecker.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/LDAPCertStore.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/OCSPChecker.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/OCSPRequest.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/OCSPResponse.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/PKIXCertPathValidator.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/PKIXMasterCertPathValidator.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/PolicyChecker.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/PolicyNodeImpl.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/ReverseBuilder.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/ReverseState.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/State.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/SunCertPathBuilder.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/SunCertPathBuilderException.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/SunCertPathBuilderParameters.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/SunCertPathBuilderResult.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/URICertStore.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/Vertex.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/X509CertPath.java
trunk/core/src/openjdk/sun/sun/security/provider/certpath/X509CertificatePair.java
trunk/core/src/openjdk/sun/sun/security/timestamp/
trunk/core/src/openjdk/sun/sun/security/timestamp/HttpTimestamper.java
trunk/core/src/openjdk/sun/sun/security/timestamp/TSRequest.java
trunk/core/src/openjdk/sun/sun/security/timestamp/TSResponse.java
trunk/core/src/openjdk/sun/sun/security/timestamp/TimestampToken.java
trunk/core/src/openjdk/sun/sun/security/timestamp/Timestamper.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_de.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_es.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_fr.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_it.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_ja.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_ko.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_sv.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_zh_CN.java
trunk/core/src/openjdk/sun/sun/security/util/AuthResources_zh_TW.java
trunk/core/src/openjdk/sun/sun/security/util/BigInt.java
trunk/core/src/openjdk/sun/sun/security/util/BitArray.java
trunk/core/src/openjdk/sun/sun/security/util/ByteArrayLexOrder.java
trunk/core/src/openjdk/sun/sun/security/util/ByteArrayTagOrder.java
trunk/core/src/openjdk/sun/sun/security/util/Cache.java
trunk/core/src/openjdk/sun/sun/security/util/DerEncoder.java
trunk/core/src/openjdk/sun/sun/security/util/DerIndefLenConverter.java
trunk/core/src/openjdk/sun/sun/security/util/DerInputBuffer.java
trunk/core/src/openjdk/sun/sun/security/util/DerInputStream.java
trunk/core/src/openjdk/sun/sun/security/util/DerOutputStream.java
trunk/core/src/openjdk/sun/sun/security/util/DerValue.java
trunk/core/src/openjdk/sun/sun/security/util/HostnameChecker.java
trunk/core/src/openjdk/sun/sun/security/util/ManifestDigester.java
trunk/core/src/openjdk/sun/sun/security/util/ObjectIdentifier.java
trunk/core/src/openjdk/sun/sun/security/util/Password.java
trunk/core/src/openjdk/sun/sun/security/util/PathList.java
trunk/core/src/openjdk/sun/sun/security/util/PendingException.java
trunk/core/src/openjdk/sun/sun/security/util/PolicyUtil.java
trunk/core/src/openjdk/sun/sun/security/util/Resources.java
trunk/core/src/openjdk/sun/sun/security/util/ResourcesMgr.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_de.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_es.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_fr.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_it.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_ja.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_ko.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_sv.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_zh_CN.java
trunk/core/src/openjdk/sun/sun/security/util/Resources_zh_TW.java
trunk/core/src/openjdk/sun/sun/security/x509/
trunk/core/src/openjdk/sun/sun/security/x509/AVA.java
trunk/core/src/openjdk/sun/sun/security/x509/AccessDescription.java
trunk/core/src/openjdk/sun/sun/security/x509/AlgIdDSA.java
trunk/core/src/openjdk/sun/sun/security/x509/AlgorithmId.java
trunk/core/src/openjdk/sun/sun/security/x509/AttributeNameEnumeration.java
trunk/core/src/openjdk/sun/sun/security/x509/AuthorityInfoAccessExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/AuthorityKeyIdentifierExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/BasicConstraintsExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/CRLDistributionPointsExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/CRLExtensions.java
trunk/core/src/openjdk/sun/sun/security/x509/CRLNumberExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/CRLReasonCodeExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/CertAndKeyGen.java
trunk/core/src/openjdk/sun/sun/security/x509/CertAttrSet.java
trunk/core/src/openjdk/sun/sun/security/x509/CertException.java
trunk/core/src/openjdk/sun/sun/security/x509/CertParseError.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateAlgorithmId.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateExtensions.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateIssuerExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateIssuerName.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateIssuerUniqueIdentity.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificatePoliciesExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificatePolicyId.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificatePolicyMap.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificatePolicySet.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateSerialNumber.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateSubjectName.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateSubjectUniqueIdentity.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateValidity.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateVersion.java
trunk/core/src/openjdk/sun/sun/security/x509/CertificateX509Key.java
trunk/core/src/openjdk/sun/sun/security/x509/DNSName.java
trunk/core/src/openjdk/sun/sun/security/x509/DeltaCRLIndicatorExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/DistributionPoint.java
trunk/core/src/openjdk/sun/sun/security/x509/DistributionPointName.java
trunk/core/src/openjdk/sun/sun/security/x509/EDIPartyName.java
trunk/core/src/openjdk/sun/sun/security/x509/ExtendedKeyUsageExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/Extension.java
trunk/core/src/openjdk/sun/sun/security/x509/FreshestCRLExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/GeneralName.java
trunk/core/src/openjdk/sun/sun/security/x509/GeneralNameInterface.java
trunk/core/src/openjdk/sun/sun/security/x509/GeneralNames.java
trunk/core/src/openjdk/sun/sun/security/x509/GeneralSubtree.java
trunk/core/src/openjdk/sun/sun/security/x509/GeneralSubtrees.java
trunk/core/src/openjdk/sun/sun/security/x509/IPAddressName.java
trunk/core/src/openjdk/sun/sun/security/x509/InhibitAnyPolicyExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/IssuerAlternativeNameExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/IssuingDistributionPointExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/KeyIdentifier.java
trunk/core/src/openjdk/sun/sun/security/x509/KeyUsageExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/NameConstraintsExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/NetscapeCertTypeExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/OIDMap.java
trunk/core/src/openjdk/sun/sun/security/x509/OIDName.java
trunk/core/src/openjdk/sun/sun/security/x509/OtherName.java
trunk/core/src/openjdk/sun/sun/security/x509/PKIXExtensions.java
trunk/core/src/openjdk/sun/sun/security/x509/PolicyConstraintsExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/PolicyInformation.java
trunk/core/src/openjdk/sun/sun/security/x509/PolicyMappingsExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/PrivateKeyUsageExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/RDN.java
trunk/core/src/openjdk/sun/sun/security/x509/README
trunk/core/src/openjdk/sun/sun/security/x509/RFC822Name.java
trunk/core/src/openjdk/sun/sun/security/x509/ReasonFlags.java
trunk/core/src/openjdk/sun/sun/security/x509/SerialNumber.java
trunk/core/src/openjdk/sun/sun/security/x509/SubjectAlternativeNameExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/SubjectKeyIdentifierExtension.java
trunk/core/src/openjdk/sun/sun/security/x509/URIName.java
trunk/core/src/openjdk/sun/sun/security/x509/UniqueIdentity.java
trunk/core/src/openjdk/sun/sun/security/x509/X400Address.java
trunk/core/src/openjdk/sun/sun/security/x509/X500Name.java
trunk/core/src/openjdk/sun/sun/security/x509/X500Signer.java
trunk/core/src/openjdk/sun/sun/security/x509/X509AttributeName.java
trunk/core/src/openjdk/sun/sun/security/x509/X509CRLEntryImpl.java
trunk/core/src/openjdk/sun/sun/security/x509/X509CRLImpl.java
trunk/core/src/openjdk/sun/sun/security/x509/X509Cert.java
trunk/core/src/openjdk/sun/sun/security/x509/X509CertImpl.java
trunk/core/src/openjdk/sun/sun/security/x509/X509CertInfo.java
trunk/core/src/openjdk/sun/sun/security/x509/X509Key.java
trunk/core/src/openjdk/sun/sun/security/x509/certAttributes.html
Added: trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfiguration.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfiguration.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfiguration.java 2007-06-23 05:00:54 UTC (rev 3291)
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.net.dns;
+
+import java.util.List;
+import java.io.IOException;
+
+/**
+ * The configuration of the client resolver.
+ *
+ * <p>A ResolverConfiguration is a singleton that represents the
+ * configuration of the client resolver. The ResolverConfiguration
+ * is opened by invoking the {@link #open() open} method.
+ *
+ * @since 1.4
+ */
+
+public abstract class ResolverConfiguration {
+
+ private static final Object lock = new Object();
+
+ private static ResolverConfiguration provider;
+
+ protected ResolverConfiguration() { }
+
+ /**
+ * Opens the resolver configuration.
+ *
+ * @return the resolver configuration
+ */
+ public static ResolverConfiguration open() {
+ synchronized (lock) {
+ if (provider == null) {
+ provider = new sun.net.dns.ResolverConfigurationImpl();
+ }
+ return provider;
+ }
+ }
+
+ /**
+ * Returns a list corresponding to the domain search path. The
+ * list is ordered by the search order used for host name lookup.
+ * Each element in the list returns a {@link java.lang.String}
+ * containing a domain name or suffix.
+ *
+ * @return list of domain names
+ */
+ public abstract List searchlist();
+
+ /**
+ * Returns a list of name servers used for host name lookup.
+ * Each element in the list returns a {@link java.lang.String}
+ * containing the textual representation of the IP address of
+ * the name server.
+ *
+ * @return list of the name servers
+ */
+ public abstract List nameservers();
+
+
+ /**
+ * Options representing certain resolver variables of
+ * a {@link ResolverConfiguration}.
+ */
+ public static abstract class Options {
+
+ /**
+ * Returns the maximum number of attempts the resolver
+ * will connect to each name server before giving up
+ * and returning an error.
+ *
+ * @return the resolver attempts value or -1 is unknown
+ */
+ public int attempts() {
+ return -1;
+ }
+
+ /**
+ * Returns the basic retransmit timeout, in milliseconds,
+ * used by the resolver. The resolver will typically use
+ * an exponential backoff algorithm where the timeout is
+ * doubled for every retransmit attempt. The basic
+ * retransmit timeout, returned here, is the initial
+ * timeout for the exponential backoff algorithm.
+ *
+ * @return the basic retransmit timeout value or -1
+ * if unknown
+ */
+ public int retrans() {
+ return -1;
+ }
+ }
+
+ /**
+ * Returns the {@link #Options} for the resolver.
+ *
+ * @return options for the resolver
+ */
+ public abstract Options options();
+}
+
+
Added: trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfigurationImpl.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfigurationImpl.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/net/dns/ResolverConfigurationImpl.java 2007-06-23 05:00:54 UTC (rev 3291)
@@ -0,0 +1,256 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.net.dns;
+
+import java.util.List;
+import java.util.LinkedList;
+import java.util.StringTokenizer;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+
+/*
+ * An implementation of ResolverConfiguration for Solaris
+ * and Linux.
+ */
+
+public class ResolverConfigurationImpl
+ extends ResolverConfiguration
+{
+ // Lock helds whilst loading configuration or checking
+ private static Object lock = new Object();
+
+ // Time of last refresh.
+ private static long lastRefresh = -1;
+
+ // Cache timeout (300 seconds) - should be converted into property
+ // or configured as preference in the future.
+ private static final int TIMEOUT = 300000;
+
+ // Resolver options
+ private final Options opts;
+
+ // Parse /etc/resolv.conf to get the values for a particular
+ // keyword.
+ //
+ private LinkedList resolvconf(String keyword, int maxperkeyword, int maxkeywords) {
+ LinkedList ll = new LinkedList();
+
+ try {
+ BufferedReader in =
+ new BufferedReader(new FileReader("/etc/resolv.conf"));
+ String line;
+ while ((line = in.readLine()) != null) {
+ int maxvalues = maxperkeyword;
+ if (line.length() == 0)
+ continue;
+ if (line.charAt(0) == '#' || line.charAt(0) == ';')
+ continue;
+ if (!line.startsWith(keyword))
+ continue;
+ String value = line.substring(keyword.length());
+ if (value.length() == 0)
+ continue;
+ if (value.charAt(0) != ' ' && value.charAt(0) != '\t')
+ continue;
+ StringTokenizer st = new StringTokenizer(value, " \t");
+ while (st.hasMoreTokens()) {
+ String val = st.nextToken();
+ if (val.charAt(0) == '#' || val.charAt(0) == ';') {
+ break;
+ }
+ ll.add(val);
+ if (--maxvalues == 0) {
+ break;
+ }
+ }
+ if (--maxkeywords == 0) {
+ break;
+ }
+ }
+ in.close();
+ } catch (IOException ioe) {
+ // problem reading value
+ }
+
+ return ll;
+ }
+
+ private LinkedList searchlist;
+ private LinkedList nameservers;
+
+
+ // Load DNS configuration from OS
+
+ private void loadConfig() {
+ assert Thread.holdsLock(lock);
+
+ // check if cached settings have expired.
+ if (lastRefresh >= 0) {
+ long currTime = System.currentTimeMillis();
+ if ((currTime - lastRefresh) < TIMEOUT) {
+ return;
+ }
+ }
+
+ // get the name servers from /etc/resolv.conf
+ nameservers =
+ (LinkedList)java.security.AccessController.doPrivileged(
+ new java.security.PrivilegedAction() {
+ public Object run() {
+ // typically MAXNS is 3 but we've picked 5 here
+ // to allow for additional servers if required.
+ return resolvconf("nameserver", 1, 5);
+ } /* run */
+ });
+
+ // get the search list (or domain)
+ searchlist = getSearchList();
+
+ // update the timestamp on the configuration
+ lastRefresh = System.currentTimeMillis();
+ }
+
+
+ // obtain search list or local domain
+
+ private LinkedList getSearchList() {
+
+ LinkedList sl;
+
+ // first try the search keyword in /etc/resolv.conf
+
+ sl = (LinkedList)java.security.AccessController.doPrivileged(
+ new java.security.PrivilegedAction() {
+ public Object run() {
+ LinkedList ll;
+
+ // first try search keyword (max 6 domains)
+ ll = resolvconf("search", 6, 1);
+ if (ll.size() > 0) {
+ return ll;
+ }
+
+ return null;
+
+ } /* run */
+
+ });
+ if (sl != null) {
+ return sl;
+ }
+
+ // No search keyword so use local domain
+
+
+ // LOCALDOMAIN has absolute priority on Solaris
+
+ String localDomain = localDomain0();
+ if (localDomain != null && localDomain.length() > 0) {
+ sl = new LinkedList();
+ sl.add(localDomain);
+ return sl;
+ }
+
+ // try domain keyword in /etc/resolv.conf
+
+ sl = (LinkedList)java.security.AccessController.doPrivileged(
+ new java.security.PrivilegedAction() {
+ public Object run() {
+ LinkedList ll;
+
+ ll = resolvconf("domain", 1, 1);
+ if (ll.size() > 0) {
+ return ll;
+ }
+ return null;
+
+ } /* run */
+ });
+ if (sl != null) {
+ return sl;
+ }
+
+ // no local domain so try fallback (RPC) domain or
+ // hostname
+
+ sl = new LinkedList();
+ String domain = fallbackDomain0();
+ if (domain != null && domain.length() > 0) {
+ sl.add(domain);
+ }
+
+ return sl;
+ }
+
+
+ // ----
+
+ ResolverConfigurationImpl() {
+ opts = new OptionsImpl();
+ }
+
+ public List searchlist() {
+ synchronized (lock) {
+ loadConfig();
+
+ // List is mutable so return a shallow copy
+ return (List)searchlist.clone();
+ }
+ }
+
+ public List nameservers() {
+ synchronized (lock) {
+ loadConfig();
+
+ // List is mutable so return a shallow copy
+ return (List)nameservers.clone();
+ }
+ }
+
+ public Options options() {
+ return opts;
+ }
+
+
+ // --- Native methods --
+
+ static native String localDomain0();
+
+ static native String fallbackDomain0();
+
+ static {
+ java.security.AccessController.doPrivileged(
+ new sun.security.action.LoadLibraryAction("net"));
+ }
+
+}
+
+/**
+ * Implementation of {@link ResolverConfiguration.Options}
+ */
+class OptionsImpl extends ResolverConfiguration.Options {
+}
Added: trunk/core/src/openjdk/sun/sun/net/util/IPAddressUtil.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/net/util/IPAddressUtil.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/net/util/IPAddressUtil.java 2007-06-23 05:00:54 UTC (rev 3291)
@@ -0,0 +1,304 @@
+/*
+ * Copyright 2004-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.net.util;
+
+public class IPAddressUtil {
+ private final static int INADDR4SZ = 4;
+ private final static int INADDR16SZ = 16;
+ private final static int INT16SZ = 2;
+
+ /*
+ * Converts IPv4 address in its textual presentation form
+ * into its numeric binary form.
+ *
+ * @param src a String representing an IPv4 address in standard format
+ * @return a byte array representing the IPv4 numeric address
+ */
+ public static byte[] textToNumericFormatV4(String src)
+ {
+ if (src.length() == 0) {
+ return null;
+ }
+
+ byte[] res = new byte[INADDR4SZ];
+ String[] s = src.split("\\.", -1);
+ long val;
+ try {
+ switch(s.length) {
+ case 1:
+ /*
+ * When only one part is given, the value is stored directly in
+ * the network address without any byte rearrangement.
+ */
+
+ val = Long.parseLong(s[0]);
+ if (val < 0 || val > 0xffffffffL)
+ return null;
+ res[0] = (byte) ((val >> 24) & 0xff);
+ res[1] = (byte) (((val & 0xffffff) >> 16) & 0xff);
+ res[2] = (byte) (((val & 0xffff) >> 8) & 0xff);
+ res[3] = (byte) (val & 0xff);
+ break;
+ case 2:
+ /*
+ * When a two part address is supplied, the last part is
+ * interpreted as a 24-bit quantity and placed in the right
+ * most three bytes of the network address. This makes the
+ * two part address format convenient for specifying Class A
+ * network addresses as net.host.
+ */
+
+ val = Integer.parseInt(s[0]);
+ if (val < 0 || val > 0xff)
+ return null;
+ res[0] = (byte) (val & 0xff);
+ val = Integer.parseInt(s[1]);
+ if (val < 0 || val > 0xffffff)
+ return null;
+ res[1] = (byte) ((val >> 16) & 0xff);
+ res[2] = (byte) (((val & 0xffff) >> 8) &0xff);
+ res[3] = (byte) (val & 0xff);
+ break;
+ case 3:
+ /*
+ * When a three part address is specified, the last part is
+ * interpreted as a 16-bit quantity and placed in the right
+ * most two bytes of the network address. This makes the
+ * three part address format convenient for specifying
+ * Class B net- work addresses as 128.net.host.
+ */
+ for (int i = 0; i < 2; i++) {
+ val = Integer.parseInt(s[i]);
+ if (val < 0 || val > 0xff)
+ return null;
+ res[i] = (byte) (val & 0xff);
+ }
+ val = Integer.parseInt(s[2]);
+ if (val < 0 || val > 0xffff)
+ return null;
+ res[2] = (byte) ((val >> 8) & 0xff);
+ res[3] = (byte) (val & 0xff);
+ break;
+ case 4:
+ /*
+ * When four parts are specified, each is interpreted as a
+ * byte of data and assigned, from left to right, to the
+ * four bytes of an IPv4 address.
+ */
+ for (int i = 0; i < 4; i++) {
+ val = Integer.parseInt(s[i]);
+ if (val < 0 || val > 0xff)
+ return null;
+ res[i] = (byte) (val & 0xff);
+ }
+ break;
+ default:
+ return null;
+ }
+ } catch(NumberFormatException e) {
+ return null;
+ }
+ return res;
+ }
+
+ /*
+ * Convert IPv6 presentation level address to network order binary form.
+ * credit:
+ * Converted from C code from Solaris 8 (inet_pton)
+ *
+ * Any component of the string following a per-cent % is ignored.
+ *
+ * @param src a String representing an IPv6 address in textual format
+ * @return a byte array representing the IPv6 numeric address
+ */
+ public static byte[] textToNumericFormatV6(String src)
+ {
+ // Shortest valid string is "::", hence at least 2 chars
+ if (src.length() < 2) {
+ return null;
+ }
+
+ int colonp;
+ char ch;
+ boolean saw_xdigit;
+ int val;
+ char[] srcb = src.toCharArray();
+ byte[] dst = new byte[INADDR16SZ];
+
+ int srcb_length = srcb.length;
+ int pc = src.indexOf ("%");
+ if (pc == srcb_length -1) {
+ return null;
+ }
+
+ if (pc != -1) {
+ srcb_length = pc;
+ }
+
+ colonp = -1;
+ int i = 0, j = 0;
+ /* Leading :: requires some special handling. */
+ if (srcb[i] == ':')
+ if (srcb[++i] != ':')
+ return null;
+ int curtok = i;
+ saw_xdigit = false;
+ val = 0;
+ while (i < srcb_length) {
+ ch = srcb[i++];
+ int chval = Character.digit(ch, 16);
+ if (chval != -1) {
+ val <<= 4;
+ val |= chval;
+ if (val > 0xffff)
+ return null;
+ saw_xdigit = true;
+ continue;
+ }
+ if (ch == ':') {
+ curtok = i;
+ if (!saw_xdigit) {
+ if (colonp != -1)
+ return null;
+ colonp = j;
+ continue;
+ } else if (i == srcb_length) {
+ return null;
+ }
+ if (j + INT16SZ > INADDR16SZ)
+ return null;
+ dst[j++] = (byte) ((val >> 8) & 0xff);
+ dst[j++] = (byte) (val & 0xff);
+ saw_xdigit = false;
+ val = 0;
+ continue;
+ }
+ if (ch == '.' && ((j + INADDR4SZ) <= INADDR16SZ)) {
+ String ia4 = src.substring(curtok, srcb_length);
+ /* check this IPv4 address has 3 dots, ie. A.B.C.D */
+ int dot_count = 0, index=0;
+ while ((index = ia4.indexOf ('.', index)) != -1) {
+ dot_count ++;
+ index ++;
+ }
+ if (dot_count != 3) {
+ return null;
+ }
+ byte[] v4addr = textToNumericFormatV4(ia4);
+ if (v4addr == null) {
+ return null;
+ }
+ for (int k = 0; k < INADDR4SZ; k++) {
+ dst[j++] = v4addr[k];
+ }
+ saw_xdigit = false;
+ break; /* '\0' was seen by inet_pton4(). */
+ }
+ return null;
+ }
+ if (saw_xdigit) {
+ if (j + INT16SZ > INADDR16SZ)
+ return null;
+ dst[j++] = (byte) ((val >> 8) & 0xff);
+ dst[j++] = (byte) (val & 0xff);
+ }
+
+ if (colonp != -1) {
+ int n = j - colonp;
+
+ if (j == INADDR16SZ)
+ return null;
+ for (i = 1; i <= n; i++) {
+ dst[INADDR16SZ - i] = dst[colonp + n - i];
+ dst[colonp + n - i] = 0;
+ }
+ j = INADDR16SZ;
+ }
+ if (j != INADDR16SZ)
+ return null;
+ byte[] newdst = convertFromIPv4MappedAddress(dst);
+ if (newdst != null) {
+ return newdst;
+ } else {
+ return dst;
+ }
+ }
+
+ /**
+ * @param src a String representing an IPv4 address in textual format
+ * @return a boolean indicating whether src is an IPv4 literal address
+ */
+ public static boolean isIPv4LiteralAddress(String src) {
+ return textToNumericFormatV4(src) != null;
+ }
+
+ /**
+ * @param src a String representing an IPv6 address in textual format
+ * @return a boolean indicating whether src is an IPv6 literal address
+ */
+ public static boolean isIPv6LiteralAddress(String src) {
+ return textToNumericFormatV6(src) != null;
+ }
+
+ /*
+ * Convert IPv4-Mapped address to IPv4 address. Both input and
+ * returned value are in network order binary form.
+ *
+ * @param src a String representing an IPv4-Mapped address in textual format
+ * @return a byte array representing the IPv4 numeric address
+ */
+ public static byte[] convertFromIPv4MappedAddress(byte[] addr) {
+ if (isIPv4MappedAddress(addr)) {
+ byte[] newAddr = new byte[INADDR4SZ];
+ System.arraycopy(addr, 12, newAddr, 0, INADDR4SZ);
+ return newAddr;
+ }
+ return null;
+ }
+
+ /**
+ * Utility routine to check if the InetAddress is an
+ * IPv4 mapped IPv6 address.
+ *
+ * @return a <code>boolean</code> indicating if the InetAddress is
+ * an IPv4 mapped IPv6 address; or false if address is IPv4 address.
+ */
+ private static boolean isIPv4MappedAddress(byte[] addr) {
+ if (addr.length < INADDR16SZ) {
+ return false;
+ }
+ if ((addr[0] == 0x00) && (addr[1] == 0x00) &&
+ (addr[2] == 0x00) && (addr[3] == 0x00) &&
+ (addr[4] == 0x00) && (addr[5] == 0x00) &&
+ (addr[6] == 0x00) && (addr[7] == 0x00) &&
+ (addr[8] == 0x00) && (addr[9] == 0x00) &&
+ (addr[10] == (byte)0xff) &&
+ (addr[11] == (byte)0xff)) {
+ return true;
+ }
+ return false;
+ }
+}
Added: trunk/core/src/openjdk/sun/sun/security/ec/ECKeyFactory.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/security/ec/ECKeyFactory.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/security/ec/ECKeyFactory.java 2007-06-23 05:00:54 UTC (rev 3291)
@@ -0,0 +1,296 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.security.ec;
+
+import java.security.*;
+import java.security.interfaces.*;
+import java.security.spec.*;
+
+/**
+ * KeyFactory for EC keys. Keys must be instances of PublicKey or PrivateKey
+ * and getAlgorithm() must return "EC". For such keys, it supports conversion
+ * between the following:
+ *
+ * For public keys:
+ * . PublicKey with an X.509 encoding
+ * . ECPublicKey
+ * . ECPublicKeySpec
+ * . X509EncodedKeySpec
+ *
+ * For private keys:
+ * . PrivateKey with a PKCS#8 encoding
+ * . ECPrivateKey
+ * . ECPrivateKeySpec
+ * . PKCS8EncodedKeySpec
+ *
+ * @since 1.6
+ * @version 1.7, 05/05/07
+ * @author Andreas Sterbenz
+ */
+public final class ECKeyFactory extends KeyFactorySpi {
+
+ // Used by translateKey() and the SunPKCS11 provider
+ public final static KeyFactory INSTANCE;
+
+ // Internal provider object we can obtain the KeyFactory and
+ // AlgorithmParameters from. Used by ECParameters and AlgorithmId.
+ // This can go away once we have EC always available in the SUN provider.
+ // Used by ECParameters and AlgorithmId.
+ public final static Provider ecInternalProvider;
+
+ static {
+ final Provider p = new Provider("SunEC-Internal", 1.0d, null) {};
+ AccessController.doPrivileged(new PrivilegedAction<Void>() {
+ public Void run() {
+ p.put("KeyFactory.EC", "sun.security.ec.ECKeyFactory");
+ p.put("AlgorithmParameters.EC", "sun.security.ec.ECParameters");
+ p.put("Alg.Alias.AlgorithmParameters.1.2.840.10045.2.1", "EC");
+ return null;
+ }
+ });
+ try {
+ INSTANCE = KeyFactory.getInstance("EC", p);
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException(e);
+ }
+ ecInternalProvider = p;
+ }
+
+ public ECKeyFactory() {
+ // empty
+ }
+
+ /**
+ * Static method to convert Key into a useable instance of
+ * ECPublicKey or ECPrivateKey. Check the key and convert it
+ * to a Sun key if necessary. If the key is not an EC key
+ * or cannot be used, throw an InvalidKeyException.
+ *
+ * The difference between this method and engineTranslateKey() is that
+ * we do not convert keys of other providers that are already an
+ * instance of ECPublicKey or ECPrivateKey.
+ *
+ * To be used by future Java ECDSA and ECDH implementations.
+ */
+ public static ECKey toECKey(Key key) throws InvalidKeyException {
+ if (key instanceof ECKey) {
+ ECKey ecKey = (ECKey)key;
+ checkKey(ecKey);
+ return ecKey;
+ } else {
+ return (ECKey)INSTANCE.translateKey(key);
+ }
+ }
+
+ /**
+ * Check that the given EC key is valid.
+ */
+ private static void checkKey(ECKey key) throws InvalidKeyException {
+ // check for subinterfaces, omit additional checks for our keys
+ if (key instanceof ECPublicKey) {
+ if (key instanceof ECPublicKeyImpl) {
+ return;
+ }
+ } else if (key instanceof ECPrivateKey) {
+ if (key instanceof ECPrivateKeyImpl) {
+ return;
+ }
+ } else {
+ throw new InvalidKeyException("Neither a public nor a private key");
+ }
+ // ECKey does not extend Key, so we need to do a cast
+ String keyAlg = ((Key)key).getAlgorithm();
+ if (keyAlg.equals("EC") == false) {
+ throw new InvalidKeyException("Not an EC key: " + keyAlg);
+ }
+ // XXX further sanity checks about whether this key uses supported
+ // fields, point formats, etc. would go here
+ }
+
+ /**
+ * Translate an EC key into a Sun EC key. If conversion is
+ * not possible, throw an InvalidKeyException.
+ * See also JCA doc.
+ */
+ protected Key engineTranslateKey(Key key) throws InvalidKeyException {
+ if (key == null) {
+ throw new InvalidKeyException("Key must not be null");
+ }
+ String keyAlg = key.getAlgorithm();
+ if (keyAlg.equals("EC") == false) {
+ throw new InvalidKeyException("Not an EC key: " + keyAlg);
+ }
+ if (key instanceof PublicKey) {
+ return implTranslatePublicKey((PublicKey)key);
+ } else if (key instanceof PrivateKey) {
+ return implTranslatePrivateKey((PrivateKey)key);
+ } else {
+ throw new InvalidKeyException("Neither a public nor a private key");
+ }
+ }
+
+ // see JCA doc
+ protected PublicKey engineGeneratePublic(KeySpec keySpec)
+ throws InvalidKeySpecException {
+ try {
+ return implGeneratePublic(keySpec);
+ } catch (InvalidKeySpecException e) {
+ throw e;
+ } catch (GeneralSecurityException e) {
+ throw new InvalidKeySpecException(e);
+ }
+ }
+
+ // see JCA doc
+ protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
+ throws InvalidKeySpecException {
+ try {
+ return implGeneratePrivate(keySpec);
+ } catch (InvalidKeySpecException e) {
+ throw e;
+ } catch (GeneralSecurityException e) {
+ throw new InvalidKeySpecException(e);
+ }
+ }
+
+ // internal implementation of translateKey() for public keys. See JCA doc
+ private PublicKey implTranslatePublicKey(PublicKey key)
+ throws InvalidKeyException {
+ if (key instanceof ECPublicKey) {
+ if (key instanceof ECPublicKeyImpl) {
+ return key;
+ }
+ ECPublicKey ecKey = (ECPublicKey)key;
+ return new ECPublicKeyImpl(
+ ecKey.getW(),
+ ecKey.getParams()
+ );
+ } else if ("X.509".equals(key.getFormat())) {
+ byte[] encoded = key.getEncoded();
+ return new ECPublicKeyImpl(encoded);
+ } else {
+ throw new InvalidKeyException("Public keys must be instance "
+ + "of ECPublicKey or have X.509 encoding");
+ }
+ }
+
+ // internal implementation of translateKey() for private keys. See JCA doc
+ private PrivateKey implTranslatePrivateKey(PrivateKey key)
+ throws InvalidKeyException {
+ if (key instanceof ECPrivateKey) {
+ if (key instanceof ECPrivateKeyImpl) {
+ return key;
+ }
+ ECPrivateKey ecKey = (ECPrivateKey)key;
+ return new ECPrivateKeyImpl(
+ ecKey.getS(),
+ ecKey.getParams()
+ );
+ } else if ("PKCS#8".equals(key.getFormat())) {
+ return new ECPrivateKeyImpl(key.getEncoded());
+ } else {
+ throw new InvalidKeyException("Private keys must be instance "
+ + "of ECPrivateKey or have PKCS#8 encoding");
+ }
+ }
+
+ // internal implementation of generatePublic. See JCA doc
+ private PublicKey implGeneratePublic(KeySpec keySpec)
+ throws GeneralSecurityException {
+ if (keySpec instanceof X509EncodedKeySpec) {
+ X509EncodedKeySpec x509Spec = (X509EncodedKeySpec)keySpec;
+ return new ECPublicKeyImpl(x509Spec.getEncoded());
+ } else if (keySpec instanceof ECPublicKeySpec) {
+ ECPublicKeySpec ecSpec = (ECPublicKeySpec)keySpec;
+ return new ECPublicKeyImpl(
+ ecSpec.getW(),
+ ecSpec.getParams()
+ );
+ } else {
+ throw new InvalidKeySpecException("Only ECPublicKeySpec "
+ + "and X509EncodedKeySpec supported for EC public keys");
+ }
+ }
+
+ // internal implementation of generatePrivate. See JCA doc
+ private PrivateKey implGeneratePrivate(KeySpec keySpec)
+ throws GeneralSecurityException {
+ if (keySpec instanceof PKCS8EncodedKeySpec) {
+ PKCS8EncodedKeySpec pkcsSpec = (PKCS8EncodedKeySpec)keySpec;
+ return new ECPrivateKeyImpl(pkcsSpec.getEncoded());
+ } else if (keySpec instanceof ECPrivateKeySpec) {
+ ECPrivateKeySpec ecSpec = (ECPrivateKeySpec)keySpec;
+ return new ECPrivateKeyImpl(ecSpec.getS(), ecSpec.getParams());
+ } else {
+ throw new InvalidKeySpecException("Only ECPrivateKeySpec "
+ + "and PKCS8EncodedKeySpec supported for EC private keys");
+ }
+ }
+
+ protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
+ throws InvalidKeySpecException {
+ try {
+ // convert key to one of our keys
+ // this also verifies that the key is a valid EC key and ensures
+ // that the encoding is X.509/PKCS#8 for public/private keys
+ key = engineTranslateKey(key);
+ } catch (InvalidKeyException e) {
+ throw new InvalidKeySpecException(e);
+ }
+ if (key instanceof ECPublicKey) {
+ ECPublicKey ecKey = (ECPublicKey)key;
+ if (ECPublicKeySpec.class.isAssignableFrom(keySpec)) {
+ return (T) new ECPublicKeySpec(
+ ecKey.getW(),
+ ecKey.getParams()
+ );
+ } else if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) {
+ return (T) new X509EncodedKeySpec(key.getEncoded());
+ } else {
+ throw new InvalidKeySpecException
+ ("KeySpec must be ECPublicKeySpec or "
+ + "X509EncodedKeySpec for EC public keys");
+ }
+ } else if (key instanceof ECPrivateKey) {
+ if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) {
+ return (T) new PKCS8EncodedKeySpec(key.getEncoded());
+ } else if (ECPrivateKeySpec.class.isAssignableFrom(keySpec)) {
+ ECPrivateKey ecKey = (ECPrivateKey)key;
+ return (T) new ECPrivateKeySpec(
+ ecKey.getS(),
+ ecKey.getParams()
+ );
+ } else {
+ throw new InvalidKeySpecException
+ ("KeySpec must be ECPrivateKeySpec or "
+ + "PKCS8EncodedKeySpec for EC private keys");
+ }
+ } else {
+ // should not occur, caught in engineTranslateKey()
+ throw new InvalidKeySpecException("Neither public nor private key");
+ }
+ }
+}
Added: trunk/core/src/openjdk/sun/sun/security/ec/ECParameters.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/security/ec/ECParameters.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/security/ec/ECParameters.java 2007-06-23 05:00:54 UTC (rev 3291)
@@ -0,0 +1,350 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.security.ec;
+
+import java.io.IOException;
+import java.math.BigInteger;
+
+import java.security.*;
+import java.security.spec.*;
+
+import sun.security.util.*;
+
+/**
+ * This class implements encoding and decoding of Elliptic Curve parameters
+ * as specified in RFC 3279.
+ *
+ * However, only named curves are currently supported.
+ *
+ * ASN.1 from RFC 3279 follows. Note that X9.62 (2005) has added some additional
+ * options.
+ *
+ * <pre>
+ * EcpkParameters ::= CHOICE {
+ * ecParameters ECParameters,
+ * namedCurve OBJECT IDENTIFIER,
+ * implicitlyCA NULL }
+ *
+ * ECParameters ::= SEQUENCE {
+ * version ECPVer, -- version is always 1
+ * fieldID FieldID, -- identifies the finite field over
+ * -- which the curve is defined
+ * curve Curve, -- coefficients a and b of the
+ * -- elliptic curve
+ * base ECPoint, -- specifies the base point P
+ * -- on the elliptic curve
+ * order INTEGER, -- the order n of the base point
+ * cofactor INTEGER OPTIONAL -- The integer h = #E(Fq)/n
+ * }
+ *
+ * ECPVer ::= INTEGER {ecpVer1(1)}
+ *
+...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-23 04:57:10
|
Revision: 3290
http://jnode.svn.sourceforge.net/jnode/?rev=3290&view=rev
Author: lsantha
Date: 2007-06-22 21:57:09 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/javax/javax/naming/
trunk/core/src/openjdk/javax/javax/naming/AuthenticationException.java
trunk/core/src/openjdk/javax/javax/naming/AuthenticationNotSupportedException.java
trunk/core/src/openjdk/javax/javax/naming/BinaryRefAddr.java
trunk/core/src/openjdk/javax/javax/naming/Binding.java
trunk/core/src/openjdk/javax/javax/naming/CannotProceedException.java
trunk/core/src/openjdk/javax/javax/naming/CommunicationException.java
trunk/core/src/openjdk/javax/javax/naming/CompositeName.java
trunk/core/src/openjdk/javax/javax/naming/CompoundName.java
trunk/core/src/openjdk/javax/javax/naming/ConfigurationException.java
trunk/core/src/openjdk/javax/javax/naming/Context.java
trunk/core/src/openjdk/javax/javax/naming/ContextNotEmptyException.java
trunk/core/src/openjdk/javax/javax/naming/InitialContext.java
trunk/core/src/openjdk/javax/javax/naming/InsufficientResourcesException.java
trunk/core/src/openjdk/javax/javax/naming/InterruptedNamingException.java
trunk/core/src/openjdk/javax/javax/naming/InvalidNameException.java
trunk/core/src/openjdk/javax/javax/naming/LimitExceededException.java
trunk/core/src/openjdk/javax/javax/naming/LinkException.java
trunk/core/src/openjdk/javax/javax/naming/LinkLoopException.java
trunk/core/src/openjdk/javax/javax/naming/LinkRef.java
trunk/core/src/openjdk/javax/javax/naming/MalformedLinkException.java
trunk/core/src/openjdk/javax/javax/naming/Name.java
trunk/core/src/openjdk/javax/javax/naming/NameAlreadyBoundException.java
trunk/core/src/openjdk/javax/javax/naming/NameClassPair.java
trunk/core/src/openjdk/javax/javax/naming/NameImpl.java
trunk/core/src/openjdk/javax/javax/naming/NameNotFoundException.java
trunk/core/src/openjdk/javax/javax/naming/NameParser.java
trunk/core/src/openjdk/javax/javax/naming/NamingEnumeration.java
trunk/core/src/openjdk/javax/javax/naming/NamingException.java
trunk/core/src/openjdk/javax/javax/naming/NamingSecurityException.java
trunk/core/src/openjdk/javax/javax/naming/NoInitialContextException.java
trunk/core/src/openjdk/javax/javax/naming/NoPermissionException.java
trunk/core/src/openjdk/javax/javax/naming/NotContextException.java
trunk/core/src/openjdk/javax/javax/naming/OperationNotSupportedException.java
trunk/core/src/openjdk/javax/javax/naming/PartialResultException.java
trunk/core/src/openjdk/javax/javax/naming/RefAddr.java
trunk/core/src/openjdk/javax/javax/naming/Reference.java
trunk/core/src/openjdk/javax/javax/naming/Referenceable.java
trunk/core/src/openjdk/javax/javax/naming/ReferralException.java
trunk/core/src/openjdk/javax/javax/naming/ServiceUnavailableException.java
trunk/core/src/openjdk/javax/javax/naming/SizeLimitExceededException.java
trunk/core/src/openjdk/javax/javax/naming/StringRefAddr.java
trunk/core/src/openjdk/javax/javax/naming/TimeLimitExceededException.java
trunk/core/src/openjdk/javax/javax/naming/directory/
trunk/core/src/openjdk/javax/javax/naming/directory/Attribute.java
trunk/core/src/openjdk/javax/javax/naming/directory/AttributeInUseException.java
trunk/core/src/openjdk/javax/javax/naming/directory/AttributeModificationException.java
trunk/core/src/openjdk/javax/javax/naming/directory/Attributes.java
trunk/core/src/openjdk/javax/javax/naming/directory/BasicAttribute.java
trunk/core/src/openjdk/javax/javax/naming/directory/BasicAttributes.java
trunk/core/src/openjdk/javax/javax/naming/directory/DirContext.java
trunk/core/src/openjdk/javax/javax/naming/directory/InitialDirContext.java
trunk/core/src/openjdk/javax/javax/naming/directory/InvalidAttributeIdentifierException.java
trunk/core/src/openjdk/javax/javax/naming/directory/InvalidAttributeValueException.java
trunk/core/src/openjdk/javax/javax/naming/directory/InvalidAttributesException.java
trunk/core/src/openjdk/javax/javax/naming/directory/InvalidSearchControlsException.java
trunk/core/src/openjdk/javax/javax/naming/directory/InvalidSearchFilterException.java
trunk/core/src/openjdk/javax/javax/naming/directory/ModificationItem.java
trunk/core/src/openjdk/javax/javax/naming/directory/NoSuchAttributeException.java
trunk/core/src/openjdk/javax/javax/naming/directory/SchemaViolationException.java
trunk/core/src/openjdk/javax/javax/naming/directory/SearchControls.java
trunk/core/src/openjdk/javax/javax/naming/directory/SearchResult.java
trunk/core/src/openjdk/javax/javax/naming/directory/package.html
trunk/core/src/openjdk/javax/javax/naming/event/
trunk/core/src/openjdk/javax/javax/naming/event/EventContext.java
trunk/core/src/openjdk/javax/javax/naming/event/EventDirContext.java
trunk/core/src/openjdk/javax/javax/naming/event/NamespaceChangeListener.java
trunk/core/src/openjdk/javax/javax/naming/event/NamingEvent.java
trunk/core/src/openjdk/javax/javax/naming/event/NamingExceptionEvent.java
trunk/core/src/openjdk/javax/javax/naming/event/NamingListener.java
trunk/core/src/openjdk/javax/javax/naming/event/ObjectChangeListener.java
trunk/core/src/openjdk/javax/javax/naming/event/package.html
trunk/core/src/openjdk/javax/javax/naming/ldap/
trunk/core/src/openjdk/javax/javax/naming/ldap/BasicControl.java
trunk/core/src/openjdk/javax/javax/naming/ldap/Control.java
trunk/core/src/openjdk/javax/javax/naming/ldap/ControlFactory.java
trunk/core/src/openjdk/javax/javax/naming/ldap/ExtendedRequest.java
trunk/core/src/openjdk/javax/javax/naming/ldap/ExtendedResponse.java
trunk/core/src/openjdk/javax/javax/naming/ldap/HasControls.java
trunk/core/src/openjdk/javax/javax/naming/ldap/InitialLdapContext.java
trunk/core/src/openjdk/javax/javax/naming/ldap/LdapContext.java
trunk/core/src/openjdk/javax/javax/naming/ldap/LdapName.java
trunk/core/src/openjdk/javax/javax/naming/ldap/LdapReferralException.java
trunk/core/src/openjdk/javax/javax/naming/ldap/ManageReferralControl.java
trunk/core/src/openjdk/javax/javax/naming/ldap/PagedResultsControl.java
trunk/core/src/openjdk/javax/javax/naming/ldap/PagedResultsResponseControl.java
trunk/core/src/openjdk/javax/javax/naming/ldap/Rdn.java
trunk/core/src/openjdk/javax/javax/naming/ldap/Rfc2253Parser.java
trunk/core/src/openjdk/javax/javax/naming/ldap/SortControl.java
trunk/core/src/openjdk/javax/javax/naming/ldap/SortKey.java
trunk/core/src/openjdk/javax/javax/naming/ldap/SortResponseControl.java
trunk/core/src/openjdk/javax/javax/naming/ldap/StartTlsRequest.java
trunk/core/src/openjdk/javax/javax/naming/ldap/StartTlsResponse.java
trunk/core/src/openjdk/javax/javax/naming/ldap/UnsolicitedNotification.java
trunk/core/src/openjdk/javax/javax/naming/ldap/UnsolicitedNotificationEvent.java
trunk/core/src/openjdk/javax/javax/naming/ldap/UnsolicitedNotificationListener.java
trunk/core/src/openjdk/javax/javax/naming/ldap/package.html
trunk/core/src/openjdk/javax/javax/naming/package.html
trunk/core/src/openjdk/javax/javax/naming/spi/
trunk/core/src/openjdk/javax/javax/naming/spi/ContinuationContext.java
trunk/core/src/openjdk/javax/javax/naming/spi/ContinuationDirContext.java
trunk/core/src/openjdk/javax/javax/naming/spi/DirObjectFactory.java
trunk/core/src/openjdk/javax/javax/naming/spi/DirStateFactory.java
trunk/core/src/openjdk/javax/javax/naming/spi/DirectoryManager.java
trunk/core/src/openjdk/javax/javax/naming/spi/InitialContextFactory.java
trunk/core/src/openjdk/javax/javax/naming/spi/InitialContextFactoryBuilder.java
trunk/core/src/openjdk/javax/javax/naming/spi/NamingManager.java
trunk/core/src/openjdk/javax/javax/naming/spi/ObjectFactory.java
trunk/core/src/openjdk/javax/javax/naming/spi/ObjectFactoryBuilder.java
trunk/core/src/openjdk/javax/javax/naming/spi/ResolveResult.java
trunk/core/src/openjdk/javax/javax/naming/spi/Resolver.java
trunk/core/src/openjdk/javax/javax/naming/spi/StateFactory.java
trunk/core/src/openjdk/javax/javax/naming/spi/package.html
trunk/core/src/openjdk/javax/javax/rmi/
trunk/core/src/openjdk/javax/javax/rmi/CORBA/
trunk/core/src/openjdk/javax/javax/rmi/CORBA/ClassDesc.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/GetORBPropertiesFileAction.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/PortableRemoteObjectDelegate.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/Stub.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/StubDelegate.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/Tie.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/Util.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/UtilDelegate.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/ValueHandler.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/ValueHandlerMultiFormat.java
trunk/core/src/openjdk/javax/javax/rmi/CORBA/package.html
trunk/core/src/openjdk/javax/javax/rmi/PortableRemoteObject.java
trunk/core/src/openjdk/javax/javax/rmi/package.html
trunk/core/src/openjdk/javax/javax/rmi/ssl/
trunk/core/src/openjdk/javax/javax/rmi/ssl/SslRMIClientSocketFactory.java
trunk/core/src/openjdk/javax/javax/rmi/ssl/SslRMIServerSocketFactory.java
trunk/core/src/openjdk/javax/javax/rmi/ssl/package.html
trunk/core/src/openjdk/javax/javax/security/
trunk/core/src/openjdk/javax/javax/security/auth/
trunk/core/src/openjdk/javax/javax/security/auth/login/
trunk/core/src/openjdk/javax/javax/security/auth/login/ConfigurationSpi.java
Added: trunk/core/src/openjdk/javax/javax/naming/AuthenticationException.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/naming/AuthenticationException.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/naming/AuthenticationException.java 2007-06-23 04:57:09 UTC (rev 3290)
@@ -0,0 +1,76 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.naming;
+
+/**
+ * This exception is thrown when an authentication error occurs while
+ * accessing the naming or directory service.
+ * An authentication error can happen, for example, when the credentials
+ * supplied by the user program is invalid or otherwise fails to
+ * authenticate the user to the naming/directory service.
+ *<p>
+ * If the program wants to handle this exception in particular, it
+ * should catch AuthenticationException explicitly before attempting to
+ * catch NamingException. After catching AuthenticationException, the
+ * program could reattempt the authentication by updating
+ * the resolved context's environment properties with the appropriate
+ * appropriate credentials.
+ * <p>
+ * Synchronization and serialization issues that apply to NamingException
+ * apply directly here.
+ *
+ * @author Rosanna Lee
+ * @author Scott Seligman
+ * @version 1.14 07/05/05
+ * @since 1.3
+ */
+
+public class AuthenticationException extends NamingSecurityException {
+ /**
+ * Constructs a new instance of AuthenticationException using the
+ * explanation supplied. All other fields default to null.
+ *
+ * @param explanation A possibly null string containing
+ * additional detail about this exception.
+ * @see java.lang.Throwable#getMessage
+ */
+ public AuthenticationException(String explanation) {
+ super(explanation);
+ }
+
+ /**
+ * Constructs a new instance of AuthenticationException.
+ * All fields are set to null.
+ */
+ public AuthenticationException() {
+ super();
+ }
+
+ /**
+ * Use serialVersionUID from JNDI 1.1.1 for interoperability
+ */
+ private static final long serialVersionUID = 3678497619904568096L;
+}
Added: trunk/core/src/openjdk/javax/javax/naming/AuthenticationNotSupportedException.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/naming/AuthenticationNotSupportedException.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/naming/AuthenticationNotSupportedException.java 2007-06-23 04:57:09 UTC (rev 3290)
@@ -0,0 +1,81 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.naming;
+
+/**
+ * This exception is thrown when
+ * the particular flavor of authentication requested is not supported.
+ * For example, if the program
+ * is attempting to use strong authentication but the directory/naming
+ * supports only simple authentication, this exception would be thrown.
+ * Identification of a particular flavor of authentication is
+ * provider- and server-specific. It may be specified using
+ * specific authentication schemes such
+ * those identified using SASL, or a generic authentication specifier
+ * (such as "simple" and "strong").
+ *<p>
+ * If the program wants to handle this exception in particular, it
+ * should catch AuthenticationNotSupportedException explicitly before
+ * attempting to catch NamingException. After catching
+ * <code>AuthenticationNotSupportedException</code>, the program could
+ * reattempt the authentication using a different authentication flavor
+ * by updating the resolved context's environment properties accordingly.
+ * <p>
+ * Synchronization and serialization issues that apply to NamingException
+ * apply directly here.
+ *
+ * @author Rosanna Lee
+ * @author Scott Seligman
+ * @version 1.14 07/05/05
+ * @since 1.3
+ */
+
+public class AuthenticationNotSupportedException extends NamingSecurityException {
+ /**
+ * Constructs a new instance of AuthenticationNotSupportedException using
+ * an explanation. All other fields default to null.
+ *
+ * @param explanation A possibly null string containing additional
+ * detail about this exception.
+ * @see java.lang.Throwable#getMessage
+ */
+ public AuthenticationNotSupportedException(String explanation) {
+ super(explanation);
+ }
+
+ /**
+ * Constructs a new instance of AuthenticationNotSupportedException
+ * all name resolution fields and explanation initialized to null.
+ */
+ public AuthenticationNotSupportedException() {
+ super();
+ }
+
+ /**
+ * Use serialVersionUID from JNDI 1.1.1 for interoperability
+ */
+ private static final long serialVersionUID = -7149033933259492300L;
+}
Added: trunk/core/src/openjdk/javax/javax/naming/BinaryRefAddr.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/naming/BinaryRefAddr.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/naming/BinaryRefAddr.java 2007-06-23 04:57:09 UTC (rev 3290)
@@ -0,0 +1,184 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.naming;
+
+/**
+ * This class represents the binary form of the address of
+ * a communications end-point.
+ *<p>
+ * A BinaryRefAddr consists of a type that describes the communication mechanism
+ * and an opaque buffer containing the address description
+ * specific to that communication mechanism. The format and interpretation of
+ * the address type and the contents of the opaque buffer are based on
+ * the agreement of three parties: the client that uses the address,
+ * the object/server that can be reached using the address,
+ * and the administrator or program that creates the address.
+ *<p>
+ * An example of a binary reference address is an BER X.500 presentation address.
+ * Another example of a binary reference address is a serialized form of
+ * a service's object handle.
+ *<p>
+ * A binary reference address is immutable in the sense that its fields
+ * once created, cannot be replaced. However, it is possible to access
+ * the byte array used to hold the opaque buffer. Programs are strongly
+ * recommended against changing this byte array. Changes to this
+ * byte array need to be explicitly synchronized.
+ *
+ * @author Rosanna Lee
+ * @author Scott Seligman
+ * @version 1.14 07/05/05
+ *
+ * @see RefAddr
+ * @see StringRefAddr
+ * @since 1.3
+ */
+
+ /*
+ * The serialized form of a BinaryRefAddr object consists of its type
+ * name String and a byte array containing its "contents".
+ */
+
+public class BinaryRefAddr extends RefAddr {
+ /**
+ * Contains the bytes of the address.
+ * This field is initialized by the constructor and returned
+ * using getAddressBytes() and getAddressContents().
+ * @serial
+ */
+ private byte[] buf = null;
+
+ /**
+ * Constructs a new instance of BinaryRefAddr using its address type and a byte
+ * array for contents.
+ *
+ * @param addrType A non-null string describing the type of the address.
+ * @param src The non-null contents of the address as a byte array.
+ * The contents of src is copied into the new BinaryRefAddr.
+ */
+ public BinaryRefAddr(String addrType, byte[] src) {
+ this(addrType, src, 0, src.length);
+ }
+
+ /**
+ * Constructs a new instance of BinaryRefAddr using its address type and
+ * a region of a byte array for contents.
+ *
+ * @param addrType A non-null string describing the type of the address.
+ * @param src The non-null contents of the address as a byte array.
+ * The contents of src is copied into the new BinaryRefAddr.
+ * @param offset The starting index in src to get the bytes.
+ * 0 <= offset <= src.length.
+ * @param count The number of bytes to extract from src.
+ * 0 <= count <= src.length-offset.
+ */
+ public BinaryRefAddr(String addrType, byte[] src, int offset, int count) {
+ super(addrType);
+ buf = new byte[count];
+ System.arraycopy(src, offset, buf, 0, count);
+ }
+
+ /**
+ * Retrieves the contents of this address as an Object.
+ * The result is a byte array.
+ * Changes to this array will affect this BinaryRefAddr's contents.
+ * Programs are recommended against changing this array's contents
+ * and to lock the buffer if they need to change it.
+ *
+ * @return The non-null buffer containing this address's contents.
+ */
+ public Object getContent() {
+ return buf;
+ }
+
+
+ /**
+ * Determines whether obj is equal to this address. It is equal if
+ * it contains the same address type and their contents are byte-wise
+ * equivalent.
+ * @param obj The possibly null object to check.
+ * @return true if the object is equal; false otherwise.
+ */
+ public boolean equals(Object obj) {
+ if ((obj != null) && (obj instanceof BinaryRefAddr)) {
+ BinaryRefAddr target = (BinaryRefAddr)obj;
+ if (addrType.compareTo(target.addrType) == 0) {
+ if (buf == null && target.buf == null)
+ return true;
+ if (buf == null || target.buf == null ||
+ buf.length != target.buf.length)
+ return false;
+ for (int i = 0; i < buf.length; i++)
+ if (buf[i] != target.buf[i])
+ return false;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Computes the hash code of this address using its address type and contents.
+ * Two BinaryRefAddrs have the same hash code if they have
+ * the same address type and the same contents.
+ * It is also possible for different BinaryRefAddrs to have
+ * the same hash code.
+ *
+ * @return The hash code of this address as an int.
+ */
+ public int hashCode() {
+ int hash = addrType.hashCode();
+ for (int i = 0; i < buf.length; i++) {
+ hash += buf[i]; // %%% improve later
+ }
+ return hash;
+ }
+
+ /**
+ * Generates the string representation of this address.
+ * The string consists of the address's type and contents with labels.
+ * The first 32 bytes of contents are displayed (in hexadecimal).
+ * If there are more than 32 bytes, "..." is used to indicate more.
+ * This string is meant to used for debugging purposes and not
+ * meant to be interpreted programmatically.
+ * @return The non-null string representation of this address.
+ */
+ public String toString(){
+ StringBuffer str = new StringBuffer("Address Type: " + addrType + "\n");
+
+ str.append("AddressContents: ");
+ for (int i = 0; i<buf.length && i < 32; i++) {
+ str.append(Integer.toHexString(buf[i]) +" ");
+ }
+ if (buf.length >= 32)
+ str.append(" ...\n");
+ return (str.toString());
+ }
+
+ /**
+ * Use serialVersionUID from JNDI 1.1.1 for interoperability
+ */
+ private static final long serialVersionUID = -3415254970957330361L;
+}
Added: trunk/core/src/openjdk/javax/javax/naming/Binding.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/naming/Binding.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/naming/Binding.java 2007-06-23 04:57:09 UTC (rev 3290)
@@ -0,0 +1,201 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.naming;
+
+/**
+ * This class represents a name-to-object binding found in a context.
+ *<p>
+ * A context consists of name-to-object bindings.
+ * The Binding class represents such a binding. It consists
+ * of a name and an object. The <code>Context.listBindings()</code>
+ * method returns an enumeration of Binding.
+ *<p>
+ * Use subclassing for naming systems that generate contents of
+ * a binding dynamically.
+ *<p>
+ * A Binding instance is not synchronized against concurrent access by multiple
+ * threads. Threads that need to access a Binding concurrently should
+ * synchronize amongst themselves and provide the necessary locking.
+ *
+ * @author Rosanna Lee
+ * @author Scott Seligman
+ * @version 1.15 07/05/05
+ * @since 1.3
+ */
+
+public class Binding extends NameClassPair {
+ /**
+ * Contains this binding's object.
+ * It is initialized by the constuctor and can be updated using
+ * <tt>setObject</tt>.
+ * @serial
+ * @see #getObject
+ * @see #setObject
+ */
+ private Object boundObj;
+
+ /**
+ * Constructs an instance of a Binding given its name and object.
+ *<p>
+ * <tt>getClassName()</tt> will return
+ * the class name of <tt>obj</tt> (or null if <tt>obj</tt> is null)
+ * unless the class name has been explicitly set using <tt>setClassName()</tt>
+ *
+ * @param name The non-null name of the object. It is relative
+ * to the <em>target context</em> (which is
+ * named by the first parameter of the <code>listBindings()</code> method)
+ * @param obj The possibly null object bound to name.
+ * @see NameClassPair#setClassName
+ */
+ public Binding(String name, Object obj) {
+ super(name, null);
+ this.boundObj = obj;
+ }
+
+ /**
+ * Constructs an instance of a Binding given its name, object, and whether
+ * the name is relative.
+ *<p>
+ * <tt>getClassName()</tt> will return the class name of <tt>obj</tt>
+ * (or null if <tt>obj</tt> is null) unless the class name has been
+ * explicitly set using <tt>setClassName()</tt>
+ *
+ * @param name The non-null string name of the object.
+ * @param obj The possibly null object bound to name.
+ * @param isRelative true if <code>name</code> is a name relative
+ * to the target context (which is named by
+ * the first parameter of the <code>listBindings()</code> method);
+ * false if <code>name</code> is a URL string.
+ * @see NameClassPair#isRelative
+ * @see NameClassPair#setRelative
+ * @see NameClassPair#setClassName
+ */
+ public Binding(String name, Object obj, boolean isRelative) {
+ super(name, null, isRelative);
+ this.boundObj = obj;
+ }
+
+ /**
+ * Constructs an instance of a Binding given its name, class name, and object.
+ *
+ * @param name The non-null name of the object. It is relative
+ * to the <em>target context</em> (which is
+ * named by the first parameter of the <code>listBindings()</code> method)
+ * @param className The possibly null class name of the object
+ * bound to <tt>name</tt>. If null, the class name of <tt>obj</tt> is
+ * returned by <tt>getClassName()</tt>. If <tt>obj</tt> is also
+ * null, <tt>getClassName()</tt> will return null.
+ * @param obj The possibly null object bound to name.
+ * @see NameClassPair#setClassName
+ */
+ public Binding(String name, String className, Object obj) {
+ super(name, className);
+ this.boundObj = obj;
+ }
+
+ /**
+ * Constructs an instance of a Binding given its
+ * name, class name, object, and whether the name is relative.
+ *
+ * @param name The non-null string name of the object.
+ * @param className The possibly null class name of the object
+ * bound to <tt>name</tt>. If null, the class name of <tt>obj</tt> is
+ * returned by <tt>getClassName()</tt>. If <tt>obj</tt> is also
+ * null, <tt>getClassName()</tt> will return null.
+ * @param obj The possibly null object bound to name.
+ * @param isRelative true if <code>name</code> is a name relative
+ * to the target context (which is named by
+ * the first parameter of the <code>listBindings()</code> method);
+ * false if <code>name</code> is a URL string.
+ * @see NameClassPair#isRelative
+ * @see NameClassPair#setRelative
+ * @see NameClassPair#setClassName
+ */
+ public Binding(String name, String className, Object obj, boolean isRelative) {
+ super(name, className, isRelative);
+ this.boundObj = obj;
+ }
+
+ /**
+ * Retrieves the class name of the object bound to the name of this binding.
+ * If the class name has been set explicitly, return it.
+ * Otherwise, if this binding contains a non-null object,
+ * that object's class name is used. Otherwise, null is returned.
+ *
+ * @return A possibly null string containing class name of object bound.
+ */
+ public String getClassName() {
+ String cname = super.getClassName();
+ if (cname != null) {
+ return cname;
+ }
+ if (boundObj != null)
+ return boundObj.getClass().getName();
+ else
+ return null;
+ }
+
+ /**
+ * Retrieves the object bound to the name of this binding.
+ *
+ * @return The object bound; null if this binding does not contain an object.
+ * @see #setObject
+ */
+
+ public Object getObject() {
+ return boundObj;
+ }
+
+ /**
+ * Sets the object associated with this binding.
+ * @param obj The possibly null object to use.
+ * @see #getObject
+ */
+ public void setObject(Object obj) {
+ boundObj = obj;
+ }
+
+ /**
+ * Generates the string representation of this binding.
+ * The string representation consists of the string representation
+ * of the name/class pair and the string representation of
+ * this binding's object, separated by ':'.
+ * The contents of this string is useful
+ * for debugging and is not meant to be interpreted programmatically.
+ *
+ * @return The non-null string representation of this binding.
+ */
+
+ public String toString() {
+ return super.toString() + ":" + getObject();
+ }
+
+ /**
+ * Use serialVersionUID from JNDI 1.1.1 for interoperability
+ */
+ private static final long serialVersionUID = 8839217842691845890L;
+};
+
Added: trunk/core/src/openjdk/javax/javax/naming/CannotProceedException.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/naming/CannotProceedException.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/naming/CannotProceedException.java 2007-06-23 04:57:09 UTC (rev 3290)
@@ -0,0 +1,287 @@
+/*
+ * Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.naming;
+
+import java.util.Hashtable;
+
+/**
+ * This exception is thrown to indicate that the operation reached
+ * a point in the name where the operation cannot proceed any further.
+ * When performing an operation on a composite name, a naming service
+ * provider may reach a part of the name that does not belong to its
+ * namespace. At that point, it can construct a
+ * CannotProceedException and then invoke methods provided by
+ * javax.naming.spi.NamingManager (such as getContinuationContext())
+ * to locate another provider to continue the operation. If this is
+ * not possible, this exception is raised to the caller of the
+ * context operation.
+ *<p>
+ * If the program wants to handle this exception in particular, it
+ * should catch CannotProceedException explicitly before attempting to
+ * catch NamingException.
+ *<p>
+ * A CannotProceedException instance is not synchronized against concurrent
+ * multithreaded access. Multiple threads trying to access and modify
+ * CannotProceedException should lock the object.
+ *
+ * @author Rosanna Lee
+ * @author Scott Seligman
+ * @version 1.18 07/05/05
+ * @since 1.3
+ */
+
+/*
+ * The serialized form of a CannotProceedException object consists of
+ * the serialized fields of its NamingException superclass, the remaining new
+ * name (a Name object), the environment (a Hashtable), the altName field
+ * (a Name object), and the serialized form of the altNameCtx field.
+ */
+
+
+public class CannotProceedException extends NamingException {
+ /**
+ * Contains the remaining unresolved part of the second
+ * "name" argument to Context.rename().
+ * This information necessary for
+ * continuing the Context.rename() operation.
+ * <p>
+ * This field is initialized to null.
+ * It should not be manipulated directly: it should
+ * be accessed and updated using getRemainingName() and setRemainingName().
+ * @serial
+ *
+ * @see #getRemainingNewName
+ * @see #setRemainingNewName
+ */
+ protected Name remainingNewName = null;
+
+ /**
+ * Contains the environment
+ * relevant for the Context or DirContext method that cannot proceed.
+ * <p>
+ * This field is initialized to null.
+ * It should not be manipulated directly: it should be accessed
+ * and updated using getEnvironment() and setEnvironment().
+ * @serial
+ *
+ * @see #getEnvironment
+ * @see #setEnvironment
+ */
+ protected Hashtable<?,?> environment = null;
+
+ /**
+ * Contains the name of the resolved object, relative
+ * to the context <code>altNameCtx</code>. It is a composite name.
+ * If null, then no name is specified.
+ * See the <code>javax.naming.spi.ObjectFactory.getObjectInstance</code>
+ * method for details on how this is used.
+ * <p>
+ * This field is initialized to null.
+ * It should not be manipulated directly: it should
+ * be accessed and updated using getAltName() and setAltName().
+ * @serial
+ *
+ * @see #getAltName
+ * @see #setAltName
+ * @see #altNameCtx
+ * @see javax.naming.spi.ObjectFactory#getObjectInstance
+ */
+ protected Name altName = null;
+
+ /**
+ * Contains the context relative to which
+ * <code>altName</code> is specified. If null, then the default initial
+ * context is implied.
+ * See the <code>javax.naming.spi.ObjectFactory.getObjectInstance</code>
+ * method for details on how this is used.
+ * <p>
+ * This field is initialized to null.
+ * It should not be manipulated directly: it should
+ * be accessed and updated using getAltNameCtx() and setAltNameCtx().
+ * @serial
+ *
+ * @see #getAltNameCtx
+ * @see #setAltNameCtx
+ * @see #altName
+ * @see javax.naming.spi.ObjectFactory#getObjectInstance
+ */
+ protected Context altNameCtx = null;
+
+ /**
+ * Constructs a new instance of CannotProceedException using an
+ * explanation. All unspecified fields default to null.
+ *
+ * @param explanation A possibly null string containing additional
+ * detail about this exception.
+ * If null, this exception has no detail message.
+ * @see java.lang.Throwable#getMessage
+ */
+ public CannotProceedException(String explanation) {
+ super(explanation);
+ }
+
+ /**
+ * Constructs a new instance of CannotProceedException.
+ * All fields default to null.
+ */
+ public CannotProceedException() {
+ super();
+ }
+
+ /**
+ * Retrieves the environment that was in effect when this exception
+ * was created.
+ * @return Possibly null environment property set.
+ * null means no environment was recorded for this exception.
+ * @see #setEnvironment
+ */
+ public Hashtable<?,?> getEnvironment() {
+ return environment;
+ }
+
+ /**
+ * Sets the environment that will be returned when getEnvironment()
+ * is called.
+ * @param environment A possibly null environment property set.
+ * null means no environment is being recorded for
+ * this exception.
+ * @see #getEnvironment
+ */
+ public void setEnvironment(Hashtable<?,?> environment) {
+ this.environment = environment; // %%% clone it??
+ }
+
+ /**
+ * Retrieves the "remaining new name" field of this exception, which is
+ * used when this exception is thrown during a rename() operation.
+ *
+ * @return The possibly null part of the new name that has not been resolved.
+ * It is a composite name. It can be null, which means
+ * the remaining new name field has not been set.
+ *
+ * @see #setRemainingNewName
+ */
+ public Name getRemainingNewName() {
+ return remainingNewName;
+ }
+
+ /**
+ * Sets the "remaining new name" field of this exception.
+ * This is the value returned by <code>getRemainingNewName()</code>.
+ *<p>
+ * <tt>newName</tt> is a composite name. If the intent is to set
+ * this field using a compound name or string, you must
+ * "stringify" the compound name, and create a composite
+ * name with a single component using the string. You can then
+ * invoke this method using the resulting composite name.
+ *<p>
+ * A copy of <code>newName</code> is made and stored.
+ * Subsequent changes to <code>name</code> does not
+ * affect the copy in this NamingException and vice versa.
+ *
+ * @param newName The possibly null name to set the "remaining new name" to.
+ * If null, it sets the remaining name field to null.
+ *
+ * @see #getRemainingNewName
+ */
+ public void setRemainingNewName(Name newName) {
+ if (newName != null)
+ this.remainingNewName = (Name)(newName.clone());
+ else
+ this.remainingNewName = null;
+ }
+
+ /**
+ * Retrieves the <code>altName</code> field of this exception.
+ * This is the name of the resolved object, relative to the context
+ * <code>altNameCtx</code>. It will be used during a subsequent call to the
+ * <code>javax.naming.spi.ObjectFactory.getObjectInstance</code> method.
+ *
+ * @return The name of the resolved object, relative to
+ * <code>altNameCtx</code>.
+ * It is a composite name. If null, then no name is specified.
+ *
+ * @see #setAltName
+ * @see #getAltNameCtx
+ * @see javax.naming.spi.ObjectFactory#getObjectInstance
+ */
+ public Name getAltName() {
+ return altName;
+ }
+
+ /**
+ * Sets the <code>altName</code> field of this exception.
+ *
+ * @param altName The name of the resolved object, relative to
+ * <code>altNameCtx</code>.
+ * It is a composite name.
+ * If null, then no name is specified.
+ *
+ * @see #getAltName
+ * @see #setAltNameCtx
+ */
+ public void setAltName(Name altName) {
+ this.altName = altName;
+ }
+
+ /**
+ * Retrieves the <code>altNameCtx</code> field of this exception.
+ * This is the context relative to which <code>altName</code> is named.
+ * It will be used during a subsequent call to the
+ * <code>javax.naming.spi.ObjectFactory.getObjectInstance</code> method.
+ *
+ * @return The context relative to which <code>altName</code> is named.
+ * If null, then the default initial context is implied.
+ *
+ * @see #setAltNameCtx
+ * @see #getAltName
+ * @see javax.naming.spi.ObjectFactory#getObjectInstance
+ */
+ public Context getAltNameCtx() {
+ return altNameCtx;
+ }
+
+ /**
+ * Sets the <code>altNameCtx</code> field of this exception.
+ *
+ * @param altNameCtx
+ * The context relative to which <code>altName</code>
+ * is named. If null, then the default initial context
+ * is implied.
+ *
+ * @see #getAltNameCtx
+ * @see #setAltName
+ */
+ public void setAltNameCtx(Context altNameCtx) {
+ this.altNameCtx = altNameCtx;
+ }
+
+
+ /**
+ * Use serialVersionUID from JNDI 1.1.1 for interoperability
+ */
+ private static final long serialVersionUID = 1219724816191576813L;
+}
Added: trunk/core/src/openjdk/javax/javax/naming/CommunicationException.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/naming/CommunicationException.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/naming/CommunicationException.java 2007-06-23 04:57:09 UTC (rev 3290)
@@ -0,0 +1,67 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.naming;
+
+/**
+ * This exception is thrown when the client is
+ * unable to communicate with the directory or naming service.
+ * The inability to communicate with the service might be a result
+ * of many factors, such as network partitioning, hardware or interface problems,
+ * failures on either the client or server side.
+ * This exception is meant to be used to capture such communication problems.
+ * <p>
+ * Synchronization and serialization issues that apply to NamingException
+ * apply directly here.
+ *
+ * @author Rosanna Lee
+ * @author Scott Seligman
+ * @version 1.14 07/05/05
+ * @since 1.3
+ */
+public class CommunicationException extends NamingException {
+ /**
+ * Constructs a new instance of CommunicationException using the
+ * arguments supplied.
+ *
+ * @param explanation Additional detail about this exception.
+ * @see java.lang.Throwable#getMessage
+ */
+ public CommunicationException(String explanation) {
+ super(explanation);
+ }
+
+ /**
+ * Constructs a new instance of CommunicationException.
+ */
+ public CommunicationException() {
+ super();
+ }
+
+ /**
+ * Use serialVersionUID from JNDI 1.1.1 for interoperability
+ */
+ private static final long serialVersionUID = 3618507780299986611L;
+}
Added: trunk/core/src/openjdk/javax/javax/naming/CompositeName.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/naming/CompositeName.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/naming/CompositeName.java 2007-06-23 04:57:09 UTC (rev 3290)
@@ -0,0 +1,631 @@
+/*
+ * Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.naming;
+
+import java.util.Enumeration;
+import java.util.Properties;
+
+/**
+ * This class represents a composite name -- a sequence of
+ * component names spanning multiple namespaces.
+ * Each component is a string name from the namespace of a
+ * naming system. If the component comes from a hierarchical
+ * namespace, that component can be further parsed into
+ * its atomic parts by using the CompoundName class.
+ *<p>
+ * The components of a composite name are numbered. The indexes of a
+ * composite name with N components range from 0 up to, but not including, N.
+ * This range may be written as [0,N).
+ * The most significant component is at index 0.
+ * An empty composite name has no components.
+ *<p>
+ * <h4>JNDI Composite Name Syntax</h4>
+ * JNDI defines a standard string representation for composite names. This
+ * representation is the concatenation of the components of a composite name
+ * from left to right using the component separator (a forward
+ * slash character (/)) to separate each component.
+ * The JNDI syntax defines the following meta characters:
+ * <ul>
+ * <li>escape (backward slash \),
+ * <li>quote characters (single (') and double quotes (")), and
+ * <li>component separator (forward slash character (/)).
+ * </ul>
+ * Any occurrence of a leading quote, an escape preceding any meta character,
+ * an escape at the end of a component, or a component separator character
+ * in an unquoted component must be preceded by an escape character when
+ * that component is being composed into a composite name string.
+ * Alternatively, to avoid adding escape characters as described,
+ * the entire component can be quoted using matching single quotes
+ * or matching double quotes. A single quote occurring within a double-quoted
+ * component is not considered a meta character (and need not be escaped),
+ * and vice versa.
+ *<p>
+ * When two composite names are compared, the case of the characters
+ * is significant.
+ *<p>
+ * A leading component separator (the composite name string begins with
+ * a separator) denotes a leading empty component (a component consisting
+ * of an empty string).
+ * A trailing component separator (the composite name string ends with
+ * a separator) denotes a trailing empty component.
+ * Adjacent component separators denote an empty component.
+ *<p>
+ *<h4>Composite Name Examples</h4>
+ *This table shows examples of some composite names. Each row shows
+ *the string form of a composite name and its corresponding structural form
+ *(<tt>CompositeName</tt>).
+ *<p>
+<table border="1" cellpadding=3 width="70%" summary="examples showing string form of composite name and its corresponding structural form (CompositeName)">
+
+<tr>
+<th>String Name</th>
+<th>CompositeName</th>
+</tr>
+
+<tr>
+<td>
+""
+</td>
+<td>{} (the empty name == new CompositeName("") == new CompositeName())
+</td>
+</tr>
+
+<tr>
+<td>
+"x"
+</td>
+<td>{"x"}
+</td>
+</tr>
+
+<tr>
+<td>
+"x/y"
+</td>
+<td>{"x", "y"}</td>
+</tr>
+
+<tr>
+<td>"x/"</td>
+<td>{"x", ""}</td>
+</tr>
+
+<tr>
+<td>"/x"</td>
+<td>{"", "x"}</td>
+</tr>
+
+<tr>
+<td>"/"</td>
+<td>{""}</td>
+</tr>
+
+<tr>
+<td>"//"</td>
+<td>{"", ""}</td>
+</tr>
+
+<tr><td>"/x/"</td>
+<td>{"", "x", ""}</td>
+</tr>
+
+<tr><td>"x//y"</td>
+<td>{"x", "", "y"}</td>
+</tr>
+</table>
+ * <p>
+ *<h4>Composition Examples</h4>
+ * Here are some composition examples. The right column shows composing
+ * string composite names while the left column shows composing the
+ * corresponding <tt>CompositeName</tt>s. Notice that composing the
+ * string forms of two composite names simply involves concatenating
+ * their string forms together.
+
+<p> <table border="1" cellpadding=3 width="70%" summary="composition examples showing string names and composite names">
+
+<tr>
+<th>String Names</th>
+<th>CompositeNames</th>
+</tr>
+
+<tr>
+<td>
+"x/y" + "/" = x/y/
+</td>
+<td>
+{"x", "y"} + {""} = {"x", "y", ""}
+</td>
+</tr>
+
+<tr>
+<td>
+"" + "x" = "x"
+</td>
+<td>
+{} + {"x"} = {"x"}
+</td>
+</tr>
+
+<tr>
+<td>
+"/" + "x" = "/x"
+</td>
+<td>
+{""} + {"x"} = {"", "x"}
+</td>
+</tr>
+
+<tr>
+<td>
+"x" + "" + "" = "x"
+</td>
+<td>
+{"x"} + {} + {} = {"x"}
+</td>
+</tr>
+
+</table>
+ *<p>
+ *<h4>Multithreaded Access</h4>
+ * A <tt>CompositeName</tt> instance is not synchronized against concurrent
+ * multithreaded access. Multiple threads trying to access and modify a
+ * <tt>CompositeName</tt> should lock the object.
+ *
+ * @author Rosanna Lee
+ * @author Scott Seligman
+ * @version 1.21 07/05/05
+ * @since 1.3
+ */
+
+
+public class CompositeName implements Name {
+
+ private transient NameImpl impl;
+ /**
+ * Constructs a new composite name instance using the components
+ * specified by 'comps'. This protected method is intended to be
+ * to be used by subclasses of CompositeName when they override
+ * methods such as clone(), getPrefix(), getSuffix().
+ *
+ * @param comps A non-null enumeration containing the components for the new
+ * composite name. Each element is of class String.
+ * The enumeration will be consumed to extract its
+ * elements.
+ */
+ protected CompositeName(Enumeration<String> comps) {
+ impl = new NameImpl(null, comps); // null means use default syntax
+ }
+
+ /**
+ * Constructs a new composite name instance by parsing the string n
+ * using the composite name syntax (left-to-right, slash separated).
+ * The composite name syntax is described in detail in the class
+ * description.
+ *
+ * @param n The non-null string to parse.
+ * @exception InvalidNameException If n has invalid composite name syntax.
+ */
+ public CompositeName(String n) throws InvalidNameException {
+ impl = new NameImpl(null, n); // null means use default syntax
+ }
+
+ /**
+ * Constructs a new empty composite name. Such a name returns true
+ * when <code>isEmpty()</code> is invoked on it.
+ */
+ public CompositeName() {
+ impl = new NameImpl(null); // null means use default syntax
+ }
+
+ /**
+ * Generates the string representation of this composite name.
+ * The string representation consists of enumerating in order
+ * each component of the composite name and separating
+ * each component by a forward slash character. Quoting and
+ * escape characters are applied where necessary according to
+ * the JNDI syntax, which is described in the class description.
+ * An empty component is represented by an empty string.
+ *
+ * The string representation thus generated can be passed to
+ * the CompositeName constructor to create a new equivalent
+ * composite name.
+ *
+ * @return A non-null string representation of this composite name.
+ */
+ public String toString() {
+ return impl.toString();
+ }
+
+ /**
+ * Determines whether two composite names are equal.
+ * If obj is null or not a composite name, false is returned.
+ * Two composite names are equal if each component in one is equal
+ * to the corresponding component in the other. This implies
+ * both have the same number of components, and each component's
+ * equals() test against the corresponding component in the other name
+ * returns true.
+ *
+ * @param obj The possibly null object to compare against.
+ * @return true if obj is equal to this composite name, false otherwise.
+ * @see #hashCode
+ */
+ public boolean equals(Object obj) {
+ return (obj != null &&
+ obj instanceof CompositeName &&
+ impl.equals(((CompositeName)obj).impl));
+ }
+
+ /**
+ * Computes the hash code of this composite name.
+ * The hash code is the sum of the hash codes of individual components
+ * of this composite name.
+ *
+ * @return An int representing the hash code of this name.
+ * @see #equals
+ */
+ public int hashCode() {
+ return impl.hashCode();
+ }
+
+
+ /**
+ * Compares this CompositeName with the specified Object for order.
+ * Returns a
+ * negative integer, zero, or a positive integer as this Name is less
+ * than, equal to, or greater than the given Object.
+ * <p>
+ * If obj is null or not an instance of CompositeName, ClassCastException
+ * is thrown.
+ * <p>
+ * See equals() for what it means for two composite names to be equal.
+ * If two composite names are equal, 0 is returned.
+ * <p>
+ * Ordering of composite names follows the lexicographical rules for
+ * string comparison, with the extension that this applies to all
+ * the components in the composite name. The effect is as if all the
+ * components were lined up in their specified ordered and the
+ * lexicographical rules applied over the two line-ups.
+ * If this composite name is "lexicographically" lesser than obj,
+ * a negative number is returned.
+ * If this composite name is "lexicographically" greater than obj,
+ * a positive number is returned.
+ * @param obj The non-null object to compare against.
+ *
+ * @return a negative integer, zero, or a positive integer as this Name
+ * is less than, equal to, or greater than the given Object.
+ * @exception ClassCastException if obj is not a CompositeName.
+ */
+ public int compareTo(Object obj) {
+ if (!(obj instanceof CompositeName)) {
+ throw new ClassCastException("Not a CompositeName");
+ }
+ return impl.compareTo(((CompositeName)obj).impl);
+ }
+
+ /**
+ * Generates a copy of this composite name.
+ * Changes to the components of this composite name won't
+ * affect the new copy and vice versa.
+ *
+ * @return A non-null copy of this composite name.
+ */
+ public Object clone() {
+ return (new CompositeName(getAll()));
+ }
+
+ /**
+ * Retrieves the number of components in this composite name.
+ *
+ * @return The nonnegative number of components in this composite name.
+ */
+ public int size() {
+ return (impl.size());
+ }
+
+ /**
+ * Determines whether this composite name is empty. A composite name
+ * is empty if it has zero components.
+ *
+ * @return true if this composite name is empty, false otherwise.
+ */
+ public boolean isEmpty() {
+ return (impl.isEmpty());
+ }
+
+ /**
+ * Retrieves the components of this composite name as an enumeration
+ * of strings.
+ * The effects of updates to this composite name on this enumeration
+ * is undefined.
+ *
+ * @return A non-null enumeration of the components of
+ * this composite name. Each element of the enumeration is of
+ * class String.
+ */
+ public Enumeration<String> getAll() {
+ return (impl.getAll());
+ }
+
+ /**
+ * Retrieves a component of this composite name.
+ *
+ * @param posn The 0-based index of the component to retrieve.
+ * Must be in the range [0,size()).
+ * @return The non-null component at index posn.
+ * @exception ArrayIndexOutOfBoundsException if posn is outside the
+ * specified range.
+ */
+ public String get(int posn) {
+ return (impl.get(posn));
+ }
+
+ /**
+ * Creates a composite name whose components consist of a prefix of the
+ * components in this composite name. Subsequent changes to
+ * this composite name does not affect the name that is returned.
+ *
+ * @param posn The 0-based index of the component at which to stop.
+ * Must be in the range [0,size()].
+ * @return A composite name consisting of the components at indexes in
+ * the range [0,posn).
+ * @exception ArrayIndexOutOfBoundsException
+ * If posn is outside the specified range.
+ */
+ public Name getPrefix(int posn) {
+ Enumeration comps = impl.getPrefix(posn);
+ return (new CompositeName(comps));
+ }
+
+ /**
+ * Creates a composite name whose components consist of a suffix of the
+ * components in this composite name. Subsequent changes to
+ * this composite name does not affect the name that is returned.
+ *
+ * @param posn The 0-based index of the component at which to start.
+ * Must be in the range [0,size()].
+ * @return A composite name consisting of the components at indexes in
+ * the range [posn,size()). If posn is equal to
+ * size(), an empty composite name is returned.
+ * @exception ArrayIndexOutOfBoundsException
+ * If posn is outside the specified range.
+ */
+ public Name getSuffix(int posn) {
+ Enumeration comps = impl....
[truncated message content] |
|
From: <ls...@us...> - 2007-06-23 04:55:42
|
Revision: 3289
http://jnode.svn.sourceforge.net/jnode/?rev=3289&view=rev
Author: lsantha
Date: 2007-06-22 21:55:40 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Modified Paths:
--------------
trunk/core/src/classpath/javax/javax/crypto/Cipher.java
Removed Paths:
-------------
trunk/core/src/classpath/javax/javax/naming/
trunk/core/src/classpath/javax/javax/rmi/
Modified: trunk/core/src/classpath/javax/javax/crypto/Cipher.java
===================================================================
--- trunk/core/src/classpath/javax/javax/crypto/Cipher.java 2007-06-23 04:54:32 UTC (rev 3288)
+++ trunk/core/src/classpath/javax/javax/crypto/Cipher.java 2007-06-23 04:55:40 UTC (rev 3289)
@@ -1145,4 +1145,31 @@
}
return cipherSpi.engineWrap(key);
}
+
+ //jnode openjdk
+ /**
+ * Returns the maximum key length for the specified transformation
+ * according to the installed JCE jurisdiction policy files. If
+ * JCE unlimited strength jurisdiction policy files are installed,
+ * Integer.MAX_VALUE will be returned.
+ * For more information on default key size in JCE jurisdiction
+ * policy files, please see Appendix E in the
+ * <a href=
+ * "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#AppE">
+ * Java Cryptography Architecture Reference Guide</a>.
+ *
+ * @param transformation the cipher transformation.
+ * @return the maximum key length in bits or Integer.MAX_VALUE.
+ * @exception NullPointerException if <code>transformation</code> is null.
+ * @exception NoSuchAlgorithmException if <code>transformation</code>
+ * is not a valid transformation, i.e. in the form of "algorithm" or
+ * "algorithm/mode/padding".
+ * @since 1.5
+ */
+ public static final int getMaxAllowedKeyLength(String transformation)
+ throws NoSuchAlgorithmException
+ {
+ return 0;
+ }
+
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-23 04:54:33
|
Revision: 3288
http://jnode.svn.sourceforge.net/jnode/?rev=3288&view=rev
Author: lsantha
Date: 2007-06-22 21:54:32 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/com/com/sun/corba/
trunk/core/src/openjdk/com/com/sun/corba/se/
trunk/core/src/openjdk/com/com/sun/corba/se/impl/
trunk/core/src/openjdk/com/com/sun/corba/se/impl/orbutil/
trunk/core/src/openjdk/com/com/sun/corba/se/impl/orbutil/GetPropertyAction.java
trunk/core/src/openjdk/com/com/sun/jndi/
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNBindingEnumeration.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNCtx.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNCtxFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNNameParser.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CorbanameUrl.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/ExceptionMapper.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/IiopUrl.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/OrbReuseTracker.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/RemoteToCorba.java
trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/jndiprovider.properties
trunk/core/src/openjdk/com/com/sun/jndi/dns/
trunk/core/src/openjdk/com/com/sun/jndi/dns/DnsClient.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/DnsContext.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/DnsContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/DnsName.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/DnsNameParser.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/DnsUrl.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/Header.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/NameNode.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/Resolver.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/ResourceRecord.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/ResourceRecords.java
trunk/core/src/openjdk/com/com/sun/jndi/dns/ZoneNode.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/
trunk/core/src/openjdk/com/com/sun/jndi/ldap/BasicControl.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/Ber.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/BerDecoder.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/BerEncoder.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/BindingWithControls.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/ClientId.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/Connection.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/DefaultResponseControlFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/DigestClientId.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/EntryChangeResponseControl.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/EventQueue.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/EventSupport.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/Filter.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapAttribute.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapBindingEnumeration.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapClient.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapClientFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapCtx.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapCtxFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapEntry.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapName.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapNameParser.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapNamingEnumeration.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapPoolManager.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapReferralContext.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapReferralException.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapRequest.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapResult.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapSchemaCtx.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapSchemaParser.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapSearchEnumeration.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/LdapURL.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/ManageReferralControl.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/NameClassPairWithControls.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/NamingEventNotifier.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/NotifierArgs.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/Obj.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/PersistentSearchControl.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/ReferralEnumeration.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/SearchResultWithControls.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/ServiceLocator.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/SimpleClientId.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/UnsolicitedResponseImpl.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/VersionHelper.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/VersionHelper12.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/ext/
trunk/core/src/openjdk/com/com/sun/jndi/ldap/ext/StartTlsResponseImpl.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/jndiprovider.properties
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/ConnectionDesc.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/Connections.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/ConnectionsRef.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/ConnectionsWeakRef.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/Pool.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/PoolCallback.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/PoolCleaner.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/PooledConnection.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/pool/PooledConnectionFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/sasl/
trunk/core/src/openjdk/com/com/sun/jndi/ldap/sasl/DefaultCallbackHandler.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/sasl/LdapSasl.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/sasl/SaslInputStream.java
trunk/core/src/openjdk/com/com/sun/jndi/ldap/sasl/SaslOutputStream.java
trunk/core/src/openjdk/com/com/sun/jndi/rmi/
trunk/core/src/openjdk/com/com/sun/jndi/rmi/registry/
trunk/core/src/openjdk/com/com/sun/jndi/rmi/registry/ReferenceWrapper.java
trunk/core/src/openjdk/com/com/sun/jndi/rmi/registry/RegistryContext.java
trunk/core/src/openjdk/com/com/sun/jndi/rmi/registry/RegistryContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/rmi/registry/RemoteReference.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/corba/
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/corba/CorbaUtils.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/AtomicContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/AtomicDirContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/ComponentContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/ComponentDirContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/Continuation.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/HeadTail.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/PartialCompositeDirContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/ctx/StringHeadTail.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/AttrFilter.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/ContainmentFilter.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/ContextEnumerator.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/DirSearch.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/HierMemDirCtx.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/LazySearchEnumerationImpl.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/dir/SearchFilter.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/url/
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/url/GenericURLContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/url/GenericURLDirContext.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/url/Uri.java
trunk/core/src/openjdk/com/com/sun/jndi/toolkit/url/UrlUtil.java
trunk/core/src/openjdk/com/com/sun/jndi/url/
trunk/core/src/openjdk/com/com/sun/jndi/url/corbaname/
trunk/core/src/openjdk/com/com/sun/jndi/url/corbaname/corbanameURLContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/url/dns/
trunk/core/src/openjdk/com/com/sun/jndi/url/dns/dnsURLContext.java
trunk/core/src/openjdk/com/com/sun/jndi/url/dns/dnsURLContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/url/iiop/
trunk/core/src/openjdk/com/com/sun/jndi/url/iiop/iiopURLContext.java
trunk/core/src/openjdk/com/com/sun/jndi/url/iiop/iiopURLContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/url/iiopname/
trunk/core/src/openjdk/com/com/sun/jndi/url/iiopname/iiopnameURLContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/url/ldap/
trunk/core/src/openjdk/com/com/sun/jndi/url/ldap/ldapURLContext.java
trunk/core/src/openjdk/com/com/sun/jndi/url/ldap/ldapURLContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/url/ldaps/
trunk/core/src/openjdk/com/com/sun/jndi/url/ldaps/ldapsURLContextFactory.java
trunk/core/src/openjdk/com/com/sun/jndi/url/rmi/
trunk/core/src/openjdk/com/com/sun/jndi/url/rmi/rmiURLContext.java
trunk/core/src/openjdk/com/com/sun/jndi/url/rmi/rmiURLContextFactory.java
trunk/core/src/openjdk/com/com/sun/naming/
trunk/core/src/openjdk/com/com/sun/naming/internal/
trunk/core/src/openjdk/com/com/sun/naming/internal/FactoryEnumeration.java
trunk/core/src/openjdk/com/com/sun/naming/internal/NamedWeakReference.java
trunk/core/src/openjdk/com/com/sun/naming/internal/ResourceManager.java
trunk/core/src/openjdk/com/com/sun/naming/internal/VersionHelper.java
trunk/core/src/openjdk/com/com/sun/naming/internal/VersionHelper12.java
Added: trunk/core/src/openjdk/com/com/sun/corba/se/impl/orbutil/GetPropertyAction.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/corba/se/impl/orbutil/GetPropertyAction.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/corba/se/impl/orbutil/GetPropertyAction.java 2007-06-23 04:54:32 UTC (rev 3288)
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.corba.se.impl.orbutil ;
+
+/**
+ * A convenience class for retrieving the string value of a system
+ * property as a privileged action. This class is directly copied
+ * from sun.security.action.GetPropertyAction in order to avoid
+ * depending on the sun.security.action package.
+ *
+ * <p>An instance of this class can be used as the argument of
+ * <code>AccessController.doPrivileged</code>.
+ *
+ * <p>The following code retrieves the value of the system
+ * property named <code>"prop"</code> as a privileged action: <p>
+ *
+ * <pre>
+ * String s = (String) java.security.AccessController.doPrivileged(
+ * new GetPropertyAction("prop"));
+ * </pre>
+ *
+ * @author Roland Schemers
+ * @author Ken Cavanaugh
+ * @see java.security.PrivilegedAction
+ * @see java.security.AccessController
+ */
+
+public class GetPropertyAction implements java.security.PrivilegedAction {
+ private String theProp;
+ private String defaultVal;
+
+ /**
+ * Constructor that takes the name of the system property whose
+ * string value needs to be determined.
+ *
+ * @param theProp the name of the system property.
+ */
+ public GetPropertyAction(String theProp) {
+ this.theProp = theProp;
+ }
+
+ /**
+ * Constructor that takes the name of the system property and the default
+ * value of that property.
+ *
+ * @param theProp the name of the system property.
+ * @param defaulVal the default value.
+ */
+ public GetPropertyAction(String theProp, String defaultVal) {
+ this.theProp = theProp;
+ this.defaultVal = defaultVal;
+ }
+
+ /**
+ * Determines the string value of the system property whose
+ * name was specified in the constructor.
+ *
+ * @return the string value of the system property,
+ * or the default value if there is no property with that key.
+ */
+ public Object run() {
+ String value = System.getProperty(theProp);
+ return (value == null) ? defaultVal : value;
+ }
+}
Added: trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNBindingEnumeration.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNBindingEnumeration.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNBindingEnumeration.java 2007-06-23 04:54:32 UTC (rev 3288)
@@ -0,0 +1,237 @@
+/*
+ * Copyright 1999-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.jndi.cosnaming;
+
+import javax.naming.*;
+import javax.naming.spi.NamingManager;
+
+import java.util.NoSuchElementException;
+import java.util.Hashtable;
+
+import org.omg.CosNaming.*;
+import org.omg.CosNaming.NamingContextPackage.*;
+import org.omg.CORBA.*;
+
+/**
+ * Implements the JNDI NamingEnumeration interface for COS
+ * Naming. Gets hold of a list of bindings from the COS Naming Server
+ * and allows the client to iterate through them.
+ *
+ * @author Raj Krishnamurthy
+ * @author Rosanna Lee
+ * @version 1.17 07/05/05
+ */
+
+final class CNBindingEnumeration implements NamingEnumeration {
+
+ private static final int DEFAULT_BATCHSIZE = 100;
+ private BindingListHolder _bindingList; // list of bindings
+ private BindingIterator _bindingIter; // iterator for getting list of bindings
+ private int counter; // pointer in _bindingList
+ private int batchsize = DEFAULT_BATCHSIZE; // how many to ask for each time
+ private CNCtx _ctx; // ctx to list
+ private Hashtable _env; // environment for getObjectInstance
+ private boolean more = false; // iterator done?
+ private boolean isLookedUpCtx = false; // iterating on a context beneath this context ?
+
+ /**
+ * Creates a CNBindingEnumeration object.
+ * @param ctx Context to enumerate
+ */
+ CNBindingEnumeration(CNCtx ctx, boolean isLookedUpCtx, Hashtable env) {
+ // Get batch size to use
+ String batch = (env != null ?
+ (String)env.get(javax.naming.Context.BATCHSIZE) : null);
+ if (batch != null) {
+ try {
+ batchsize = Integer.parseInt(batch);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Batch size not numeric: " + batch);
+ }
+ }
+ _ctx = ctx;
+ _ctx.incEnumCount();
+ this.isLookedUpCtx = isLookedUpCtx;
+ _env = env;
+ _bindingList = new BindingListHolder();
+ BindingIteratorHolder _bindingIterH = new BindingIteratorHolder();
+
+ // Perform listing and request that bindings be returned in _bindingIter
+ // Upon return,_bindingList returns a zero length list
+ _ctx._nc.list(0, _bindingList, _bindingIterH);
+
+ _bindingIter = _bindingIterH.value;
+
+ // Get first batch using _bindingIter
+ if (_bindingIter != null) {
+ more = _bindingIter.next_n(batchsize, _bindingList);
+ } else {
+ more = false;
+ }
+ counter = 0;
+ }
+
+ /**
+ * Returns the next binding in the list.
+ * @exception NamingException any naming exception.
+ */
+
+ public java.lang.Object next() throws NamingException {
+ if (more && counter >= _bindingList.value.length) {
+ getMore();
+ }
+ if (more && counter < _bindingList.value.length) {
+ org.omg.CosNaming.Binding bndg = _bindingList.value[counter];
+ counter++;
+ return mapBinding(bndg);
+ } else {
+ throw new NoSuchElementException();
+ }
+ }
+
+
+ /**
+ * Returns true or false depending on whether there are more bindings.
+ * @return boolean value
+ */
+
+ public boolean hasMore() throws NamingException {
+ // If there's more, check whether current bindingList has been exhausted,
+ // and if so, try to get more.
+ // If no more, just say so.
+ return more ? (counter < _bindingList.value.length || getMore()) : false;
+ }
+
+ /**
+ * Returns true or false depending on whether there are more bindings.
+ * Need to define this to satisfy the Enumeration api requirement.
+ * @return boolean value
+ */
+
+ public boolean hasMoreElements() {
+ try {
+ return hasMore();
+ } catch (NamingException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns the next binding in the list.
+ * @exception NoSuchElementException Thrown when the end of the
+ * list is reached.
+ */
+
+ public java.lang.Object nextElement() {
+ try {
+ return next();
+ } catch (NamingException ne) {
+ throw new NoSuchElementException();
+ }
+ }
+
+ public void close() throws NamingException {
+ more = false;
+ if (_bindingIter != null) {
+ _bindingIter.destroy();
+ _bindingIter = null;
+ }
+ if (_ctx != null) {
+ _ctx.decEnumCount();
+
+ /**
+ * context was obtained by CNCtx, the user doesn't have a handle to
+ * it, close it as we are done enumerating through the context
+ */
+ if (isLookedUpCtx) {
+ _ctx.close();
+ }
+ _ctx = null;
+ }
+ }
+
+ protected void finalize() {
+ try {
+ close();
+ } catch (NamingException e) {
+ // ignore failures
+ }
+ }
+
+ /**
+ * Get the next batch using _bindingIter. Update the 'more' field.
+ */
+ private boolean getMore() throws NamingException {
+ try {
+ more = _bindingIter.next_n(batchsize, _bindingList);
+ counter = 0; // reset
+ } catch (Exception e) {
+ more = false;
+ NamingException ne = new NamingException(
+ "Problem getting binding list");
+ ne.setRootCause(e);
+ throw ne;
+ }
+ return more;
+ }
+
+ /**
+ * Constructs a JNDI Binding object from the COS Naming binding
+ * object.
+ * @exception NameNotFound No objects under the name.
+ * @exception CannotProceed Unable to obtain a continuation context
+ * @exception InvalidName Name not understood.
+ * @exception NamingException One of the above.
+ */
+
+ private javax.naming.Binding mapBinding(org.omg.CosNaming.Binding bndg)
+ throws NamingException {
+ java.lang.Object obj = _ctx.callResolve(bndg.binding_name);
+
+ Name cname = CNNameParser.cosNameToName(bndg.binding_name);
+
+ try {
+ obj = NamingManager.getObjectInstance(obj, cname, _ctx, _env);
+ } catch (NamingException e) {
+ throw e;
+ } catch (Exception e) {
+ NamingException ne = new NamingException(
+ "problem generating object using object factory");
+ ne.setRootCause(e);
+ throw ne;
+ }
+
+ // Use cname.toString() instead of bindingName because the name
+ // in the binding should be a composite name
+ String cnameStr = cname.toString();
+ javax.naming.Binding jbndg = new javax.naming.Binding(cnameStr, obj);
+
+ NameComponent[] comps = _ctx.makeFullName(bndg.binding_name);
+ String fullName = CNNameParser.cosNameToInsString(comps);
+ jbndg.setNameInNamespace(fullName);
+ return jbndg;
+ }
+}
Added: trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNCtx.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNCtx.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/jndi/cosnaming/CNCtx.java 2007-06-23 04:54:32 UTC (rev 3288)
@@ -0,0 +1,1161 @@
+/*
+ * Copyright 1999-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.jndi.cosnaming;
+
+import javax.naming.*;
+import javax.naming.spi.NamingManager;
+import javax.naming.spi.ResolveResult;
+
+import java.util.Hashtable;
+import java.util.Vector;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.BufferedReader;
+import java.io.IOException;
+
+import org.omg.CosNaming.*;
+import org.omg.CosNaming.NamingContextPackage.*;
+import org.omg.CORBA.*;
+
+import com.sun.jndi.toolkit.corba.CorbaUtils;
+
+// Needed for creating default ORB
+import java.applet.Applet;
+
+/**
+ * Provides a bridge to the CosNaming server provided by
+ * JavaIDL. This class provides the InitialContext from CosNaming.
+ *
+ * @author Raj Krishnamurthy
+ * @author Rosanna Lee
+ * @version 1.23 07/05/05
+ */
+
+public class CNCtx implements javax.naming.Context {
+
+ private final static boolean debug = false;
+
+ ORB _orb; // used by ExceptionMapper and RMI/IIOP factory
+ public NamingContext _nc; // public for accessing underlying NamingContext
+ private NameComponent[] _name = null;
+
+ Hashtable _env; // used by ExceptionMapper
+ static final CNNameParser parser = new CNNameParser();
+
+ private static final String FED_PROP = "com.sun.jndi.cosnaming.federation";
+ boolean federation = false;
+
+ // Reference counter for tracking _orb references
+ OrbReuseTracker orbTracker = null;
+ int enumCount;
+ boolean isCloseCalled = false;
+
+ /**
+ * Create a CNCtx object. Gets the initial naming
+ * reference for the COS Naming Service from the ORB.
+ * The ORB can be passed in via the java.naming.corba.orb property
+ * or be created using properties in the environment properties.
+ * @param env Environment properties for initializing name service.
+ * @exception NamingException Cannot initialize ORB or naming context.
+ */
+ CNCtx(Hashtable env) throws NamingException {
+ if (env != null) {
+ env = (Hashtable) env.clone();
+ }
+ _env = env;
+ federation = "true".equals(env != null ? env.get(FED_PROP) : null);
+ initOrbAndRootContext(env);
+ }
+
+ private CNCtx() {
+ }
+
+ /**
+ * This method is used by the iiop and iiopname URL Context factories.
+ */
+ public static ResolveResult createUsingURL(String url, Hashtable env)
+ throws NamingException {
+ CNCtx ctx = new CNCtx();
+ if (env != null) {
+ env = (Hashtable) env.clone();
+ }
+ ctx._env = env;
+ String rest = ctx.initUsingUrl(
+ env != null ?
+ (org.omg.CORBA.ORB) env.get("java.naming.corba.orb")
+ : null,
+ url, env);
+
+ // rest is the INS name
+ // Return the parsed form to prevent subsequent lookup
+ // from parsing the string as a composite name
+ // The caller should be aware that a toString() of the name
+ // will yield its INS syntax, rather than a composite syntax
+ return new ResolveResult(ctx, parser.parse(rest));
+ }
+
+ /**
+ * Creates a CNCtx object which supports the javax.naming
+ * apis given a COS Naming Context object.
+ * @param orb The ORB used by this context
+ * @param tracker The ORB reuse tracker for tracking references to the
+ * orb object
+ * @param nctx The COS NamingContext object associated with this context
+ * @param name The name of this context relative to the root
+ */
+
+ CNCtx(ORB orb, OrbReuseTracker tracker, NamingContext nctx, Hashtable env,
+ NameComponent[]name)
+ throws NamingException {
+ if (orb == null || nctx == null)
+ throw new ConfigurationException(
+ "Must supply ORB or NamingContext");
+ _orb = orb;
+ orbTracker = tracker;
+ if (orbTracker != null) {
+ orbTracker.incRefCount();
+ }
+ _nc = nctx;
+ _env = env;
+ _name = name;
+ federation = "true".equals(env != null ? env.get(FED_PROP) : null);
+ }
+
+ NameComponent[] makeFullName(NameComponent[] child) {
+ if (_name == null || _name.length == 0) {
+ return child;
+ }
+ NameComponent[] answer = new NameComponent[_name.length+child.length];
+
+ // parent
+ System.arraycopy(_name, 0, answer, 0, _name.length);
+
+ // child
+ System.arraycopy(child, 0, answer, _name.length, child.length);
+ return answer;
+ }
+
+
+ public String getNameInNamespace() throws NamingException {
+ if (_name == null || _name.length == 0) {
+ return "";
+ }
+ return CNNameParser.cosNameToInsString(_name);
+ }
+
+ /**
+ * These are the URL schemes that need to be processed.
+ * IOR and corbaloc URLs can be passed directly to ORB.string_to_object()
+ */
+ private static boolean isCorbaUrl(String url) {
+ return url.startsWith("iiop://")
+ || url.startsWith("iiopname://")
+ || url.startsWith("corbaname:")
+ ;
+ }
+
+ /**
+ * Initializes the COS Naming Service.
+ * This method initializes the three instance fields:
+ * _nc : The root naming context.
+ * _orb: The ORB to use for connecting RMI/IIOP stubs and for
+ * getting the naming context (_nc) if one was not specified
+ * explicitly via PROVIDER_URL.
+ * _name: The name of the root naming context.
+ *<p>
+ * _orb is obtained from java.naming.corba.orb if it has been set.
+ * Otherwise, _orb is created using the host/port from PROVIDER_URL
+ * (if it contains an "iiop" or "iiopname" URL), or from initialization
+ * properties specified in env.
+ *<p>
+ * _nc is obtained from the IOR stored in PROVIDER_URL if it has been
+ * set and does not contain an "iiop" or "iiopname" URL. It can be
+ * a stringified IOR, "corbaloc" URL, "corbaname" URL,
+ * or a URL (such as file/http/ftp) to a location
+ * containing a stringified IOR. If PROVIDER_URL has not been
+ * set in this way, it is obtained from the result of
+ * ORB.resolve_initial_reference("NameService");
+ *<p>
+ * _name is obtained from the "iiop", "iiopname", or "corbaname" URL.
+ * It is the empty name by default.
+ *
+ * @param env Environment The possibly null environment.
+ * @exception NamingException When an error occurs while initializing the
+ * ORB or the naming context.
+ */
+ private void initOrbAndRootContext(Hashtable env) throws NamingException {
+ org.omg.CORBA.ORB inOrb = null;
+ String ncIor = null;
+
+ if (env != null) {
+ inOrb = (org.omg.CORBA.ORB) env.get("java.naming.corba.orb");
+ }
+
+ // Extract PROVIDER_URL from environment
+ String provUrl = null;
+ if (env != null) {
+ provUrl = (String)env.get(javax.naming.Context.PROVIDER_URL);
+ }
+
+ if (provUrl != null && !isCorbaUrl(provUrl)) {
+ // Initialize the root naming context by using the IOR supplied
+ // in the PROVIDER_URL
+ ncIor = getStringifiedIor(provUrl);
+
+ if (inOrb == null) {
+
+ // no ORB instance specified; create one using env and defaults
+ inOrb = CorbaUtils.getOrb(null, -1, env);
+ orbTracker = new OrbReuseTracker(inOrb);
+ }
+ setOrbAndRootContext(inOrb, ncIor);
+ } else if (provUrl != null) {
+ // Initialize the root naming context by using the URL supplied
+ // in the PROVIDER_URL
+ String insName = initUsingUrl(inOrb, provUrl, env);
+
+ // If name supplied in URL, resolve it to a NamingContext
+ if (insName.length() > 0) {
+ _name = parser.nameToCosName(parser.parse(insName));
+ try {
+ org.omg.CORBA.Object obj = _nc.resolve(_name);
+ _nc = NamingContextHelper.narrow(obj);
+ if (_nc == null) {
+ throw new ConfigurationException(insName +
+ " does not name a NamingContext");
+ }
+ } catch (org.omg.CORBA.BAD_PARAM e) {
+ throw new ConfigurationException(insName +
+ " does not name a NamingContext");
+ } catch (Exception e) {
+ throw ExceptionMapper.mapException(e, this, _name);
+ }
+ }
+ } else {
+ // No PROVIDER_URL supplied; initialize using defaults
+ if (inOrb == null) {
+
+ // No ORB instance specified; create one using env and defaults
+ inOrb = CorbaUtils.getOrb(null, -1, env);
+ orbTracker = new OrbReuseTracker(inOrb);
+ if (debug) {
+ System.err.println("Getting default ORB: " + inOrb + env);
+ }
+ }
+ setOrbAndRootContext(inOrb, (String)null);
+ }
+ }
+
+
+ private String initUsingUrl(ORB orb, String url, Hashtable env)
+ throws NamingException {
+ if (url.startsWith("iiop://") || url.startsWith("iiopname://")) {
+ return initUsingIiopUrl(orb, url, env);
+ } else {
+ return initUsingCorbanameUrl(orb, url, env);
+ }
+ }
+
+ /**
+ * Handles "iiop" and "iiopname" URLs (INS 98-10-11)
+ */
+ private String initUsingIiopUrl(ORB defOrb, String url, Hashtable env)
+ throws NamingException {
+ try {
+ IiopUrl parsedUrl = new IiopUrl(url);
+
+ Vector addrs = parsedUrl.getAddresses();
+ IiopUrl.Address addr;
+ NamingException savedException = null;
+
+ for (int i = 0; i < addrs.size(); i++) {
+ addr = (IiopUrl.Address)addrs.elementAt(i);
+
+ try {
+ if (defOrb != null) {
+ try {
+ String tmpUrl = "corbaloc:iiop:" + addr.host
+ + ":" + addr.port + "/NameService";
+ if (debug) {
+ System.err.println("Using url: " + tmpUrl);
+ }
+ org.omg.CORBA.Object rootCtx =
+ defOrb.string_to_object(tmpUrl);
+ setOrbAndRootContext(defOrb, rootCtx);
+ return parsedUrl.getStringName();
+ } catch (Exception e) {} // keep going
+ }
+
+ // Get ORB
+ if (debug) {
+ System.err.println("Getting ORB for " + addr.host
+ + " and port " + addr.port);
+ }
+
+ // Get ORB
+ ORB orb = CorbaUtils.getOrb(addr.host, addr.port, env);
+ orbTracker = new OrbReuseTracker(orb);
+
+ // Assign to fields
+ setOrbAndRootContext(orb, (String)null);
+ return parsedUrl.getStringName();
+
+ } catch (NamingException ne) {
+ savedException = ne;
+ }
+ }
+ if (savedException != null) {
+ throw savedException;
+ } else {
+ throw new ConfigurationException("Problem with URL: " + url);
+ }
+ } catch (MalformedURLException e) {
+ throw new ConfigurationException(e.getMessage());
+ }
+ }
+
+ /**
+ * Initializes using "corbaname" URL (INS 99-12-03)
+ */
+ private String initUsingCorbanameUrl(ORB orb, String url, Hashtable env)
+ throws NamingException {
+ try {
+ CorbanameUrl parsedUrl = new CorbanameUrl(url);
+
+ String corbaloc = parsedUrl.getLocation();
+ String cosName = parsedUrl.getStringName();
+
+ if (orb == null) {
+
+ // No ORB instance specified; create one using env and defaults
+ orb = CorbaUtils.getOrb(null, -1, env);
+ orbTracker = new OrbReuseTracker(orb);
+ }
+ setOrbAndRootContext(orb, corbaloc);
+
+ return parsedUrl.getStringName();
+ } catch (MalformedURLException e) {
+ throw new ConfigurationException(e.getMessage());
+ }
+ }
+
+ private void setOrbAndRootContext(ORB orb, String ncIor)
+ throws NamingException {
+ _orb = orb;
+ try {
+ org.omg.CORBA.Object ncRef;
+ if (ncIor != null) {
+ if (debug) {
+ System.err.println("Passing to string_to_object: " + ncIor);
+ }
+ ncRef = _orb.string_to_object(ncIor);
+ } else {
+ ncRef = _orb.resolve_initial_references("NameService");
+ }
+ if (debug) {
+ System.err.println("Naming Context Ref: " + ncRef);
+ }
+ _nc = NamingContextHelper.narrow(ncRef);
+ if (_nc == null) {
+ if (ncIor != null) {
+ throw new ConfigurationException(
+ "Cannot convert IOR to a NamingContext: " + ncIor);
+ } else {
+ throw new ConfigurationException(
+"ORB.resolve_initial_references(\"NameService\") does not return a NamingContext");
+ }
+ }
+ } catch (org.omg.CORBA.ORBPackage.InvalidName in) {
+ NamingException ne =
+ new ConfigurationException(
+"COS Name Service not registered with ORB under the name 'NameService'");
+ ne.setRootCause(in);
+ throw ne;
+ } catch (org.omg.CORBA.COMM_FAILURE e) {
+ NamingException ne =
+ new CommunicationException("Cannot connect to ORB");
+ ne.setRootCause(e);
+ throw ne;
+ } catch (org.omg.CORBA.BAD_PARAM e) {
+ NamingException ne = new ConfigurationException(
+ "Invalid URL or IOR: " + ncIor);
+ ne.setRootCause(e);
+ throw ne;
+ } catch (org.omg.CORBA.INV_OBJREF e) {
+ NamingException ne = new ConfigurationException(
+ "Invalid object reference: " + ncIor);
+ ne.setRootCause(e);
+ throw ne;
+ }
+ }
+
+ private void setOrbAndRootContext(ORB orb, org.omg.CORBA.Object ncRef)
+ throws NamingException {
+ _orb = orb;
+ try {
+ _nc = NamingContextHelper.narrow(ncRef);
+ if (_nc == null) {
+ throw new ConfigurationException(
+ "Cannot convert object reference to NamingContext: " + ncRef);
+ }
+ } catch (org.omg.CORBA.COMM_FAILURE e) {
+ NamingException ne =
+ new CommunicationException("Cannot connect to ORB");
+ ne.setRootCause(e);
+ throw ne;
+ }
+ }
+
+ private String getStringifiedIor(String url) throws NamingException {
+ if (url.startsWith("IOR:") || url.startsWith("corbaloc:")) {
+ return url;
+ } else {
+ InputStream in = null;
+ try {
+ URL u = new URL(url);
+ in = u.openStream();
+ if (in != null) {
+ BufferedReader bufin =
+ new BufferedReader(new InputStreamReader(in, "8859_1"));
+ String str;
+ while ((str = bufin.readLine()) != null) {
+ if (str.startsWith("IOR:")) {
+ return str;
+ }
+ }
+ }
+ } catch (IOException e) {
+ NamingException ne =
+ new ConfigurationException("Invalid URL: " + url);
+ ne.setRootCause(e);
+ throw ne;
+ } finally {
+ try {
+ if (in != null) {
+ in.close();
+ }
+ } catch (IOException e) {
+ NamingException ne =
+ new ConfigurationException("Invalid URL: " + url);
+ ne.setRootCause(e);
+ throw ne;
+ }
+ }
+ throw new ConfigurationException(url + " does not contain an IOR");
+ }
+ }
+
+
+ /**
+ * Does the job of calling the COS Naming API,
+ * resolve, and performs the exception mapping. If the resolved
+ * object is a COS Naming Context (sub-context), then this function
+ * returns a new JNDI naming context object.
+ * @param path the NameComponent[] object.
+ * @exception NotFound No objects under the name.
+ * @exception CannotProceed Unable to obtain a continuation context
+ * @exception InvalidName Name not understood.
+ * @return Resolved object returned by the COS Name Server.
+ */
+ java.lang.Object callResolve(NameComponent[] path)
+ throws NamingException {
+ try {
+ org.omg.CORBA.Object obj = _nc.resolve(path);
+ try {
+ NamingContext nc =
+ NamingContextHelper.narrow(obj);
+ if (nc != null) {
+ return new CNCtx(_orb, orbTracker, nc, _env,
+ makeFullName(path));
+ } else {
+ return obj;
+ }
+ } catch (org.omg.CORBA.SystemException e) {
+ return obj;
+ }
+ } catch (Exception e) {
+ throw ExceptionMapper.mapException(e, this, path);
+ }
+ }
+
+ /**
+ * Converts the "String" name into a CompositeName
+ * returns the object resolved by the COS Naming api,
+ * resolve. Returns the current context if the name is empty.
+ * Returns either an org.omg.CORBA.Object or javax.naming.Context object.
+ * @param name string used to resolve the object.
+ * @exception NamingException See callResolve.
+ * @return the resolved object
+ */
+ public java.lang.Object lookup(String name) throws NamingException {
+ if (debug) {
+ System.out.println("Looking up: " + name);
+ }
+ return lookup(new CompositeName(name));
+ }
+
+ /**
+ * Converts the "Name" name into a NameComponent[] object and
+ * returns the object resolved by the COS Naming api,
+ * resolve. Returns the current context if the name is empty.
+ * Returns either an org.omg.CORBA.Object or javax.naming.Context object.
+ * @param name JNDI Name used to resolve the object.
+ * @exception NamingException See callResolve.
+ * @return the resolved object
+ */
+ public java.lang.Object lookup(Name name)
+ throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ if (name.size() == 0 )
+ return this; // %%% should clone() so that env can be changed
+ NameComponent[] path = CNNameParser.nameToCosName(name);
+
+ try {
+ java.lang.Object answer = callResolve(path);
+
+ try {
+ return NamingManager.getObjectInstance(answer, name, this, _env);
+ } catch (NamingException e) {
+ throw e;
+ } catch (Exception e) {
+ NamingException ne = new NamingException(
+ "problem generating object using object factory");
+ ne.setRootCause(e);
+ throw ne;
+ }
+ } catch (CannotProceedException cpe) {
+ javax.naming.Context cctx = getContinuationContext(cpe);
+ return cctx.lookup(cpe.getRemainingName());
+ }
+ }
+
+ /**
+ * Performs bind or rebind in the context depending on whether the
+ * flag rebind is set. The only objects allowed to be bound are of
+ * types org.omg.CORBA.Object, org.omg.CosNaming.NamingContext.
+ * You can use a state factory to turn other objects (such as
+ * Remote) into these acceptable forms.
+ *
+ * Uses the COS Naming apis bind/rebind or
+ * bind_context/rebind_context.
+ * @param pth NameComponent[] object
+ * @param obj Object to be bound.
+ * @param rebind perform rebind ? if true performs a rebind.
+ * @exception NotFound No objects under the name.
+ * @exception CannotProceed Unable to obtain a continuation context
+ * @exception AlreadyBound An object is already bound to this name.
+ */
+ private void callBindOrRebind(NameComponent[] pth, Name name,
+ java.lang.Object obj, boolean rebind) throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ try {
+ // Call state factories to convert
+ obj = NamingManager.getStateToBind(obj, name, this, _env);
+
+ if (obj instanceof CNCtx) {
+ // Use naming context object reference
+ obj = ((CNCtx)obj)._nc;
+ }
+
+ if ( obj instanceof org.omg.CosNaming.NamingContext) {
+ NamingContext nobj =
+ NamingContextHelper.narrow((org.omg.CORBA.Object)obj);
+ if (rebind)
+ _nc.rebind_context(pth,nobj);
+ else
+ _nc.bind_context(pth,nobj);
+
+ } else if (obj instanceof org.omg.CORBA.Object) {
+ if (rebind)
+ _nc.rebind(pth,(org.omg.CORBA.Object)obj);
+ else
+ _nc.bind(pth,(org.omg.CORBA.Object)obj);
+ }
+ else
+ throw new IllegalArgumentException(
+ "Only instances of org.omg.CORBA.Object can be bound");
+ } catch (BAD_PARAM e) {
+ // probably narrow() failed?
+ NamingException ne = new NotContextException(name.toString());
+ ne.setRootCause(e);
+ throw ne;
+ } catch (Exception e) {
+ throw ExceptionMapper.mapException(e, this, pth);
+ }
+ }
+
+ /**
+ * Converts the "Name" name into a NameComponent[] object and
+ * performs the bind operation. Uses callBindOrRebind. Throws an
+ * invalid name exception if the name is empty. We need a name to
+ * bind the object even when we work within the current context.
+ * @param name JNDI Name object
+ * @param obj Object to be bound.
+ * @exception NamingException See callBindOrRebind
+ */
+ public void bind(Name name, java.lang.Object obj)
+ throws NamingException {
+ if (name.size() == 0 ) {
+ throw new InvalidNameException("Name is empty");
+ }
+
+ if (debug) {
+ System.out.println("Bind: " + name);
+ }
+ NameComponent[] path = CNNameParser.nameToCosName(name);
+
+ try {
+ callBindOrRebind(path, name, obj, false);
+ } catch (CannotProceedException e) {
+ javax.naming.Context cctx = getContinuationContext(e);
+ cctx.bind(e.getRemainingName(), obj);
+ }
+ }
+
+ static private javax.naming.Context
+ getContinuationContext(CannotProceedException cpe)
+ throws NamingException {
+ try {
+ return NamingManager.getContinuationContext(cpe);
+ } catch (CannotProceedException e) {
+ java.lang.Object resObj = e.getResolvedObj();
+ if (resObj instanceof Reference) {
+ Reference ref = (Reference)resObj;
+ RefAddr addr = ref.get("nns");
+ if (addr.getContent() instanceof javax.naming.Context) {
+ NamingException ne = new NameNotFoundException(
+ "No object reference bound for specified name");
+ ne.setRootCause(cpe.getRootCause());
+ ne.setRemainingName(cpe.getRemainingName());
+ throw ne;
+ }
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Converts the "String" name into a CompositeName object and
+ * performs the bind operation. Uses callBindOrRebind. Throws an
+ * invalid name exception if the name is empty.
+ * @param name string
+ * @param obj Object to be bound.
+ * @exception NamingException See callBindOrRebind
+ */
+ public void bind(String name, java.lang.Object obj) throws NamingException {
+ bind(new CompositeName(name), obj);
+ }
+
+ /**
+ * Converts the "Name" name into a NameComponent[] object and
+ * performs the rebind operation. Uses callBindOrRebind. Throws an
+ * invalid name exception if the name is empty. We must have a name
+ * to rebind the object to even if we are working within the current
+ * context.
+ * @param name string
+ * @param obj Object to be bound.
+ * @exception NamingException See callBindOrRebind
+ */
+ public void rebind(Name name, java.lang.Object obj)
+ throws NamingException {
+ if (name.size() == 0 ) {
+ throw new InvalidNameException("Name is empty");
+ }
+ NameComponent[] path = CNNameParser.nameToCosName(name);
+ try {
+ callBindOrRebind(path, name, obj, true);
+ } catch (CannotProceedException e) {
+ javax.naming.Context cctx = getContinuationContext(e);
+ cctx.rebind(e.getRemainingName(), obj);
+ }
+ }
+
+ /**
+ * Converts the "String" name into a CompositeName object and
+ * performs the rebind operation. Uses callBindOrRebind. Throws an
+ * invalid name exception if the name is an empty string.
+ * @param name string
+ * @param obj Object to be bound.
+ * @exception NamingException See callBindOrRebind
+ */
+ public void rebind(String name, java.lang.Object obj)
+ throws NamingException {
+ rebind(new CompositeName(name), obj);
+ }
+
+ /**
+ * Calls the unbind api of COS Naming and uses the exception mapper
+ * class to map the exceptions
+ * @param path NameComponent[] object
+ * @exception NotFound No objects under the name. If leaf
+ * is not found, that's OK according to the JNDI spec
+ * @exception CannotProceed Unable to obtain a continuation context
+ * @exception InvalidName Name not understood.
+ */
+ private void callUnbind(NameComponent[] path) throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ try {
+ _nc.unbind(path);
+ } catch (NotFound e) {
+ // If leaf is the one missing, return success
+ // as per JNDI spec
+
+ if (leafNotFound(e, path[path.length-1])) {
+ ; // do nothing
+ } else {
+ throw ExceptionMapper.mapException(e, this, path);
+ }
+ } catch (Exception e) {
+ throw ExceptionMapper.mapException(e, this, path);
+ }
+ }
+
+ private boolean leafNotFound(NotFound e, NameComponent leaf) {
+
+ // This test is not foolproof because some name servers
+ // always just return one component in rest_of_name
+ // so you might not be able to tell whether that is
+ // the leaf (e.g. aa/aa/aa, which one is missing?)
+
+ NameComponent rest;
+ return e.why.value() == NotFoundReason._missing_node &&
+ e.rest_of_name.length == 1 &&
+ (rest=e.rest_of_name[0]).id.equals(leaf.id) &&
+ (rest.kind == leaf.kind ||
+ (rest.kind != null && rest.kind.equals(leaf.kind)));
+ }
+
+ /**
+ * Converts the "String" name into a CompositeName object and
+ * performs the unbind operation. Uses callUnbind. If the name is
+ * empty, throws an invalid name exception. Do we unbind the
+ * current context (JNDI spec says work with the current context if
+ * the name is empty) ?
+ * @param name string
+ * @exception NamingException See callUnbind
+ */
+ public void unbind(String name) throws NamingException {
+ unbind(new CompositeName(name));
+ }
+
+ /**
+ * Converts the "Name" name into a NameComponent[] object and
+ * performs the unbind operation. Uses callUnbind. Throws an
+ * invalid name exception if the name is empty.
+ * @param name string
+ * @exception NamingException See callUnbind
+ */
+ public void unbind(Name name)
+ throws NamingException {
+ if (name.size() == 0 )
+ throw new InvalidNameException("Name is empty");
+ NameComponent[] path = CNNameParser.nameToCosName(name);
+ try {
+ callUnbind(path);
+ } catch (CannotProceedException e) {
+ javax.naming.Context cctx = getContinuationContext(e);
+ cctx.unbind(e.getRemainingName());
+ }
+ }
+
+ /**
+ * Renames an object. Since COS Naming does not support a rename
+ * api, this method unbinds the object with the "oldName" and
+ * creates a new binding.
+ * @param oldName string, existing name for the binding.
+ * @param newName string, name used to replace.
+ * @exception NamingException See bind
+ */
+ public void rename(String oldName,String newName)
+ throws NamingException {
+ rename(new CompositeName(oldName), new CompositeName(newName));
+ }
+
+ /**
+ * Renames an object. Since COS Naming does not support a rename
+ * api, this method unbinds the object with the "oldName" and
+ * creates a new binding.
+ * @param oldName JNDI Name, existing name for the binding.
+ * @param newName JNDI Name, name used to replace.
+ * @exception NamingException See bind
+ */
+ public void rename(Name oldName,Name newName)
+ throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ if (oldName.size() == 0 || newName.size() == 0)
+ throw new InvalidNameException("One or both names empty");
+ java.lang.Object obj = lookup(oldName);
+ bind(newName,obj);
+ unbind(oldName);
+ }
+
+ /**
+ * Returns a NameClassEnumeration object which has a list of name
+ * class pairs. Lists the current context if the name is empty.
+ * @param name string
+ * @exception NamingException All exceptions thrown by lookup
+ * with a non-null argument
+ * @return a list of name-class objects as a NameClassEnumeration.
+ */
+ public NamingEnumeration list(String name) throws NamingException {
+ return list(new CompositeName(name));
+ }
+
+ /**
+ * Returns a NameClassEnumeration object which has a list of name
+ * class pairs. Lists the current context if the name is empty.
+ * @param name JNDI Name
+ * @exception NamingException All exceptions thrown by lookup
+ * @return a list of name-class objects as a NameClassEnumeration.
+ */
+ public NamingEnumeration list(Name name)
+ throws NamingException {
+ return listBindings(name);
+ }
+
+ /**
+ * Returns a BindingEnumeration object which has a list of name
+ * object pairs. Lists the current context if the name is empty.
+ * @param name string
+ * @exception NamingException all exceptions returned by lookup
+ * @return a list of bindings as a BindingEnumeration.
+ */
+ public NamingEnumeration listBindings(String name)
+ throws NamingException {
+ return listBindings(new CompositeName(name));
+ }
+
+ /**
+ * Returns a BindingEnumeration object which has a list of name
+ * class pairs. Lists the current context if the name is empty.
+ * @param name JNDI Name
+ * @exception NamingException all exceptions returned by lookup.
+ * @return a list of bindings as a BindingEnumeration.
+ */
+ public NamingEnumeration listBindings(Name name)
+ throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ if (name.size() > 0) {
+ try {
+ java.lang.Object obj = lookup(name);
+ if (obj instanceof CNCtx) {
+ return new CNBindingEnumeration(
+ (CNCtx) obj, true, _env);
+ } else {
+ throw new NotContextException(name.toString());
+ }
+ } catch (NamingException ne) {
+ throw ne;
+ } catch (BAD_PARAM e) {
+ NamingException ne =
+ new NotContextException(name.toString());
+ ne.setRootCause(e);
+ throw ne;
+ }
+ }
+ return new CNBindingEnumeration(this, false, _env);
+ }
+
+ /**
+ * Calls the destroy on the COS Naming Server
+ * @param nc The NamingContext object to use.
+ * @exception NotEmpty when the context is not empty and cannot be destroyed.
+ */
+ private void callDestroy(NamingContext nc)
+ throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ try {
+ nc.destroy();
+ } catch (Exception e) {
+ throw ExceptionMapper.mapException(e, this, null);
+ }
+ }
+
+ /**
+ * Uses the callDestroy function to destroy the context. If name is
+ * empty destroys the current context.
+ * @param name string
+ * @exception OperationNotSupportedException when list is invoked
+ * with a non-null argument
+ */
+ public void destroySubcontext(String name) throws NamingException {
+ destroySubcontext(new CompositeName(name));
+ }
+
+ /**
+ * Uses the callDestroy function to destroy the context. Destroys
+ * the current context if name is empty.
+ * @param name JNDI Name
+ * @exception OperationNotSupportedException when list is invoked
+ * with a non-null argument
+ */
+ public void destroySubcontext(Name name)
+ throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ NamingContext the_nc = _nc;
+ NameComponent[] path = CNNameParser.nameToCosName(name);
+ if ( name.size() > 0) {
+ try {
+ javax.naming.Context ctx =
+ (javax.naming.Context) callResolve(path);
+ CNCtx cnc = (CNCtx)ctx;
+ the_nc = cnc._nc;
+ cnc.close(); //remove the reference to the context
+ } catch (ClassCastException e) {
+ throw new NotContextException(name.toString());
+ } catch (CannotProceedException e) {
+ javax.naming.Context cctx = getContinuationContext(e);
+ cctx.destroySubcontext(e.getRemainingName());
+ return;
+ } catch (NameNotFoundException e) {
+ // If leaf is the one missing, return success
+ // as per JNDI spec
+
+ if (e.getRootCause() instanceof NotFound &&
+ leafNotFound((NotFound)e.getRootCause(),
+ path[path.length-1])) {
+ return; // leaf missing OK
+ }
+ throw e;
+ } catch (NamingException e) {
+ throw e;
+ }
+ }
+ callDestroy(the_nc);
+ callUnbind(path);
+ }
+
+ /**
+ * Calls the bind_new_context COS naming api to create a new subcontext.
+ * @param path NameComponent[] object
+ * @exception NotFound No objects under the name.
+ * @exception CannotProceed Unable to obtain a continuation context
+ * @exception InvalidName Name not understood.
+ * @exception AlreadyBound An object is already bound to this name.
+ * @return the new context object.
+ */
+ private javax.naming.Context callBindNewContext(NameComponent[] path)
+ throws NamingException {
+ if (_nc == null)
+ throw new ConfigurationException(
+ "Context does not have a corresponding NamingContext");
+ try {
+ NamingContext nctx = _nc.bind_new_context(path);
+ return new CNCtx(_orb, orbTracker, nctx, _env,
+ makeFullName(path));
+ } catch (Exception e) {
+ throw ExceptionMapper.mapException(e, this, path);
+ }
+ }
+
+ /**
+ * Uses the callBindNewContext convenience function to create a new
+ * context. Throws an invalid name exception if the name is empty.
+ * @param name string
+ * @exception NamingException See callBindNewContext
+ * @return the new context object.
+ */
+ public javax.naming.Context createSubcontext(String name)
+ throws NamingException {
+ return createSubcontext(new CompositeName(name));
+ }
+
+ /**
+ * Uses the callBindNewContext convenience function to create a new
+ * context. Throws an invalid name exception if the name is empty.
+ * @param name string
+ * @exception NamingException See callBindNewContext
+ * @return the new context object.
+ */
+ public javax.naming.Context createSubcontext(Name name)
+ throws NamingException {
+ if (name.size() == 0 )
+ throw new InvalidNameException("Name is empty");
+ NameComponent[] path = CNNameParser.nameToCosName(name);
+ try {
+ return callBindNewContext(path);
+ } catch (CannotProceedException e) {
+ javax.naming.Context cctx = getContinuationContext(e);
+ return cctx.createSubcontext(e.getRemainingName());
+ }
+ }
+
+ /**
+ * Is mapped to resolve in the COS Naming api.
+ * @param name string
+ * @exception NamingException See lookup.
+ * @return the resolved object.
+ */
+ public java.lang.Object lookupLink(String name) throws NamingException {
+ return lookupLink(new CompositeName(name));
+ }
+
+ /**
+ * Is mapped to resolve in the COS Naming api.
+ * @param name string
+ * @exception NamingException See lookup.
+ * @return the resolved object.
+ */
+ public java.lang.Object lookupLink(Name name) throws NamingException {
+ return lookup(name);
+ }
+
+ /**
+ * Allow access to the name parser object.
+ * @param String JNDI name, is ignored since there is only one Name
+ * Parser object.
+ * @exception NamingException --
+ * @return NameParser object
+ */
+ public NameParser getNameParser(String name) throws NamingException {
+ return parser;
+ }
+
+ /**
+ * Allow access to the name parser object.
+ * @param Name JNDI name, is ignored since there is only one Name
+ * Parser object.
+ * @exception NamingException --
+ * @return NameParser object
+ */
+ public NameParser getNameParser(Name name) throws NamingException {
+ return parser;
+ }
+
+ /**
+ * Returns the current environment.
+ * @return Environment.
+ */
+ public Hashtable getEnvironment() throws NamingException {
+ if (_env == null) {
+ return new Hashtable(5, 0.75f);
+ } else {
+ return (Hashtable)_env.clone();
+ }
+ }
+
+ public String composeName(String name, String prefix) throws NamingException {
+ return composeName(new CompositeName(name),
+ new CompositeName(prefix)).toString();
+ }
+
+ public Name composeName(Name name, Name prefix) throws NamingException {
+ Name result = (Name)prefix.clone();
+ return result.addAll(name);
+ }
+
+ /**
+ * Adds to the environment for the current context.
+ * Record change but do not reinitialize ORB.
+ *
+ * @param propName The property name.
+ * @param propVal The ORB.
+ * @return the previous value of this property if any.
+ */
+ public java.lang.Object addToEnvironment(String propName,
+ java.lang.Object propValue)
+ throws NamingException {
+ if (_env == null) {
+ _env = new Hashtable(7, 0.75f);
+ } else {
+ // copy-on-write
+ _env = (Hashtable)_env.clone();
+ }
+
+ return _env.put(propName, propValue);
+ }
+
+ // Record change but do not reinitialize ORB
+ public java.lang.Object removeFromEnvironment(String propName)
+ throws NamingException {
+ if (_env != null && _env.get(propName) != null) {
+ // copy-on-write
+ _env = (Hashtable)_env.clone();
+ return _env.remove(propName);
+ }
+ return null;
+ }
+
+ synchronized public void incEnumCount() {
+ if (orbTracker == nu...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-23 04:52:59
|
Revision: 3287
http://jnode.svn.sourceforge.net/jnode/?rev=3287&view=rev
Author: lsantha
Date: 2007-06-22 21:52:58 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/java/java/security/AlgorithmParameters.java
trunk/core/src/openjdk/java/java/security/KeyRep.java
trunk/core/src/openjdk/java/java/security/Provider.java
trunk/core/src/openjdk/java/java/security/cert/
trunk/core/src/openjdk/java/java/security/cert/CRL.java
trunk/core/src/openjdk/java/java/security/cert/CRLException.java
trunk/core/src/openjdk/java/java/security/cert/CRLSelector.java
trunk/core/src/openjdk/java/java/security/cert/CertPath.java
trunk/core/src/openjdk/java/java/security/cert/CertPathBuilder.java
trunk/core/src/openjdk/java/java/security/cert/CertPathBuilderException.java
trunk/core/src/openjdk/java/java/security/cert/CertPathBuilderResult.java
trunk/core/src/openjdk/java/java/security/cert/CertPathBuilderSpi.java
trunk/core/src/openjdk/java/java/security/cert/CertPathHelperImpl.java
trunk/core/src/openjdk/java/java/security/cert/CertPathParameters.java
trunk/core/src/openjdk/java/java/security/cert/CertPathValidator.java
trunk/core/src/openjdk/java/java/security/cert/CertPathValidatorException.java
trunk/core/src/openjdk/java/java/security/cert/CertPathValidatorResult.java
trunk/core/src/openjdk/java/java/security/cert/CertPathValidatorSpi.java
trunk/core/src/openjdk/java/java/security/cert/CertSelector.java
trunk/core/src/openjdk/java/java/security/cert/CertStore.java
trunk/core/src/openjdk/java/java/security/cert/CertStoreException.java
trunk/core/src/openjdk/java/java/security/cert/CertStoreParameters.java
trunk/core/src/openjdk/java/java/security/cert/CertStoreSpi.java
trunk/core/src/openjdk/java/java/security/cert/Certificate.java
trunk/core/src/openjdk/java/java/security/cert/CertificateEncodingException.java
trunk/core/src/openjdk/java/java/security/cert/CertificateException.java
trunk/core/src/openjdk/java/java/security/cert/CertificateExpiredException.java
trunk/core/src/openjdk/java/java/security/cert/CertificateFactory.java
trunk/core/src/openjdk/java/java/security/cert/CertificateFactorySpi.java
trunk/core/src/openjdk/java/java/security/cert/CertificateNotYetValidException.java
trunk/core/src/openjdk/java/java/security/cert/CertificateParsingException.java
trunk/core/src/openjdk/java/java/security/cert/CollectionCertStoreParameters.java
trunk/core/src/openjdk/java/java/security/cert/LDAPCertStoreParameters.java
trunk/core/src/openjdk/java/java/security/cert/PKIXBuilderParameters.java
trunk/core/src/openjdk/java/java/security/cert/PKIXCertPathBuilderResult.java
trunk/core/src/openjdk/java/java/security/cert/PKIXCertPathChecker.java
trunk/core/src/openjdk/java/java/security/cert/PKIXCertPathValidatorResult.java
trunk/core/src/openjdk/java/java/security/cert/PKIXParameters.java
trunk/core/src/openjdk/java/java/security/cert/PolicyNode.java
trunk/core/src/openjdk/java/java/security/cert/PolicyQualifierInfo.java
trunk/core/src/openjdk/java/java/security/cert/TrustAnchor.java
trunk/core/src/openjdk/java/java/security/cert/X509CRL.java
trunk/core/src/openjdk/java/java/security/cert/X509CRLEntry.java
trunk/core/src/openjdk/java/java/security/cert/X509CRLSelector.java
trunk/core/src/openjdk/java/java/security/cert/X509CertSelector.java
trunk/core/src/openjdk/java/java/security/cert/X509Certificate.java
trunk/core/src/openjdk/java/java/security/cert/X509Extension.java
trunk/core/src/openjdk/java/java/security/cert/package.html
trunk/core/src/openjdk/java/java/security/interfaces/
trunk/core/src/openjdk/java/java/security/interfaces/ECKey.java
trunk/core/src/openjdk/java/java/security/interfaces/ECPrivateKey.java
trunk/core/src/openjdk/java/java/security/interfaces/ECPublicKey.java
trunk/core/src/openjdk/java/java/security/spec/
trunk/core/src/openjdk/java/java/security/spec/ECField.java
trunk/core/src/openjdk/java/java/security/spec/ECFieldF2m.java
trunk/core/src/openjdk/java/java/security/spec/ECFieldFp.java
trunk/core/src/openjdk/java/java/security/spec/ECGenParameterSpec.java
trunk/core/src/openjdk/java/java/security/spec/ECParameterSpec.java
trunk/core/src/openjdk/java/java/security/spec/ECPoint.java
trunk/core/src/openjdk/java/java/security/spec/ECPrivateKeySpec.java
trunk/core/src/openjdk/java/java/security/spec/ECPublicKeySpec.java
trunk/core/src/openjdk/java/java/security/spec/EllipticCurve.java
Added: trunk/core/src/openjdk/java/java/security/AlgorithmParameters.java
===================================================================
--- trunk/core/src/openjdk/java/java/security/AlgorithmParameters.java (rev 0)
+++ trunk/core/src/openjdk/java/java/security/AlgorithmParameters.java 2007-06-23 04:52:58 UTC (rev 3287)
@@ -0,0 +1,383 @@
+/*
+ * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.security;
+
+import java.io.*;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+
+/**
+ * This class is used as an opaque representation of cryptographic parameters.
+ *
+ * <p>An <code>AlgorithmParameters</code> object for managing the parameters
+ * for a particular algorithm can be obtained by
+ * calling one of the <code>getInstance</code> factory methods
+ * (static methods that return instances of a given class).
+ *
+ * <p>Once an <code>AlgorithmParameters</code> object is obtained, it must be
+ * initialized via a call to <code>init</code>, using an appropriate parameter
+ * specification or parameter encoding.
+ *
+ * <p>A transparent parameter specification is obtained from an
+ * <code>AlgorithmParameters</code> object via a call to
+ * <code>getParameterSpec</code>, and a byte encoding of the parameters is
+ * obtained via a call to <code>getEncoded</code>.
+ *
+ * @author Jan Luehe
+ *
+ * @version 1.33, 05/05/07
+ *
+ * @see java.security.spec.AlgorithmParameterSpec
+ * @see java.security.spec.DSAParameterSpec
+ * @see KeyPairGenerator
+ *
+ * @since 1.2
+ */
+
+public class AlgorithmParameters {
+
+ // The provider
+ private Provider provider;
+
+ // The provider implementation (delegate)
+ private AlgorithmParametersSpi paramSpi;
+
+ // The algorithm
+ private String algorithm;
+
+ // Has this object been initialized?
+ private boolean initialized = false;
+
+ /**
+ * Creates an AlgorithmParameters object.
+ *
+ * @param paramSpi the delegate
+ * @param provider the provider
+ * @param algorithm the algorithm
+ */
+ protected AlgorithmParameters(AlgorithmParametersSpi paramSpi,
+ Provider provider, String algorithm)
+ {
+ this.paramSpi = paramSpi;
+ this.provider = provider;
+ this.algorithm = algorithm;
+ }
+
+ /**
+ * Returns the name of the algorithm associated with this parameter object.
+ *
+ * @return the algorithm name.
+ */
+ public final String getAlgorithm() {
+ return this.algorithm;
+ }
+
+ /**
+ * Returns a parameter object for the specified algorithm.
+ *
+ * <p> This method traverses the list of registered security Providers,
+ * starting with the most preferred Provider.
+ * A new AlgorithmParameters object encapsulating the
+ * AlgorithmParametersSpi implementation from the first
+ * Provider that supports the specified algorithm is returned.
+ *
+ * <p> Note that the list of registered providers may be retrieved via
+ * the {@link Security#getProviders() Security.getProviders()} method.
+ *
+ * <p> The returned parameter object must be initialized via a call to
+ * <code>init</code>, using an appropriate parameter specification or
+ * parameter encoding.
+ *
+ * @param algorithm the name of the algorithm requested.
+ * See Appendix A in the <a href=
+ * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
+ * Java Cryptography Architecture API Specification & Reference </a>
+ * for information about standard algorithm names.
+ *
+ * @return the new parameter object.
+ *
+ * @exception NoSuchAlgorithmException if no Provider supports an
+ * AlgorithmParametersSpi implementation for the
+ * specified algorithm.
+ *
+ * @see Provider
+ */
+ public static AlgorithmParameters getInstance(String algorithm)
+ throws NoSuchAlgorithmException {
+ try {
+ Object[] objs = Security.getImpl(algorithm, "AlgorithmParameters",
+ (String)null);
+ return new AlgorithmParameters((AlgorithmParametersSpi)objs[0],
+ (Provider)objs[1],
+ algorithm);
+ } catch(NoSuchProviderException e) {
+ throw new NoSuchAlgorithmException(algorithm + " not found");
+ }
+ }
+
+ /**
+ * Returns a parameter object for the specified algorithm.
+ *
+ * <p> A new AlgorithmParameters object encapsulating the
+ * AlgorithmParametersSpi implementation from the specified provider
+ * is returned. The specified provider must be registered
+ * in the security provider list.
+ *
+ * <p> Note that the list of registered providers may be retrieved via
+ * the {@link Security#getProviders() Security.getProviders()} method.
+ *
+ * <p>The returned parameter object must be initialized via a call to
+ * <code>init</code>, using an appropriate parameter specification or
+ * parameter encoding.
+ *
+ * @param algorithm the name of the algorithm requested.
+ * See Appendix A in the <a href=
+ * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
+ * Java Cryptography Architecture API Specification & Reference </a>
+ * for information about standard algorithm names.
+ *
+ * @param provider the name of the provider.
+ *
+ * @return the new parameter object.
+ *
+ * @exception NoSuchAlgorithmException if an AlgorithmParametersSpi
+ * implementation for the specified algorithm is not
+ * available from the specified provider.
+ *
+ * @exception NoSuchProviderException if the specified provider is not
+ * registered in the security provider list.
+ *
+ * @exception IllegalArgumentException if the provider name is null
+ * or empty.
+ *
+ * @see Provider
+ */
+ public static AlgorithmParameters getInstance(String algorithm,
+ String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ if (provider == null || provider.length() == 0)
+ throw new IllegalArgumentException("missing provider");
+ Object[] objs = Security.getImpl(algorithm, "AlgorithmParameters",
+ provider);
+ return new AlgorithmParameters((AlgorithmParametersSpi)objs[0],
+ (Provider)objs[1],
+ algorithm);
+ }
+
+ /**
+ * Returns a parameter object for the specified algorithm.
+ *
+ * <p> A new AlgorithmParameters object encapsulating the
+ * AlgorithmParametersSpi implementation from the specified Provider
+ * object is returned. Note that the specified Provider object
+ * does not have to be registered in the provider list.
+ *
+ * <p>The returned parameter object must be initialized via a call to
+ * <code>init</code>, using an appropriate parameter specification or
+ * parameter encoding.
+ *
+ * @param algorithm the name of the algorithm requested.
+ * See Appendix A in the <a href=
+ * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
+ * Java Cryptography Architecture API Specification & Reference </a>
+ * for information about standard algorithm names.
+ *
+ * @param provider the name of the provider.
+ *
+ * @return the new parameter object.
+ *
+ * @exception NoSuchAlgorithmException if an AlgorithmParameterGeneratorSpi
+ * implementation for the specified algorithm is not available
+ * from the specified Provider object.
+ *
+ * @exception IllegalArgumentException if the provider is null.
+ *
+ * @see Provider
+ *
+ * @since 1.4
+ */
+ public static AlgorithmParameters getInstance(String algorithm,
+ Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ if (provider == null)
+ throw new IllegalArgumentException("missing provider");
+ Object[] objs = Security.getImpl(algorithm, "AlgorithmParameters",
+ provider);
+ return new AlgorithmParameters((AlgorithmParametersSpi)objs[0],
+ (Provider)objs[1],
+ algorithm);
+ }
+
+ /**
+ * Returns the provider of this parameter object.
+ *
+ * @return the provider of this parameter object
+ */
+ public final Provider getProvider() {
+ return this.provider;
+ }
+
+ /**
+ * Initializes this parameter object using the parameters
+ * specified in <code>paramSpec</code>.
+ *
+ * @param paramSpec the parameter specification.
+ *
+ * @exception InvalidParameterSpecException if the given parameter
+ * specification is inappropriate for the initialization of this parameter
+ * object, or if this parameter object has already been initialized.
+ */
+ public final void init(AlgorithmParameterSpec paramSpec)
+ throws InvalidParameterSpecException
+ {
+ if (this.initialized)
+ throw new InvalidParameterSpecException("already initialized");
+ paramSpi.engineInit(paramSpec);
+ this.initialized = true;
+ }
+
+ /**
+ * Imports the specified parameters and decodes them according to the
+ * primary decoding format for parameters. The primary decoding
+ * format for parameters is ASN.1, if an ASN.1 specification for this type
+ * of parameters exists.
+ *
+ * @param params the encoded parameters.
+ *
+ * @exception IOException on decoding errors, or if this parameter object
+ * has already been initialized.
+ */
+ public final void init(byte[] params) throws IOException {
+ if (this.initialized)
+ throw new IOException("already initialized");
+ paramSpi.engineInit(params);
+ this.initialized = true;
+ }
+
+ /**
+ * Imports the parameters from <code>params</code> and decodes them
+ * according to the specified decoding scheme.
+ * If <code>format</code> is null, the
+ * primary decoding format for parameters is used. The primary decoding
+ * format is ASN.1, if an ASN.1 specification for these parameters
+ * exists.
+ *
+ * @param params the encoded parameters.
+ *
+ * @param format the name of the decoding scheme.
+ *
+ * @exception IOException on decoding errors, or if this parameter object
+ * has already been initialized.
+ */
+ public final void init(byte[] params, String format) throws IOException {
+ if (this.initialized)
+ throw new IOException("already initialized");
+ paramSpi.engineInit(params, format);
+ this.initialized = true;
+ }
+
+ /**
+ * Returns a (transparent) specification of this parameter object.
+ * <code>paramSpec</code> identifies the specification class in which
+ * the parameters should be returned. It could, for example, be
+ * <code>DSAParameterSpec.class</code>, to indicate that the
+ * parameters should be returned in an instance of the
+ * <code>DSAParameterSpec</code> class.
+ *
+ * @param paramSpec the specification class in which
+ * the parameters should be returned.
+ *
+ * @return the parameter specification.
+ *
+ * @exception InvalidParameterSpecException if the requested parameter
+ * specification is inappropriate for this parameter object, or if this
+ * parameter object has not been initialized.
+ */
+ public final <T extends AlgorithmParameterSpec>
+ T getParameterSpec(Class<T> paramSpec)
+ throws InvalidParameterSpecException
+ {
+ if (this.initialized == false) {
+ throw new InvalidParameterSpecException("not initialized");
+ }
+ return paramSpi.engineGetParameterSpec(paramSpec);
+ }
+
+ /**
+ * Returns the parameters in their primary encoding format.
+ * The primary encoding format for parameters is ASN.1, if an ASN.1
+ * specification for this type of parameters exists.
+ *
+ * @return the parameters encoded using their primary encoding format.
+ *
+ * @exception IOException on encoding errors, or if this parameter object
+ * has not been initialized.
+ */
+ public final byte[] getEncoded() throws IOException
+ {
+ if (this.initialized == false) {
+ throw new IOException("not initialized");
+ }
+ return paramSpi.engineGetEncoded();
+ }
+
+ /**
+ * Returns the parameters encoded in the specified scheme.
+ * If <code>format</code> is null, the
+ * primary encoding format for parameters is used. The primary encoding
+ * format is ASN.1, if an ASN.1 specification for these parameters
+ * exists.
+ *
+ * @param format the name of the encoding format.
+ *
+ * @return the parameters encoded using the specified encoding scheme.
+ *
+ * @exception IOException on encoding errors, or if this parameter object
+ * has not been initialized.
+ */
+ public final byte[] getEncoded(String format) throws IOException
+ {
+ if (this.initialized == false) {
+ throw new IOException("not initialized");
+ }
+ return paramSpi.engineGetEncoded(format);
+ }
+
+ /**
+ * Returns a formatted string describing the parameters.
+ *
+ * @return a formatted string describing the parameters, or null if this
+ * parameter object has not been initialized.
+ */
+ public final String toString() {
+ if (this.initialized == false) {
+ return null;
+ }
+ return paramSpi.engineToString();
+ }
+}
Added: trunk/core/src/openjdk/java/java/security/KeyRep.java
===================================================================
--- trunk/core/src/openjdk/java/java/security/KeyRep.java (rev 0)
+++ trunk/core/src/openjdk/java/java/security/KeyRep.java 2007-06-23 04:52:58 UTC (rev 3287)
@@ -0,0 +1,196 @@
+/*
+ * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.security;
+
+import java.io.*;
+
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.security.spec.InvalidKeySpecException;
+
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * Standardized representation for serialized Key objects.
+ *
+ * <p>
+ *
+ * Note that a serialized Key may contain sensitive information
+ * which should not be exposed in untrusted environments. See the
+ * <a href="../../../platform/serialization/spec/security.html">
+ * Security Appendix</a>
+ * of the Serialization Specification for more information.
+ *
+ * @see Key
+ * @see KeyFactory
+ * @see javax.crypto.spec.SecretKeySpec
+ * @see java.security.spec.X509EncodedKeySpec
+ * @see java.security.spec.PKCS8EncodedKeySpec
+ *
+ * @version 1.16, 07/05/05
+ * @since 1.5
+ */
+
+public class KeyRep implements Serializable {
+
+ private static final long serialVersionUID = -4757683898830641853L;
+
+ /**
+ * Key type.
+ *
+ * @since 1.5
+ */
+ public static enum Type {
+
+ /** Type for secret keys. */
+ SECRET,
+
+ /** Type for public keys. */
+ PUBLIC,
+
+ /** Type for private keys. */
+ PRIVATE,
+
+ }
+
+ private static final String PKCS8 = "PKCS#8";
+ private static final String X509 = "X.509";
+ private static final String RAW = "RAW";
+
+ /**
+ * Either one of Type.SECRET, Type.PUBLIC, or Type.PRIVATE
+ *
+ * @serial
+ */
+ private Type type;
+
+ /**
+ * The Key algorithm
+ *
+ * @serial
+ */
+ private String algorithm;
+
+ /**
+ * The Key encoding format
+ *
+ * @serial
+ */
+ private String format;
+
+ /**
+ * The encoded Key bytes
+ *
+ * @serial
+ */
+ private byte[] encoded;
+
+ /**
+ * Construct the alternate Key class.
+ *
+ * <p>
+ *
+ * @param type either one of Type.SECRET, Type.PUBLIC, or Type.PRIVATE
+ * @param algorithm the algorithm returned from
+ * <code>Key.getAlgorithm()</code>
+ * @param format the encoding format returned from
+ * <code>Key.getFormat()</code>
+ * @param encoded the encoded bytes returned from
+ * <code>Key.getEncoded()</code>
+ *
+ * @exception NullPointerException
+ * if type is <code>null</code>,
+ * if algorithm is <code>null</code>,
+ * if format is <code>null</code>,
+ * or if encoded is <code>null</code>
+ */
+ public KeyRep(Type type, String algorithm,
+ String format, byte[] encoded) {
+
+ if (type == null || algorithm == null ||
+ format == null || encoded == null) {
+ throw new NullPointerException("invalid null input(s)");
+ }
+
+ this.type = type;
+ this.algorithm = algorithm;
+ this.format = format.toUpperCase();
+ this.encoded = (byte[])encoded.clone();
+ }
+
+ /**
+ * Resolve the Key object.
+ *
+ * <p> This method supports three Type/format combinations:
+ * <ul>
+ * <li> Type.SECRET/"RAW" - returns a SecretKeySpec object
+ * constructed using encoded key bytes and algorithm
+ * <li> Type.PUBLIC/"X.509" - gets a KeyFactory instance for
+ * the key algorithm, constructs an X509EncodedKeySpec with the
+ * encoded key bytes, and generates a public key from the spec
+ * <li> Type.PRIVATE/"PKCS#8" - gets a KeyFactory instance for
+ * the key algorithm, constructs a PKCS8EncodedKeySpec with the
+ * encoded key bytes, and generates a private key from the spec
+ * </ul>
+ *
+ * <p>
+ *
+ * @return the resolved Key object
+ *
+ * @exception ObjectStreamException if the Type/format
+ * combination is unrecognized, if the algorithm, key format, or
+ * encoded key bytes are unrecognized/invalid, of if the
+ * resolution of the key fails for any reason
+ */
+ protected Object readResolve() throws ObjectStreamException {
+ try {
+ if (type == Type.SECRET && RAW.equals(format)) {
+ return new SecretKeySpec(encoded, algorithm);
+ } else if (type == Type.PUBLIC && X509.equals(format)) {
+ KeyFactory f = KeyFactory.getInstance(algorithm);
+ return f.generatePublic(new X509EncodedKeySpec(encoded));
+ } else if (type == Type.PRIVATE && PKCS8.equals(format)) {
+ KeyFactory f = KeyFactory.getInstance(algorithm);
+ return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
+ } else {
+ throw new NotSerializableException
+ ("unrecognized type/format combination: " +
+ type + "/" + format);
+ }
+ } catch (NotSerializableException nse) {
+ throw nse;
+ } catch (Exception e) {
+ NotSerializableException nse = new NotSerializableException
+ ("java.security.Key: " +
+ "[" + type + "] " +
+ "[" + algorithm + "] " +
+ "[" + format + "]");
+ nse.initCause(e);
+ throw nse;
+ }
+ }
+}
Added: trunk/core/src/openjdk/java/java/security/Provider.java
===================================================================
--- trunk/core/src/openjdk/java/java/security/Provider.java (rev 0)
+++ trunk/core/src/openjdk/java/java/security/Provider.java 2007-06-23 04:52:58 UTC (rev 3287)
@@ -0,0 +1,1481 @@
+/*
+ * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.security;
+
+import java.io.*;
+import java.util.*;
+import static java.util.Locale.ENGLISH;
+import java.lang.ref.*;
+import java.lang.reflect.*;
+
+import java.security.cert.CertStoreParameters;
+import javax.security.auth.login.Configuration;
+
+/**
+ * This class represents a "provider" for the
+ * Java Security API, where a provider implements some or all parts of
+ * Java Security. Services that a provider may implement include:
+ *
+ * <ul>
+ *
+ * <li>Algorithms (such as DSA, RSA, MD5 or SHA-1).
+ *
+ * <li>Key generation, conversion, and management facilities (such as for
+ * algorithm-specific keys).
+ *
+ *</ul>
+ *
+ * <p>Each provider has a name and a version number, and is configured
+ * in each runtime it is installed in.
+ *
+ * <p>See <a href =
+ * "../../../technotes/guides/security/crypto/CryptoSpec.html#Provider">The Provider Class</a>
+ * in the "Java Cryptography Architecture API Specification & Reference"
+ * for information about how a particular type of provider, the
+ * cryptographic service provider, works and is installed. However,
+ * please note that a provider can be used to implement any security
+ * service in Java that uses a pluggable architecture with a choice
+ * of implementations that fit underneath.
+ *
+ * <p>Some provider implementations may encounter unrecoverable internal
+ * errors during their operation, for example a failure to communicate with a
+ * security token. A {@link ProviderException} should be used to indicate
+ * such errors.
+ *
+ * <p>The service type <code>Provider</code> is reserved for use by the
+ * security framework. Services of this type cannot be added, removed,
+ * or modified by applications.
+ * The following attributes are automatically placed in each Provider object:
+ * <table cellspacing=4>
+ * <tr><th>Name</th><th>Value</th>
+ * <tr><td><code>Provider.id name</code></td>
+ * <td><code>String.valueOf(provider.getName())</code></td>
+ * <tr><td><code>Provider.id version</code></td>
+ * <td><code>String.valueOf(provider.getVersion())</code></td>
+ * <tr><td><code>Provider.id info</code></td>
+ <td><code>String.valueOf(provider.getInfo())</code></td>
+ * <tr><td><code>Provider.id className</code></td>
+ * <td><code>provider.getClass().getName()</code></td>
+ * </table>
+ *
+ * @version 1.84, 05/05/07
+ * @author Benjamin Renaud
+ * @author Andreas Sterbenz
+ */
+public abstract class Provider extends Properties {
+
+ // Declare serialVersionUID to be compatible with JDK1.1
+ static final long serialVersionUID = -4298000515446427739L;
+
+ private static final sun.security.util.Debug debug =
+ sun.security.util.Debug.getInstance
+ ("provider", "Provider");
+
+ /**
+ * The provider name.
+ *
+ * @serial
+ */
+ private String name;
+
+ /**
+ * A description of the provider and its services.
+ *
+ * @serial
+ */
+ private String info;
+
+ /**
+ * The provider version number.
+ *
+ * @serial
+ */
+ private double version;
+
+
+ private transient Set<Map.Entry<Object,Object>> entrySet = null;
+ private transient int entrySetCallCount = 0;
+
+ private transient boolean initialized;
+
+ /**
+ * Constructs a provider with the specified name, version number,
+ * and information.
+ *
+ * @param name the provider name.
+ *
+ * @param version the provider version number.
+ *
+ * @param info a description of the provider and its services.
+ */
+ protected Provider(String name, double version, String info) {
+ this.name = name;
+ this.version = version;
+ this.info = info;
+ putId();
+ initialized = true;
+ }
+
+ /**
+ * Returns the name of this provider.
+ *
+ * @return the name of this provider.
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Returns the version number for this provider.
+ *
+ * @return the version number for this provider.
+ */
+ public double getVersion() {
+ return version;
+ }
+
+ /**
+ * Returns a human-readable description of the provider and its
+ * services. This may return an HTML page, with relevant links.
+ *
+ * @return a description of the provider and its services.
+ */
+ public String getInfo() {
+ return info;
+ }
+
+ /**
+ * Returns a string with the name and the version number
+ * of this provider.
+ *
+ * @return the string with the name and the version number
+ * for this provider.
+ */
+ public String toString() {
+ return name + " version " + version;
+ }
+
+ /*
+ * override the following methods to ensure that provider
+ * information can only be changed if the caller has the appropriate
+ * permissions.
+ */
+
+ /**
+ * Clears this provider so that it no longer contains the properties
+ * used to look up facilities implemented by the provider.
+ *
+ * <p>First, if there is a security manager, its
+ * <code>checkSecurityAccess</code> method is called with the string
+ * <code>"clearProviderProperties."+name</code> (where <code>name</code>
+ * is the provider name) to see if it's ok to clear this provider.
+ * If the default implementation of <code>checkSecurityAccess</code>
+ * is used (that is, that method is not overriden), then this results in
+ * a call to the security manager's <code>checkPermission</code> method
+ * with a <code>SecurityPermission("clearProviderProperties."+name)</code>
+ * permission.
+ *
+ * @throws SecurityException
+ * if a security manager exists and its <code>{@link
+ * java.lang.SecurityManager#checkSecurityAccess}</code> method
+ * denies access to clear this provider
+ *
+ * @since 1.2
+ */
+ public synchronized void clear() {
+ check("clearProviderProperties."+name);
+ if (debug != null) {
+ debug.println("Remove " + name + " provider properties");
+ }
+ implClear();
+ }
+
+ /**
+ * Reads a property list (key and element pairs) from the input stream.
+ *
+ * @param inStream the input stream.
+ * @exception IOException if an error occurred when reading from the
+ * input stream.
+ * @see java.util.Properties#load
+ */
+ public synchronized void load(InputStream inStream) throws IOException {
+ check("putProviderProperty."+name);
+ if (debug != null) {
+ debug.println("Load " + name + " provider properties");
+ }
+ Properties tempProperties = new Properties();
+ tempProperties.load(inStream);
+ implPutAll(tempProperties);
+ }
+
+ /**
+ * Copies all of the mappings from the specified Map to this provider.
+ * These mappings will replace any properties that this provider had
+ * for any of the keys currently in the specified Map.
+ *
+ * @since 1.2
+ */
+ public synchronized void putAll(Map<?,?> t) {
+ check("putProviderProperty."+name);
+ if (debug != null) {
+ debug.println("Put all " + name + " provider properties");
+ }
+ implPutAll(t);
+ }
+
+ /**
+ * Returns an unmodifiable Set view of the property entries contained
+ * in this Provider.
+ *
+ * @see java.util.Map.Entry
+ * @since 1.2
+ */
+ public synchronized Set<Map.Entry<Object,Object>> entrySet() {
+ checkInitialized();
+ if (entrySet == null) {
+ if (entrySetCallCount++ == 0) // Initial call
+ entrySet = Collections.unmodifiableMap(this).entrySet();
+ else
+ return super.entrySet(); // Recursive call
+ }
+
+ // This exception will be thrown if the implementation of
+ // Collections.unmodifiableMap.entrySet() is changed such that it
+ // no longer calls entrySet() on the backing Map. (Provider's
+ // entrySet implementation depends on this "implementation detail",
+ // which is unlikely to change.
+ if (entrySetCallCount != 2)
+ throw new RuntimeException("Internal error.");
+
+ return entrySet;
+ }
+
+ /**
+ * Returns an unmodifiable Set view of the property keys contained in
+ * this provider.
+ *
+ * @since 1.2
+ */
+ public Set<Object> keySet() {
+ checkInitialized();
+ return Collections.unmodifiableSet(super.keySet());
+ }
+
+ /**
+ * Returns an unmodifiable Collection view of the property values
+ * contained in this provider.
+ *
+ * @since 1.2
+ */
+ public Collection<Object> values() {
+ checkInitialized();
+ return Collections.unmodifiableCollection(super.values());
+ }
+
+ /**
+ * Sets the <code>key</code> property to have the specified
+ * <code>value</code>.
+ *
+ * <p>First, if there is a security manager, its
+ * <code>checkSecurityAccess</code> method is called with the string
+ * <code>"putProviderProperty."+name</code>, where <code>name</code> is the
+ * provider name, to see if it's ok to set this provider's property values.
+ * If the default implementation of <code>checkSecurityAccess</code>
+ * is used (that is, that method is not overriden), then this results in
+ * a call to the security manager's <code>checkPermission</code> method
+ * with a <code>SecurityPermission("putProviderProperty."+name)</code>
+ * permission.
+ *
+ * @param key the property key.
+ *
+ * @param value the property value.
+ *
+ * @return the previous value of the specified property
+ * (<code>key</code>), or null if it did not have one.
+ *
+ * @throws SecurityException
+ * if a security manager exists and its <code>{@link
+ * java.lang.SecurityManager#checkSecurityAccess}</code> method
+ * denies access to set property values.
+ *
+ * @since 1.2
+ */
+ public synchronized Object put(Object key, Object value) {
+ check("putProviderProperty."+name);
+ if (debug != null) {
+ debug.println("Set " + name + " provider property [" +
+ key + "/" + value +"]");
+ }
+ return implPut(key, value);
+ }
+
+ /**
+ * Removes the <code>key</code> property (and its corresponding
+ * <code>value</code>).
+ *
+ * <p>First, if there is a security manager, its
+ * <code>checkSecurityAccess</code> method is called with the string
+ * <code>"removeProviderProperty."+name</code>, where <code>name</code> is
+ * the provider name, to see if it's ok to remove this provider's
+ * properties. If the default implementation of
+ * <code>checkSecurityAccess</code> is used (that is, that method is not
+ * overriden), then this results in a call to the security manager's
+ * <code>checkPermission</code> method with a
+ * <code>SecurityPermission("removeProviderProperty."+name)</code>
+ * permission.
+ *
+ * @param key the key for the property to be removed.
+ *
+ * @return the value to which the key had been mapped,
+ * or null if the key did not have a mapping.
+ *
+ * @throws SecurityException
+ * if a security manager exists and its <code>{@link
+ * java.lang.SecurityManager#checkSecurityAccess}</code> method
+ * denies access to remove this provider's properties.
+ *
+ * @since 1.2
+ */
+ public synchronized Object remove(Object key) {
+ check("removeProviderProperty."+name);
+ if (debug != null) {
+ debug.println("Remove " + name + " provider property " + key);
+ }
+ return implRemove(key);
+ }
+
+ // let javadoc show doc from superclass
+ public Object get(Object key) {
+ checkInitialized();
+ return super.get(key);
+ }
+
+ // let javadoc show doc from superclass
+ public Enumeration<Object> keys() {
+ checkInitialized();
+ return super.keys();
+ }
+
+ // let javadoc show doc from superclass
+ public Enumeration<Object> elements() {
+ checkInitialized();
+ return super.elements();
+ }
+
+ // let javadoc show doc from superclass
+ public String getProperty(String key) {
+ checkInitialized();
+ return super.getProperty(key);
+ }
+
+ private void checkInitialized() {
+ if (!initialized) {
+ throw new IllegalStateException();
+ }
+ }
+
+ private void check(String directive) {
+ checkInitialized();
+ SecurityManager security = System.getSecurityManager();
+ if (security != null) {
+ security.checkSecurityAccess(directive);
+ }
+ }
+
+ // legacy properties changed since last call to any services method?
+ private transient boolean legacyChanged;
+ // serviceMap changed since last call to getServices()
+ private transient boolean servicesChanged;
+
+ // Map<String,String>
+ private transient Map<String,String> legacyStrings;
+
+ // Map<ServiceKey,Service>
+ // used for services added via putService(), initialized on demand
+ private transient Map<ServiceKey,Service> serviceMap;
+
+ // Map<ServiceKey,Service>
+ // used for services added via legacy methods, init on demand
+ private transient Map<ServiceKey,Service> legacyMap;
+
+ // Set<Service>
+ // Unmodifiable set of all services. Initialized on demand.
+ private transient Set<Service> serviceSet;
+
+ // register the id attributes for this provider
+ // this is to ensure that equals() and hashCode() do not incorrectly
+ // report to different provider objects as the same
+ private void putId() {
+ // note: name and info may be null
+ super.put("Provider.id name", String.valueOf(name));
+ super.put("Provider.id version", String.valueOf(version));
+ super.put("Provider.id info", String.valueOf(info));
+ super.put("Provider.id className", this.getClass().getName());
+ }
+
+ private void readObject(ObjectInputStream in)
+ throws IOException, ClassNotFoundException {
+ Map<Object,Object> copy = new HashMap<Object,Object>();
+ for (Map.Entry<Object,Object> entry : super.entrySet()) {
+ copy.put(entry.getKey(), entry.getValue());
+ }
+ defaults = null;
+ in.defaultReadObject();
+ implClear();
+ initialized = true;
+ putAll(copy);
+ }
+
+ /**
+ * Copies all of the mappings from the specified Map to this provider.
+ * Internal method to be called AFTER the security check has been
+ * performed.
+ */
+ private void implPutAll(Map t) {
+ for (Map.Entry e : ((Map<?,?>)t).entrySet()) {
+ implPut(e.getKey(), e.getValue());
+ }
+ }
+
+ private Object implRemove(Object key) {
+ if (key instanceof String) {
+ String keyString = (String)key;
+ if (keyString.startsWith("Provider.")) {
+ return null;
+ }
+ legacyChanged = true;
+ if (legacyStrings == null) {
+ legacyStrings = new LinkedHashMap<String,String>();
+ }
+ legacyStrings.remove(keyString);
+ }
+ return super.remove(key);
+ }
+
+ private Object implPut(Object key, Object value) {
+ if ((key instanceof String) && (value instanceof String)) {
+ String keyString = (String)key;
+ if (keyString.startsWith("Provider.")) {
+ return null;
+ }
+ legacyChanged = true;
+ if (legacyStrings == null) {
+ legacyStrings = new LinkedHashMap<String,String>();
+ }
+ legacyStrings.put(keyString, (String)value);
+ }
+ return super.put(key, value);
+ }
+
+ private void implClear() {
+ if (legacyStrings != null) {
+ legacyStrings.clear();
+ }
+ if (legacyMap != null) {
+ legacyMap.clear();
+ }
+ if (serviceMap != null) {
+ serviceMap.clear();
+ }
+ legacyChanged = false;
+ servicesChanged = false;
+ serviceSet = null;
+ super.clear();
+ putId();
+ }
+
+ // used as key in the serviceMap and legacyMap HashMaps
+ private static class ServiceKey {
+ private final String type;
+ private final String algorithm;
+ private final String originalAlgorithm;
+ private ServiceKey(String type, String algorithm, boolean intern) {
+ this.type = type;
+ this.originalAlgorithm = algorithm;
+ algorithm = algorithm.toUpperCase(ENGLISH);
+ this.algorithm = intern ? algorithm.intern() : algorithm;
+ }
+ public int hashCode() {
+ return type.hashCode() + algorithm.hashCode();
+ }
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof ServiceKey == false) {
+ return false;
+ }
+ ServiceKey other = (ServiceKey)obj;
+ return this.type.equals(other.type)
+ && this.algorithm.equals(other.algorithm);
+ }
+ boolean matches(String type, String algorithm) {
+ return (this.type == type) && (this.originalAlgorithm == algorithm);
+ }
+ }
+
+ /**
+ * Ensure all the legacy String properties are fully parsed into
+ * service objects.
+ */
+ private void ensureLegacyParsed() {
+ if ((legacyChanged == false) || (legacyStrings == null)) {
+ return;
+ }
+ serviceSet = null;
+ if (legacyMap == null) {
+ legacyMap = new LinkedHashMap<ServiceKey,Service>();
+ } else {
+ legacyMap.clear();
+ }
+ for (Map.Entry<String,String> entry : legacyStrings.entrySet()) {
+ parseLegacyPut(entry.getKey(), entry.getValue());
+ }
+ removeInvalidServices(legacyMap);
+ legacyChanged = false;
+ }
+
+ /**
+ * Remove all invalid services from the Map. Invalid services can only
+ * occur if the legacy properties are inconsistent or incomplete.
+ */
+ private void removeInvalidServices(Map<ServiceKey,Service> map) {
+ for (Iterator t = map.entrySet().iterator(); t.hasNext(); ) {
+ Map.Entry entry = (Map.Entry)t.next();
+ Service s = (Service)entry.getValue();
+ if (s.isValid() == false) {
+ t.remove();
+ }
+ }
+ }
+
+ private String[] getTypeAndAlgorithm(String key) {
+ int i = key.indexOf(".");
+ if (i < 1) {
+ if (debug != null) {
+ debug.println("Ignoring invalid entry in provider "
+ + name + ":" + key);
+ }
+ return null;
+ }
+ String type = key.substring(0, i);
+ String alg = key.substring(i + 1);
+ return new String[] {type, alg};
+ }
+
+ private final static String ALIAS_PREFIX = "Alg.Alias.";
+ private final static String ALIAS_PREFIX_LOWER = "alg.alias.";
+ private final static int ALIAS_LENGTH = ALIAS_PREFIX.length();
+
+ private void parseLegacyPut(String name, String value) {
+ if (name.toLowerCase(ENGLISH).startsWith(ALIAS_PREFIX_LOWER)) {
+ // e.g. put("Alg.Alias.MessageDigest.SHA", "SHA-1");
+ // aliasKey ~ MessageDigest.SHA
+ String stdAlg = value;
+ String aliasKey = name.substring(ALIAS_LENGTH);
+ String[] typeAndAlg = getTypeAndAlgorithm(aliasKey);
+ if (typeAndAlg == null) {
+ return;
+ }
+ String type = getEngineName(typeAndAlg[0]);
+ String aliasAlg = typeAndAlg[1].intern();
+ ServiceKey key = new ServiceKey(type, stdAlg, true);
+ Service s = (Service)legacyMap.get(key);
+ if (s == null) {
+ s = new Service(this);
+ s.type = type;
+ s.algorithm = stdAlg;
+ legacyMap.put(key, s);
+ }
+ legacyMap.put(new ServiceKey(type, aliasAlg, true), s);
+ s.addAlias(aliasAlg);
+ } else {
+ String[] typeAndAlg = getTypeAndAlgorithm(name);
+ if (typeAndAlg == null) {
+ return;
+ }
+ int i = typeAndAlg[1].indexOf(' ');
+ if (i == -1) {
+ // e.g. put("MessageDigest.SHA-1", "sun.security.provider.SHA");
+ String type = getEngineName(typeAndAlg[0]);
+ String stdAlg = typeAndAlg[1].intern();
+ String className = value;
+ ServiceKey key = new ServiceKey(type, stdAlg, true);
+ Service s = (Service)legacyMap.get(key);
+ if (s == null) {
+ s = new Service(this);
+ s.type = type;
+ s.algorithm = stdAlg;
+ legacyMap.put(key, s);
+ }
+ s.className = className;
+ } else { // attribute
+ // e.g. put("MessageDigest.SHA-1 ImplementedIn", "Software");
+ String attributeValue = value;
+ String type = getEngineName(typeAndAlg[0]);
+ String attributeString = typeAndAlg[1];
+ String stdAlg = attributeString.substring(0, i).intern();
+ String attributeName = attributeString.substring(i + 1);
+ // kill additional spaces
+ while (attributeName.startsWith(" ")) {
+ attributeName = attributeName.substring(1);
+ }
+ attributeName = attributeName.intern();
+ ServiceKey key = new ServiceKey(type, stdAlg, true);
+ Service s = (Service)legacyMap.get(key);
+ if (s == null) {
+ s = new Service(this);
+ s.type = type;
+ s.algorithm = stdAlg;
+ legacyMap.put(key, s);
+ }
+ s.addAttribute(attributeName, attributeValue);
+ }
+ }
+ }
+
+ /**
+ * Get the service describing this Provider's implementation of the
+ * specified type of this algorithm or alias. If no such
+ * implementation exists, this method returns null. If there are two
+ * matching services, one added to this provider using
+ * {@link #putService putService()} and one added via {@link #put put()},
+ * the service added via {@link #putService putService()} is returned.
+ *
+ * @param type the type of {@link Service service} requested
+ * (for example, <code>MessageDigest</code>)
+ * @param algorithm the case insensitive algorithm name (or alternate
+ * alias) of the service requested (for example, <code>SHA-1</code>)
+ *
+ * @return the service describing this Provider's matching service
+ * or null if no such service exists
+ *
+ * @throws NullPointerException if type or algorithm is null
+ *
+ * @since 1.5
+ */
+ public synchronized Service getService(String type, String algorithm) {
+ checkInitialized();
+ // avoid allocating a new key object if possible
+ ServiceKey key = previousKey;
+ if (key.matches(type, algorithm) == false) {
+ key = new ServiceKey(type, algorithm, false);
+ previousKey = key;
+ }
+ if (serviceMap != null) {
+ Service service = serviceMap.get(key);
+ if (service != null) {
+ return service;
+ }
+ }
+ ensureLegacyParsed();
+ return (legacyMap != null) ? legacyMap.get(key) : null;
+ }
+
+ // ServiceKey from previous getService() call
+ // by re-using it if possible we avoid allocating a new object
+ // and the toUpperCase() call.
+ // re-use will occur e.g. as the framework traverses the provider
+ // list and queries each provider with the same values until it finds
+ // a matching service
+ private static volatile ServiceKey previousKey =
+ new ServiceKey("", "", false);
+
+ /**
+ * Get an unmodifiable Set of all services supported by
+ * this Provider.
+ *
+ * @return an unmodifiable Set of all services supported by
+ * this Provider
+ *
+ * @since 1.5
+ */
+ public synchronized Set<Service> getServices() {
+ checkInitialized();
+ if (legacyChanged || servicesChanged) {
+ serviceSet = null;
+ }
+ if (serviceSet == null) {
+ ensureLegacyParsed();
+ Set<Service> set = new LinkedHashSet<Service>();
+ if (serviceMap != null) {
+ set.addAll(serviceMap.values());
+ }
+ if (legacyMap != null) {
+ set.addAll(legacyMap.values());
+ }
+ serviceSet = Collections.unmodifiableSet(set);
+ servicesChanged = false;
+ }
+ return serviceSet;
+ }
+
+ /**
+ * Add a service. If a service of the same type with the same algorithm
+ * name exists and it was added using {@link #putService putService()},
+ * it is replaced by the new service.
+ * This method also places information about this service
+ * in the provider's Hashtable values in the format described in the
+ * <a href="../../../technotes/guides/security/crypto/CryptoSpec.html">
+ * Java Cryptography Architecture API Specification & Reference </a>.
+ *
+ * <p>Also, if there is a security manager, its
+ * <code>checkSecurityAccess</code> method is called with the string
+ * <code>"putProviderProperty."+name</code>, where <code>name</code> is
+ * the provider name, to see if it's ok to set this provider's property
+ * values. If the default implementation of <code>checkSecurityAccess</code>
+ * is used (that is, that method is not overriden), then this results in
+ * a call to the security manager's <code>checkPermission</code> method with
+ * a <code>SecurityPermission("putProviderProperty."+name)</code>
+ * permission.
+ *
+ * @param s the Service to add
+ *
+ * @throws SecurityException
+ * if a security manager exists and its <code>{@link
+ * java.lang.SecurityManager#checkSecurityAccess}</code> method denies
+ * access to set property values.
+ * @throws NullPointerException if s is null
+ *
+ * @since 1.5
+ */
+ protected synchronized void putService(Service s) {
+ check("putProviderProperty." + name);
+ if (debug != null) {
+ debug.println(name + ".putService(): " + s);
+ }
+ if (s == null) {
+ throw new NullPointerException();
+ }
+ if (s.getProvider() != this) {
+ throw new IllegalArgumentException
+ ("service.getProvider() must match this Provider object");
+ }
+ if (serviceMap == null) {
+ serviceMap = new LinkedHashMap<ServiceKey,Service>();
+ }
+ servicesChanged = true;
+ String type = s.getType();
+ String algorithm = s.getAlgorithm();
+ ServiceKey key = new ServiceKey(type, algorithm, true);
+ // remove existing service
+ implRemoveService(serviceMap.get(key));
+ serviceMap.put(key, s);
+ for (String alias : s.getAliases()) {
+ serviceMap.put(new ServiceKey(type, alias, true), s);
+ }
+ putPropertyStrings(s);
+ }
+
+ /**
+ * Put the string properties for this Service in this Provider's
+ * Hashtable.
+ */
+ private void putPropertyStrings(Service s) {
+ String type = s.getType();
+ String algorithm = s.getAlgorithm();
+ // use super() to avoid permission check and other processing
+ super.put(type + "." + algorithm, s.getClassName());
+ for (String alias : s.getAliases()) {
+ super.put(ALIAS_PREFIX + type + "." + alias, algorithm);
+ }
+ for (Map.Entry<UString,String> entry : s.attributes.entrySet()) {
+ String key = type + "." + algorithm + " " + entry.getKey();
+ super.put(key, entry.getValue());
+ }
+ }
+
+ /**
+ * Remove the string properties for this Service from this Provider's
+ * Hashtable.
+ */
+ private void removePropertyStrings(Service s) {
+ String type = s.getType();
+ String algorithm = s.getAlgorithm();
+ // use super() to avoid permission check and other processing
+ super.remove(type + "." + algorithm);
+ for (String alias : s.getAliases()) {
+ super.remove(ALIAS_PREFIX + type + "." + alias);
+ }
+ for (Map.Entry<UString,String> entry : s.attributes.entrySet()) {
+ String key = type + "." + algorithm + " " + entry.getKey();
+ super.remove(key);
+ }
+ }
+
+ /**
+ * Remove a service previously added using
+ * {@link #putService putService()}. The specified service is removed from
+ * this provider. It will no longer be returned by
+ * {@link #getService getService()} and its information will be removed
+ * from this provider's Hashtable.
+ *
+ * <p>Also, if there is a security manager, its
+ * <code>checkSecurityAccess</code> method is called with the string
+ * <code>"removeProviderProperty."+name</code>, where <code>name</code> is
+ * the provider name, to see if it's ok to remove this provider's
+ * properties. If the default implementation of
+ * <code>checkSecurityAccess</code> is used (that is, that method is not
+ * overriden), then this results in a call to the security manager's
+ * <code>checkPermission</code> method with a
+ * <code>SecurityPermission("removeProviderProperty."+name)</code>
+ * permission.
+ *
+ * @param s the Service to be removed
+ *
+ * @throws SecurityException
+ * if a security manager exists and its <code>{@link
+ * java.lang.SecurityManager#checkSecurityAccess}</code> method denies
+ * access to remove this provider's properties.
+ * @throws NullPointerException if s is null
+ *
+ * @since 1.5
+ */
+ protected synchronized void removeService(Service s) {
+ check("removeProviderProperty." + name);
+ if (debug != null) {
+ debug.println(name + ".removeService(): " + s);
+ }
+ if (s == null) {
+ throw new NullPointerException();
+ }
+ implRemoveService(s);
+ }
+
+ private void implRemoveService(Service s) {
+ if ((s == null) || (serviceMap == null)) {
+ return;
+ }
+ String type = s.getType();
+ String algorithm = s.getAlgorithm();
+ ServiceKey key = new ServiceKey(type, algorithm, false);
+ Service oldService = serviceMap.get(key);
+ if (s != oldService) {
+ return;
+ }
+ servicesChanged = true;
+ serviceMap.remove(key);
+ for (String alias : s.getAliases()) {
+ serviceMap.remove(new ServiceKey(type, alias, false));
+ }
+ removePropertyStrings(s);
+ }
+
+ // Wrapped String that behaves in a case insensitive way for equals/hashCode
+ private static class UString {
+ final String string;
+ final String lowerString;
+
+ UString(String s) {
+ this.string = s;
+ this.lowerString = s.toLowerCase(ENGLISH);
+ }
+
+ public int hashCode() {
+ return lowerString.hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof UString == false) {
+ return false;
+ }
+ UString other = (UString)obj;
+ return lowerString.equals(other.lowerString);
+ }
+
+ public String toString() {
+ return string;
+ }
+ }
+
+ // describe relevant properties of a type of engine
+ private static class EngineDescription {
+ final String name;
+ final boolean supportsParameter;
+ final String constructorParameterClassName;
+ private volatile Class constructorParameterClass;
+
+ EngineDescription(String name, boolean sp, String paramName) {
+ this.name = name;
+ this.supportsParameter = sp;
+ this.constructorParameterClassName = paramName;
+ }
+ Class getConstructorParameterClass() throws ClassNotFoundException {
+ Class clazz = constructorParameterClass;
+ if (clazz == null) {
+ clazz = Class.forName(constructorParameterClassName);
+ constructorParameterClass = clazz;
+ }
+ return clazz;
+ }
+ }
+
+ // built in knowledge of the engine types shipped as part of the JDK
+ private static final Map<String,EngineDescription> knownEngines;
+
+ private static void addEngine(String name, boolean sp, String paramName) {
+ EngineDescription ed = new EngineDescription(name, sp, paramName);
+ // also index by canonical name to avoid toLowerCase() for some lookups
+ knownEngines.put(name.toLowerCase(ENGLISH), ed);
+ knownEngines.put(name, ed);
+ }
+
+ static {
+ knownEngines = new HashMap<String,EngineDescription>();
+ // JCA
+ addEngine("AlgorithmParameterGenerator", false, null);
+ addEngine("AlgorithmParameters", false, null);
+ addEngine("KeyFactory", false, null);
+ addEngine("KeyPairGenerator", false, null);
+ addEngine("KeyStore", false, null);
+ addEngine("MessageDigest", false, null);
+ addEngine("SecureRandom", false, null);
+ addEngine("Signature", true, null);
+ addEngine("CertificateFactory", false, null);
+ addEngine("CertPathBuilder", false, null);
+ addEngine("CertPathValidator", false, null);
+ addEngine("CertStore", false,
+ "java.security.cert.CertStoreParameters");
+ // JCE
+ addEngine("Cipher", true, null);
+ addEngine("ExemptionMechanism", false, null);
+ addEngine("Mac", true, null);
+ addEngine("KeyAgreement", true, null);
+ addEngine("KeyGenerator", false, null);
+ addEngine("SecretKeyFactory", false, null);
+ // JSSE
+ addEngine("KeyManagerFactory", false, null);
+ addEngine("SSLContext", false, null);
+ addEngine("TrustManagerFactory", false, null);
+ // JGSS
+ addEngine("GssApiMechanism", false, null);
+ // SASL
+ addEngine("SaslClientFactory", false, null);
+ addEngine("SaslServerFactory", false, null);
+ // POLICY
+ addEngine("Policy", false,
+ "java.security.Policy$Parameters");
+ // CONFIGURATION
+ addEngine("Configuration", false,
+ "javax.security.auth.login.Configuration$Parameters");
+ // XML DSig
+ addEngine("XMLSignatureFactory", false, null);
+ addEngine("KeyInfoFactory", false, null);
+ addEngine("TransformService", false, null);
+ // Smart Card I/O
+ addEngine("TerminalFactory", false,
+ "java.lang.Object");
+ }
+
+ // get the "standard" (mixed-case) engine name for arbitary case engine name
+ // if there is no known engine by that name, return s
+ private static String getEngineName(String s) {
+ // try original case first, usually correct
+ EngineDescription e = knownEngines.get(s);
+ if (e == null) {
+ e = knownEngines.get(s.toLowerCase(ENGLISH));
+ }
+ return (e == null) ? s : e.name;
+ }
+
+ /**
+ * The description of a security service. It encapsulates the properties
+ * of a service and contains a factory method to obtain new implementation
+ * instances of this service.
+ *
+ * <p>Each service has a provider that offers the service, a type,
+ * an algorithm name, and the name of the class that implements the
+ * service. Optionally, it also includes a list of alternate ...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-23 04:52:08
|
Revision: 3286
http://jnode.svn.sourceforge.net/jnode/?rev=3286&view=rev
Author: lsantha
Date: 2007-06-22 21:52:05 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/java/java/io/IOException.java
Added: trunk/core/src/openjdk/java/java/io/IOException.java
===================================================================
--- trunk/core/src/openjdk/java/java/io/IOException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/io/IOException.java 2007-06-23 04:52:05 UTC (rev 3286)
@@ -0,0 +1,102 @@
+/*
+ * Copyright 1994-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.io;
+
+/**
+ * Signals that an I/O exception of some sort has occurred. This
+ * class is the general class of exceptions produced by failed or
+ * interrupted I/O operations.
+ *
+ * @author unascribed
+ * @version 1.30, 05/05/07
+ * @see java.io.InputStream
+ * @see java.io.OutputStream
+ * @since JDK1.0
+ */
+public
+class IOException extends Exception {
+ static final long serialVersionUID = 7818375828146090155L;
+
+ /**
+ * Constructs an {@code IOException} with {@code null}
+ * as its error detail message.
+ */
+ public IOException() {
+ super();
+ }
+
+ /**
+ * Constructs an {@code IOException} with the specified detail message.
+ *
+ * @param message
+ * The detail message (which is saved for later retrieval
+ * by the {@link #getMessage()} method)
+ */
+ public IOException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs an {@code IOException} with the specified detail message
+ * and cause.
+ *
+ * <p> Note that the detail message associated with {@code cause} is
+ * <i>not</i> automatically incorporated into this exception's detail
+ * message.
+ *
+ * @param message
+ * The detail message (which is saved for later retrieval
+ * by the {@link #getMessage()} method)
+ *
+ * @param cause
+ * The cause (which is saved for later retrieval by the
+ * {@link #getCause()} method). (A null value is permitted,
+ * and indicates that the cause is nonexistent or unknown.)
+ *
+ * @since 1.6
+ */
+ public IOException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs an {@code IOException} with the specified cause and a
+ * detail message of {@code (cause==null ? null : cause.toString())}
+ * (which typically contains the class and detail message of {@code cause}).
+ * This constructor is useful for IO exceptions that are little more
+ * than wrappers for other throwables.
+ *
+ * @param cause
+ * The cause (which is saved for later retrieval by the
+ * {@link #getCause()} method). (A null value is permitted,
+ * and indicates that the cause is nonexistent or unknown.)
+ *
+ * @since 1.6
+ */
+ public IOException(Throwable cause) {
+ super(cause);
+ }
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-23 04:51:37
|
Revision: 3285
http://jnode.svn.sourceforge.net/jnode/?rev=3285&view=rev
Author: lsantha
Date: 2007-06-22 21:51:34 -0700 (Fri, 22 Jun 2007)
Log Message:
-----------
Openjdk integration.
Modified Paths:
--------------
trunk/core/src/classpath/java/java/security/Security.java
Removed Paths:
-------------
trunk/core/src/classpath/java/java/security/AlgorithmParameters.java
trunk/core/src/classpath/java/java/security/Provider.java
trunk/core/src/classpath/java/java/security/cert/
Deleted: trunk/core/src/classpath/java/java/security/AlgorithmParameters.java
===================================================================
--- trunk/core/src/classpath/java/java/security/AlgorithmParameters.java 2007-06-21 19:33:38 UTC (rev 3284)
+++ trunk/core/src/classpath/java/java/security/AlgorithmParameters.java 2007-06-23 04:51:34 UTC (rev 3285)
@@ -1,304 +0,0 @@
-/* AlgorithmParameters.java --- Algorithm Parameters Implementation Class
- Copyright (C) 1999, 2003, 2004 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package java.security;
-
-import gnu.java.security.Engine;
-
-import java.io.IOException;
-import java.security.spec.AlgorithmParameterSpec;
-import java.security.spec.InvalidParameterSpecException;
-
-/**
- * <code>AlgorithmParameters</code> is an Algorithm Parameters class which
- * provides an interface through which the user can manage the parameters of an
- * Algorithm.
- *
- * @author Mark Benvenuto
- * @since 1.2
- * @see AlgorithmParameterSpec
- * @see java.security.spec.DSAParameterSpec
- * @see KeyPairGenerator
- */
-public class AlgorithmParameters
-{
- /** Service name for algorithm parameters. */
- private static final String ALGORITHM_PARAMETERS = "AlgorithmParameters";
-
- private AlgorithmParametersSpi paramSpi;
- private Provider provider;
- private String algorithm;
-
- /**
- * Constructs a new instance of <code>AlgorithmParameters</code>.
- *
- * @param paramSpi
- * the engine to use.
- * @param provider
- * the provider to use.
- * @param algorithm
- * the algorithm to use.
- */
- protected AlgorithmParameters(AlgorithmParametersSpi paramSpi,
- Provider provider, String algorithm)
- {
- this.paramSpi = paramSpi;
- this.provider = provider;
- this.algorithm = algorithm;
- }
-
- /** @return A string with the name of the algorithm used. */
- public final String getAlgorithm()
- {
- return algorithm;
- }
-
- /**
- * Returns a new instance of <code>AlgorithmParameters</code> representing
- * the specified algorithm parameters.
- *
- * <p>The returned <code>AlgorithmParameters</code> must still be initialized
- * with an <code>init()</code> method.</p>
- *
- * @param algorithm
- * the algorithm to use.
- * @return the new instance repesenting the desired algorithm.
- * @throws NoSuchAlgorithmException
- * if the algorithm is not implemented by any provider.
- */
- public static AlgorithmParameters getInstance(String algorithm)
- throws NoSuchAlgorithmException
- {
- Provider[] p = Security.getProviders();
-
- for (int i = 0; i < p.length; i++)
- try
- {
- return getInstance(algorithm, p[i]);
- }
- catch (NoSuchAlgorithmException e)
- {
- // Ignore this.
- }
-
- throw new NoSuchAlgorithmException(algorithm);
- }
-
- /**
- * Returns a new instance of <code>AlgorithmParameters</code> representing
- * the specified algorithm parameters from a named provider.
- *
- * <p>The returned <code>AlgorithmParameters</code> must still be intialized
- * with an <code>init()</code> method.</p>
- *
- * @param algorithm
- * the algorithm to use.
- * @param provider
- * the name of the {@link Provider} to use.
- * @return the new instance repesenting the desired algorithm.
- * @throws NoSuchAlgorithmException
- * if the algorithm is not implemented by the named provider.
- * @throws NoSuchProviderException
- * if the named provider was not found.
- * @throws IllegalArgumentException
- * if <code>provider</code> is <code>null</code> or is an empty
- * string.
- */
- public static AlgorithmParameters getInstance(String algorithm, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException
- {
- if (provider == null || provider.length() == 0)
- throw new IllegalArgumentException("Illegal provider");
-
- Provider p = Security.getProvider(provider);
- if (p == null)
- throw new NoSuchProviderException(provider);
-
- return getInstance(algorithm, p);
- }
-
- /**
- * Returns a new instance of <code>AlgorithmParameters</code> representing
- * the specified algorithm parameters from the specified {@link Provider}.
- *
- * <p>The returned <code>AlgorithmParameters</code> must still be intialized
- * with an <code>init()</code> method.</p>
- *
- * @param algorithm
- * the algorithm to use.
- * @param provider
- * the {@link Provider} to use.
- * @return the new instance repesenting the desired algorithm.
- * @throws NoSuchAlgorithmException
- * if the algorithm is not implemented by the {@link Provider}.
- * @throws IllegalArgumentException
- * if <code>provider</code> is <code>null</code>.
- * @since 1.4
- */
- public static AlgorithmParameters getInstance(String algorithm,
- Provider provider)
- throws NoSuchAlgorithmException
- {
- if (provider == null)
- throw new IllegalArgumentException("Illegal provider");
-
- try
- {
- return new AlgorithmParameters((AlgorithmParametersSpi)
- Engine.getInstance(ALGORITHM_PARAMETERS, algorithm, provider),
- provider, algorithm);
- }
- catch (java.lang.reflect.InvocationTargetException ite)
- {
- throw new NoSuchAlgorithmException(algorithm);
- }
- catch (ClassCastException cce)
- {
- throw new NoSuchAlgorithmException(algorithm);
- }
- }
-
- /** @return the provider of this parameter object. */
- public final Provider getProvider()
- {
- return provider;
- }
-
- /**
- * Initializes the engine with the specified {@link AlgorithmParameterSpec}.
- *
- * @param paramSpec
- * A {@link AlgorithmParameterSpec} to use.
- * @throws InvalidParameterSpecException
- * if <code>paramSpec</code> is invalid.
- */
- public final void init(AlgorithmParameterSpec paramSpec)
- throws InvalidParameterSpecException
- {
- paramSpi.engineInit(paramSpec);
- }
-
- /**
- * Initializes the engine with the specified parameters stored in the byte
- * array and decodes them according to the ASN.1 specification. If the ASN.1
- * specification exists then it succeeds otherwise an {@link IOException} is
- * thrown.
- *
- * @param params
- * the parameters to use.
- * @throws IOException
- * if a decoding error occurs.
- */
- public final void init(byte[]params) throws IOException
- {
- paramSpi.engineInit(params);
- }
-
- /**
- * Initializes the engine with the specified parameters stored in the byte
- * array and decodes them according to the specified decoding specification.
- * If <code>format</code> is <code>null</code>, then this method decodes the
- * byte array using the ASN.1 specification if it exists, otherwise it throws
- * an {@link IOException}.
- *
- * @param params
- * the parameters to use.
- * @param format
- * the name of decoding format to use.
- * @throws IOException
- * if a decoding error occurs.
- */
- public final void init(byte[]params, String format) throws IOException
- {
- paramSpi.engineInit(params, format);
- }
-
- /**
- * Returns a new instance of <code>AlgorithmParameters</code> as a
- * designated parameter specification {@link Class}.
- *
- * @param paramSpec
- * the {@link Class} to use.
- * @return the parameter specification.
- * @throws InvalidParameterSpecException
- * if <code>paramSpec</code> is invalid.
- */
- public final AlgorithmParameterSpec getParameterSpec(Class paramSpec)
- throws InvalidParameterSpecException
- {
- return paramSpi.engineGetParameterSpec(paramSpec);
- }
-
- /**
- * Returns the parameters in the default encoding format. The primary encoding
- * format is ASN.1 if it exists for the specified type.
- *
- * @return byte array representing the parameters.
- */
- public final byte[] getEncoded() throws IOException
- {
- return paramSpi.engineGetEncoded();
- }
-
- /**
- * Returns the parameters in the specified encoding format. If
- * <code>format</code> is <code>null</code> then the ASN.1 encoding
- * format is used if it exists for the specified type.
- *
- * @param format
- * the name of the encoding format to use.
- * @return the parameters encoded using the specified encoding scheme.
- * @throws IOException
- * if an encoding exception occurs, or if this parameter object has
- * not been initialized.
- */
- public final byte[] getEncoded(String format) throws IOException
- {
- return paramSpi.engineGetEncoded(format);
- }
-
- /**
- * Returns a string representation of the encoded form.
- *
- * @return a string representation of the encoded form.
- */
- public final String toString()
- {
- return paramSpi.engineToString();
- }
-}
Deleted: trunk/core/src/classpath/java/java/security/Provider.java
===================================================================
--- trunk/core/src/classpath/java/java/security/Provider.java 2007-06-21 19:33:38 UTC (rev 3284)
+++ trunk/core/src/classpath/java/java/security/Provider.java 2007-06-23 04:51:34 UTC (rev 3285)
@@ -1,202 +0,0 @@
-/* Provider.java -- Security provider information
- Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package java.security;
-
-import java.io.Serializable;
-import java.util.Properties;
-
-/**
- * This class represents a Java security architecture service provider.
- * The services provided by a such a provider can range from security
- * algorithms to key generation.
- * <p>
- * Providers are installed by name and version number. There is one
- * standard provider supplied with the class library. This is the
- * "GNU" provider, which can also be accessed by the alias "SUN" for
- * compatibility with the JDK.
- *
- * @version 0.0
- *
- * @author Aaron M. Renn (ar...@ur...)
- */
-public abstract class Provider extends Properties implements Serializable
-{
- private static final long serialVersionUID = -4298000515446427739L;
-
- /**
- * This is a textual description of the provider
- */
- private String info;
-
- /**
- * This is the name of the provider
- */
- private String name;
-
- /**
- * This is the version number of the provider
- */
- private double version;
-
- /**
- * This method initializes a new instance of <code>Provider</code> to have
- * the specified name, version, and description information.
- *
- * @param name The name to assign to this <code>Provider</code>.
- * @param version The version number for this <code>Provider</code>.
- * @param info A textual description of this provider.
- */
- protected Provider(String name, double version, String info)
- {
- this.name = name;
- this.version = version;
- this.info = info;
- }
-
- /**
- * This method returns the name assigned to this <code>Provider</code>.
- *
- * @return The <code>Provider</code>'s name.
- */
- public String getName()
- {
- return (name);
- }
-
- /**
- * This method retunrs the version number of this <code>Provider</code>.
- *
- * @return The <code>Provider</code>'s version number.
- */
- public double getVersion()
- {
- return (version);
- }
-
- /**
- * This method returns a textual description of the <code>Provider</code>.
- *
- * @return A description of the <code>Provider</code>.
- */
- public String getInfo()
- {
- return (info);
- }
-
- /**
- * Sets the key property to have the specified value.
- * <p>
- * <bold>NOT IMPLEMENTED YET</bold>[
- * First, if there is a security manager, its <code>checkSecurityAccess</code>
- * method is called with the string "putProviderProperty."+name, where name is
- * the provider name, to see if it's ok to set this provider's property
- * values.
- * If the default implementation of <code>checkSecurityAccess</code> is used
- * (that is, that method is not overriden), then this results in a call to the
- * security manager's <code>checkPermission</code> method with a
- * <code>SecurityPermission("putProviderProperty."+name)</code>
- * permission.<br>]
- *
- * @param key The property key.
- * @param value The property value.
- *
- * @return The previous value of the specified property (<code>key</code>),
- * or <code>null</code> if it did not have one.
- * @throws SecurityException If a security manager exists and its
- * {@link java.lang.SecurityManager.checkSecurityAccess(java.lang.String)}
- * method denies access to set property values.
- * @since Classpath 0.4+cvs, JDK 1.2
- * @see java.lang.Object.equals(Object)
- * @see java.util.Hashtable.get(Object)
- */
- public Object put(Object key, Object value)
- {
- return super.put(toCanonicalKey(key), value);
- }
-
- // overrides same in java.util.Hashtable
- public Object get(Object key)
- {
- return super.get(toCanonicalKey(key));
- }
-
- /**
- * This method removes the specified key entry (and its associated value)
- * from the property mapping list.
- *
- * @param key The key to remove
- *
- * @return The previous value for this key, or <code>null</code> if no
- * previous value.
- */
- public Object remove(Object key)
- {
- return super.remove(toCanonicalKey(key));
- }
-
- /**
- * This method clears the entire property list such that it no longer
- * contains the properties used to look up the services provided by
- * the <code>Provider</code>.
- */
- public void clear()
- {
- super.clear();
- }
-
- /**
- * This method returns a <code>String</code> representation of this
- * object. This will include the <code>Provider</code> name and
- * version number.
- *
- * @return A <code>String</code> representation of this object.
- */
- public String toString()
- {
- return (getClass().getName() + ": name=" + getName() + " version=" +
- version);
- }
-
- private Object toCanonicalKey(Object key)
- {
- if (key.getClass().isAssignableFrom(String.class)) // is it ours?
- return ((String) key).toUpperCase(); // use default locale
- else
- return key;
- }
-}
Modified: trunk/core/src/classpath/java/java/security/Security.java
===================================================================
--- trunk/core/src/classpath/java/java/security/Security.java 2007-06-21 19:33:38 UTC (rev 3284)
+++ trunk/core/src/classpath/java/java/security/Security.java 2007-06-23 04:51:34 UTC (rev 3285)
@@ -57,6 +57,7 @@
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
+import sun.security.jca.GetInstance;
/**
* This class centralizes all security properties and common security methods.
@@ -707,4 +708,67 @@
return false;
}
+
+ //jnode openjdk
+ /*
+ * Returns an array of objects: the first object in the array is
+ * an instance of an implementation of the requested algorithm
+ * and type, and the second object in the array identifies the provider
+ * of that implementation.
+ * The <code>provider</code> argument can be null, in which case all
+ * configured providers will be searched in order of preference.
+ */
+ static Object[] getImpl(String algorithm, String type, String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException {
+ if (provider == null) {
+ return GetInstance.getInstance
+ (type, getSpiClass(type), algorithm).toArray();
+ } else {
+ return GetInstance.getInstance
+ (type, getSpiClass(type), algorithm, provider).toArray();
+ }
+ }
+
+ // Map containing cached Spi Class objects of the specified type
+ private static final Map<String,Class> spiMap =
+ new java.util.Hashtable<String,Class>();
+
+ /**
+ * Return the Class object for the given engine type
+ * (e.g. "MessageDigest"). Works for Spis in the java.security package
+ * only.
+ */
+ private static Class getSpiClass(String type) {
+ Class clazz = spiMap.get(type);
+ if (clazz != null) {
+ return clazz;
+ }
+ try {
+ clazz = Class.forName("java.security." + type + "Spi");
+ spiMap.put(type, clazz);
+ return clazz;
+ } catch (ClassNotFoundException e) {
+ throw (Error)new AssertionError("Spi class not found").initCause(e);
+ }
+ }
+
+ /*
+ * Returns an array of objects: the first object in the array is
+ * an instance of an implementation of the requested algorithm
+ * and type, and the second object in the array identifies the provider
+ * of that implementation.
+ * The <code>provider</code> argument cannot be null.
+ */
+ static Object[] getImpl(String algorithm, String type, Provider provider)
+ throws NoSuchAlgorithmException {
+ return GetInstance.getInstance
+ (type, getSpiClass(type), algorithm, provider).toArray();
+ }
+
+ static Object[] getImpl(String algorithm, String type, Provider provider,
+ Object params) throws NoSuchAlgorithmException,
+ InvalidAlgorithmParameterException {
+ return GetInstance.getInstance
+ (type, getSpiClass(type), algorithm, params, provider).toArray();
+ }
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-21 19:33:42
|
Revision: 3284
http://jnode.svn.sourceforge.net/jnode/?rev=3284&view=rev
Author: lsantha
Date: 2007-06-21 12:33:38 -0700 (Thu, 21 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/com/com/sun/rowset/
trunk/core/src/openjdk/com/com/sun/rowset/CachedRowSetImpl.java
trunk/core/src/openjdk/com/com/sun/rowset/FilteredRowSetImpl.java
trunk/core/src/openjdk/com/com/sun/rowset/JdbcRowSetImpl.java
trunk/core/src/openjdk/com/com/sun/rowset/JdbcRowSetResourceBundle.java
trunk/core/src/openjdk/com/com/sun/rowset/JoinRowSetImpl.java
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_de.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_es.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_fr.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_it.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_ja.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_ko.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_sv.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_zh_CN.properties
trunk/core/src/openjdk/com/com/sun/rowset/RowSetResourceBundle_zh_TW.properties
trunk/core/src/openjdk/com/com/sun/rowset/WebRowSetImpl.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/
trunk/core/src/openjdk/com/com/sun/rowset/internal/BaseRow.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/CachedRowSetReader.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/CachedRowSetWriter.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/InsertRow.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/Row.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/SyncResolverImpl.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/WebRowSetXmlReader.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/WebRowSetXmlWriter.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/XmlErrorHandler.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/XmlReaderContentHandler.java
trunk/core/src/openjdk/com/com/sun/rowset/internal/XmlResolver.java
trunk/core/src/openjdk/com/com/sun/rowset/package.html
trunk/core/src/openjdk/com/com/sun/rowset/providers/
trunk/core/src/openjdk/com/com/sun/rowset/providers/RIOptimisticProvider.java
trunk/core/src/openjdk/com/com/sun/rowset/providers/RIXMLProvider.java
trunk/core/src/openjdk/com/com/sun/rowset/providers/package.html
trunk/core/src/openjdk/sun/sun/security/util/Debug.java
trunk/core/src/openjdk/sun/sun/security/util/PropertyExpander.java
Added: trunk/core/src/openjdk/com/com/sun/rowset/CachedRowSetImpl.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/rowset/CachedRowSetImpl.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/rowset/CachedRowSetImpl.java 2007-06-21 19:33:38 UTC (rev 3284)
@@ -0,0 +1,10134 @@
+/*
+ * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.rowset;
+
+import java.sql.*;
+import javax.sql.*;
+import java.io.*;
+import java.math.*;
+import java.util.*;
+import java.text.*;
+
+import javax.sql.rowset.*;
+import javax.sql.rowset.spi.*;
+import javax.sql.rowset.serial.*;
+import com.sun.rowset.internal.*;
+import com.sun.rowset.providers.*;
+
+/**
+ * The standard implementation of the <code>CachedRowSet</code> interface.
+ *
+ * See interface defintion for full behaviour and implementation requirements.
+ * This reference implementation has made provision for a one-to-one write back
+ * facility and it is curremtly be possible to change the peristence provider
+ * during the life-time of any CachedRowSetImpl.
+ *
+ * @author Jonathan Bruce, Amit Handa
+ */
+
+public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetInternal, Serializable, Cloneable, CachedRowSet {
+
+ /**
+ * The <code>SyncProvider</code> used by the CachedRowSet
+ */
+ private SyncProvider provider;
+
+ /**
+ * The <code>RowSetReaderImpl</code> object that is the reader
+ * for this rowset. The method <code>execute</code> uses this
+ * reader as part of its implementation.
+ * @serial
+ */
+ private RowSetReader rowSetReader;
+
+ /**
+ * The <code>RowSetWriterImpl</code> object that is the writer
+ * for this rowset. The method <code>acceptChanges</code> uses
+ * this writer as part of its implementation.
+ * @serial
+ */
+ private RowSetWriter rowSetWriter;
+
+ /**
+ * The <code>Connection</code> object that connects with this
+ * <code>CachedRowSetImpl</code> object's current underlying data source.
+ */
+ private transient Connection conn;
+
+ /**
+ * The <code>ResultSetMetaData</code> object that contains information
+ * about the columns in the <code>ResultSet</code> object that is the
+ * current source of data for this <code>CachedRowSetImpl</code> object.
+ */
+ private transient ResultSetMetaData RSMD;
+
+ /**
+ * The <code>RowSetMetaData</code> object that contains information about
+ * the columns in this <code>CachedRowSetImpl</code> object.
+ * @serial
+ */
+ private RowSetMetaDataImpl RowSetMD;
+
+ // Properties of this RowSet
+
+ /**
+ * An array containing the columns in this <code>CachedRowSetImpl</code>
+ * object that form a unique identifier for a row. This array
+ * is used by the writer.
+ * @serial
+ */
+ private int keyCols[];
+
+ /**
+ * The name of the table in the underlying database to which updates
+ * should be written. This name is needed because most drivers
+ * do not return this information in a <code>ResultSetMetaData</code>
+ * object.
+ * @serial
+ */
+ private String tableName;
+
+
+ /**
+ * A <code>Vector</code> object containing the <code>Row</code>
+ * objects that comprise this <code>CachedRowSetImpl</code> object.
+ * @serial
+ */
+ private Vector rvh;
+ /**
+ * The current postion of the cursor in this <code>CachedRowSetImpl</code>
+ * object.
+ * @serial
+ */
+ private int cursorPos;
+
+ /**
+ * The current postion of the cursor in this <code>CachedRowSetImpl</code>
+ * object not counting rows that have been deleted, if any.
+ * <P>
+ * For example, suppose that the cursor is on the last row of a rowset
+ * that started with five rows and subsequently had the second and third
+ * rows deleted. The <code>absolutePos</code> would be <code>3</code>,
+ * whereas the <code>cursorPos</code> would be <code>5</code>.
+ * @serial
+ */
+ private int absolutePos;
+
+ /**
+ * The number of deleted rows currently in this <code>CachedRowSetImpl</code>
+ * object.
+ * @serial
+ */
+ private int numDeleted;
+
+ /**
+ * The total number of rows currently in this <code>CachedRowSetImpl</code>
+ * object.
+ * @serial
+ */
+ private int numRows;
+
+ /**
+ * A special row used for constructing a new row. A new
+ * row is constructed by using <code>ResultSet.updateXXX</code>
+ * methods to insert column values into the insert row.
+ * @serial
+ */
+ private InsertRow insertRow;
+
+ /**
+ * A <code>boolean</code> indicating whether the cursor is
+ * currently on the insert row.
+ * @serial
+ */
+ private boolean onInsertRow;
+
+ /**
+ * The field that temporarily holds the last position of the
+ * cursor before it moved to the insert row, thus preserving
+ * the number of the current row to which the cursor may return.
+ * @serial
+ */
+ private int currentRow;
+
+ /**
+ * A <code>boolean</code> indicating whether the last value
+ * returned was an SQL <code>NULL</code>.
+ * @serial
+ */
+ private boolean lastValueNull;
+
+ /**
+ * A <code>SQLWarning</code> which logs on the warnings
+ */
+ private SQLWarning sqlwarn;
+
+ /**
+ * Used to track match column for JoinRowSet consumption
+ */
+ private String strMatchColumn ="";
+
+ /**
+ * Used to track match column for JoinRowSet consumption
+ */
+ private int iMatchColumn = -1;
+
+ /**
+ * A <code>RowSetWarning</code> which logs on the warnings
+ */
+ private RowSetWarning rowsetWarning;
+
+ /**
+ * The default SyncProvider for the RI CachedRowSetImpl
+ */
+ private String DEFAULT_SYNC_PROVIDER = "com.sun.rowset.providers.RIOptimisticProvider";
+
+ /**
+ * The boolean variable indicating locatorsUpdateValue
+ */
+ private boolean dbmslocatorsUpdateCopy;
+
+ /**
+ * The <code>ResultSet</code> object that is used to maintain the data when
+ * a ResultSet and start position are passed as parameters to the populate function
+ */
+ private ResultSet resultSet;
+
+ /**
+ * The integer value indicating the end position in the ResultSetwhere the picking
+ * up of rows for populating a CachedRowSet object was left off.
+ */
+ private int endPos;
+
+ /**
+ * The integer value indicating the end position in the ResultSetwhere the picking
+ * up of rows for populating a CachedRowSet object was left off.
+ */
+ private int prevEndPos;
+
+ /**
+ * The integer value indicating the position in the ResultSet, to populate the
+ * CachedRowSet object.
+ */
+ private int startPos;
+
+ /**
+ * The integer value indicating the positon from where the page prior to this
+ * was populated.
+ */
+ private int startPrev;
+
+ /**
+ * The integer value indicating size of the page.
+ */
+ private int pageSize;
+
+ /**
+ * The integer value indicating number of rows that have been processed so far.
+ * Used for checking whether maxRows has been reached or not.
+ */
+ private int maxRowsreached;
+ /**
+ * The boolean value when true signifies that pages are still to follow and a
+ * false value indicates that this is the last page.
+ */
+ private boolean pagenotend = true;
+
+ /**
+ * The boolean value indicating whether this is the first page or not.
+ */
+ private boolean onFirstPage;
+
+ /**
+ * The boolean value indicating whether this is the last page or not.
+ */
+ private boolean onLastPage;
+
+ /**
+ * The integer value indicating how many times the populate function has been called.
+ */
+ private int populatecallcount;
+
+ /**
+ * The integer value indicating the total number of rows to be processed in the
+ * ResultSet object passed to the populate function.
+ */
+ private int totalRows;
+
+ /**
+ * The boolean value indicating how the CahedRowSet object has been populated for
+ * paging purpose. True indicates that connection parameter is passed.
+ */
+ private boolean callWithCon;
+
+ /**
+ * CachedRowSet reader object to read the data from the ResultSet when a connection
+ * parameter is passed to populate the CachedRowSet object for paging.
+ */
+ private CachedRowSetReader crsReader;
+
+ /**
+ * The Vector holding the Match Columns
+ */
+ private Vector iMatchColumns;
+
+ /**
+ * The Vector that will hold the Match Column names.
+ */
+ private Vector strMatchColumns;
+
+ /**
+ * Trigger that indicates whether the active SyncProvider is exposes the
+ * additional TransactionalWriter method
+ */
+ private boolean tXWriter = false;
+
+ /**
+ * The field object for a transactional RowSet writer
+ */
+ private TransactionalWriter tWriter = null;
+
+ private transient JdbcRowSetResourceBundle resBundle;
+
+
+
+ /**
+ * Constructs a new default <code>CachedRowSetImpl</code> object with
+ * the capacity to hold 100 rows. This new object has no metadata
+ * and has the following default values:
+ * <pre>
+ * onInsertRow = false
+ * insertRow = null
+ * cursorPos = 0
+ * numRows = 0
+ * showDeleted = false
+ * queryTimeout = 0
+ * maxRows = 0
+ * maxFieldSize = 0
+ * rowSetType = ResultSet.TYPE_SCROLL_INSENSITIVE
+ * concurrency = ResultSet.CONCUR_UPDATABLE
+ * readOnly = false
+ * isolation = Connection.TRANSACTION_READ_COMMITTED
+ * escapeProcessing = true
+ * onInsertRow = false
+ * insertRow = null
+ * cursorPos = 0
+ * absolutePos = 0
+ * numRows = 0
+ * </pre>
+ * A <code>CachedRowSetImpl</code> object is configured to use the default
+ * <code>RIOptimisticProvider</code> implementation to provide connectivity
+ * and synchronization capabilities to the set data source.
+ * <P>
+ * @throws SQLException if an error occurs
+ */
+ public CachedRowSetImpl() throws SQLException {
+
+ try {
+ resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+ } catch(IOException ioe) {
+
+ }
+
+ // set the Reader, this maybe overridden latter
+ provider =
+ (SyncProvider)SyncFactory.getInstance(DEFAULT_SYNC_PROVIDER);
+
+ if (!(provider instanceof RIOptimisticProvider)) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.invalidp").toString());
+ }
+
+ rowSetReader = (CachedRowSetReader)provider.getRowSetReader();
+ rowSetWriter = (CachedRowSetWriter)provider.getRowSetWriter();
+
+ // allocate the parameters collection
+ initParams();
+
+ initContainer();
+
+ // set up some default values
+ initProperties();
+
+ // insert row setup
+ onInsertRow = false;
+ insertRow = null;
+
+ // set the warninings
+ sqlwarn = new SQLWarning();
+ rowsetWarning = new RowSetWarning();
+
+ }
+
+ /**
+ * Provides a <code>CachedRowSetImpl</code> instance with the same default properties as
+ * as the zero parameter constructor.
+ * <pre>
+ * onInsertRow = false
+ * insertRow = null
+ * cursorPos = 0
+ * numRows = 0
+ * showDeleted = false
+ * queryTimeout = 0
+ * maxRows = 0
+ * maxFieldSize = 0
+ * rowSetType = ResultSet.TYPE_SCROLL_INSENSITIVE
+ * concurrency = ResultSet.CONCUR_UPDATABLE
+ * readOnly = false
+ * isolation = Connection.TRANSACTION_READ_COMMITTED
+ * escapeProcessing = true
+ * onInsertRow = false
+ * insertRow = null
+ * cursorPos = 0
+ * absolutePos = 0
+ * numRows = 0
+ * </pre>
+ *
+ * However, applications will have the means to specify at runtime the
+ * desired <code>SyncProvider</code> object.
+ * <p>
+ * For example, creating a <code>CachedRowSetImpl</code> object as follows ensures
+ * that a it is established with the <code>com.foo.provider.Impl</code> synchronization
+ * implementation providing the synchronization mechanism for this disconnected
+ * <code>RowSet</code> object.
+ * <pre>
+ * Hashtable env = new Hashtable();
+ * env.put(javax.sql.rowset.spi.SyncFactory.ROWSET_PROVIDER_NAME,
+ * "com.foo.provider.Impl");
+ * CachedRowSetImpl crs = new CachedRowSet(env);
+ * </pre>
+ * <p>
+ * Calling this constructor with a <code>null</code> parameter will
+ * cause the <code>SyncFactory</code> to provide the reference
+ * optimistic provider <code>com.sun.rowset.providers.RIOptimisticProvider</code>.
+ * <p>
+ * In addition, the following properties can be associated with the
+ * provider to assist in determining the choice of the synchronizaton
+ * provider such as:
+ * <ul>
+ * <li><code>ROWSET_SYNC_PROVIDER</code> - the property specifying the the
+ * <code>SyncProvider</code> class name to be instantiated by the
+ * <code>SyncFacttory</code>
+ * <li><code>ROWSET_SYNC_VENDOR</code> - the property specifying the software
+ * vendor associated with a <code>SyncProvider</code> implementation.
+ * <li><code>ROWSET_SYNC_PROVIDER_VER</code> - the property specifying the
+ * version of the <code>SyncProvider</code> implementation provided by the
+ * software vendor.
+ * </ul>
+ * More specific detailes are available in the <code>SyncFactory</code>
+ * and <code>SyncProvider</code> specificiations later in this document.
+ * <p>
+ * @param env a <code>Hashtable</code> object with a list of desired
+ * synchronization providers
+ * @throws SQLException if the requested provider cannot be found by the
+ * synchonization factory
+ * @see SyncProvider
+ */
+
+ public CachedRowSetImpl(Hashtable env) throws SQLException {
+
+
+ try {
+ resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+ } catch(IOException ioe) {
+ }
+
+
+ if (env == null) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.nullhash").toString());
+ }
+
+ String providerName = (String)env.get(
+ javax.sql.rowset.spi.SyncFactory.ROWSET_SYNC_PROVIDER);
+
+ // set the Reader, this maybe overridden latter
+ provider =
+ (SyncProvider)SyncFactory.getInstance(providerName);
+
+ rowSetReader = provider.getRowSetReader();
+ rowSetWriter = provider.getRowSetWriter();
+
+ initParams(); // allocate the parameters collection
+ initContainer();
+ initProperties(); // set up some default values
+
+ // insert row setup
+ onInsertRow = false;
+ insertRow = null;
+
+ }
+
+ /**
+ * Sets the <code>rvh</code> field to a new <code>Vector</code>
+ * object with a capacity of 100 and sets the
+ * <code>cursorPos</code> and <code>numRows</code> fields to zero.
+ */
+ private void initContainer() {
+
+ rvh = new Vector(100);
+ cursorPos = 0;
+ absolutePos = 0;
+ numRows = 0;
+ numDeleted = 0;
+ }
+
+ /**
+ * Sets the properties for this <code>CachedRowSetImpl</code> object to
+ * their default values. This method is called internally by the
+ * default constructor.
+ */
+
+ private void initProperties() throws SQLException {
+
+ try {
+ resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
+ } catch(IOException ioe) {
+ }
+ setShowDeleted(false);
+ setQueryTimeout(0);
+ setMaxRows(0);
+ setMaxFieldSize(0);
+ setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
+ setConcurrency(ResultSet.CONCUR_UPDATABLE);
+ if((rvh.size() > 0) && (isReadOnly() == false))
+ setReadOnly(false);
+ else
+ setReadOnly(true);
+ setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
+ setEscapeProcessing(true);
+ setTypeMap(null);
+ checkTransactionalWriter();
+
+ //Instantiating the vector for MatchColumns
+
+ iMatchColumns = new Vector(10);
+ for(int i = 0; i < 10 ; i++) {
+ iMatchColumns.add(i,new Integer(-1));
+ }
+
+ strMatchColumns = new Vector(10);
+ for(int j = 0; j < 10; j++) {
+ strMatchColumns.add(j,null);
+ }
+ }
+
+ /**
+ * Determine whether the SyncProvider's writer implements the
+ * <code>TransactionalWriter<code> interface
+ */
+ private void checkTransactionalWriter() {
+ if (rowSetWriter != null) {
+ Class c = rowSetWriter.getClass();
+ if (c != null) {
+ Class[] theInterfaces = c.getInterfaces();
+ for (int i = 0; i < theInterfaces.length; i++) {
+ if ((theInterfaces[i].getName()).indexOf("TransactionalWriter") > 0) {
+ tXWriter = true;
+ establishTransactionalWriter();
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Sets an private field to all transaction bounddaries to be set
+ */
+ private void establishTransactionalWriter() {
+ tWriter = (TransactionalWriter)provider.getRowSetWriter();
+ }
+
+ //-----------------------------------------------------------------------
+ // Properties
+ //-----------------------------------------------------------------------
+
+ /**
+ * Sets this <code>CachedRowSetImpl</code> object's command property
+ * to the given <code>String</code> object and clears the parameters,
+ * if any, that were set for the previous command.
+ * <P>
+ * The command property may not be needed
+ * if the rowset is produced by a data source, such as a spreadsheet,
+ * that does not support commands. Thus, this property is optional
+ * and may be <code>null</code>.
+ *
+ * @param cmd a <code>String</code> object containing an SQL query
+ * that will be set as the command; may be <code>null</code>
+ * @throws SQLException if an error occurs
+ */
+ public void setCommand(String cmd) throws SQLException {
+
+ super.setCommand(cmd);
+
+ if(!buildTableName(cmd).equals("")) {
+ this.setTableName(buildTableName(cmd));
+ }
+ }
+
+
+ //---------------------------------------------------------------------
+ // Reading and writing data
+ //---------------------------------------------------------------------
+
+ /**
+ * Populates this <code>CachedRowSetImpl</code> object with data from
+ * the given <code>ResultSet</code> object. This
+ * method is an alternative to the method <code>execute</code>
+ * for filling the rowset with data. The method <code>populate</code>
+ * does not require that the properties needed by the method
+ * <code>execute</code>, such as the <code>command</code> property,
+ * be set. This is true because the method <code>populate</code>
+ * is given the <code>ResultSet</code> object from
+ * which to get data and thus does not need to use the properties
+ * required for setting up a connection and executing this
+ * <code>CachedRowSetImpl</code> object's command.
+ * <P>
+ * After populating this rowset with data, the method
+ * <code>populate</code> sets the rowset's metadata and
+ * then sends a <code>RowSetChangedEvent</code> object
+ * to all registered listeners prior to returning.
+ *
+ * @param data the <code>ResultSet</code> object containing the data
+ * to be read into this <code>CachedRowSetImpl</code> object
+ * @throws SQLException if an error occurs; or the max row setting is
+ * violated while populating the RowSet
+ * @see #execute
+ */
+ public void populate(ResultSet data) throws SQLException {
+ int rowsFetched;
+ Row currentRow;
+ int numCols;
+ int i;
+ Map map = getTypeMap();
+ Object obj;
+ int mRows;
+
+ if (data == null) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.populate").toString());
+ }
+
+
+ // get the meta data for this ResultSet
+ RSMD = data.getMetaData();
+
+ // set up the metadata
+ RowSetMD = new RowSetMetaDataImpl();
+ initMetaData(RowSetMD, RSMD);
+
+ // release the meta-data so that aren't tempted to use it.
+ RSMD = null;
+ numCols = RowSetMD.getColumnCount();
+ mRows = this.getMaxRows();
+ rowsFetched = 0;
+ currentRow = null;
+
+ while ( data.next()) {
+
+ currentRow = new Row(numCols);
+
+ if ( rowsFetched > mRows && mRows > 0) {
+ rowsetWarning.setNextWarning(new RowSetWarning("Populating rows "
+ + "setting has exceeded max row setting"));
+ }
+ for ( i = 1; i <= numCols; i++) {
+ /*
+ * check if the user has set a map. If no map
+ * is set then use plain getObject. This lets
+ * us work with drivers that do not support
+ * getObject with a map in fairly sensible way
+ */
+ if (map == null) {
+ obj = data.getObject(i);
+ } else {
+ obj = data.getObject(i, map);
+ }
+ /*
+ * the following block checks for the various
+ * types that we have to serialize in order to
+ * store - right now only structs have been tested
+ */
+ if (obj instanceof Struct) {
+ obj = new SerialStruct((Struct)obj, map);
+ } else if (obj instanceof SQLData) {
+ obj = new SerialStruct((SQLData)obj, map);
+ } else if (obj instanceof Blob) {
+ obj = new SerialBlob((Blob)obj);
+ } else if (obj instanceof Clob) {
+ obj = new SerialClob((Clob)obj);
+ } else if (obj instanceof java.sql.Array) {
+ obj = new SerialArray((java.sql.Array)obj, map);
+ }
+
+ ((Row)currentRow).initColumnObject(i, obj);
+ }
+ rowsFetched++;
+ rvh.add(currentRow);
+ }
+
+ numRows = rowsFetched ;
+ // Also rowsFetched should be equal to rvh.size()
+
+ // notify any listeners that the rowset has changed
+ notifyRowSetChanged();
+
+
+ }
+
+ /**
+ * Initializes the given <code>RowSetMetaData</code> object with the values
+ * in the given <code>ResultSetMetaData</code> object.
+ *
+ * @param md the <code>RowSetMetaData</code> object for this
+ * <code>CachedRowSetImpl</code> object, which will be set with
+ * values from rsmd
+ * @param rsmd the <code>ResultSetMetaData</code> object from which new
+ * values for md will be read
+ * @throws SQLException if an error occurs
+ */
+ private void initMetaData(RowSetMetaDataImpl md, ResultSetMetaData rsmd) throws SQLException {
+ int numCols = rsmd.getColumnCount();
+
+ md.setColumnCount(numCols);
+ for (int col=1; col <= numCols; col++) {
+ md.setAutoIncrement(col, rsmd.isAutoIncrement(col));
+ md.setCaseSensitive(col, rsmd.isCaseSensitive(col));
+ md.setCurrency(col, rsmd.isCurrency(col));
+ md.setNullable(col, rsmd.isNullable(col));
+ md.setSigned(col, rsmd.isSigned(col));
+ md.setSearchable(col, rsmd.isSearchable(col));
+ md.setColumnDisplaySize(col, rsmd.getColumnDisplaySize(col));
+ md.setColumnLabel(col, rsmd.getColumnLabel(col));
+ md.setColumnName(col, rsmd.getColumnName(col));
+ md.setSchemaName(col, rsmd.getSchemaName(col));
+ md.setPrecision(col, rsmd.getPrecision(col));
+ md.setScale(col, rsmd.getScale(col));
+ md.setTableName(col, rsmd.getTableName(col));
+ md.setCatalogName(col, rsmd.getCatalogName(col));
+ md.setColumnType(col, rsmd.getColumnType(col));
+ md.setColumnTypeName(col, rsmd.getColumnTypeName(col));
+
+ if( conn != null){
+
+ try {
+ dbmslocatorsUpdateCopy = conn.getMetaData().locatorsUpdateCopy();
+ } catch(SQLException sqle) {
+ /*
+ * Since the Lobs and this method is not mandated by J2EE spec,
+ * drivers are not implementing it. We need to catch this
+ * and do nothing in this block and help populate()
+ * method do it's task(bug id 5055528)
+ */
+ }
+ }
+ }
+ }
+
+ /**
+ * Populates this <code>CachedRowSetImpl</code> object with data,
+ * using the given connection to produce the result set from
+ * which data will be read. A second form of this method,
+ * which takes no arguments, uses the values from this rowset's
+ * user, password, and either url or data source properties to
+ * create a new database connection. The form of <code>execute</code>
+ * that is given a connection ignores these properties.
+ *
+ * @param conn A standard JDBC <code>Connection</code> object that this
+ * <code>CachedRowSet</code> object can pass to a synchronization provider
+ * to establish a connection to the data source
+ * @throws SQLException if an invalid <code>Connection</code> is supplied
+ * or an error occurs in establishing the connection to the
+ * data source
+ * @see #populate
+ * @see java.sql.Connection
+ */
+ public void execute(Connection conn) throws SQLException {
+ // store the connection so the reader can find it.
+ setConnection(conn);
+
+ if(getPageSize() != 0){
+ crsReader = (CachedRowSetReader)provider.getRowSetReader();
+ crsReader.setStartPosition(1);
+ callWithCon = true;
+ crsReader.readData((RowSetInternal)this);
+ }
+
+ // Now call the current reader's readData method
+ else {
+ rowSetReader.readData((RowSetInternal)this);
+ }
+ RowSetMD = (RowSetMetaDataImpl)this.getMetaData();
+
+ if(conn != null){
+
+ try {
+ dbmslocatorsUpdateCopy = conn.getMetaData().locatorsUpdateCopy();
+ } catch(SQLException sqle) {
+ /*
+ * Since the Lobs and this method is not mandated by J2EE spec,
+ * drivers are not implementing it. We need to catch this
+ * and do nothing in this block and help populate()
+ * method do it's task
+ */
+ } //end catch
+
+ } else {
+
+ CachedRowSetReader crsTempReader = (CachedRowSetReader)rowSetReader;
+ Connection tempCon = crsTempReader.connect((RowSetInternal)this);
+
+ try {
+ dbmslocatorsUpdateCopy = tempCon.getMetaData().locatorsUpdateCopy();
+ } catch(SQLException sqle) {
+ /*
+ * Since the Lobs and this method is not mandated by J2EE spec,
+ * drivers are not implementing it. We need to catch this
+ * and do nothing in this block and help populate()
+ * method do it's task(bug id 5055528)
+ */
+ } //end catch
+ tempCon = null;
+ } // end if ... else
+ }
+
+ /**
+ * Sets this <code>CachedRowSetImpl</code> object's connection property
+ * to the given <code>Connection</code> object. This method is called
+ * internally by the version of the method <code>execute</code> that takes a
+ * <code>Connection</code> object as an argument. The reader for this
+ * <code>CachedRowSetImpl</code> object can retrieve the connection stored
+ * in the rowset's connection property by calling its
+ * <code>getConnection</code> method.
+ *
+ * @param connection the <code>Connection</code> object that was passed in
+ * to the method <code>execute</code> and is to be stored
+ * in this <code>CachedRowSetImpl</code> object's connection
+ * property
+ */
+ private void setConnection (Connection connection) {
+ conn = connection;
+ }
+
+
+ /**
+ * Propagates all row update, insert, and delete changes to the
+ * underlying data source backing this <code>CachedRowSetImpl</code>
+ * object.
+ * <P>
+ * <b>Note</b>In the reference implementation an optimistic concurrency implementation
+ * is provided as a sample implementation of a the <code>SyncProvider</code>
+ * abstract class.
+ * <P>
+ * This method fails if any of the updates cannot be propagated back
+ * to the data source. When it fails, the caller can assume that
+ * none of the updates are reflected in the data source.
+ * When an exception is thrown, the current row
+ * is set to the first "updated" row that resulted in an exception
+ * unless the row that caused the exception is a "deleted" row.
+ * In that case, when deleted rows are not shown, which is usually true,
+ * the current row is not affected.
+ * <P>
+ * If no <code>SyncProvider</code> is configured, the reference implementation
+ * leverages the <code>RIOptimisticProvider</code> available which provides the
+ * default and reference synchronization capabilities for disconnected
+ * <code>RowSets</code>.
+ *
+ * @throws SQLException if the cursor is on the insert row or the underlying
+ * reference synchronization provider fails to commit the updates
+ * to the datasource
+ * @throws SyncProviderException if an internal error occurs within the
+ * <code>SyncProvider</code> instance during either during the
+ * process or at any time when the <code>SyncProvider</code>
+ * instance touches the data source.
+ * @see #acceptChanges(java.sql.Connection)
+ * @see javax.sql.RowSetWriter
+ * @see javax.sql.rowset.spi.SyncProvider
+ */
+ public void acceptChanges() throws SyncProviderException {
+ if (onInsertRow == true) {
+ throw new SyncProviderException(resBundle.handleGetObject("cachedrowsetimpl.invalidop").toString());
+ }
+
+ int saveCursorPos = cursorPos;
+ boolean success = false;
+ boolean conflict = false;
+
+ try {
+ if (rowSetWriter != null) {
+ saveCursorPos = cursorPos;
+ conflict = rowSetWriter.writeData((RowSetInternal)this);
+ cursorPos = saveCursorPos;
+ }
+
+ if ((tXWriter) && this.COMMIT_ON_ACCEPT_CHANGES) {
+ // do commit/rollback's here
+ if (!conflict) {
+ tWriter = (TransactionalWriter)rowSetWriter;
+ tWriter.rollback();
+ success = false;
+ } else {
+ tWriter = (TransactionalWriter)rowSetWriter;
+ tWriter.commit();
+ success = true;
+ }
+ }
+
+ if (success == true) {
+ setOriginal();
+ } else if (!(success) && !(this.COMMIT_ON_ACCEPT_CHANGES)) {
+ throw new SyncProviderException(resBundle.handleGetObject("cachedrowsetimpl.accfailed").toString());
+ }
+
+ } catch (SyncProviderException spe) {
+ throw spe;
+ } catch (SQLException e) {
+ e.printStackTrace();
+ throw new SyncProviderException(e.getMessage());
+ } catch (SecurityException e) {
+ throw new SyncProviderException(e.getMessage());
+ }
+ }
+
+ /**
+ * Propagates all row update, insert, and delete changes to the
+ * data source backing this <code>CachedRowSetImpl</code> object
+ * using the given <code>Connection</code> object.
+ * <P>
+ * The reference implementation <code>RIOptimisticProvider</code>
+ * modifies its synchronization to a write back function given
+ * the updated connection
+ * The reference implementation modifies its synchronization behaviour
+ * via the <code>SyncProvider</code> to ensure the synchronization
+ * occurs according to the updated JDBC <code>Connection</code>
+ * properties.
+ *
+ * @param con a standard JDBC <code>Connection</code> object
+ * @throws SQLException if the cursor is on the insert row or the underlying
+ * synchronization provider fails to commit the updates
+ * back to the data source
+ * @see #acceptChanges
+ * @see javax.sql.RowSetWriter
+ * @see javax.sql.rowset.spi.SyncFactory
+ * @see javax.sql.rowset.spi.SyncProvider
+ */
+ public void acceptChanges(Connection con) throws SyncProviderException{
+
+ try{
+ setConnection(con);
+ acceptChanges();
+ } catch (SyncProviderException spe) {
+ throw spe;
+ } catch(SQLException sqle){
+ throw new SyncProviderException(sqle.getMessage());
+ }
+ }
+
+ /**
+ * Restores this <code>CachedRowSetImpl</code> object to its original state,
+ * that is, its state before the last set of changes.
+ * <P>
+ * Before returning, this method moves the cursor before the first row
+ * and sends a <code>rowSetChanged</code> event to all registered
+ * listeners.
+ * @throws SQLException if an error is occurs rolling back the RowSet
+ * state to the definied original value.
+ * @see javax.sql.RowSetListener#rowSetChanged
+ */
+ public void restoreOriginal() throws SQLException {
+ Row currentRow;
+ for (Iterator i = rvh.iterator(); i.hasNext();) {
+ currentRow = (Row)i.next();
+ if (currentRow.getInserted() == true) {
+ i.remove();
+ --numRows;
+ } else {
+ if (currentRow.getDeleted() == true) {
+ currentRow.clearDeleted();
+ }
+ if (currentRow.getUpdated() == true) {
+ currentRow.clearUpdated();
+ }
+ }
+ }
+ // move to before the first
+ cursorPos = 0;
+
+ // notify any listeners
+ notifyRowSetChanged();
+ }
+
+ /**
+ * Releases the current contents of this <code>CachedRowSetImpl</code>
+ * object and sends a <code>rowSetChanged</code> event object to all
+ * registered listeners.
+ *
+ * @throws SQLException if an error occurs flushing the contents of
+ * RowSet.
+ * @see javax.sql.RowSetListener#rowSetChanged
+ */
+ public void release() throws SQLException {
+ initContainer();
+ notifyRowSetChanged();
+ }
+
+ /**
+ * Cancels deletion of the current row and notifies listeners that
+ * a row has changed.
+ * <P>
+ * Note: This method can be ignored if deleted rows are not being shown,
+ * which is the normal case.
+ *
+ * @throws SQLException if the cursor is not on a valid row
+ */
+ public void undoDelete() throws SQLException {
+ if (getShowDeleted() == false) {
+ return;
+ }
+ // make sure we are on a row
+ checkCursor();
+
+ // don't want this to happen...
+ if (onInsertRow == true) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.invalidcp").toString());
+ }
+
+ Row currentRow = (Row)getCurrentRow();
+ if (currentRow.getDeleted() == true) {
+ currentRow.clearDeleted();
+ --numDeleted;
+ notifyRowChanged();
+ }
+ }
+
+ /**
+ * Immediately removes the current row from this
+ * <code>CachedRowSetImpl</code> object if the row has been inserted, and
+ * also notifies listeners the a row has changed. An exception is thrown
+ * if the row is not a row that has been inserted or the cursor is before
+ * the first row, after the last row, or on the insert row.
+ * <P>
+ * This operation cannot be undone.
+ *
+ * @throws SQLException if an error occurs,
+ * the cursor is not on a valid row,
+ * or the row has not been inserted
+ */
+ public void undoInsert() throws SQLException {
+ // make sure we are on a row
+ checkCursor();
+
+ // don't want this to happen...
+ if (onInsertRow == true) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.invalidcp").toString());
+ }
+
+ Row currentRow = (Row)getCurrentRow();
+ if (currentRow.getInserted() == true) {
+ rvh.remove(cursorPos-1);
+ --numRows;
+ notifyRowChanged();
+ } else {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.illegalop").toString());
+ }
+ }
+
+ /**
+ * Immediately reverses the last update operation if the
+ * row has been modified. This method can be
+ * called to reverse updates on a all columns until all updates in a row have
+ * been rolled back to their originating state since the last synchronization
+ * (<code>acceptChanges</code>) or population. This method may also be called
+ * while performing updates to the insert row.
+ * <P>
+ * <code>undoUpdate</code may be called at any time during the life-time of a
+ * rowset, however after a synchronization has occurs this method has no
+ * affect until further modification to the RowSet data occurs.
+ *
+ * @throws SQLException if cursor is before the first row, after the last
+ * row in rowset.
+ * @see #undoDelete
+ * @see #undoInsert
+ * @see java.sql.ResultSet#cancelRowUpdates
+ */
+ public void undoUpdate() throws SQLException {
+ // if on insert row, cancel the insert row
+ // make the insert row flag,
+ // cursorPos back to the current row
+ moveToCurrentRow();
+
+ // else if not on insert row
+ // call undoUpdate or undoInsert
+ undoDelete();
+
+ undoInsert();
+
+ }
+
+ //--------------------------------------------------------------------
+ // Views
+ //--------------------------------------------------------------------
+
+ /**
+ * Returns a new <code>RowSet</code> object backed by the same data as
+ * that of this <code>CachedRowSetImpl</code> object and sharing a set of cursors
+ * with it. This allows cursors to interate over a shared set of rows, providing
+ * multiple views of the underlying data.
+ *
+ * @return a <code>RowSet</code> object that is a copy of this <code>CachedRowSetImpl</code>
+ * object and shares a set of cursors with it
+ * @throws SQLException if an error occurs or cloning is
+ * not supported
+ * @see javax.sql.RowSetEvent
+ * @see javax.sql.RowSetListener
+ */
+ public RowSet createShared() throws SQLException {
+ RowSet clone;
+ try {
+ clone = (RowSet)clone();
+ } catch (CloneNotSupportedException ex) {
+ throw new SQLException(ex.getMessage());
+ }
+ return clone;
+ }
+
+ /**
+ * Returns a new <code>RowSet</code> object containing by the same data
+ * as this <code>CachedRowSetImpl</code> object. This method
+ * differs from the method <code>createCopy</code> in that it throws a
+ * <code>CloneNotSupportedException</code> object instead of an
+ * <code>SQLException</code> object, as the method <code>createShared</code>
+ * does. This <code>clone</code>
+ * method is called internally by the method <code>createShared</code>,
+ * which catches the <code>CloneNotSupportedException</code> object
+ * and in turn throws a new <code>SQLException</code> object.
+ *
+ * @return a copy of this <code>CachedRowSetImpl</code> object
+ * @throws CloneNotSupportedException if an error occurs when
+ * attempting to clone this <code>CachedRowSetImpl</code> object
+ * @see #createShared
+ */
+ protected Object clone() throws CloneNotSupportedException {
+ return (super.clone());
+ }
+
+ /**
+ * Creates a <code>RowSet</code> object that is a deep copy of
+ * this <code>CachedRowSetImpl</code> object's data, including
+ * constraints. Updates made
+ * on a copy are not visible to the original rowset;
+ * a copy of a rowset is completely independent from the original.
+ * <P>
+ * Making a copy saves the cost of creating an identical rowset
+ * from first principles, which can be quite expensive.
+ * For example, it can eliminate the need to query a
+ * remote database server.
+ * @return a new <code>CachedRowSet</code> object that is a deep copy
+ * of this <code>CachedRowSet</code> object and is
+ * completely independent from this <code>CachedRowSetImpl</code>
+ * object.
+ * @throws SQLException if an error occurs in generating the copy of this
+ * of the <code>CachedRowSetImpl</code>
+ * @see #createShared
+ * @see javax.sql.RowSetEvent
+ * @see javax.sql.RowSetListener
+ */
+ public CachedRowSet createCopy() throws SQLException {
+ ObjectOutputStream out;
+ ByteArrayOutputStream bOut = new ByteArrayOutputStream();
+ try {
+ out = new ObjectOutputStream(bOut);
+ out.writeObject(this);
+ } catch (IOException ex) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.clonefail").toString() + ex.getMessage());
+ }
+
+ ObjectInputStream in;
+
+ try {
+ ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
+ in = new ObjectInputStream(bIn);
+ } catch (StreamCorruptedException ex) {
+ throw new SQLException("Clone failed: " + ex.getMessage());
+ } catch (IOException ex) {
+ throw new SQLException("Clone failed: " + ex.getMessage());
+ }
+
+ try {
+ //return ((CachedRowSet)(in.readObject()));
+ CachedRowSetImpl crsTemp = (CachedRowSetImpl)in.readObject();
+ crsTemp.resBundle = this.resBundle;
+ return ((CachedRowSet)crsTemp);
+
+ } catch (ClassNotFoundException ex) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.clonefail").toString() + ex.getMessage());
+ } catch (OptionalDataException ex) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.clonefail").toString() + ex.getMessage());
+ } catch (IOException ex) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.clonefail").toString() + ex.getMessage());
+ }
+ }
+
+ /**
+ * Creates a <code>RowSet</code> object that is a copy of
+ * this <code>CachedRowSetImpl</code> object's table structure
+ * and the constraints only.
+ * There will be no data in the object being returned.
+ * Updates made on a copy are not visible to the original rowset.
+ * <P>
+ * This helps in getting the underlying XML schema which can
+ * be used as the basis for populating a <code>WebRowSet</code>.
+ *
+ * @return a new <code>CachedRowSet</code> object that is a copy
+ * of this <code>CachedRowSetImpl</code> object's schema and
+ * retains all the constraints on the original rowset but contains
+ * no data
+ * @throws SQLException if an error occurs in generating the copy
+ * of the <code>CachedRowSet</code> object
+ * @see #createShared
+ * @see #createCopy
+ * @see #createCopyNoConstraints
+ * @see javax.sql.RowSetEvent
+ * @see javax.sql.RowSetListener
+ */
+ public CachedRowSet createCopySchema() throws SQLException {
+ // Copy everything except data i.e all constraints
+
+ // Store the number of rows of "this"
+ // and make numRows equals zero.
+ // and make data also zero.
+ int nRows = numRows;
+ numRows = 0;
+
+ CachedRowSet crs = this.createCopy();
+
+ // reset this object back to number of rows.
+ numRows = nRows;
+
+ return crs;
+ }
+
+ /**
+ * Creates a <code>CachedRowSet</code> object that is a copy of
+ * this <code>CachedRowSetImpl</code> object's data only.
+ * All constraints set in this object will not be there
+ * in the returning object. Updates made
+ * on a copy are not visible to the original rowset.
+ *
+ * @return a new <code>CachedRowSet</code> object that is a deep copy
+ * of this <code>CachedRowSetImpl</code> object and is
+ * completely independent from this <code>CachedRowSetImpl</code> object
+ * @throws SQLException if an error occurs in generating the copy of the
+ * of the <code>CachedRowSet</code>
+ * @see #createShared
+ * @see #createCopy
+ * @see #createCopySchema
+ * @see javax.sql.RowSetEvent
+ * @see javax.sql.RowSetListener
+ */
+ public CachedRowSet createCopyNoConstraints() throws SQLException {
+ // Copy the whole data ONLY without any constraints.
+ CachedRowSetImpl crs;
+ crs = (CachedRowSetImpl)this.createCopy();
+
+ crs.initProperties();
+ try {
+ crs.unsetMatchColumn(crs.getMatchColumnIndexes());
+ } catch(SQLException sqle) {
+ //do nothing, if the setMatchColumn is not set.
+ }
+
+ try {
+ crs.unsetMatchColumn(crs.getMatchColumnNames());
+ } catch(SQLException sqle) {
+ //do nothing, if the setMatchColumn is not set.
+ }
+
+ return crs;
+ }
+
+ /**
+ * Converts this <code>CachedRowSetImpl</code> object to a collection
+ * of tables. The sample implementation utilitizes the <code>TreeMap</code>
+ * collection type.
+ * This class guarantees that the map will be in ascending key order,
+ * sorted according to the natural order for the key's class.
+ *
+ * @return a <code>Collection</code> object consisting of tables,
+ * each of which is a copy of a row in this
+ * <code>CachedRowSetImpl</code> object
+ * @throws SQLException if an error occurs in generating the collection
+ * @see #toCollection(int)
+ * @see #toCollection(String)
+ * @see java.util.TreeMap
+ */
+ public Collection<?> toCollection() throws SQLException {
+
+ System.out.println("in crs toColl");
+ TreeMap tMap;
+ int count = 0;
+ Row origRow;
+ Vector newRow;
+
+ int colCount = ((RowSetMetaDataImpl)this.getMetaData()).getColumnCount();
+ //int colCount = RowSetMD.getColumnCount();
+
+ System.out.println("in crs toColl 2");
+
+ tMap = new TreeMap();
+
+ for (int i = 0; i<numRows; i++) {
+ System.out.println("in crs toColl 3");
+ tMap.put(new Integer(i), rvh.get(i));
+ System.out.println("in crs toColl 4");
+ }
+
+ return (tMap.values());
+ }
+
+ /**
+ * Returns the specified column of this <code>CachedRowSetImpl</code> object
+ * as a <code>Collection</code> object. This method makes a copy of the
+ * column's data and utilitizes the <code>Vector</code> to establish the
+ * collection. The <code>Vector</code> class implements a growable array
+ * objects allowing the individual components to be accessed using an
+ * an integer index similar to that of an array.
+ *
+ * @return a <code>Collection</code> object that contains the value(s)
+ * stored in the specified column of this
+ * <code>CachedRowSetImpl</code>
+ * object
+ * @throws SQLException if an error occurs generated the collection; or
+ * an invalid column is provided.
+ * @see #toCollection()
+ * @see #toCollection(String)
+ * @see java.util.Vector
+ */
+ public Collection<?> toCollection(int column) throws SQLException {
+
+ Vector vec;
+ Row origRow;
+ int nRows = numRows;
+ vec = new Vector(nRows);
+
+ // create a copy
+ CachedRowSetImpl crsTemp;
+ crsTemp = (CachedRowSetImpl) this.createCopy();
+
+ while(nRows!=0) {
+ crsTemp.next();
+ vec.add(crsTemp.getObject(column));
+ nRows--;
+ }
+
+ return (Collection)vec;
+ }
+
+ /**
+ * Returns the specified column of this <code>CachedRowSetImpl</code> object
+ * as a <code>Collection</code> object. This method makes a copy of the
+ * column's data and utilitizes the <code>Vector</code> to establish the
+ * collection. The <code>Vector</code> class implements a growable array
+ * objects allowing the individual components to be accessed using an
+ * an integer index similar to that of an array.
+ *
+ * @return a <code>Collection</code> object that contains the value(s)
+ * stored in the specified column of this
+ * <code>CachedRowSetImpl</code>
+ * object
+ * @throws SQLException if an error occurs generated the collection; or
+ * an invalid column is provided.
+ * @see #toCollection()
+ * @see #toCollection(int)
+ * @see java.util.Vector
+ */
+ public Collection<?> toCollection(String column) throws SQLException {
+ return toCollection(getColIdxByName(column));
+ }
+
+ //--------------------------------------------------------------------
+ // Advanced features
+ //--------------------------------------------------------------------
+
+
+ /**
+ * Returns the <code>SyncProvider</code> implementation being used
+ * with this <code>CachedRowSetImpl</code> implementation rowset.
+ *
+ * @return the SyncProvider used by the rowset. If not provider was
+ * set when the rowset was instantiated, the reference
+ * implementation (default) provider is returned.
+ * @throws SQLException if error occurs while return the
+ * <code>SyncProvider</code> instance.
+ */
+ public SyncProvider getSyncProvider() throws SQLException {
+ return provider;
+ }
+
+ /**
+ * Sets the active <code>SyncProvider</code> and attempts to load
+ * load the new provider using the <code>SyncFactory</code> SPI.
+ *
+ * @throws SQLException if an error occurs while resetting the
+ * <code>SyncProvider</code>.
+ */
+ public void setSyncProvider(String providerStr) throws SQLException {
+ provider =
+ (SyncProvider)SyncFactory.getInstance(providerStr);
+
+ rowSetReader = provider.getRowSetReader();
+ rowSetWriter = (TransactionalWriter)provider.getRowSetWriter();
+ }
+
+
+ //-----------------
+ // methods inherited from RowSet
+ //-----------------
+
+
+
+
+
+
+ //---------------------------------------------------------------------
+ // Reading and writing data
+ //---------------------------------------------------------------------
+
+ /**
+ * Populates this <code>CachedRowSetImpl</code> object with data.
+ * This form of the method uses the rowset's user, password, and url or
+ * data source name properties to create a database
+ * connection. If properties that are needed
+ * have not been set, this method will throw an exception.
+ * <P>
+ * Another form of this method uses an existing JDBC <code>Connection</code>
+ * object instead of creating a new one; therefore, it ignores the
+ * properties used for establishing a new connection.
+ * <P>
+ * The query specified by the command property is executed to create a
+ * <code>ResultSet</code> object from which to retrieve data.
+ * The current contents of the rowset are discarded, and the
+ * rowset's metadata is also (re)set. If there are outstanding updates,
+ * they are also ignored.
+ * <P>
+ * The method <code>execute</code> closes any database connections that it
+ * creates.
+ *
+ * @throws SQLException if an error occurs or the
+ * necessary properties have not been set
+ */
+ public void execute() throws SQLException {
+ execute(null);
+ }
+
+
+
+ //-----------------------------------
+ // Methods inherited from ResultSet
+ //-----------------------------------
+
+ /**
+ * Moves the cursor down one row from its current position and
+ * returns <code>true</code> if the new cursor position is a
+ * valid row.
+ * The cursor for a new <code>ResultSet</code> object is initially
+ * positioned before the first row. The first call to the method
+ * <code>next</code> moves the cursor to the first row, making it
+ * the current row; the second call makes the second row the
+ * current row, and so on.
+ *
+ * <P>If an input stream from the previous row is open, it is
+ * implicitly closed. The <code>ResultSet</code> object's warning
+ * chain is cleared when a new row is read.
+ *
+ * @return <code>true</code> if the new current row is valid;
+ * <code>false</code> if there are no more rows
+ * @throws SQLException if an error occurs or
+ * the cursor is not positioned in the rowset, before
+ * the first row, or after the last row
+ */
+ public boolean next() throws SQLException {
+ /*
+ * make sure things look sane. The cursor must be
+ * positioned in the rowset or before first (0) or
+ * after last (numRows + 1)
+ */
+ if (cursorPos < 0 || cursorPos >= numRows + 1) {
+ throw new SQLException(resBundle.handleGetObject("cachedrowsetimpl.invalidcp").toString());
+ }
+ // now move and notify
+ boolean ret = this.internalNext();
+ notifyCursorMoved();
+
+ return ret;
+ }
+
+ /**
+ * Moves this <code>CachedRowSetImpl</code> object's cursor to the next
+ * row and returns <code>true</code> if the cursor is still in the rowset;
+ * returns <code>false</code> if the cursor has moved to the position after
+ * the last row.
+ * <P>
+ * This method handles the cases where the cursor moves to a row that
+ * has been deleted.
+ * If this rowset shows deleted rows and the cursor moves to a row
+ * that has been deleted, this method moves the cursor to the ...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-21 19:31:59
|
Revision: 3283
http://jnode.svn.sourceforge.net/jnode/?rev=3283&view=rev
Author: lsantha
Date: 2007-06-21 12:31:53 -0700 (Thu, 21 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/javax/javax/sql/
trunk/core/src/openjdk/javax/javax/sql/CommonDataSource.java
trunk/core/src/openjdk/javax/javax/sql/ConnectionEvent.java
trunk/core/src/openjdk/javax/javax/sql/ConnectionEventListener.java
trunk/core/src/openjdk/javax/javax/sql/ConnectionPoolDataSource.java
trunk/core/src/openjdk/javax/javax/sql/DataSource.java
trunk/core/src/openjdk/javax/javax/sql/PooledConnection.java
trunk/core/src/openjdk/javax/javax/sql/RowSet.java
trunk/core/src/openjdk/javax/javax/sql/RowSetEvent.java
trunk/core/src/openjdk/javax/javax/sql/RowSetInternal.java
trunk/core/src/openjdk/javax/javax/sql/RowSetListener.java
trunk/core/src/openjdk/javax/javax/sql/RowSetMetaData.java
trunk/core/src/openjdk/javax/javax/sql/RowSetReader.java
trunk/core/src/openjdk/javax/javax/sql/RowSetWriter.java
trunk/core/src/openjdk/javax/javax/sql/StatementEvent.java
trunk/core/src/openjdk/javax/javax/sql/StatementEventListener.java
trunk/core/src/openjdk/javax/javax/sql/XAConnection.java
trunk/core/src/openjdk/javax/javax/sql/XADataSource.java
trunk/core/src/openjdk/javax/javax/sql/package.html
trunk/core/src/openjdk/javax/javax/sql/rowset/
trunk/core/src/openjdk/javax/javax/sql/rowset/BaseRowSet.java
trunk/core/src/openjdk/javax/javax/sql/rowset/CachedRowSet.java
trunk/core/src/openjdk/javax/javax/sql/rowset/FilteredRowSet.java
trunk/core/src/openjdk/javax/javax/sql/rowset/JdbcRowSet.java
trunk/core/src/openjdk/javax/javax/sql/rowset/JoinRowSet.java
trunk/core/src/openjdk/javax/javax/sql/rowset/Joinable.java
trunk/core/src/openjdk/javax/javax/sql/rowset/Predicate.java
trunk/core/src/openjdk/javax/javax/sql/rowset/RowSetMetaDataImpl.java
trunk/core/src/openjdk/javax/javax/sql/rowset/RowSetWarning.java
trunk/core/src/openjdk/javax/javax/sql/rowset/WebRowSet.java
trunk/core/src/openjdk/javax/javax/sql/rowset/package.html
trunk/core/src/openjdk/javax/javax/sql/rowset/rowset.properties
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SQLInputImpl.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SQLOutputImpl.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialArray.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialBlob.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialClob.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialDatalink.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialException.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialJavaObject.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialRef.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/SerialStruct.java
trunk/core/src/openjdk/javax/javax/sql/rowset/serial/package.html
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/SyncFactory.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/SyncFactoryException.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/SyncProvider.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/SyncProviderException.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/SyncResolver.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/TransactionalWriter.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/XmlReader.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/XmlWriter.java
trunk/core/src/openjdk/javax/javax/sql/rowset/spi/package.html
trunk/core/src/openjdk/javax/javax/sql/rowset/sqlxml.xsd
trunk/core/src/openjdk/javax/javax/sql/rowset/webrowset.xsd
trunk/core/src/openjdk/javax/javax/transaction/
trunk/core/src/openjdk/javax/javax/transaction/InvalidTransactionException.java
trunk/core/src/openjdk/javax/javax/transaction/TransactionRequiredException.java
trunk/core/src/openjdk/javax/javax/transaction/TransactionRolledbackException.java
trunk/core/src/openjdk/javax/javax/transaction/package.html
trunk/core/src/openjdk/javax/javax/transaction/xa/
trunk/core/src/openjdk/javax/javax/transaction/xa/XAException.java
trunk/core/src/openjdk/javax/javax/transaction/xa/XAResource.java
trunk/core/src/openjdk/javax/javax/transaction/xa/Xid.java
trunk/core/src/openjdk/javax/javax/transaction/xa/package.html
Added: trunk/core/src/openjdk/javax/javax/sql/CommonDataSource.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/sql/CommonDataSource.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/sql/CommonDataSource.java 2007-06-21 19:31:53 UTC (rev 3283)
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.sql;
+
+import java.sql.SQLException;
+import java.io.PrintWriter;
+
+/**
+ * Interface that defines the methods which are common between <code>DataSource</code>,
+ * <code>XADataSource</code> and <code>ConnectionPoolDataSource</code>.
+ *<p>
+ */
+public interface CommonDataSource {
+
+ /**
+ * <p>Retrieves the log writer for this <code>DataSource</code>
+ * object.
+ *
+ * <p>The log writer is a character output stream to which all logging
+ * and tracing messages for this data source will be
+ * printed. This includes messages printed by the methods of this
+ * object, messages printed by methods of other objects manufactured
+ * by this object, and so on. Messages printed to a data source
+ * specific log writer are not printed to the log writer associated
+ * with the <code>java.sql.DriverManager</code> class. When a
+ * <code>DataSource</code> object is
+ * created, the log writer is initially null; in other words, the
+ * default is for logging to be disabled.
+ *
+ * @return the log writer for this data source or null if
+ * logging is disabled
+ * @exception java.sql.SQLException if a database access error occurs
+ * @see #setLogWriter
+ * @since 1.4
+ */
+ java.io.PrintWriter getLogWriter() throws SQLException;
+
+ /**
+ * <p>Sets the log writer for this <code>DataSource</code>
+ * object to the given <code>java.io.PrintWriter</code> object.
+ *
+ * <p>The log writer is a character output stream to which all logging
+ * and tracing messages for this data source will be
+ * printed. This includes messages printed by the methods of this
+ * object, messages printed by methods of other objects manufactured
+ * by this object, and so on. Messages printed to a data source-
+ * specific log writer are not printed to the log writer associated
+ * with the <code>java.sql.DriverManager</code> class. When a
+ * <code>DataSource</code> object is created the log writer is
+ * initially null; in other words, the default is for logging to be
+ * disabled.
+ *
+ * @param out the new log writer; to disable logging, set to null
+ * @exception SQLException if a database access error occurs
+ * @see #getLogWriter
+ * @since 1.4
+ */
+ void setLogWriter(java.io.PrintWriter out) throws SQLException;
+
+ /**
+ * <p>Sets the maximum time in seconds that this data source will wait
+ * while attempting to connect to a database. A value of zero
+ * specifies that the timeout is the default system timeout
+ * if there is one; otherwise, it specifies that there is no timeout.
+ * When a <code>DataSource</code> object is created, the login timeout is
+ * initially zero.
+ *
+ * @param seconds the data source login time limit
+ * @exception SQLException if a database access error occurs.
+ * @see #getLoginTimeout
+ * @since 1.4
+ */
+ void setLoginTimeout(int seconds) throws SQLException;
+
+ /**
+ * Gets the maximum time in seconds that this data source can wait
+ * while attempting to connect to a database. A value of zero
+ * means that the timeout is the default system timeout
+ * if there is one; otherwise, it means that there is no timeout.
+ * When a <code>DataSource</code> object is created, the login timeout is
+ * initially zero.
+ *
+ * @return the data source login time limit
+ * @exception SQLException if a database access error occurs.
+ * @see #setLoginTimeout
+ * @since 1.4
+ */
+ int getLoginTimeout() throws SQLException;
+
+}
Property changes on: trunk/core/src/openjdk/javax/javax/sql/CommonDataSource.java
___________________________________________________________________
Name: svn:executable
+ *
Added: trunk/core/src/openjdk/javax/javax/sql/ConnectionEvent.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/sql/ConnectionEvent.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/sql/ConnectionEvent.java 2007-06-21 19:31:53 UTC (rev 3283)
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.sql;
+
+import java.sql.SQLException;
+
+/**
+ * <P>An <code>Event</code> object that provides information about the
+ * source of a connection-related event. <code>ConnectionEvent</code>
+ * objects are generated when an application closes a pooled connection
+ * and when an error occurs. The <code>ConnectionEvent</code> object
+ * contains two kinds of information:
+ * <UL>
+ * <LI>The pooled connection closed by the application
+ * <LI>In the case of an error event, the <code>SQLException</code>
+ * about to be thrown to the application
+ * </UL>
+ *
+ * @since 1.4
+ */
+
+public class ConnectionEvent extends java.util.EventObject {
+
+ /**
+ * <P>Constructs a <code>ConnectionEvent</code> object initialized with
+ * the given <code>PooledConnection</code> object. <code>SQLException</code>
+ * defaults to <code>null</code>.
+ *
+ * @param con the pooled connection that is the source of the event
+ * @throws IllegalArgumentException if <code>con</code> is null.
+ */
+ public ConnectionEvent(PooledConnection con) {
+ super(con);
+ }
+
+ /**
+ * <P>Constructs a <code>ConnectionEvent</code> object initialized with
+ * the given <code>PooledConnection</code> object and
+ * <code>SQLException</code> object.
+ *
+ * @param con the pooled connection that is the source of the event
+ * @param ex the SQLException about to be thrown to the application
+ * @throws IllegalArgumentException if <code>con</code> is null.
+ */
+ public ConnectionEvent(PooledConnection con, SQLException ex) {
+ super(con);
+ this.ex = ex;
+ }
+
+ /**
+ * <P>Retrieves the <code>SQLException</code> for this
+ * <code>ConnectionEvent</code> object. May be <code>null</code>.
+ *
+ * @return the SQLException about to be thrown or <code>null</code>
+ */
+ public SQLException getSQLException() { return ex; }
+
+ /**
+ * The <code>SQLException</code> that the driver will throw to the
+ * application when an error occurs and the pooled connection is no
+ * longer usable.
+ * @serial
+ */
+ private SQLException ex = null;
+
+ /**
+ * Private serial version unique ID to ensure serialization
+ * compatibility.
+ */
+ static final long serialVersionUID = -4843217645290030002L;
+
+ }
+
+
+
+
+
Added: trunk/core/src/openjdk/javax/javax/sql/ConnectionEventListener.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/sql/ConnectionEventListener.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/sql/ConnectionEventListener.java 2007-06-21 19:31:53 UTC (rev 3283)
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.sql;
+
+/**
+ * <P>
+ * An object that registers to be notified of events generated by a
+ * <code>PooledConnection</code> object.
+ * <P>
+ * The <code>ConnectionEventListener</code> interface is implemented by a
+ * connection pooling component. A connection pooling component will
+ * usually be provided by a JDBC driver vendor or another system software
+ * vendor. A JDBC driver notifies a <code>ConnectionEventListener</code>
+ * object when an application is finished using a pooled connection with
+ * which the listener has registered. The notification
+ * occurs after the application calls the method <code>close</code> on
+ * its representation of a <code>PooledConnection</code> object. A
+ * <code>ConnectionEventListener</code> is also notified when a
+ * connection error occurs due to the fact that the <code>PooledConnection</code>
+ * is unfit for future use---the server has crashed, for example.
+ * The listener is notified by the JDBC driver just before the driver throws an
+ * <code>SQLException</code> to the application using the
+ * <code>PooledConnection</code> object.
+ *
+ * @since 1.4
+ */
+
+public interface ConnectionEventListener extends java.util.EventListener {
+
+ /**
+ * Notifies this <code>ConnectionEventListener</code> that
+ * the application has called the method <code>close</code> on its
+ * representation of a pooled connection.
+ *
+ * @param event an event object describing the source of
+ * the event
+ */
+ void connectionClosed(ConnectionEvent event);
+
+ /**
+ * Notifies this <code>ConnectionEventListener</code> that
+ * a fatal error has occurred and the pooled connection can
+ * no longer be used. The driver makes this notification just
+ * before it throws the application the <code>SQLException</code>
+ * contained in the given <code>ConnectionEvent</code> object.
+ *
+ * @param event an event object describing the source of
+ * the event and containing the <code>SQLException</code> that the
+ * driver is about to throw
+ */
+ void connectionErrorOccurred(ConnectionEvent event);
+
+ }
+
+
+
+
+
Added: trunk/core/src/openjdk/javax/javax/sql/ConnectionPoolDataSource.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/sql/ConnectionPoolDataSource.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/sql/ConnectionPoolDataSource.java 2007-06-21 19:31:53 UTC (rev 3283)
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.sql;
+
+import java.sql.SQLException;
+
+
+/**
+ * A factory for <code>PooledConnection</code>
+ * objects. An object that implements this interface will typically be
+ * registered with a naming service that is based on the
+ * Java<sup><font size=-2>TM</font></sup> Naming and Directory Interface
+ * (JNDI).
+ *
+ * @since 1.4
+ */
+
+public interface ConnectionPoolDataSource extends CommonDataSource {
+
+ /**
+ * Attempts to establish a physical database connection that can
+ * be used as a pooled connection.
+ *
+ * @return a <code>PooledConnection</code> object that is a physical
+ * connection to the database that this
+ * <code>ConnectionPoolDataSource</code> object represents
+ * @exception SQLException if a database access error occurs
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @since 1.4
+ */
+ PooledConnection getPooledConnection() throws SQLException;
+
+ /**
+ * Attempts to establish a physical database connection that can
+ * be used as a pooled connection.
+ *
+ * @param user the database user on whose behalf the connection is being made
+ * @param password the user's password
+ * @return a <code>PooledConnection</code> object that is a physical
+ * connection to the database that this
+ * <code>ConnectionPoolDataSource</code> object represents
+ * @exception SQLException if a database access error occurs
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @since 1.4
+ */
+ PooledConnection getPooledConnection(String user, String password)
+ throws SQLException;
+ }
+
+
+
+
+
Added: trunk/core/src/openjdk/javax/javax/sql/DataSource.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/sql/DataSource.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/sql/DataSource.java 2007-06-21 19:31:53 UTC (rev 3283)
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.sql;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Wrapper;
+
+/**
+ * <p>A factory for connections to the physical data source that this
+ * <code>DataSource</code> object represents. An alternative to the
+ * <code>DriverManager</code> facility, a <code>DataSource</code> object
+ * is the preferred means of getting a connection. An object that implements
+ * the <code>DataSource</code> interface will typically be
+ * registered with a naming service based on the
+ * Java<sup><font size=-2>TM</font></sup> Naming and Directory (JNDI) API.
+ * <P>
+ * The <code>DataSource</code> interface is implemented by a driver vendor.
+ * There are three types of implementations:
+ * <OL>
+ * <LI>Basic implementation -- produces a standard <code>Connection</code>
+ * object
+ * <LI>Connection pooling implementation -- produces a <code>Connection</code>
+ * object that will automatically participate in connection pooling. This
+ * implementation works with a middle-tier connection pooling manager.
+ * <LI>Distributed transaction implementation -- produces a
+ * <code>Connection</code> object that may be used for distributed
+ * transactions and almost always participates in connection pooling.
+ * This implementation works with a middle-tier
+ * transaction manager and almost always with a connection
+ * pooling manager.
+ * </OL>
+ * <P>
+ * A <code>DataSource</code> object has properties that can be modified
+ * when necessary. For example, if the data source is moved to a different
+ * server, the property for the server can be changed. The benefit is that
+ * because the data source's properties can be changed, any code accessing
+ * that data source does not need to be changed.
+ * <P>
+ * A driver that is accessed via a <code>DataSource</code> object does not
+ * register itself with the <code>DriverManager</code>. Rather, a
+ * <code>DataSource</code> object is retrieved though a lookup operation
+ * and then used to create a <code>Connection</code> object. With a basic
+ * implementation, the connection obtained through a <code>DataSource</code>
+ * object is identical to a connection obtained through the
+ * <code>DriverManager</code> facility.
+ *
+ * @since 1.4
+ */
+
+public interface DataSource extends CommonDataSource,Wrapper {
+
+ /**
+ * <p>Attempts to establish a connection with the data source that
+ * this <code>DataSource</code> object represents.
+ *
+ * @return a connection to the data source
+ * @exception SQLException if a database access error occurs
+ */
+ Connection getConnection() throws SQLException;
+
+ /**
+ * <p>Attempts to establish a connection with the data source that
+ * this <code>DataSource</code> object represents.
+ *
+ * @param username the database user on whose behalf the connection is
+ * being made
+ * @param password the user's password
+ * @return a connection to the data source
+ * @exception SQLException if a database access error occurs
+ * @since 1.4
+ */
+ Connection getConnection(String username, String password)
+ throws SQLException;
+
+}
+
+
+
+
+
Added: trunk/core/src/openjdk/javax/javax/sql/PooledConnection.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/sql/PooledConnection.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/sql/PooledConnection.java 2007-06-21 19:31:53 UTC (rev 3283)
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.sql;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+/**
+ * An object that provides hooks for connection pool management.
+ * A <code>PooledConnection</code> object
+ * represents a physical connection to a data source. The connection
+ * can be recycled rather than being closed when an application is
+ * finished with it, thus reducing the number of connections that
+ * need to be made.
+ * <P>
+ * An application programmer does not use the <code>PooledConnection</code>
+ * interface directly; rather, it is used by a middle tier infrastructure
+ * that manages the pooling of connections.
+ * <P>
+ * When an application calls the method <code>DataSource.getConnection</code>,
+ * it gets back a <code>Connection</code> object. If connection pooling is
+ * being done, that <code>Connection</code> object is actually a handle to
+ * a <code>PooledConnection</code> object, which is a physical connection.
+ * <P>
+ * The connection pool manager, typically the application server, maintains
+ * a pool of <code>PooledConnection</code> objects. If there is a
+ * <code>PooledConnection</code> object available in the pool, the
+ * connection pool manager returns a <code>Connection</code> object that
+ * is a handle to that physical connection.
+ * If no <code>PooledConnection</code> object is available, the
+ * connection pool manager calls the <code>ConnectionPoolDataSource</code>
+ * method <code>getPoolConnection</code> to create a new physical connection. The
+ * JDBC driver implementing <code>ConnectionPoolDataSource</code> creates a
+ * new <code>PooledConnection</code> object and returns a handle to it.
+ * <P>
+ * When an application closes a connection, it calls the <code>Connection</code>
+ * method <code>close</code>. When connection pooling is being done,
+ * the connection pool manager is notified because it has registered itself as
+ * a <code>ConnectionEventListener</code> object using the
+ * <code>ConnectionPool</code> method <code>addConnectionEventListener</code>.
+ * The connection pool manager deactivates the handle to
+ * the <code>PooledConnection</code> object and returns the
+ * <code>PooledConnection</code> object to the pool of connections so that
+ * it can be used again. Thus, when an application closes its connection,
+ * the underlying physical connection is recycled rather than being closed.
+ * <P>
+ * The physical connection is not closed until the connection pool manager
+ * calls the <code>PooledConnection</code> method <code>close</code>.
+ * This method is generally called to have an orderly shutdown of the server or
+ * if a fatal error has made the connection unusable.
+ *
+ * <p>
+ * A connection pool manager is often also a statement pool manager, maintining
+ * a pool of <code>PreparedStatement</code> objects.
+ * When an application closes a prepared statement, it calls the
+ * <code>PreparedStatement</code>
+ * method <code>close</code>. When <code>Statement</code> pooling is being done,
+ * the pool manager is notified because it has registered itself as
+ * a <code>StatementEventListener</code> object using the
+ * <code>ConnectionPool</code> method <code>addStatementEventListener</code>.
+ * Thus, when an application closes its <code>PreparedStatement</code>,
+ * the underlying prepared statement is recycled rather than being closed.
+ * <P>
+ *
+ * @since 1.4
+ */
+
+public interface PooledConnection {
+
+ /**
+ * Creates and returns a <code>Connection</code> object that is a handle
+ * for the physical connection that
+ * this <code>PooledConnection</code> object represents.
+ * The connection pool manager calls this method when an application has
+ * called the method <code>DataSource.getConnection</code> and there are
+ * no <code>PooledConnection</code> objects available. See the
+ * {@link PooledConnection interface description} for more information.
+ *
+ * @return a <code>Connection</code> object that is a handle to
+ * this <code>PooledConnection</code> object
+ * @exception SQLException if a database access error occurs
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @since 1.4
+ */
+ Connection getConnection() throws SQLException;
+
+ /**
+ * Closes the physical connection that this <code>PooledConnection</code>
+ * object represents. An application never calls this method directly;
+ * it is called by the connection pool module, or manager.
+ * <P>
+ * See the {@link PooledConnection interface description} for more
+ * information.
+ *
+ * @exception SQLException if a database access error occurs
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @since 1.4
+ */
+ void close() throws SQLException;
+
+ /**
+ * Registers the given event listener so that it will be notified
+ * when an event occurs on this <code>PooledConnection</code> object.
+ *
+ * @param listener a component, usually the connection pool manager,
+ * that has implemented the
+ * <code>ConnectionEventListener</code> interface and wants to be
+ * notified when the connection is closed or has an error
+ * @see #removeConnectionEventListener
+ */
+ void addConnectionEventListener(ConnectionEventListener listener);
+
+ /**
+ * Removes the given event listener from the list of components that
+ * will be notified when an event occurs on this
+ * <code>PooledConnection</code> object.
+ *
+ * @param listener a component, usually the connection pool manager,
+ * that has implemented the
+ * <code>ConnectionEventListener</code> interface and
+ * been registered with this <code>PooledConnection</code> object as
+ * a listener
+ * @see #addConnectionEventListener
+ */
+ void removeConnectionEventListener(ConnectionEventListener listener);
+
+ /**
+ * Registers a <code>StatementEventListener</code> with this <code>PooledConnection</code> object. Components that
+ * wish to be notified when <code>PreparedStatement</code>s created by the
+ * connection are closed or are detected to be invalid may use this method
+ * to register a <code>StatementEventListener</code> with this <code>PooledConnection</code> object.
+ * <p>
+ * @param listener an component which implements the <code>StatementEventListener</code>
+ * interface that is to be registered with this <code>PooledConnection</code> object
+ * <p>
+ * @since 1.6
+ */
+ public void addStatementEventListener(StatementEventListener listener);
+
+ /**
+ * Removes the specified <code>StatementEventListener</code> from the list of
+ * components that will be notified when the driver detects that a
+ * <code>PreparedStatement</code> has been closed or is invalid.
+ * <p>
+ * @param listener the component which implements the
+ * <code>StatementEventListener</code> interface that was previously
+ * registered with this <code>PooledConnection</code> object
+ * <p>
+ * @since 1.6
+ */
+ public void removeStatementEventListener(StatementEventListener listener);
+
+ }
Added: trunk/core/src/openjdk/javax/javax/sql/RowSet.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/sql/RowSet.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/sql/RowSet.java 2007-06-21 19:31:53 UTC (rev 3283)
@@ -0,0 +1,2195 @@
+/*
+ * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.sql;
+
+import java.sql.*;
+import java.io.*;
+import java.math.*;
+import java.util.*;
+
+/**
+ * The interface that adds support to the JDBC API for the
+ * JavaBeans<sup><font size=-2>TM</font></sup> component model.
+ * A rowset, which can be used as a JavaBeans component in
+ * a visual Bean development environment, can be created and
+ * configured at design time and executed at run time.
+ * <P>
+ * The <code>RowSet</code>
+ * interface provides a set of JavaBeans properties that allow a <code>RowSet</code>
+ * instance to be configured to connect to a JDBC data source and read
+ * some data from the data source. A group of setter methods (<code>setInt</code>,
+ * <code>setBytes</code>, <code>setString</code>, and so on)
+ * provide a way to pass input parameters to a rowset's command property.
+ * This command is the SQL query the rowset uses when it gets its data from
+ * a relational database, which is generally the case.
+ * <P>
+ * The <code>RowSet</code>
+ * interface supports JavaBeans events, allowing other components in an
+ * application to be notified when an event occurs on a rowset,
+ * such as a change in its value.
+ *
+ * <P>The <code>RowSet</code> interface is unique in that it is intended to be
+ * implemented using the rest of the JDBC API. In other words, a
+ * <code>RowSet</code> implementation is a layer of software that executes "on top"
+ * of a JDBC driver. Implementations of the <code>RowSet</code> interface can
+ * be provided by anyone, including JDBC driver vendors who want to
+ * provide a <code>RowSet</code> implementation as part of their JDBC products.
+ * <P>
+ * A <code>RowSet</code> object may make a connection with a data source and
+ * maintain that connection throughout its life cycle, in which case it is
+ * called a <i>connected</i> rowset. A rowset may also make a connection with
+ * a data source, get data from it, and then close the connection. Such a rowset
+ * is called a <i>disconnected</i> rowset. A disconnected rowset may make
+ * changes to its data while it is disconnected and then send the changes back
+ * to the original source of the data, but it must reestablish a connection to do so.
+ * <P>
+ * A disconnected rowset may have a reader (a <code>RowSetReader</code> object)
+ * and a writer (a <code>RowSetWriter</code> object) associated with it.
+ * The reader may be implemented in many different ways to populate a rowset
+ * with data, including getting data from a non-relational data source. The
+ * writer can also be implemented in many different ways to propagate changes
+ * made to the rowset's data back to the underlying data source.
+ * <P>
+ * Rowsets are easy to use. The <code>RowSet</code> interface extends the standard
+ * <code>java.sql.ResultSet</code> interface. The <code>RowSetMetaData</code>
+ * interface extends the <code>java.sql.ResultSetMetaData</code> interface.
+ * Thus, developers familiar
+ * with the JDBC API will have to learn a minimal number of new APIs to
+ * use rowsets. In addition, third-party software tools that work with
+ * JDBC <code>ResultSet</code> objects will also easily be made to work with rowsets.
+ *
+ * @since 1.4
+ */
+
+public interface RowSet extends ResultSet {
+
+ //-----------------------------------------------------------------------
+ // Properties
+ //-----------------------------------------------------------------------
+
+ //-----------------------------------------------------------------------
+ // The following properties may be used to create a Connection.
+ //-----------------------------------------------------------------------
+
+ /**
+ * Retrieves the url property this <code>RowSet</code> object will use to
+ * create a connection if it uses the <code>DriverManager</code>
+ * instead of a <code>DataSource</code> object to establish the connection.
+ * The default value is <code>null</code>.
+ *
+ * @return a string url
+ * @exception SQLException if a database access error occurs
+ * @see #setUrl
+ */
+ String getUrl() throws SQLException;
+
+ /**
+ * Sets the URL this <code>RowSet</code> object will use when it uses the
+ * <code>DriverManager</code> to create a connection.
+ *
+ * Setting this property is optional. If a URL is used, a JDBC driver
+ * that accepts the URL must be loaded before the
+ * rowset is used to connect to a database. The rowset will use the URL
+ * internally to create a database connection when reading or writing
+ * data. Either a URL or a data source name is used to create a
+ * connection, whichever was set to non null value most recently.
+ *
+ * @param url a string value; may be <code>null</code>
+ * @exception SQLException if a database access error occurs
+ * @see #getUrl
+ */
+ void setUrl(String url) throws SQLException;
+
+ /**
+ * Retrieves the logical name that identifies the data source for this
+ * <code>RowSet</code> object.
+ *
+ * @return a data source name
+ * @see #setDataSourceName
+ * @see #setUrl
+ */
+ String getDataSourceName();
+
+ /**
+ * Sets the data source name property for this <code>RowSet</code> object to the
+ * given <code>String</code>.
+ * <P>
+ * The value of the data source name property can be used to do a lookup of
+ * a <code>DataSource</code> object that has been registered with a naming
+ * service. After being retrieved, the <code>DataSource</code> object can be
+ * used to create a connection to the data source that it represents.
+ *
+ * @param name the logical name of the data source for this <code>RowSet</code>
+ * object; may be <code>null</code>
+ * @exception SQLException if a database access error occurs
+ * @see #getDataSourceName
+ */
+ void setDataSourceName(String name) throws SQLException;
+
+ /**
+ * Retrieves the username used to create a database connection for this
+ * <code>RowSet</code> object.
+ * The username property is set at run time before calling the method
+ * <code>execute</code>. It is
+ * not usually part of the serialized state of a <code>RowSet</code> object.
+ *
+ * @return the username property
+ * @see #setUsername
+ */
+ String getUsername();
+
+ /**
+ * Sets the username property for this <code>RowSet</code> object to the
+ * given <code>String</code>.
+ *
+ * @param name a user name
+ * @exception SQLException if a database access error occurs
+ * @see #getUsername
+ */
+ void setUsername(String name) throws SQLException;
+
+ /**
+ * Retrieves the password used to create a database connection.
+ * The password property is set at run time before calling the method
+ * <code>execute</code>. It is not usually part of the serialized state
+ * of a <code>RowSet</code> object.
+ *
+ * @return the password for making a database connection
+ * @see #setPassword
+ */
+ String getPassword();
+
+ /**
+ * Sets the database password for this <code>RowSet</code> object to
+ * the given <code>String</code>.
+ *
+ * @param password the password string
+ * @exception SQLException if a database access error occurs
+ * @see #getPassword
+ */
+ void setPassword(String password) throws SQLException;
+
+ /**
+ * Retrieves the transaction isolation level set for this
+ * <code>RowSet</code> object.
+ *
+ * @return the transaction isolation level; one of
+ * <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
+ * <code>Connection.TRANSACTION_READ_COMMITTED</code>,
+ * <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
+ * <code>Connection.TRANSACTION_SERIALIZABLE</code>
+ * @see #setTransactionIsolation
+ */
+ int getTransactionIsolation();
+
+ /**
+ * Sets the transaction isolation level for this <code>RowSet</code> obejct.
+ *
+ * @param level the transaction isolation level; one of
+ * <code>Connection.TRANSACTION_READ_UNCOMMITTED</code>,
+ * <code>Connection.TRANSACTION_READ_COMMITTED</code>,
+ * <code>Connection.TRANSACTION_REPEATABLE_READ</code>, or
+ * <code>Connection.TRANSACTION_SERIALIZABLE</code>
+ * @exception SQLException if a database access error occurs
+ * @see #getTransactionIsolation
+ */
+ void setTransactionIsolation(int level) throws SQLException;
+
+ /**
+ * Retrieves the <code>Map</code> object associated with this
+ * <code>RowSet</code> object, which specifies the custom mapping
+ * of SQL user-defined types, if any. The default is for the
+ * type map to be empty.
+ *
+ * @return a <code>java.util.Map</code> object containing the names of
+ * SQL user-defined types and the Java classes to which they are
+ * to be mapped
+ *
+ * @exception SQLException if a database access error occurs
+ * @see #setTypeMap
+ */
+ java.util.Map<String,Class<?>> getTypeMap() throws SQLException;
+
+ /**
+ * Installs the given <code>java.util.Map</code> object as the default
+ * type map for this <code>RowSet</code> object. This type map will be
+ * used unless another type map is supplied as a method parameter.
+ *
+ * @param map a <code>java.util.Map</code> object containing the names of
+ * SQL user-defined types and the Java classes to which they are
+ * to be mapped
+ * @exception SQLException if a database access error occurs
+ * @see #getTypeMap
+ */
+ void setTypeMap(java.util.Map<String,Class<?>> map) throws SQLException;
+
+ //-----------------------------------------------------------------------
+ // The following properties may be used to create a Statement.
+ //-----------------------------------------------------------------------
+
+ /**
+ * Retrieves this <code>RowSet</code> object's command property.
+ *
+ * The command property contains a command string, which must be an SQL
+ * query, that can be executed to fill the rowset with data.
+ * The default value is <code>null</code>.
+ *
+ * @return the command string; may be <code>null</code>
+ * @see #setCommand
+ */
+ String getCommand();
+
+ /**
+ * Sets this <code>RowSet</code> object's command property to the given
+ * SQL query.
+ *
+ * This property is optional
+ * when a rowset gets its data from a data source that does not support
+ * commands, such as a spreadsheet.
+ *
+ * @param cmd the SQL query that will be used to get the data for this
+ * <code>RowSet</code> object; may be <code>null</code>
+ * @exception SQLException if a database access error occurs
+ * @see #getCommand
+ */
+ void setCommand(String cmd) throws SQLException;
+
+ /**
+ * Retrieves whether this <code>RowSet</code> object is read-only.
+ * If updates are possible, the default is for a rowset to be
+ * updatable.
+ * <P>
+ * Attempts to update a read-only rowset will result in an
+ * <code>SQLException</code> being thrown.
+ *
+ * @return <code>true</code> if this <code>RowSet</code> object is
+ * read-only; <code>false</code> if it is updatable
+ * @see #setReadOnly
+ */
+ boolean isReadOnly();
+
+ /**
+ * Sets whether this <code>RowSet</code> object is read-only to the
+ * given <code>boolean</code>.
+ *
+ * @param value <code>true</code> if read-only; <code>false</code> if
+ * updatable
+ * @exception SQLException if a database access error occurs
+ * @see #isReadOnly
+ */
+ void setReadOnly(boolean value) throws SQLException;
+
+ /**
+ * Retrieves the maximum number of bytes that may be returned
+ * for certain column values.
+ * This limit applies only to <code>BINARY</code>,
+ * <code>VARBINARY</code>, <code>LONGVARBINARYBINARY</code>, <code>CHAR</code>,
+ * <code>VARCHAR</code>, <code>LONGVARCHAR</code>, <code>NCHAR</code>
+ * and <code>NVARCHAR</code> columns.
+ * If the limit is exceeded, the excess data is silently discarded.
+ *
+ * @return the current maximum column size limit; zero means that there
+ * is no limit
+ * @exception SQLException if a database access error occurs
+ * @see #setMaxFieldSize
+ */
+ int getMaxFieldSize() throws SQLException;
+
+ /**
+ * Sets the maximum number of bytes that can be returned for a column
+ * value to the given number of bytes.
+ * This limit applies only to <code>BINARY</code>,
+ * <code>VARBINARY</code>, <code>LONGVARBINARYBINARY</code>, <code>CHAR</code>,
+ * <code>VARCHAR</code>, <code>LONGVARCHAR</code>, <code>NCHAR</code>
+ * and <code>NVARCHAR</code> columns.
+ * If the limit is exceeded, the excess data is silently discarded.
+ * For maximum portability, use values greater than 256.
+ *
+ * @param max the new max column size limit in bytes; zero means unlimited
+ * @exception SQLException if a database access error occurs
+ * @see #getMaxFieldSize
+ */
+ void setMaxFieldSize(int max) throws SQLException;
+
+ /**
+ * Retrieves the maximum number of rows that this <code>RowSet</code>
+ * object can contain.
+ * If the limit is exceeded, the excess rows are silently dropped.
+ *
+ * @return the current maximum number of rows that this <code>RowSet</code>
+ * object can contain; zero means unlimited
+ * @exception SQLException if a database access error occurs
+ * @see #setMaxRows
+ */
+ int getMaxRows() throws SQLException;
+
+ /**
+ * Sets the maximum number of rows that this <code>RowSet</code>
+ * object can contain to the specified number.
+ * If the limit is exceeded, the excess rows are silently dropped.
+ *
+ * @param max the new maximum number of rows; zero means unlimited
+ * @exception SQLException if a database access error occurs
+ * @see #getMaxRows
+ */
+ void setMaxRows(int max) throws SQLException;
+
+ /**
+ * Retrieves whether escape processing is enabled for this
+ * <code>RowSet</code> object.
+ * If escape scanning is enabled, which is the default, the driver will do
+ * escape substitution before sending an SQL statement to the database.
+ *
+ * @return <code>true</code> if escape processing is enabled;
+ * <code>false</code> if it is disabled
+ * @exception SQLException if a database access error occurs
+ * @see #setEscapeProcessing
+ */
+ boolean getEscapeProcessing() throws SQLException;
+
+ /**
+ * Sets escape processing for this <code>RowSet</code> object on or
+ * off. If escape scanning is on (the default), the driver will do
+ * escape substitution before sending an SQL statement to the database.
+ *
+ * @param enable <code>true</code> to enable escape processing;
+ * <code>false</code> to disable it
+ * @exception SQLException if a database access error occurs
+ * @see #getEscapeProcessing
+ */
+ void setEscapeProcessing(boolean enable) throws SQLException;
+
+ /**
+ * Retrieves the maximum number of seconds the driver will wait for
+ * a statement to execute.
+ * If this limit is exceeded, an <code>SQLException</code> is thrown.
+ *
+ * @return the current query timeout limit in seconds; zero means
+ * unlimited
+ * @exception SQLException if a database access error occurs
+ * @see #setQueryTimeout
+ */
+ int getQueryTimeout() throws SQLException;
+
+ /**
+ * Sets the maximum time the driver will wait for
+ * a statement to execute to the given number of seconds.
+ * If this limit is exceeded, an <code>SQLException</code> is thrown.
+ *
+ * @param seconds the new query timeout limit in seconds; zero means
+ * that there is no limit
+ * @exception SQLException if a database access error occurs
+ * @see #getQueryTimeout
+ */
+ void setQueryTimeout(int seconds) throws SQLException;
+
+ /**
+ * Sets the type of this <code>RowSet</code> object to the given type.
+ * This method is used to change the type of a rowset, which is by
+ * default read-only and non-scrollable.
+ *
+ * @param type one of the <code>ResultSet</code> constants specifying a type:
+ * <code>ResultSet.TYPE_FORWARD_ONLY</code>,
+ * <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
+ * <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
+ * @exception SQLException if a database access error occurs
+ * @see java.sql.ResultSet#getType
+ */
+ void setType(int type) throws SQLException;
+
+ /**
+ * Sets the concurrency of this <code>RowSet</code> object to the given
+ * concurrency level. This method is used to change the concurrency level
+ * of a rowset, which is by default <code>ResultSet.CONCUR_READ_ONLY</code>
+ *
+ * @param concurrency one of the <code>ResultSet</code> constants specifying a
+ * concurrency level: <code>ResultSet.CONCUR_READ_ONLY</code> or
+ * <code>ResultSet.CONCUR_UPDATABLE</code>
+ * @exception SQLException if a database access error occurs
+ * @see ResultSet#getConcurrency
+ */
+ void setConcurrency(int concurrency) throws SQLException;
+
+ //-----------------------------------------------------------------------
+ // Parameters
+ //-----------------------------------------------------------------------
+
+ /**
+ * The <code>RowSet</code> setter methods are used to set any input parameters
+ * needed by the <code>RowSet</code> object's command.
+ * Parameters are set at run time, as opposed to design time.
+ */
+
+ /**
+ * Sets the designated parameter in this <code>RowSet</code> object's SQL
+ * command to SQL <code>NULL</code>.
+ *
+ * <P><B>Note:</B> You must specify the parameter's SQL type.
+ *
+ * @param parameterIndex the first parameter is 1, the second is 2, ...
+ * @param sqlType a SQL type code defined by <code>java.sql.Types</code>
+ * @exception SQLException if a database access error occurs
+ */
+ void setNull(int parameterIndex, int sqlType) throws SQLException;
+
+ /**
+ * Sets the designated parameter to SQL <code>NULL</code>.
+ *
+ * <P><B>Note:</B> You must specify the parameter's SQL type.
+ *
+ * @param parameterName the name of the parameter
+ * @param sqlType the SQL type code defined in <code>java.sql.Types</code>
+ * @exception SQLException if a database access error occurs or
+ * this method is called on a closed <code>CallableStatement</code>
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @since 1.4
+ */
+ void setNull(String parameterName, int sqlType) throws SQLException;
+
+ /**
+ * Sets the designated parameter in this <code>RowSet</code> object's SQL
+ * command to SQL <code>NULL</code>. This version of the method <code>setNull</code>
+ * should be used for SQL user-defined types (UDTs) and <code>REF</code> type
+ * parameters. Examples of UDTs include: <code>STRUCT</code>, <code>DISTINCT</code>,
+ * <code>JAVA_OBJECT</code>, and named array types.
+ *
+ * <P><B>Note:</B> To be portable, applications must give the
+ * SQL type code and the fully qualified SQL type name when specifying
+ * a NULL UDT or <code>REF</code> parameter. In the case of a UDT,
+ * the name is the type name of the parameter itself. For a <code>REF</code>
+ * parameter, the name is the type name of the referenced type. If
+ * a JDBC driver does not need the type code or type name information,
+ * it may ignore it.
+ *
+ * Although it is intended for UDT and <code>REF</code> parameters,
+ * this method may be used to set a null parameter of any JDBC type.
+ * If the parameter does not have a user-defined or <code>REF</code> type,
+ * the typeName parameter is ignored.
+ *
+ *
+ * @param paramIndex the first parameter is 1, the second is 2, ...
+ * @param sqlType a value from <code>java.sql.Types</code>
+ * @param typeName the fully qualified name of an SQL UDT or the type
+ * name of the SQL structured type being referenced by a <code>REF</code>
+ * type; ignored if the parameter is not a UDT or <code>REF</code> type
+ * @exception SQLException if a database access error occurs
+ */
+ void setNull (int paramIndex, int sqlType, String typeName)
+ throws SQLException;
+
+ /**
+ * Sets the designated parameter to SQL <code>NULL</code>.
+ * This version of the method <code>setNull</code> should
+ * be used for user-defined types and REF type parameters. Examples
+ * of user-defined types include: STRUCT, DISTINCT, JAVA_OBJECT, and
+ * named array types.
+ *
+ * <P><B>Note:</B> To be portable, applications must give the
+ * SQL type code and the fully-qualified SQL type name when specifying
+ * a NULL user-defined or REF parameter. In the case of a user-defined type
+ * the name is the type name of the parameter itself. For a REF
+ * parameter, the name is the type name of the referenced type. If
+ * a JDBC driver does not need the type code or type name information,
+ * it may ignore it.
+ *
+ * Although it is intended for user-defined and Ref parameters,
+ * this method may be used to set a null parameter of any JDBC type.
+ * If the parameter does not have a user-defined or REF type, the given
+ * typeName is ignored.
+ *
+ *
+ * @param parameterName the name of the parameter
+ * @param sqlType a value from <code>java.sql.Types</code>
+ * @param typeName the fully-qualified name of an SQL user-defined type;
+ * ignored if the parameter is not a user-defined type or
+ * SQL <code>REF</code> value
+ * @exception SQLException if a database access error occurs or
+ * this method is called on a closed <code>CallableStatement</code>
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @since 1.4
+ */
+ void setNull (String parameterName, int sqlType, String typeName)
+ throws SQLException;
+
+ /**
+ * Sets the designated parameter in this <code>RowSet</code> object's command
+ * to the given Java <code>boolean</code> value. The driver converts this to
+ * an SQL <code>BIT</code> value before sending it to the database.
+ *
+ * @param parameterIndex the first parameter is 1, the second is 2, ...
+ * @param x the parameter value
+ * @exception SQLException if a database access error occurs
+ */
+ void setBoolean(int parameterIndex, boolean x) throws SQLException;
+
+ /**
+ * Sets the designated parameter to the given Java <code>boolean</code> value.
+ * The driver converts this
+ * to an SQL <code>BIT</code> or <code>BOOLEAN</code> value when it sends it to the database.
+ *
+ * @param parameterName the name of the parameter
+ * @param x the parameter value
+ * @exception SQLException if a database access error occurs or
+ * this method is called on a closed <code>CallableStatement</code>
+ * @see #getBoolean
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @since 1.4
+ */
+ void setBoolean(String parameterName, boolean x) throws SQLException;
+
+ /**
+ * Sets the designated parameter in this <code>RowSet</code> object's command
+ * to the given Java <code>byte</code> value. The driver converts this to
+ * an SQL <code>TINYINT</code> value before sending it to the database.
+ *
+ * @param parameterIndex the first parameter is 1, the second is 2, ...
+ * @param x the parameter value
+ * @exception SQLException if a database access error occurs
+ */
+ void setByte(int parameterIndex, byte x) throws SQLException;
+
+ /**
+ * Sets the designated parameter to the given Java <code>byte</code> value.
+ * The driver converts this
+ * to an SQL <code>TINYINT</code> value when it sends it to the database.
+ *
+ * @param parameterName the name of the parameter
+ * @param x the parameter value
+ * @exception SQLException if a database access error occurs or
+ * this method is called on a closed <code>CallableStatement</code>
+ * @exception SQLFeatureNotSupportedException if the JDBC driver does not support
+ * this method
+ * @see #getByte
+ * @since 1.4
+ */
+ void setByte(String parameterName, byte x) throws SQLException;
+
+ /**
+ * Sets the designated parameter in this <code>RowSet</code> object's command
+ * to the given Java <code>short</code> value. The driver converts this to
+ * an SQL <code>SMALLINT</code> value before sending it to t...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-21 19:30:37
|
Revision: 3282
http://jnode.svn.sourceforge.net/jnode/?rev=3282&view=rev
Author: lsantha
Date: 2007-06-21 12:30:34 -0700 (Thu, 21 Jun 2007)
Log Message:
-----------
Openjdk integration.
Removed Paths:
-------------
trunk/core/src/classpath/javax/javax/sql/
trunk/core/src/classpath/javax/javax/transaction/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-21 19:22:50
|
Revision: 3281
http://jnode.svn.sourceforge.net/jnode/?rev=3281&view=rev
Author: lsantha
Date: 2007-06-21 12:22:45 -0700 (Thu, 21 Jun 2007)
Log Message:
-----------
Grub installer improvements by Tango.
Modified Paths:
--------------
trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java
trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java
Modified: trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java
===================================================================
--- trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java 2007-06-17 20:37:45 UTC (rev 3280)
+++ trunk/fs/src/fs/org/jnode/fs/jfat/command/JGrubInstallCommand.java 2007-06-21 19:22:45 UTC (rev 3281)
@@ -36,6 +36,7 @@
import org.jnode.shell.help.ParsedArguments;
import org.jnode.shell.help.argument.DeviceArgument;
import org.jnode.shell.help.argument.FileArgument;
+import org.jnode.shell.help.argument.OptionArgument;
/**
* <p/>
@@ -52,10 +53,27 @@
public class JGrubInstallCommand implements Command {
static final DeviceArgument ARG_DEVICE = new DeviceArgument("device", "device where grub will be installed");
static final FileArgument ARG_DIR = new FileArgument("directory", "the directory for stage2 and menu.lst");
- static final Help.Info HELP_INFO = new Help.Info("grub", "Install GRUB to the specified location.",
- new Parameter(ARG_DEVICE, Parameter.MANDATORY),
- new Parameter(ARG_DIR, Parameter.MANDATORY));
+ static final OptionArgument TYPE = new OptionArgument("action",
+ "Type parameter",
+ new OptionArgument.Option[] { new OptionArgument.Option("-p",
+ "Set the partition point for installing Stage2,menu.lst") });
+ static final OptionArgument PS_VAL = new OptionArgument("Partition Value",
+ "Setting The Partition value like (-p 1) for the hdx1", new OptionArgument.Option[] {
+ new OptionArgument.Option("0", "hdX0"),
+ new OptionArgument.Option("1", "hdX1"),
+ new OptionArgument.Option("2", "hdX2"),
+ new OptionArgument.Option("3", "hdX3")
+ });
+
+
+
+ static final Help.Info HELP_INFO = new Help.Info ("grub", "Install the grub to the specified location.", new Parameter[] {
+ new Parameter(ARG_DEVICE, Parameter.MANDATORY),
+ new Parameter(TYPE,Parameter.MANDATORY),
+ new Parameter(PS_VAL,Parameter.MANDATORY),
+ new Parameter(ARG_DIR,Parameter.MANDATORY),
+ });
/**
* @param args
* @throws Exception
@@ -72,12 +90,19 @@
ParsedArguments cmdLine = HELP_INFO.parse(commandLine.toStringArray());
String device = ARG_DEVICE.getValue(cmdLine);
File destDir = ARG_DIR.getFile(cmdLine);
+
+ Integer bsize=null;
+ try {
+ bsize = Integer.valueOf(PS_VAL.getValue(cmdLine));
+ } catch (NumberFormatException nfe) {
+ System.out.println("ERROR: give the partition value as the 0 ,1,2,3"+"\n" +"This grub installer not support the Extended partition.");
+ }
DeviceManager dm = InitialNaming.lookup(DeviceManager.NAME);
Device dev = dm.getDevice(device);
String destDirName = destDir.getAbsolutePath();
out.println("Installing GRUB to: " + device + ", " + destDirName);
try {
- new MBRFormatter().format(dev);
+ new MBRFormatter().format(dev,bsize);
new GrubJFatFormatter().format(destDirName);
out.println("Restarting device: " + device);
dm.stop(dev);
Modified: trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java
===================================================================
--- trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java 2007-06-17 20:37:45 UTC (rev 3280)
+++ trunk/fs/src/fs/org/jnode/fs/jfat/command/MBRFormatter.java 2007-06-21 19:22:45 UTC (rev 3281)
@@ -18,10 +18,6 @@
* along with this library; If not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
-
-
-
-
package org.jnode.fs.jfat.command;
/**
@@ -30,6 +26,7 @@
*/
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
@@ -60,8 +57,11 @@
*/
final String stageResourceName1 = "/devices/sg0/boot/grub/grub.s1";
final String stageResourceName2 = "/devices/sg0/boot/grub/fat.s15";
- private static int installPartition = 0xFFFFFF;
+ private static int INSTALL_PARTITION = 0xFFFFFF;
private String configFile;
+ //The Embedded Variables values in Jnode
+ final int SAVED_ENTRY_NUMBER=0xe;
+ final String CONFIG_FILE_NAME="/boot/grub/menu.lst";
/**
*
@@ -72,7 +72,7 @@
private void checkMBR(ByteBuffer MBR) throws IOException
{
if (!IBMPartitionTable.containsPartitionTable(MBR.array()))
- throw new IOException("This device doesn't contain a valid MBR, use --initmbr.");
+ throw new IOException("This device doesn't contain a valid MBR.");
}
/**
@@ -138,7 +138,7 @@
* @throws java.io.IOException
* @see org.jnode.fs.fat.FatFormatter#format(org.jnode.driver.block.BlockDeviceAPI)
*/
- public void format(Device device) throws FileSystemException, IOException {
+ public void format(Device device,int bsize) throws FileSystemException, IOException {
BlockDeviceAPI devApi;
try {
devApi = device.getAPI(BlockDeviceAPI.class);
@@ -146,11 +146,11 @@
throw new FileSystemException("Device is not a partition!", e);
}
- log.info("The MBR Old is checked successfully.");
+ log.info("Checking the old MBR...");
ByteBuffer MBR=ByteBuffer.allocate(IDEConstants.SECTOR_SIZE);
devApi.read(0, MBR);
checkMBR(MBR);
- log.info("The MBR Old is read successfully.");
+ log.info("done.");
/*int add=LittleEndian.getInt32(MBR.array(),0x44);
System.out.println("The value at the position 0x44 is-> " +Integer.toHexString(add));*/
@@ -159,8 +159,11 @@
if(!isaValidBootSector(MBR.array())){
log.error("The OLD Boot Sector is not valid.");
}
-
+ try{
stage1=getStage1(stageResourceName1);
+ }catch(FileNotFoundException e){
+ log.error("The stage1 is not available.");
+ }
/**
* The BPB stands for the Bios Parameter Block.As the BPB of
* a disk is fixed and it is written to the disk during the
@@ -171,7 +174,7 @@
* 1) Here need to make the BPB more independently(ie without
* array of the BPB using it in MBR)
*
- * 2)The next Inportant matter is here that in the MBR's
+ * 2)The next Important matter is here that in the MBR's
* <b> 0x44 th</b> position we setting the position of the
* stage1.5 or Stage2.here as i used the Stage1.5 at the Sector
* 1(second sector) so The Value is set here as 01 00 00 00
@@ -233,7 +236,11 @@
System.out.println("The Stage1.5 is now embedding.");
- stage1_5 = getStage1_5(stageResourceName2);
+ try{
+ stage1_5 = getStage1_5(stageResourceName2);
+ }catch(FileNotFoundException ex){
+ log.error("The Stage1.5 is not available.");
+ }
int size=stage1_5.length/IDEConstants.SECTOR_SIZE;
log.info("The Size of the stage1_5 is : "+size);
@@ -253,18 +260,21 @@
* Blocklists is the size of the stage1.5 in the sectors unit.
*
**/
- LittleEndian.setInt16(stage1_5,512-4 ,size);
+ setLittleEnd_BlockLists(stage1_5,size);
+
/** Fixup the install partition */
- LittleEndian.setInt32(stage1_5, 512 + 0x08, installPartition);
+ setLittleEnd_InstallPartition(stage1_5,INSTALL_PARTITION);
- setConfigFile("/boot/grub/menu.lst");
-
+
+ setConfigFile(CONFIG_FILE_NAME);
+
/** The Saved Entry Number **/
- LittleEndian.setInt32(stage1_5,512+0xc,0xe);
+ setLittleEnd_EntryNumber(stage1_5,SAVED_ENTRY_NUMBER);
+
/**
* The most important section of the Grub
* The path of the stage2 in the stage1.5
@@ -306,8 +316,9 @@
* the JNODE.
*
**/
- LittleEndian.setInt8(stage1_5,512+0x19,0x00);
+ setLittleEnd_DrivePath(stage1_5,bsize);
+
/**
* Fixup the config file
* TODO: here to be change that the Config File
@@ -346,8 +357,48 @@
}
-
/**
+ * The Install Partition setting
+ * @arch i386
+ * @param stage1_5
+ * @param installPartition2
+ */
+ private void setLittleEnd_InstallPartition(byte[] stage1_5, int installPartition) {
+ LittleEndian.setInt32(stage1_5, 512 + 0x08, installPartition);
+
+ }
+ /**
+ * The saved Entry Number setting.
+ * @arch i386
+ * @param stage1_5
+ * @param i
+ */
+ private void setLittleEnd_EntryNumber(byte[] stage1_5, int i) {
+ LittleEndian.setInt32(stage1_5,512+0xc,i);
+
+ }
+ /**
+ * The BlockLists if the stage1.5 is setting here.
+ * @arch:i386
+ * @param stage1_5
+ * @param size
+ */
+ private void setLittleEnd_BlockLists(byte[] stage1_5, int size) {
+ LittleEndian.setInt16(stage1_5,512-4 ,size);
+
+ }
+ /**
+ *
+ * Setting the Drive path to the stage1.5.Though it is BUGGY yet.
+ * @arch i386
+ * @param stage1_5
+ * @param i
+ */
+ private void setLittleEnd_DrivePath(byte[] stage1_5, int i) {
+ LittleEndian.setInt8(stage1_5,512+0x19,i);
+ }
+
+ /**
* The Writing the BPB to the MBR to its Correct Position.
* @param bpb2
* @param stage12
@@ -397,14 +448,14 @@
* @return
*/
public int getInstallPartition() {
- return installPartition;
+ return INSTALL_PARTITION;
}
/**
* The Writtting of the InstallPartition.
* @param installPartition1
*/
public static void setInstallPartition(int installPartition1) {
- installPartition = installPartition1;
+ INSTALL_PARTITION = installPartition1;
}
/**
*
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-17 20:37:52
|
Revision: 3280
http://jnode.svn.sourceforge.net/jnode/?rev=3280&view=rev
Author: lsantha
Date: 2007-06-17 13:37:45 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Feformatted.
Modified Paths:
--------------
trunk/core/src/core/org/jnode/vm/classmgr/VmType.java
Modified: trunk/core/src/core/org/jnode/vm/classmgr/VmType.java
===================================================================
--- trunk/core/src/core/org/jnode/vm/classmgr/VmType.java 2007-06-17 20:36:33 UTC (rev 3279)
+++ trunk/core/src/core/org/jnode/vm/classmgr/VmType.java 2007-06-17 20:37:45 UTC (rev 3280)
@@ -1363,25 +1363,25 @@
*/
protected abstract VmMethod getSyntheticAbstractMethod(String name,
String signature, int hashCode);
-
+
final VmMethod getNativeMethodReplacement(String name, String signature) {
- signature = signature.substring(0, signature.indexOf(')'));
- /* Search only in my own method table */
- final VmMethod[] mt = this.methodTable;
- if (mt != null) {
- final int count = mt.length;
- for (int i = 0; i < count; i++) {
- final VmMethod mts = mt[i];
- if (mts.nameEquals(name)) {
- String sig2 = mts.getSignature();
- if (signature.equals(sig2.substring(0, sig2.indexOf(')')))) {
- return mts;
- }
+ signature = signature.substring(0, signature.indexOf(')'));
+ /* Search only in my own method table */
+ final VmMethod[] mt = this.methodTable;
+ if (mt != null) {
+ final int count = mt.length;
+ for (int i = 0; i < count; i++) {
+ final VmMethod mts = mt[i];
+ if (mts.nameEquals(name)) {
+ String sig2 = mts.getSignature();
+ if (signature.equals(sig2.substring(0, sig2.indexOf(')')))) {
+ return mts;
}
}
}
- return null;
}
+ return null;
+ }
/**
* Find the method within the given class (or super-classes) that has the
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-17 20:36:37
|
Revision: 3279
http://jnode.svn.sourceforge.net/jnode/?rev=3279&view=rev
Author: lsantha
Date: 2007-06-17 13:36:33 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Improved support for native methods.
Modified Paths:
--------------
trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java
trunk/core/src/core/org/jnode/vm/classmgr/VmType.java
Modified: trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java
===================================================================
--- trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java 2007-06-17 12:17:11 UTC (rev 3278)
+++ trunk/core/src/core/org/jnode/vm/classmgr/ClassDecoder.java 2007-06-17 20:36:33 UTC (rev 3279)
@@ -495,23 +495,14 @@
}
return null;
}
- final VmType[] argTypes;
- if (method.isStatic()) {
- final int argCount = method.getNoArguments();
- argTypes = new VmType[argCount];
- for (int i = 0; i < argCount; i++) {
- argTypes[i] = method.getArgumentType(i);
- }
- } else {
- final int argCount = method.getNoArguments();
- argTypes = new VmType[argCount + 1];
- argTypes[0] = method.getDeclaringClass();
- for (int i = 0; i < argCount; i++) {
- argTypes[i + 1] = method.getArgumentType(i);
- }
+
+ String signature = method.getSignature();
+ if(!method.isStatic()){
+ signature = "(" + Signature.toSignature(method.getDeclaringClass()) + signature.substring(1);
}
- final VmMethod nativeMethod = nativeType.getNativeMethodReplacement(method.getName(), argTypes);
+ final VmMethod nativeMethod = nativeType.getNativeMethodReplacement(method.getName(), signature);
+
if (nativeMethod == null) {
if (verbose) {
BootLog.error("Native method replacement (" + method
Modified: trunk/core/src/core/org/jnode/vm/classmgr/VmType.java
===================================================================
--- trunk/core/src/core/org/jnode/vm/classmgr/VmType.java 2007-06-17 12:17:11 UTC (rev 3278)
+++ trunk/core/src/core/org/jnode/vm/classmgr/VmType.java 2007-06-17 20:36:33 UTC (rev 3279)
@@ -1363,26 +1363,25 @@
*/
protected abstract VmMethod getSyntheticAbstractMethod(String name,
String signature, int hashCode);
-
- final VmMethod getNativeMethodReplacement(String name, VmType[] argTypes) {
- String sig1 = Signature.toSignature(null, argTypes);
- sig1 = sig1.substring(0, sig1.indexOf(')'));
- /* Search only in my own method table */
- final VmMethod[] mt = this.methodTable;
- if (mt != null) {
- final int count = mt.length;
- for (int i = 0; i < count; i++) {
- final VmMethod mts = mt[i];
- if (mts.nameEquals(name)) {
- String sig2 = mts.getSignature();
- if (sig1.equals(sig2.substring(0, sig2.indexOf(')')))) {
- return mts;
+
+ final VmMethod getNativeMethodReplacement(String name, String signature) {
+ signature = signature.substring(0, signature.indexOf(')'));
+ /* Search only in my own method table */
+ final VmMethod[] mt = this.methodTable;
+ if (mt != null) {
+ final int count = mt.length;
+ for (int i = 0; i < count; i++) {
+ final VmMethod mts = mt[i];
+ if (mts.nameEquals(name)) {
+ String sig2 = mts.getSignature();
+ if (signature.equals(sig2.substring(0, sig2.indexOf(')')))) {
+ return mts;
+ }
}
}
}
+ return null;
}
- return null;
- }
/**
* Find the method within the given class (or super-classes) that has the
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-17 12:17:13
|
Revision: 3278
http://jnode.svn.sourceforge.net/jnode/?rev=3278&view=rev
Author: lsantha
Date: 2007-06-17 05:17:11 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/java/java/math/
trunk/core/src/openjdk/java/java/math/BigDecimal.java
trunk/core/src/openjdk/java/java/math/BigInteger.java
trunk/core/src/openjdk/java/java/math/BitSieve.java
trunk/core/src/openjdk/java/java/math/MathContext.java
trunk/core/src/openjdk/java/java/math/MutableBigInteger.java
trunk/core/src/openjdk/java/java/math/RoundingMode.java
trunk/core/src/openjdk/java/java/math/SignedMutableBigInteger.java
trunk/core/src/openjdk/java/java/math/package-info.java
trunk/core/src/openjdk/java/java/util/FormatFlagsConversionMismatchException.java
trunk/core/src/openjdk/java/java/util/Formattable.java
trunk/core/src/openjdk/java/java/util/FormattableFlags.java
trunk/core/src/openjdk/java/java/util/Formatter.java
trunk/core/src/openjdk/java/java/util/FormatterClosedException.java
trunk/core/src/openjdk/java/java/util/Scanner.java
Added: trunk/core/src/openjdk/java/java/math/BigDecimal.java
===================================================================
--- trunk/core/src/openjdk/java/java/math/BigDecimal.java (rev 0)
+++ trunk/core/src/openjdk/java/java/math/BigDecimal.java 2007-06-17 12:17:11 UTC (rev 3278)
@@ -0,0 +1,3555 @@
+/*
+ * Portions Copyright 1996-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
+ */
+
+package java.math;
+
+/**
+ * Immutable, arbitrary-precision signed decimal numbers. A
+ * {@code BigDecimal} consists of an arbitrary precision integer
+ * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
+ * or positive, the scale is the number of digits to the right of the
+ * decimal point. If negative, the unscaled value of the number is
+ * multiplied by ten to the power of the negation of the scale. The
+ * value of the number represented by the {@code BigDecimal} is
+ * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.
+ *
+ * <p>The {@code BigDecimal} class provides operations for
+ * arithmetic, scale manipulation, rounding, comparison, hashing, and
+ * format conversion. The {@link #toString} method provides a
+ * canonical representation of a {@code BigDecimal}.
+ *
+ * <p>The {@code BigDecimal} class gives its user complete control
+ * over rounding behavior. If no rounding mode is specified and the
+ * exact result cannot be represented, an exception is thrown;
+ * otherwise, calculations can be carried out to a chosen precision
+ * and rounding mode by supplying an appropriate {@link MathContext}
+ * object to the operation. In either case, eight <em>rounding
+ * modes</em> are provided for the control of rounding. Using the
+ * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
+ * represent rounding mode is largely obsolete; the enumeration values
+ * of the {@code RoundingMode} {@code enum}, (such as {@link
+ * RoundingMode#HALF_UP}) should be used instead.
+ *
+ * <p>When a {@code MathContext} object is supplied with a precision
+ * setting of 0 (for example, {@link MathContext#UNLIMITED}),
+ * arithmetic operations are exact, as are the arithmetic methods
+ * which take no {@code MathContext} object. (This is the only
+ * behavior that was supported in releases prior to 5.) As a
+ * corollary of computing the exact result, the rounding mode setting
+ * of a {@code MathContext} object with a precision setting of 0 is
+ * not used and thus irrelevant. In the case of divide, the exact
+ * quotient could have an infinitely long decimal expansion; for
+ * example, 1 divided by 3. If the quotient has a nonterminating
+ * decimal expansion and the operation is specified to return an exact
+ * result, an {@code ArithmeticException} is thrown. Otherwise, the
+ * exact result of the division is returned, as done for other
+ * operations.
+ *
+ * <p>When the precision setting is not 0, the rules of
+ * {@code BigDecimal} arithmetic are broadly compatible with selected
+ * modes of operation of the arithmetic defined in ANSI X3.274-1996
+ * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
+ * standards, {@code BigDecimal} includes many rounding modes, which
+ * were mandatory for division in {@code BigDecimal} releases prior
+ * to 5. Any conflicts between these ANSI standards and the
+ * {@code BigDecimal} specification are resolved in favor of
+ * {@code BigDecimal}.
+ *
+ * <p>Since the same numerical value can have different
+ * representations (with different scales), the rules of arithmetic
+ * and rounding must specify both the numerical result and the scale
+ * used in the result's representation.
+ *
+ *
+ * <p>In general the rounding modes and precision setting determine
+ * how operations return results with a limited number of digits when
+ * the exact result has more digits (perhaps infinitely many in the
+ * case of division) than the number of digits returned.
+ *
+ * First, the
+ * total number of digits to return is specified by the
+ * {@code MathContext}'s {@code precision} setting; this determines
+ * the result's <i>precision</i>. The digit count starts from the
+ * leftmost nonzero digit of the exact result. The rounding mode
+ * determines how any discarded trailing digits affect the returned
+ * result.
+ *
+ * <p>For all arithmetic operators , the operation is carried out as
+ * though an exact intermediate result were first calculated and then
+ * rounded to the number of digits specified by the precision setting
+ * (if necessary), using the selected rounding mode. If the exact
+ * result is not returned, some digit positions of the exact result
+ * are discarded. When rounding increases the magnitude of the
+ * returned result, it is possible for a new digit position to be
+ * created by a carry propagating to a leading {@literal "9"} digit.
+ * For example, rounding the value 999.9 to three digits rounding up
+ * would be numerically equal to one thousand, represented as
+ * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
+ * the leading digit position of the returned result.
+ *
+ * <p>Besides a logical exact result, each arithmetic operation has a
+ * preferred scale for representing a result. The preferred
+ * scale for each operation is listed in the table below.
+ *
+ * <table border>
+ * <caption top><h3>Preferred Scales for Results of Arithmetic Operations
+ * </h3></caption>
+ * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
+ * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
+ * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
+ * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
+ * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
+ * </table>
+ *
+ * These scales are the ones used by the methods which return exact
+ * arithmetic results; except that an exact divide may have to use a
+ * larger scale since the exact result may have more digits. For
+ * example, {@code 1/32} is {@code 0.03125}.
+ *
+ * <p>Before rounding, the scale of the logical exact intermediate
+ * result is the preferred scale for that operation. If the exact
+ * numerical result cannot be represented in {@code precision}
+ * digits, rounding selects the set of digits to return and the scale
+ * of the result is reduced from the scale of the intermediate result
+ * to the least scale which can represent the {@code precision}
+ * digits actually returned. If the exact result can be represented
+ * with at most {@code precision} digits, the representation
+ * of the result with the scale closest to the preferred scale is
+ * returned. In particular, an exactly representable quotient may be
+ * represented in fewer than {@code precision} digits by removing
+ * trailing zeros and decreasing the scale. For example, rounding to
+ * three digits using the {@linkplain RoundingMode#FLOOR floor}
+ * rounding mode, <br>
+ *
+ * {@code 19/100 = 0.19 // integer=19, scale=2} <br>
+ *
+ * but<br>
+ *
+ * {@code 21/110 = 0.190 // integer=190, scale=3} <br>
+ *
+ * <p>Note that for add, subtract, and multiply, the reduction in
+ * scale will equal the number of digit positions of the exact result
+ * which are discarded. If the rounding causes a carry propagation to
+ * create a new high-order digit position, an additional digit of the
+ * result is discarded than when no new digit position is created.
+ *
+ * <p>Other methods may have slightly different rounding semantics.
+ * For example, the result of the {@code pow} method using the
+ * {@linkplain #pow(int, MathContext) specified algorithm} can
+ * occasionally differ from the rounded mathematical result by more
+ * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
+ *
+ * <p>Two types of operations are provided for manipulating the scale
+ * of a {@code BigDecimal}: scaling/rounding operations and decimal
+ * point motion operations. Scaling/rounding operations ({@link
+ * #setScale setScale} and {@link #round round}) return a
+ * {@code BigDecimal} whose value is approximately (or exactly) equal
+ * to that of the operand, but whose scale or precision is the
+ * specified value; that is, they increase or decrease the precision
+ * of the stored number with minimal effect on its value. Decimal
+ * point motion operations ({@link #movePointLeft movePointLeft} and
+ * {@link #movePointRight movePointRight}) return a
+ * {@code BigDecimal} created from the operand by moving the decimal
+ * point a specified distance in the specified direction.
+ *
+ * <p>For the sake of brevity and clarity, pseudo-code is used
+ * throughout the descriptions of {@code BigDecimal} methods. The
+ * pseudo-code expression {@code (i + j)} is shorthand for "a
+ * {@code BigDecimal} whose value is that of the {@code BigDecimal}
+ * {@code i} added to that of the {@code BigDecimal}
+ * {@code j}." The pseudo-code expression {@code (i == j)} is
+ * shorthand for "{@code true} if and only if the
+ * {@code BigDecimal} {@code i} represents the same value as the
+ * {@code BigDecimal} {@code j}." Other pseudo-code expressions
+ * are interpreted similarly. Square brackets are used to represent
+ * the particular {@code BigInteger} and scale pair defining a
+ * {@code BigDecimal} value; for example [19, 2] is the
+ * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
+ *
+ * <p>Note: care should be exercised if {@code BigDecimal} objects
+ * are used as keys in a {@link java.util.SortedMap SortedMap} or
+ * elements in a {@link java.util.SortedSet SortedSet} since
+ * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
+ * with equals</i>. See {@link Comparable}, {@link
+ * java.util.SortedMap} or {@link java.util.SortedSet} for more
+ * information.
+ *
+ * <p>All methods and constructors for this class throw
+ * {@code NullPointerException} when passed a {@code null} object
+ * reference for any input parameter.
+ *
+ * @see BigInteger
+ * @see MathContext
+ * @see RoundingMode
+ * @see java.util.SortedMap
+ * @see java.util.SortedSet
+ * @author Josh Bloch
+ * @author Mike Cowlishaw
+ * @author Joseph D. Darcy
+ */
+public class BigDecimal extends Number implements Comparable<BigDecimal> {
+ /**
+ * The unscaled value of this BigDecimal, as returned by {@link
+ * #unscaledValue}.
+ *
+ * @serial
+ * @see #unscaledValue
+ */
+ private volatile BigInteger intVal;
+
+ /**
+ * The scale of this BigDecimal, as returned by {@link #scale}.
+ *
+ * @serial
+ * @see #scale
+ */
+ private int scale = 0; // Note: this may have any value, so
+ // calculations must be done in longs
+ /**
+ * The number of decimal digits in this BigDecimal, or 0 if the
+ * number of digits are not known (lookaside information). If
+ * nonzero, the value is guaranteed correct. Use the precision()
+ * method to obtain and set the value if it might be 0. This
+ * field is mutable until set nonzero.
+ *
+ * @since 1.5
+ */
+ private volatile transient int precision = 0;
+
+ /**
+ * Used to store the canonical string representation, if computed.
+ */
+ private volatile transient String stringCache = null;
+
+ /**
+ * Sentinel value for {@link #intCompact} indicating the
+ * significand information is only available from {@code intVal}.
+ */
+ private static final long INFLATED = Long.MIN_VALUE;
+
+ /**
+ * If the absolute value of the significand of this BigDecimal is
+ * less than or equal to {@code Long.MAX_VALUE}, the value can be
+ * compactly stored in this field and used in computations.
+ */
+ private transient long intCompact = INFLATED;
+
+ // All 18-digit base ten strings fit into a long; not all 19-digit
+ // strings will
+ private static final int MAX_COMPACT_DIGITS = 18;
+
+ private static final int MAX_BIGINT_BITS = 62;
+
+ /* Appease the serialization gods */
+ private static final long serialVersionUID = 6108874887143696463L;
+
+ // Cache of common small BigDecimal values.
+ private static final BigDecimal zeroThroughTen[] = {
+ new BigDecimal(BigInteger.ZERO, 0, 0),
+ new BigDecimal(BigInteger.ONE, 1, 0),
+ new BigDecimal(BigInteger.valueOf(2), 2, 0),
+ new BigDecimal(BigInteger.valueOf(3), 3, 0),
+ new BigDecimal(BigInteger.valueOf(4), 4, 0),
+ new BigDecimal(BigInteger.valueOf(5), 5, 0),
+ new BigDecimal(BigInteger.valueOf(6), 6, 0),
+ new BigDecimal(BigInteger.valueOf(7), 7, 0),
+ new BigDecimal(BigInteger.valueOf(8), 8, 0),
+ new BigDecimal(BigInteger.valueOf(9), 9, 0),
+ new BigDecimal(BigInteger.TEN, 10, 0),
+ };
+
+ // Constants
+ /**
+ * The value 0, with a scale of 0.
+ *
+ * @since 1.5
+ */
+ public static final BigDecimal ZERO =
+ zeroThroughTen[0];
+
+ /**
+ * The value 1, with a scale of 0.
+ *
+ * @since 1.5
+ */
+ public static final BigDecimal ONE =
+ zeroThroughTen[1];
+
+ /**
+ * The value 10, with a scale of 0.
+ *
+ * @since 1.5
+ */
+ public static final BigDecimal TEN =
+ zeroThroughTen[10];
+
+ // Constructors
+
+ /**
+ * Translates a character array representation of a
+ * {@code BigDecimal} into a {@code BigDecimal}, accepting the
+ * same sequence of characters as the {@link #BigDecimal(String)}
+ * constructor, while allowing a sub-array to be specified.
+ *
+ * <p>Note that if the sequence of characters is already available
+ * within a character array, using this constructor is faster than
+ * converting the {@code char} array to string and using the
+ * {@code BigDecimal(String)} constructor .
+ *
+ * @param in {@code char} array that is the source of characters.
+ * @param offset first character in the array to inspect.
+ * @param len number of characters to consider.
+ * @throws NumberFormatException if {@code in} is not a valid
+ * representation of a {@code BigDecimal} or the defined subarray
+ * is not wholly within {@code in}.
+ * @since 1.5
+ */
+ public BigDecimal(char[] in, int offset, int len) {
+ // This is the primary string to BigDecimal constructor; all
+ // incoming strings end up here; it uses explicit (inline)
+ // parsing for speed and generates at most one intermediate
+ // (temporary) object (a char[] array).
+
+ // use array bounds checking to handle too-long, len == 0,
+ // bad offset, etc.
+ try {
+ // handle the sign
+ boolean isneg = false; // assume positive
+ if (in[offset] == '-') {
+ isneg = true; // leading minus means negative
+ offset++;
+ len--;
+ } else if (in[offset] == '+') { // leading + allowed
+ offset++;
+ len--;
+ }
+
+ // should now be at numeric part of the significand
+ int dotoff = -1; // '.' offset, -1 if none
+ int cfirst = offset; // record start of integer
+ long exp = 0; // exponent
+ if (len > in.length) // protect against huge length
+ throw new NumberFormatException();
+ char coeff[] = new char[len]; // integer significand array
+ char c; // work
+
+ for (; len > 0; offset++, len--) {
+ c = in[offset];
+ if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
+ // have digit
+ coeff[precision] = c;
+ precision++; // count of digits
+ continue;
+ }
+ if (c == '.') {
+ // have dot
+ if (dotoff >= 0) // two dots
+ throw new NumberFormatException();
+ dotoff = offset;
+ continue;
+ }
+ // exponent expected
+ if ((c != 'e') && (c != 'E'))
+ throw new NumberFormatException();
+ offset++;
+ c = in[offset];
+ len--;
+ boolean negexp = false;
+ // optional sign
+ if (c == '-' || c == '+') {
+ negexp = (c == '-');
+ offset++;
+ c = in[offset];
+ len--;
+ }
+ if (len <= 0) // no exponent digits
+ throw new NumberFormatException();
+ // skip leading zeros in the exponent
+ while (len > 10 && Character.digit(c, 10) == 0) {
+ offset++;
+ c = in[offset];
+ len--;
+ }
+ if (len > 10) // too many nonzero exponent digits
+ throw new NumberFormatException();
+ // c now holds first digit of exponent
+ for (;; len--) {
+ int v;
+ if (c >= '0' && c <= '9') {
+ v = c - '0';
+ } else {
+ v = Character.digit(c, 10);
+ if (v < 0) // not a digit
+ throw new NumberFormatException();
+ }
+ exp = exp * 10 + v;
+ if (len == 1)
+ break; // that was final character
+ offset++;
+ c = in[offset];
+ }
+ if (negexp) // apply sign
+ exp = -exp;
+ // Next test is required for backwards compatibility
+ if ((int)exp != exp) // overflow
+ throw new NumberFormatException();
+ break; // [saves a test]
+ }
+ // here when no characters left
+ if (precision == 0) // no digits found
+ throw new NumberFormatException();
+
+ if (dotoff >= 0) { // had dot; set scale
+ scale = precision - (dotoff - cfirst);
+ // [cannot overflow]
+ }
+ if (exp != 0) { // had significant exponent
+ try {
+ scale = checkScale(-exp + scale); // adjust
+ } catch (ArithmeticException e) {
+ throw new NumberFormatException("Scale out of range.");
+ }
+ }
+
+ // Remove leading zeros from precision (digits count)
+ int first = 0;
+ for (; (coeff[first] == '0' || Character.digit(coeff[first], 10) == 0) &&
+ precision > 1;
+ first++)
+ precision--;
+
+ // Set the significand ..
+ // Copy significand to exact-sized array, with sign if
+ // negative
+ // Later use: BigInteger(coeff, first, precision) for
+ // both cases, by allowing an extra char at the front of
+ // coeff.
+ char quick[];
+ if (!isneg) {
+ quick = new char[precision];
+ System.arraycopy(coeff, first, quick, 0, precision);
+ } else {
+ quick = new char[precision+1];
+ quick[0] = '-';
+ System.arraycopy(coeff, first, quick, 1, precision);
+ }
+ if (precision <= MAX_COMPACT_DIGITS)
+ intCompact = Long.parseLong(new String(quick));
+ else
+ intVal = new BigInteger(quick);
+ // System.out.println(" new: " +intVal+" ["+scale+"] "+precision);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ throw new NumberFormatException();
+ } catch (NegativeArraySizeException e) {
+ throw new NumberFormatException();
+ }
+ }
+
+ /**
+ * Translates a character array representation of a
+ * {@code BigDecimal} into a {@code BigDecimal}, accepting the
+ * same sequence of characters as the {@link #BigDecimal(String)}
+ * constructor, while allowing a sub-array to be specified and
+ * with rounding according to the context settings.
+ *
+ * <p>Note that if the sequence of characters is already available
+ * within a character array, using this constructor is faster than
+ * converting the {@code char} array to string and using the
+ * {@code BigDecimal(String)} constructor .
+ *
+ * @param in {@code char} array that is the source of characters.
+ * @param offset first character in the array to inspect.
+ * @param len number of characters to consider..
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @throws NumberFormatException if {@code in} is not a valid
+ * representation of a {@code BigDecimal} or the defined subarray
+ * is not wholly within {@code in}.
+ * @since 1.5
+ */
+ public BigDecimal(char[] in, int offset, int len, MathContext mc) {
+ this(in, offset, len);
+ if (mc.precision > 0)
+ roundThis(mc);
+ }
+
+ /**
+ * Translates a character array representation of a
+ * {@code BigDecimal} into a {@code BigDecimal}, accepting the
+ * same sequence of characters as the {@link #BigDecimal(String)}
+ * constructor.
+ *
+ * <p>Note that if the sequence of characters is already available
+ * as a character array, using this constructor is faster than
+ * converting the {@code char} array to string and using the
+ * {@code BigDecimal(String)} constructor .
+ *
+ * @param in {@code char} array that is the source of characters.
+ * @throws NumberFormatException if {@code in} is not a valid
+ * representation of a {@code BigDecimal}.
+ * @since 1.5
+ */
+ public BigDecimal(char[] in) {
+ this(in, 0, in.length);
+ }
+
+ /**
+ * Translates a character array representation of a
+ * {@code BigDecimal} into a {@code BigDecimal}, accepting the
+ * same sequence of characters as the {@link #BigDecimal(String)}
+ * constructor and with rounding according to the context
+ * settings.
+ *
+ * <p>Note that if the sequence of characters is already available
+ * as a character array, using this constructor is faster than
+ * converting the {@code char} array to string and using the
+ * {@code BigDecimal(String)} constructor .
+ *
+ * @param in {@code char} array that is the source of characters.
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @throws NumberFormatException if {@code in} is not a valid
+ * representation of a {@code BigDecimal}.
+ * @since 1.5
+ */
+ public BigDecimal(char[] in, MathContext mc) {
+ this(in, 0, in.length, mc);
+ }
+
+ /**
+ * Translates the string representation of a {@code BigDecimal}
+ * into a {@code BigDecimal}. The string representation consists
+ * of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or
+ * {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of
+ * zero or more decimal digits ("the integer"), optionally
+ * followed by a fraction, optionally followed by an exponent.
+ *
+ * <p>The fraction consists of a decimal point followed by zero
+ * or more decimal digits. The string must contain at least one
+ * digit in either the integer or the fraction. The number formed
+ * by the sign, the integer and the fraction is referred to as the
+ * <i>significand</i>.
+ *
+ * <p>The exponent consists of the character {@code 'e'}
+ * (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>)
+ * followed by one or more decimal digits. The value of the
+ * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
+ * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
+ *
+ * <p>More formally, the strings this constructor accepts are
+ * described by the following grammar:
+ * <blockquote>
+ * <dl>
+ * <dt><i>BigDecimalString:</i>
+ * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
+ * <p>
+ * <dt><i>Sign:</i>
+ * <dd>{@code +}
+ * <dd>{@code -}
+ * <p>
+ * <dt><i>Significand:</i>
+ * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
+ * <dd>{@code .} <i>FractionPart</i>
+ * <dd><i>IntegerPart</i>
+ * <p>
+ * <dt><i>IntegerPart:
+ * <dd>Digits</i>
+ * <p>
+ * <dt><i>FractionPart:
+ * <dd>Digits</i>
+ * <p>
+ * <dt><i>Exponent:
+ * <dd>ExponentIndicator SignedInteger</i>
+ * <p>
+ * <dt><i>ExponentIndicator:</i>
+ * <dd>{@code e}
+ * <dd>{@code E}
+ * <p>
+ * <dt><i>SignedInteger:
+ * <dd>Sign<sub>opt</sub> Digits</i>
+ * <p>
+ * <dt><i>Digits:
+ * <dd>Digit
+ * <dd>Digits Digit</i>
+ * <p>
+ * <dt><i>Digit:</i>
+ * <dd>any character for which {@link Character#isDigit}
+ * returns {@code true}, including 0, 1, 2 ...
+ * </dl>
+ * </blockquote>
+ *
+ * <p>The scale of the returned {@code BigDecimal} will be the
+ * number of digits in the fraction, or zero if the string
+ * contains no decimal point, subject to adjustment for any
+ * exponent; if the string contains an exponent, the exponent is
+ * subtracted from the scale. The value of the resulting scale
+ * must lie between {@code Integer.MIN_VALUE} and
+ * {@code Integer.MAX_VALUE}, inclusive.
+ *
+ * <p>The character-to-digit mapping is provided by {@link
+ * java.lang.Character#digit} set to convert to radix 10. The
+ * String may not contain any extraneous characters (whitespace,
+ * for example).
+ *
+ * <p><b>Examples:</b><br>
+ * The value of the returned {@code BigDecimal} is equal to
+ * <i>significand</i> × 10<sup> <i>exponent</i></sup>.
+ * For each string on the left, the resulting representation
+ * [{@code BigInteger}, {@code scale}] is shown on the right.
+ * <pre>
+ * "0" [0,0]
+ * "0.00" [0,2]
+ * "123" [123,0]
+ * "-123" [-123,0]
+ * "1.23E3" [123,-1]
+ * "1.23E+3" [123,-1]
+ * "12.3E+7" [123,-6]
+ * "12.0" [120,1]
+ * "12.3" [123,1]
+ * "0.00123" [123,5]
+ * "-1.23E-12" [-123,14]
+ * "1234.5E-4" [12345,5]
+ * "0E+7" [0,-7]
+ * "-0" [0,0]
+ * </pre>
+ *
+ * <p>Note: For values other than {@code float} and
+ * {@code double} NaN and ±Infinity, this constructor is
+ * compatible with the values returned by {@link Float#toString}
+ * and {@link Double#toString}. This is generally the preferred
+ * way to convert a {@code float} or {@code double} into a
+ * BigDecimal, as it doesn't suffer from the unpredictability of
+ * the {@link #BigDecimal(double)} constructor.
+ *
+ * @param val String representation of {@code BigDecimal}.
+ *
+ * @throws NumberFormatException if {@code val} is not a valid
+ * representation of a {@code BigDecimal}.
+ */
+ public BigDecimal(String val) {
+ this(val.toCharArray(), 0, val.length());
+ }
+
+ /**
+ * Translates the string representation of a {@code BigDecimal}
+ * into a {@code BigDecimal}, accepting the same strings as the
+ * {@link #BigDecimal(String)} constructor, with rounding
+ * according to the context settings.
+ *
+ * @param val string representation of a {@code BigDecimal}.
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @throws NumberFormatException if {@code val} is not a valid
+ * representation of a BigDecimal.
+ * @since 1.5
+ */
+ public BigDecimal(String val, MathContext mc) {
+ this(val.toCharArray(), 0, val.length());
+ if (mc.precision > 0)
+ roundThis(mc);
+ }
+
+ /**
+ * Translates a {@code double} into a {@code BigDecimal} which
+ * is the exact decimal representation of the {@code double}'s
+ * binary floating-point value. The scale of the returned
+ * {@code BigDecimal} is the smallest value such that
+ * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
+ * <p>
+ * <b>Notes:</b>
+ * <ol>
+ * <li>
+ * The results of this constructor can be somewhat unpredictable.
+ * One might assume that writing {@code new BigDecimal(0.1)} in
+ * Java creates a {@code BigDecimal} which is exactly equal to
+ * 0.1 (an unscaled value of 1, with a scale of 1), but it is
+ * actually equal to
+ * 0.1000000000000000055511151231257827021181583404541015625.
+ * This is because 0.1 cannot be represented exactly as a
+ * {@code double} (or, for that matter, as a binary fraction of
+ * any finite length). Thus, the value that is being passed
+ * <i>in</i> to the constructor is not exactly equal to 0.1,
+ * appearances notwithstanding.
+ *
+ * <li>
+ * The {@code String} constructor, on the other hand, is
+ * perfectly predictable: writing {@code new BigDecimal("0.1")}
+ * creates a {@code BigDecimal} which is <i>exactly</i> equal to
+ * 0.1, as one would expect. Therefore, it is generally
+ * recommended that the {@linkplain #BigDecimal(String)
+ * <tt>String</tt> constructor} be used in preference to this one.
+ *
+ * <li>
+ * When a {@code double} must be used as a source for a
+ * {@code BigDecimal}, note that this constructor provides an
+ * exact conversion; it does not give the same result as
+ * converting the {@code double} to a {@code String} using the
+ * {@link Double#toString(double)} method and then using the
+ * {@link #BigDecimal(String)} constructor. To get that result,
+ * use the {@code static} {@link #valueOf(double)} method.
+ * </ol>
+ *
+ * @param val {@code double} value to be converted to
+ * {@code BigDecimal}.
+ * @throws NumberFormatException if {@code val} is infinite or NaN.
+ */
+ public BigDecimal(double val) {
+ if (Double.isInfinite(val) || Double.isNaN(val))
+ throw new NumberFormatException("Infinite or NaN");
+
+ // Translate the double into sign, exponent and significand, according
+ // to the formulae in JLS, Section 20.10.22.
+ long valBits = Double.doubleToLongBits(val);
+ int sign = ((valBits >> 63)==0 ? 1 : -1);
+ int exponent = (int) ((valBits >> 52) & 0x7ffL);
+ long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
+ : (valBits & ((1L<<52) - 1)) | (1L<<52));
+ exponent -= 1075;
+ // At this point, val == sign * significand * 2**exponent.
+
+ /*
+ * Special case zero to supress nonterminating normalization
+ * and bogus scale calculation.
+ */
+ if (significand == 0) {
+ intVal = BigInteger.ZERO;
+ intCompact = 0;
+ precision = 1;
+ return;
+ }
+
+ // Normalize
+ while((significand & 1) == 0) { // i.e., significand is even
+ significand >>= 1;
+ exponent++;
+ }
+
+ // Calculate intVal and scale
+ intVal = BigInteger.valueOf(sign*significand);
+ if (exponent < 0) {
+ intVal = intVal.multiply(BigInteger.valueOf(5).pow(-exponent));
+ scale = -exponent;
+ } else if (exponent > 0) {
+ intVal = intVal.multiply(BigInteger.valueOf(2).pow(exponent));
+ }
+ if (intVal.bitLength() <= MAX_BIGINT_BITS) {
+ intCompact = intVal.longValue();
+ }
+ }
+
+ /**
+ * Translates a {@code double} into a {@code BigDecimal}, with
+ * rounding according to the context settings. The scale of the
+ * {@code BigDecimal} is the smallest value such that
+ * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
+ *
+ * <p>The results of this constructor can be somewhat unpredictable
+ * and its use is generally not recommended; see the notes under
+ * the {@link #BigDecimal(double)} constructor.
+ *
+ * @param val {@code double} value to be converted to
+ * {@code BigDecimal}.
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * RoundingMode is UNNECESSARY.
+ * @throws NumberFormatException if {@code val} is infinite or NaN.
+ * @since 1.5
+ */
+ public BigDecimal(double val, MathContext mc) {
+ this(val);
+ if (mc.precision > 0)
+ roundThis(mc);
+ }
+
+ /**
+ * Translates a {@code BigInteger} into a {@code BigDecimal}.
+ * The scale of the {@code BigDecimal} is zero.
+ *
+ * @param val {@code BigInteger} value to be converted to
+ * {@code BigDecimal}.
+ */
+ public BigDecimal(BigInteger val) {
+ intVal = val;
+ if (val.bitLength() <= MAX_BIGINT_BITS) {
+ intCompact = val.longValue();
+ }
+ }
+
+ /**
+ * Translates a {@code BigInteger} into a {@code BigDecimal}
+ * rounding according to the context settings. The scale of the
+ * {@code BigDecimal} is zero.
+ *
+ * @param val {@code BigInteger} value to be converted to
+ * {@code BigDecimal}.
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @since 1.5
+ */
+ public BigDecimal(BigInteger val, MathContext mc) {
+ intVal = val;
+ if (mc.precision > 0)
+ roundThis(mc);
+ }
+
+ /**
+ * Translates a {@code BigInteger} unscaled value and an
+ * {@code int} scale into a {@code BigDecimal}. The value of
+ * the {@code BigDecimal} is
+ * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
+ *
+ * @param unscaledVal unscaled value of the {@code BigDecimal}.
+ * @param scale scale of the {@code BigDecimal}.
+ */
+ public BigDecimal(BigInteger unscaledVal, int scale) {
+ // Negative scales are now allowed
+ intVal = unscaledVal;
+ this.scale = scale;
+ if (unscaledVal.bitLength() <= MAX_BIGINT_BITS) {
+ intCompact = unscaledVal.longValue();
+ }
+ }
+
+ /**
+ * Translates a {@code BigInteger} unscaled value and an
+ * {@code int} scale into a {@code BigDecimal}, with rounding
+ * according to the context settings. The value of the
+ * {@code BigDecimal} is <tt>(unscaledVal ×
+ * 10<sup>-scale</sup>)</tt>, rounded according to the
+ * {@code precision} and rounding mode settings.
+ *
+ * @param unscaledVal unscaled value of the {@code BigDecimal}.
+ * @param scale scale of the {@code BigDecimal}.
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @since 1.5
+ */
+ public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
+ intVal = unscaledVal;
+ this.scale = scale;
+ if (mc.precision > 0)
+ roundThis(mc);
+ }
+
+ /**
+ * Translates an {@code int} into a {@code BigDecimal}. The
+ * scale of the {@code BigDecimal} is zero.
+ *
+ * @param val {@code int} value to be converted to
+ * {@code BigDecimal}.
+ * @since 1.5
+ */
+ public BigDecimal(int val) {
+ intCompact = val;
+ }
+
+ /**
+ * Translates an {@code int} into a {@code BigDecimal}, with
+ * rounding according to the context settings. The scale of the
+ * {@code BigDecimal}, before any rounding, is zero.
+ *
+ * @param val {@code int} value to be converted to {@code BigDecimal}.
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @since 1.5
+ */
+ public BigDecimal(int val, MathContext mc) {
+ intCompact = val;
+ if (mc.precision > 0)
+ roundThis(mc);
+ }
+
+ /**
+ * Translates a {@code long} into a {@code BigDecimal}. The
+ * scale of the {@code BigDecimal} is zero.
+ *
+ * @param val {@code long} value to be converted to {@code BigDecimal}.
+ * @since 1.5
+ */
+ public BigDecimal(long val) {
+ if (compactLong(val))
+ intCompact = val;
+ else
+ intVal = BigInteger.valueOf(val);
+ }
+
+ /**
+ * Translates a {@code long} into a {@code BigDecimal}, with
+ * rounding according to the context settings. The scale of the
+ * {@code BigDecimal}, before any rounding, is zero.
+ *
+ * @param val {@code long} value to be converted to {@code BigDecimal}.
+ * @param mc the context to use.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @since 1.5
+ */
+ public BigDecimal(long val, MathContext mc) {
+ if (compactLong(val))
+ intCompact = val;
+ else
+ intVal = BigInteger.valueOf(val);
+ if (mc.precision > 0)
+ roundThis(mc);
+ }
+
+ /**
+ * Trusted internal constructor
+ */
+ private BigDecimal(long val, int scale) {
+ this.intCompact = val;
+ this.scale = scale;
+ }
+
+ /**
+ * Trusted internal constructor
+ */
+ private BigDecimal(BigInteger intVal, long val, int scale) {
+ this.intVal = intVal;
+ this.intCompact = val;
+ this.scale = scale;
+ }
+
+ // Static Factory Methods
+
+ /**
+ * Translates a {@code long} unscaled value and an
+ * {@code int} scale into a {@code BigDecimal}. This
+ * {@literal "static factory method"} is provided in preference to
+ * a ({@code long}, {@code int}) constructor because it
+ * allows for reuse of frequently used {@code BigDecimal} values..
+ *
+ * @param unscaledVal unscaled value of the {@code BigDecimal}.
+ * @param scale scale of the {@code BigDecimal}.
+ * @return a {@code BigDecimal} whose value is
+ * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
+ */
+ public static BigDecimal valueOf(long unscaledVal, int scale) {
+ if (scale == 0 && unscaledVal >= 0 && unscaledVal <= 10) {
+ return zeroThroughTen[(int)unscaledVal];
+ }
+ if (compactLong(unscaledVal))
+ return new BigDecimal(unscaledVal, scale);
+ return new BigDecimal(BigInteger.valueOf(unscaledVal), scale);
+ }
+
+ /**
+ * Translates a {@code long} value into a {@code BigDecimal}
+ * with a scale of zero. This {@literal "static factory method"}
+ * is provided in preference to a ({@code long}) constructor
+ * because it allows for reuse of frequently used
+ * {@code BigDecimal} values.
+ *
+ * @param val value of the {@code BigDecimal}.
+ * @return a {@code BigDecimal} whose value is {@code val}.
+ */
+ public static BigDecimal valueOf(long val) {
+ return valueOf(val, 0);
+ }
+
+ /**
+ * Translates a {@code double} into a {@code BigDecimal}, using
+ * the {@code double}'s canonical string representation provided
+ * by the {@link Double#toString(double)} method.
+ *
+ * <p><b>Note:</b> This is generally the preferred way to convert
+ * a {@code double} (or {@code float}) into a
+ * {@code BigDecimal}, as the value returned is equal to that
+ * resulting from constructing a {@code BigDecimal} from the
+ * result of using {@link Double#toString(double)}.
+ *
+ * @param val {@code double} to convert to a {@code BigDecimal}.
+ * @return a {@code BigDecimal} whose value is equal to or approximately
+ * equal to the value of {@code val}.
+ * @throws NumberFormatException if {@code val} is infinite or NaN.
+ * @since 1.5
+ */
+ public static BigDecimal valueOf(double val) {
+ // Reminder: a zero double returns '0.0', so we cannot fastpath
+ // to use the constant ZERO. This might be important enough to
+ // justify a factory approach, a cache, or a few private
+ // constants, later.
+ return new BigDecimal(Double.toString(val));
+ }
+
+ // Arithmetic Operations
+ /**
+ * Returns a {@code BigDecimal} whose value is {@code (this +
+ * augend)}, and whose scale is {@code max(this.scale(),
+ * augend.scale())}.
+ *
+ * @param augend value to be added to this {@code BigDecimal}.
+ * @return {@code this + augend}
+ */
+ public BigDecimal add(BigDecimal augend) {
+ BigDecimal arg[] = {this, augend};
+ matchScale(arg);
+
+ long x = arg[0].intCompact;
+ long y = arg[1].intCompact;
+
+ // Might be able to do a more clever check incorporating the
+ // inflated check into the overflow computation.
+ if (x != INFLATED && y != INFLATED) {
+ long sum = x + y;
+ /*
+ * If the sum is not an overflowed value, continue to use
+ * the compact representation. if either of x or y is
+ * INFLATED, the sum should also be regarded as an
+ * overflow. See "Hacker's Delight" section 2-12 for
+ * explanation of the overflow test.
+ */
+ if ( (((sum ^ x) & (sum ^ y)) >> 63) == 0L ) // not overflowed
+ return BigDecimal.valueOf(sum, arg[0].scale);
+ }
+ return new BigDecimal(arg[0].inflate().intVal.add(arg[1].inflate().intVal), arg[0].scale);
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
+ * with rounding according to the context settings.
+ *
+ * If either number is zero and the precision setting is nonzero then
+ * the other number, rounded if necessary, is used as the result.
+ *
+ * @param augend value to be added to this {@code BigDecimal}.
+ * @param mc the context to use.
+ * @return {@code this + augend}, rounded as necessary.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @since 1.5
+ */
+ public BigDecimal add(BigDecimal augend, MathContext mc) {
+ if (mc.precision == 0)
+ return add(augend);
+ BigDecimal lhs = this;
+
+ // Could optimize if values are compact
+ this.inflate();
+ augend.inflate();
+
+ // If either number is zero then the other number, rounded and
+ // scaled if necessary, is used as the result.
+ {
+ boolean lhsIsZero = lhs.signum() == 0;
+ boolean augendIsZero = augend.signum() == 0;
+
+ if (lhsIsZero || augendIsZero) {
+ int preferredScale = Math.max(lhs.scale(), augend.scale());
+ BigDecimal result;
+
+ // Could use a factory for zero instead of a new object
+ if (lhsIsZero && augendIsZero)
+ return new BigDecimal(BigInteger.ZERO, 0, preferredScale);
+
+
+ result = lhsIsZero ? augend.doRound(mc) : lhs.doRound(mc);
+
+ if (result.scale() == preferredScale)
+ return result;
+ else if (result.scale() > preferredScale)
+ return new BigDecimal(result.intVal, result.intCompact, result.scale).
+ stripZerosToMatchScale(preferredScale);
+ else { // result.scale < preferredScale
+ int precisionDiff = mc.precision - result.precision();
+ int scaleDiff = preferredScale - result.scale();
+
+ if (precisionDiff >= scaleDiff)
+ return result.setScale(preferredScale); // can achieve target scale
+ else
+ return result.setScale(result.scale() + precisionDiff);
+ }
+ }
+ }
+
+ long padding = (long)lhs.scale - augend.scale;
+ if (padding != 0) { // scales differ; alignment needed
+ BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
+ matchScale(arg);
+ lhs = arg[0];
+ augend = arg[1];
+ }
+
+ return new BigDecimal(lhs.inflate().intVal.add(augend.inflate().intVal),
+ lhs.scale).doRound(mc);
+ }
+
+ /**
+ * Returns an array of length two, the sum of whose entries is
+ * equal to the rounded sum of the {@code BigDecimal} arguments.
+ *
+ * <p>If the digit positions of the arguments have a sufficient
+ * gap between them, the value smaller in magnitude can be
+ * condensed into a {@literal "sticky bit"} and the end result will
+ * round the same way <em>if</em> the precision of the final
+ * result does not include the high order digit of the small
+ * magnitude operand.
+ *
+ * <p>Note that while strictly speaking this is an optimization,
+ * it makes a much wider range of additions practical.
+ *
+ * <p>This corresponds to a pre-shift operation in a fixed
+ * precision floating-point adder; this method is complicated by
+ * variable precision of the result as determined by the
+ * MathContext. A more nuanced operation could implement a
+ * {@literal "right shift"} on the smaller magnitude operand so
+ * that the number of digits of the smaller operand could be
+ * reduced even though the significands partially overlapped.
+ */
+ private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
+ long padding, MathContext mc) {
+ assert padding != 0;
+ BigDecimal big;
+ BigDecimal small;
+
+ if (padding < 0) { // lhs is big; augend is small
+ big = lhs;
+ small = augend;
+ } else { // lhs is small; augend is big
+ big = augend;
+ small = lhs;
+ }
+
+ /*
+ * This is the estimated scale of an ulp of the result; it
+ * assumes that the result doesn't have a carry-out on a true
+ * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
+ * on borrowing (e.g. 100 - 1.2 => 98.8)
+ */
+ long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
+
+ /*
+ * The low-order digit position of big is big.scale(). This
+ * is true regardless of whether big has a positive or
+ * negative scale. The high-order digit position of small is
+ * small.scale - (small.precision() - 1). To do the full
+ * condensation, the digit positions of big and small must be
+ * disjoint *and* the digit positions of small should not be
+ * directly visible in the result.
+ */
+ long smallHighDigitPos = (long)small.scale - small.precision() + 1;
+ if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
+ smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
+ small = BigDecimal.valueOf(small.signum(),
+ this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
+ }
+
+ // Since addition is symmetric, preserving input order in
+ // returned operands doesn't matter
+ BigDecimal[] result = {big, small};
+ return result;
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is {@code (this -
+ * subtrahend)}, and whose scale is {@code max(this.scale(),
+ * subtrahend.scale())}.
+ *
+ * @param subtrahend value to be subtracted from this {@code BigDecimal}.
+ * @return {@code this - subtrahend}
+ */
+ public BigDecimal subtract(BigDecimal subtrahend) {
+ BigDecimal arg[] = {this, subtrahend};
+ matchScale(arg);
+
+ long x = arg[0].intCompact;
+ long y = arg[1].intCompact;
+
+ // Might be able to do a more clever check incorporating the
+ // inflated check into the overflow computation.
+ if (x != INFLATED && y != INFLATED) {
+ long difference = x - y;
+ /*
+ * If the difference is not an overflowed value, continue
+ * to use the compact representation. if either of x or y
+ * is INFLATED, the difference should also be regarded as
+ * an overflow. See "Hacker's Delight" section 2-12 for
+ * explanation of the overflow test.
+ */
+ if ( ((x ^ y) & (difference ^ x) ) >> 63 == 0L ) // not overflowed
+ return BigDecimal.valueOf(difference, arg[0].scale);
+ }
+ return new BigDecimal(arg[0].inflate().intVal.subtract(arg[1].inflate().intVal),
+ arg[0].scale);
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
+ * with rounding according to the context settings.
+ *
+ * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
+ * result. If this is zero then the result is {@code subtrahend.negate(mc)}.
+ *
+ * @param subtrahend value to be subtracted from this {@code BigDecimal}.
+ * @param mc the context to use.
+ * @return {@code this - subtrahend}, rounded as necessary.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @since 1.5
+ */
+ public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
+ if (mc.precision == 0)
+ return subtract(subtrahend);
+ // share the special rounding code in add()
+ this.inflate();
+ subtrahend.inflate();
+ BigDecimal rhs = new BigDecimal(subtrahend.intVal.negate(), subtrahend.scale);
+ rhs.precision = subtrahend.precision;
+ return add(rhs, mc);
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is <tt>(this ×
+ * multiplicand)</tt>, and whose scale is {@code (this.scale() +
+ * multiplicand.scale())}.
+ *
+ * @param multiplicand value to be multiplied by this {@code BigDecimal}.
+ * @return {@code this * multiplicand}
+ */
+ public BigDecimal multiply(BigDecimal multiplicand) {
+ long x = this.intCompact;
+ long y = multiplicand.intCompact;
+ int productScale = checkScale((long)scale+multiplicand.scale);
+
+ // Might be able to do a more clever check incorporating the
+ // inflated check into the overflow computation.
+ if (x != INFLATED && y != INFLATED) {
+ /*
+ * If the product is not an overflowed value, continue
+ * to use the compact representation. if either of x or y
+ * is INFLATED, the product should also be regarded as
+ * an overflow. See "Hacker's Delight" section 2-12 for
+ * explanation of the overflow test.
+ */
+ long product = x * y;
+ if ( !(y != 0L && product/y != x) ) // not overflowed
+ return BigDecimal.valueOf(product, productScale);
+ }
+
+ BigDecimal result = new BigDecimal(this.inflate().intVal.multiply(multiplicand.inflate().intVal), productScale);
+ return result;
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is <tt>(this ×
+ * multiplicand)</tt>, with rounding according to the context settings.
+ *
+ * @param multiplicand value to be multiplied by this {@code BigDecimal}.
+ * @param mc the context to use.
+ * @return {@code this * multiplicand}, rounded as necessary.
+ * @throws ArithmeticException if the result is inexact but the
+ * rounding mode is {@code UNNECESSARY}.
+ * @since 1.5
+ */
+ public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
+ if (mc.precision == 0)
+ return multiply(multiplicand);
+ BigDecimal lhs = this;
+ return lhs.inflate().multiply(multiplicand.inflate()).doRound(mc);
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is {@code (this /
+ * divisor)}, and whose scale is as specified. If rounding must
+ * be performed to generate a result with the specified scale, the
+ * specified rounding mode is applied.
+ *
+ * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
+ * should be used in preference to this legacy method.
+ *
+ * @param divisor value by which this {@code BigDecimal} is to be divided.
+ * @param scale scale of the {@code BigDecimal} quotient to be returned.
+ * @param roundingMode rounding mode to apply.
+ * @return {@code this / divisor}
+ * @throws ArithmeticException if {@code divisor} is zero,
+ * {@code roundingMode==ROUND_UNNECESSARY} and
+ * the specified scale is insufficient to represent the result
+ * of the division exactly.
+ * @throws IllegalArgumentException if {@code roundingMode} does not
+ * represent a valid rounding mode.
+ * @see #ROUND_UP
+ * @see #ROUND_DOWN
+ * @see #ROUND_CEILING
+ * @see #ROUND_FLOOR
+ * @see #ROUND_HALF_UP
+ * @see #ROUND_HALF_DOWN
+ * @see #ROUND_HALF_EVEN
+ * @see #ROUND_UNNECESSARY
+ */
+ public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
+ /*
+ * IMPLEMENTATION NOTE: This method *must* return a new object
+ * since dropDigits uses divide to generate a value whose
+ * scale is then modified.
+ */
+ if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
+ throw new IllegalArgumentException("Invalid rounding mode");
+ /*
+ * Rescale dividend or divisor (whichever can be "upscaled" to
+ * produce correctly scaled quotient).
+ * Take care to detect out-of-range scales
+ */
+ BigDecimal dividend;
+ if (checkScale((long)scale + divisor.scale) >= this.scale) {
+ dividend = this.setScale(scale + divisor.scale);
+ } else {
+ dividend = this;
+ divisor = divisor.setScale(checkScale((long)this.scale - scale));
+ }
+
+ boolean compact = dividend.intCompact != INFLATED && divisor.intCompact != INFLATED;
+ long div = INFLATED;
+ long rem = INFLATED;;
+ BigInteger q=null, r=null;
+
+ if (compact) {
+ div = dividend.intCompact / divisor.intCompact;
+ rem = dividend.intCompact % divisor.intCompact;
+ } else {
+ // Do the division and return result if it's exact.
+ BigInteger i[] = dividend.inflate().intVal.divideAndRemainder(divisor.inflate().intVal);
+ q = i[0];
+ r = i[1];
+ }
+
+ // Check for exact result
+ if (compact) {
+ if (rem == 0)
+ return new BigDecimal(div, scale);
+ } else {
+ if (r.signum() == 0)
+ return new BigDecimal(q, scale);
+ }
+
+ if (roundingMode == ROUND_UNNECESSARY) // Rounding prohibited
+ throw new ArithmeticException("Rounding necessary");
+
+ /* Round as appropriate */
+ int signum = dividend.signum() * divisor.signum(); // Sign of result
+ boolean increment;
+ if (roundingMode == ROUND_UP) { // Away from zero
+ increment = true;
+ } else if (roundingMode == ROUND_DOWN) { // Towards zero
+ increment = false;
+ } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
+ increment = (signum > 0);
+ } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity
+ increment = (signum < 0);
+ } else { // Remaining modes based on nearest-neighbor determination
+ int cmpFracHalf;
+ if (compact) {
+ cmpFracHalf = longCompareTo(Math.abs(2*rem), Math.abs(divisor.intCompact));
+ } else {
+ // add(r) here is faster than multiply(2) or shiftLeft(1)
+ cmpFracHalf= r.add(r).abs().compareTo(divisor.intVal.abs());
+ }
+ if (cmpFracHalf < 0) { // We're closer to higher digit
+ increment = false;
+ } else if (cmpFracHalf > 0) { // We're closer to lower digit
+ increment = true;
+ } else { // We're dead-center
+ if (roundingMode == ROUND_HALF_UP)
+ increment = true;
+ else if (roundingMode == ROUND_HALF_DOWN)
+ increment = false;
+ else { // roundingMode == ROUND_HALF_EVEN
+ if (compact)
+ increment = (div & 1L) != 0L;
+ else
+ increment = q.testBit(0); // true iff q is odd
+ }
+ }
+ }
+
+ if (compact) {
+ if (increment)
+ div += signum; // guaranteed not to overflow
+ return new BigDecimal(div, scale);
+ } else {
+ return (increment
+ ? new BigDecimal(q.add(BigInteger.valueOf(signum)), scale)
+ : new BigDecimal(q, scale));
+ }
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is {@code (this /
+ * divisor)}, and whose scale is as specified. If rounding must
+ * be performed to generate a result with the specified scale, the
+ * specified rounding mode is applied.
+ *
+ * @param divisor value by which this {@code BigDecimal} is to be divided.
+ * @param scale scale of the {@code BigDecimal} quotient to be returned.
+ * @param roundingMode rounding mode to apply.
+ * @return {@code this / divisor}
+ * @throws ArithmeticException if {@code divisor} is zero,
+ * {@code roundingMode==RoundingMode.UNNECESSARY} and
+ * the specified scale is insufficient to represent the result
+ * of the division exactly.
+ * @since 1.5
+ */
+ public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
+ return divide(divisor, scale, roundingMode.oldMode);
+ }
+
+ /**
+ * Returns a {@code BigDecimal} whose value is {@code (this /
+ * divisor)}, and whose scale is {@code this.scale()}. If
+ * rounding must be performed to generate a result with the given
+ * scale, the specified rounding mode is applied.
+ *
+ * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
+ * should be used in preference to this legacy method.
+ *
+ * @param divisor value by which this {@code BigDecimal} is to be divided.
+ * @param roundingMode rounding mode to apply.
+ * @return {@code this / divisor}
+ * @throws ArithmeticException if {@code divisor==0}, or
+ * {@code roundingMode==ROUND_UNNECESSARY} and
+ * {@code this.scale()} is insufficient to represent the result
+ * of the division exactly.
+ * @throws IllegalArgumentException if {@code roundingMode} does not
+ * represent a va...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-17 12:16:03
|
Revision: 3277
http://jnode.svn.sourceforge.net/jnode/?rev=3277&view=rev
Author: lsantha
Date: 2007-06-17 05:15:58 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Removed Paths:
-------------
trunk/core/src/classpath/java/java/math/
trunk/core/src/classpath/java/java/util/FormatFlagsConversionMismatchException.java
trunk/core/src/classpath/java/java/util/Formattable.java
trunk/core/src/classpath/java/java/util/FormattableFlags.java
trunk/core/src/classpath/java/java/util/Formatter.java
trunk/core/src/classpath/java/java/util/FormatterClosedException.java
Deleted: trunk/core/src/classpath/java/java/util/FormatFlagsConversionMismatchException.java
===================================================================
--- trunk/core/src/classpath/java/java/util/FormatFlagsConversionMismatchException.java 2007-06-17 10:56:12 UTC (rev 3276)
+++ trunk/core/src/classpath/java/java/util/FormatFlagsConversionMismatchException.java 2007-06-17 12:15:58 UTC (rev 3277)
@@ -1,111 +0,0 @@
-/* FormatFlagsConversionMismatchException.java
- Copyright (C) 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package java.util;
-
-/**
- * Thrown when the flags supplied to the {@link Formatter#format()}
- * method of a {@link Formatter} contains a flag that does not match
- * the conversion character specified for it.
- *
- * @author Tom Tromey (tr...@re...)
- * @author Andrew John Hughes (gnu...@me...)
- * @since 1.5
- */
-public class FormatFlagsConversionMismatchException
- extends IllegalFormatException
-{
- private static final long serialVersionUID = 19120414L;
-
- /**
- * The mismatching flag.
- *
- * @serial the mismatching flag.
- */
- // Note: name fixed by serialization.
- private String f;
-
- /**
- * The conversion character which doesn't match the
- * appropriate flag.
- *
- * @serial the conversion character which doesn't match its flag.
- */
- // Note: name fixed by serialization.
- private char c;
-
- /**
- * Constructs a new <code>FormatFlagsConversionMismatchException</code>
- * which specifies that the flag, <code>f</code>, does
- * not match its appropriate conversion character, <code>c</code>.
- *
- * @param f the mismatching flag.
- * @param c the conversion character which doesn't match its flag.
- * @throws NullPointerException if <code>f</code> is null.
- */
- public FormatFlagsConversionMismatchException(String f, char c)
- {
- super("Invalid flag " + f + " for conversion " + c);
- if (f == null)
- throw new
- NullPointerException("Null flag value passed to constructor.");
- this.f = f;
- this.c = c;
- }
-
- /**
- * Returns the conversion character which doesn't
- * match the flag.
- *
- * @return the conversion character.
- */
- public char getConversion()
- {
- return c;
- }
-
- /**
- * Returns the mismatching flag.
- *
- * @return the mismatching flag.
- */
- public String getFlags()
- {
- return f;
- }
-}
Deleted: trunk/core/src/classpath/java/java/util/Formattable.java
===================================================================
--- trunk/core/src/classpath/java/java/util/Formattable.java 2007-06-17 10:56:12 UTC (rev 3276)
+++ trunk/core/src/classpath/java/java/util/Formattable.java 2007-06-17 12:15:58 UTC (rev 3277)
@@ -1,92 +0,0 @@
-/* Formattable.java -- Objects which can be passed to a Formatter
- Copyright (C) 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package java.util;
-
-/**
- * <p>
- * The <code>Formattable</code> interface is used to provide customised
- * formatting to arbitrary objects via the {@link Formatter}. The
- * {@link #formatTo} method is called for <code>Formattable</code>
- * objects used with the 's' conversion operator, allowing the object
- * to provide its own formatting of its internal data.
- * </p>
- * <p>
- * Thread safety is left up to the implementing class. Thus,
- * {@link Formattable} objects are not guaranteed to be thread-safe,
- * and users should make their own provisions for multiple thread access.
- * </p>
- *
- * @author Tom Tromey (tr...@re...)
- * @author Andrew John Hughes (gnu...@me...)
- * @since 1.5
- */
-public interface Formattable
-{
-
- /**
- * Formats the object using the supplied formatter to the specification
- * provided by the given flags, width and precision.
- *
- * @param formatter the formatter to use for formatting the object.
- * The formatter gives access to the output stream
- * and locale via {@link Formatter#out()} and
- * {@link Formatter#locale()} respectively.
- * @param flags a bit mask constructed from the flags in the
- * {@link FormattableFlags} class. When no flags
- * are set, the implementing class should use its
- * defaults.
- * @param width the minimum number of characters to include.
- * A value of -1 indicates no minimum. The remaining
- * space is padded with ' ' either on the left
- * (the default) or right (if left justification is
- * specified by the flags).
- * @param precision the maximum number of characters to include.
- * A value of -1 indicates no maximum. This value
- * is applied prior to the minimum (the width). Thus,
- * a value may meet the minimum width initially, but
- * not when the width value is applied, due to
- * characters being removed by the precision value.
- * @throws IllegalFormatException if there is a problem with
- * the syntax of the format
- * specification or a mismatch
- * between it and the arguments.
- */
- public void formatTo(Formatter formatter, int flags, int width,
- int precision);
-}
Deleted: trunk/core/src/classpath/java/java/util/FormattableFlags.java
===================================================================
--- trunk/core/src/classpath/java/java/util/FormattableFlags.java 2007-06-17 10:56:12 UTC (rev 3276)
+++ trunk/core/src/classpath/java/java/util/FormattableFlags.java 2007-06-17 12:15:58 UTC (rev 3277)
@@ -1,123 +0,0 @@
-/* FormattableFlags.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package java.util;
-
-/**
- * This class contains a set of flags used
- * by the {@link Formattable#formatTo()} method.
- * They are used to modify the output of the
- * {@link Formattable}. The interpretation and
- * validation of the flags is left to the
- * particular {@link Formattable}.
- *
- * @author Tom Tromey (tr...@re...)
- * @author Andrew John Hughes (gnu...@me...)
- * @since 1.5
- */
-public class FormattableFlags
-{
-
- /**
- * Requires the output to be left-justified. Any spaces
- * required to meet the specified width will be added to
- * the right of the output. The default output is
- * right-justified, where spaces are added to the left.
- * The output is as for the format specifier
- * '-' ('\u002d').
- */
- public static final int LEFT_JUSTIFY = 1;
-
- /**
- * Requires the output to be in uppercase. The output
- * should be the same as the result from calling
- * {@link String#toUpperCase(java.util.Locale)} with
- * the formatting locale. The output is as for the
- * format specifier '^' ('\u005e').
- */
- public static final int UPPERCASE = 2;
-
- /**
- * Requires the use of an alternate form, as specified
- * in the documentation of {@link Formattable}.
- * The output is as for the format specifier
- * '#' ('\u0023').
- */
- public static final int ALTERNATE = 4;
-
- // Used internally by Formatter.
- // Changes here must be reflected in the FLAGS string there.
-
- /**
- * Requires the output to always include a '+' sign.
- * The output is as for the format specifier '+'.
- */
- static final int PLUS = 8;
-
- /**
- * Requires the output to include a leading space on
- * positive value. The output is as for the format
- * specifier ' '.
- */
- static final int SPACE = 16;
-
- /**
- * Requires the output to be zero-padded. The output
- * is as for the format specifier '0'.
- */
- static final int ZERO = 32;
-
- /**
- * Requires the output to include locale-specific
- * grouping operators. The output is as for the
- * format specifier ','.
- */
- static final int COMMA = 64;
-
- /**
- * Requires the output to include negative numbers
- * enclosed in parentheses. The output is as for
- * the format specifier '('.
- */
- static final int PAREN = 128;
-
- // Not instantiable.
- private FormattableFlags()
- {
- }
-}
Deleted: trunk/core/src/classpath/java/java/util/Formatter.java
===================================================================
--- trunk/core/src/classpath/java/java/util/Formatter.java 2007-06-17 10:56:12 UTC (rev 3276)
+++ trunk/core/src/classpath/java/java/util/Formatter.java 2007-06-17 12:15:58 UTC (rev 3277)
@@ -1,1496 +0,0 @@
-/* Formatter.java -- printf-style formatting
- Copyright (C) 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package java.util;
-
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.Flushable;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.math.BigInteger;
-import java.text.DateFormatSymbols;
-import java.text.DecimalFormatSymbols;
-
-import gnu.classpath.SystemProperties;
-
-/**
- * <p>
- * A Java formatter for <code>printf</code>-style format strings,
- * as seen in the C programming language. This differs from the
- * C interpretation of such strings by performing much stricter
- * checking of format specifications and their corresponding
- * arguments. While unknown conversions will be ignored in C,
- * and invalid conversions will only produce compiler warnings,
- * the Java version utilises a full range of run-time exceptions to
- * handle these cases. The Java version is also more customisable
- * by virtue of the provision of the {@link Formattable} interface,
- * which allows an arbitrary class to be formatted by the formatter.
- * </p>
- * <p>
- * The formatter is accessible by more convienient static methods.
- * For example, streams now have appropriate format methods
- * (the equivalent of <code>fprintf</code>) as do <code>String</code>
- * objects (the equivalent of <code>sprintf</code>).
- * </p>
- * <p>
- * <strong>Note</strong>: the formatter is not thread-safe. For
- * multi-threaded access, external synchronization should be provided.
- * </p>
- *
- * @author Tom Tromey (tr...@re...)
- * @author Andrew John Hughes (gnu...@me...)
- * @since 1.5
- */
-public final class Formatter
- implements Closeable, Flushable
-{
-
- /**
- * The output of the formatter.
- */
- private Appendable out;
-
- /**
- * The locale used by the formatter.
- */
- private Locale locale;
-
- /**
- * Whether or not the formatter is closed.
- */
- private boolean closed;
-
- /**
- * The last I/O exception thrown by the output stream.
- */
- private IOException ioException;
-
- // Some state used when actually formatting.
- /**
- * The format string.
- */
- private String format;
-
- /**
- * The current index into the string.
- */
- private int index;
-
- /**
- * The length of the format string.
- */
- private int length;
-
- /**
- * The formatting locale.
- */
- private Locale fmtLocale;
-
- // Note that we include '-' twice. The flags are ordered to
- // correspond to the values in FormattableFlags, and there is no
- // flag (in the sense of this field used when parsing) for
- // UPPERCASE; the second '-' serves as a placeholder.
- /**
- * A string used to index into the formattable flags.
- */
- private static final String FLAGS = "--#+ 0,(";
-
- /**
- * The system line separator.
- */
- private static final String lineSeparator
- = SystemProperties.getProperty("line.separator");
-
- /**
- * The type of numeric output format for a {@link BigDecimal}.
- */
- public enum BigDecimalLayoutForm
- {
- DECIMAL_FLOAT,
- SCIENTIFIC
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale and a {@link StringBuilder} as the output stream.
- */
- public Formatter()
- {
- this(null, Locale.getDefault());
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the specified
- * locale and a {@link StringBuilder} as the output stream.
- * If the locale is <code>null</code>, then no localization
- * is applied.
- *
- * @param loc the locale to use.
- */
- public Formatter(Locale loc)
- {
- this(null, loc);
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale and the specified output stream.
- *
- * @param app the output stream to use.
- */
- public Formatter(Appendable app)
- {
- this(app, Locale.getDefault());
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the specified
- * locale and the specified output stream. If the locale is
- * <code>null</code>, then no localization is applied.
- *
- * @param app the output stream to use.
- * @param loc the locale to use.
- */
- public Formatter(Appendable app, Locale loc)
- {
- this.out = app == null ? new StringBuilder() : app;
- this.locale = loc;
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale and character set, with the specified file as the
- * output stream.
- *
- * @param file the file to use for output.
- * @throws FileNotFoundException if the file does not exist
- * and can not be created.
- * @throws SecurityException if a security manager is present
- * and doesn't allow writing to the file.
- */
- public Formatter(File file)
- throws FileNotFoundException
- {
- this(new OutputStreamWriter(new FileOutputStream(file)));
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale, with the specified file as the output stream
- * and the supplied character set.
- *
- * @param file the file to use for output.
- * @param charset the character set to use for output.
- * @throws FileNotFoundException if the file does not exist
- * and can not be created.
- * @throws SecurityException if a security manager is present
- * and doesn't allow writing to the file.
- * @throws UnsupportedEncodingException if the supplied character
- * set is not supported.
- */
- public Formatter(File file, String charset)
- throws FileNotFoundException, UnsupportedEncodingException
- {
- this(file, charset, Locale.getDefault());
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the specified
- * file as the output stream with the supplied character set
- * and locale. If the locale is <code>null</code>, then no
- * localization is applied.
- *
- * @param file the file to use for output.
- * @param charset the character set to use for output.
- * @param loc the locale to use.
- * @throws FileNotFoundException if the file does not exist
- * and can not be created.
- * @throws SecurityException if a security manager is present
- * and doesn't allow writing to the file.
- * @throws UnsupportedEncodingException if the supplied character
- * set is not supported.
- */
- public Formatter(File file, String charset, Locale loc)
- throws FileNotFoundException, UnsupportedEncodingException
- {
- this(new OutputStreamWriter(new FileOutputStream(file), charset),
- loc);
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale and character set, with the specified output stream.
- *
- * @param out the output stream to use.
- */
- public Formatter(OutputStream out)
- {
- this(new OutputStreamWriter(out));
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale, with the specified file output stream and the
- * supplied character set.
- *
- * @param out the output stream.
- * @param charset the character set to use for output.
- * @throws UnsupportedEncodingException if the supplied character
- * set is not supported.
- */
- public Formatter(OutputStream out, String charset)
- throws UnsupportedEncodingException
- {
- this(out, charset, Locale.getDefault());
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the specified
- * output stream with the supplied character set and locale.
- * If the locale is <code>null</code>, then no localization is
- * applied.
- *
- * @param file the output stream.
- * @param charset the character set to use for output.
- * @param loc the locale to use.
- * @throws UnsupportedEncodingException if the supplied character
- * set is not supported.
- */
- public Formatter(OutputStream out, String charset, Locale loc)
- throws UnsupportedEncodingException
- {
- this(new OutputStreamWriter(out, charset), loc);
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale with the specified output stream. The character
- * set used is that of the output stream.
- *
- * @param out the output stream to use.
- */
- public Formatter(PrintStream out)
- {
- this((Appendable) out);
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale and character set, with the specified file as the
- * output stream.
- *
- * @param file the file to use for output.
- * @throws FileNotFoundException if the file does not exist
- * and can not be created.
- * @throws SecurityException if a security manager is present
- * and doesn't allow writing to the file.
- */
- public Formatter(String file) throws FileNotFoundException
- {
- this(new OutputStreamWriter(new FileOutputStream(file)));
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the default
- * locale, with the specified file as the output stream
- * and the supplied character set.
- *
- * @param file the file to use for output.
- * @param charset the character set to use for output.
- * @throws FileNotFoundException if the file does not exist
- * and can not be created.
- * @throws SecurityException if a security manager is present
- * and doesn't allow writing to the file.
- * @throws UnsupportedEncodingException if the supplied character
- * set is not supported.
- */
- public Formatter(String file, String charset)
- throws FileNotFoundException, UnsupportedEncodingException
- {
- this(file, charset, Locale.getDefault());
- }
-
- /**
- * Constructs a new <code>Formatter</code> using the specified
- * file as the output stream with the supplied character set
- * and locale. If the locale is <code>null</code>, then no
- * localization is applied.
- *
- * @param file the file to use for output.
- * @param charset the character set to use for output.
- * @param loc the locale to use.
- * @throws FileNotFoundException if the file does not exist
- * and can not be created.
- * @throws SecurityException if a security manager is present
- * and doesn't allow writing to the file.
- * @throws UnsupportedEncodingException if the supplied character
- * set is not supported.
- */
- public Formatter(String file, String charset, Locale loc)
- throws FileNotFoundException, UnsupportedEncodingException
- {
- this(new OutputStreamWriter(new FileOutputStream(file), charset),
- loc);
- }
-
- /**
- * Closes the formatter, so as to release used resources.
- * If the underlying output stream supports the {@link Closeable}
- * interface, then this is also closed. Attempts to use
- * a formatter instance, via any method other than
- * {@link #ioException()}, after closure results in a
- * {@link FormatterClosedException}.
- */
- public void close()
- {
- if (closed)
- return;
- try
- {
- if (out instanceof Closeable)
- ((Closeable) out).close();
- }
- catch (IOException _)
- {
- // FIXME: do we ignore these or do we set ioException?
- // The docs seem to indicate that we should ignore.
- }
- closed = true;
- }
-
- /**
- * Flushes the formatter, writing any cached data to the output
- * stream. If the underlying output stream supports the
- * {@link Flushable} interface, it is also flushed.
- *
- * @throws FormatterClosedException if the formatter is closed.
- */
- public void flush()
- {
- if (closed)
- throw new FormatterClosedException();
- try
- {
- if (out instanceof Flushable)
- ((Flushable) out).flush();
- }
- catch (IOException _)
- {
- // FIXME: do we ignore these or do we set ioException?
- // The docs seem to indicate that we should ignore.
- }
- }
-
- /**
- * Return the name corresponding to a flag.
- *
- * @param flags the flag to return the name of.
- * @return the name of the flag.
- */
- private String getName(int flags)
- {
- // FIXME: do we want all the flags in here?
- // Or should we redo how this is reported?
- int bit = Integer.numberOfTrailingZeros(flags);
- return FLAGS.substring(bit, bit + 1);
- }
-
- /**
- * Verify the flags passed to a conversion.
- *
- * @param flags the flags to verify.
- * @param allowed the allowed flags mask.
- * @param conversion the conversion character.
- */
- private void checkFlags(int flags, int allowed, char conversion)
- {
- flags &= ~allowed;
- if (flags != 0)
- throw new FormatFlagsConversionMismatchException(getName(flags),
- conversion);
- }
-
- /**
- * Throw an exception if a precision was specified.
- *
- * @param precision the precision value (-1 indicates not specified).
- */
- private void noPrecision(int precision)
- {
- if (precision != -1)
- throw new IllegalFormatPrecisionException(precision);
- }
-
- /**
- * Apply the numeric localization algorithm to a StringBuilder.
- *
- * @param builder the builder to apply to.
- * @param flags the formatting flags to use.
- * @param width the width of the numeric value.
- * @param isNegative true if the value is negative.
- */
- private void applyLocalization(StringBuilder builder, int flags, int width,
- boolean isNegative)
- {
- DecimalFormatSymbols dfsyms;
- if (fmtLocale == null)
- dfsyms = new DecimalFormatSymbols();
- else
- dfsyms = new DecimalFormatSymbols(fmtLocale);
-
- // First replace each digit.
- char zeroDigit = dfsyms.getZeroDigit();
- int decimalOffset = -1;
- for (int i = builder.length() - 1; i >= 0; --i)
- {
- char c = builder.charAt(i);
- if (c >= '0' && c <= '9')
- builder.setCharAt(i, (char) (c - '0' + zeroDigit));
- else if (c == '.')
- {
- assert decimalOffset == -1;
- decimalOffset = i;
- }
- }
-
- // Localize the decimal separator.
- if (decimalOffset != -1)
- {
- builder.deleteCharAt(decimalOffset);
- builder.insert(decimalOffset, dfsyms.getDecimalSeparator());
- }
-
- // Insert the grouping separators.
- if ((flags & FormattableFlags.COMMA) != 0)
- {
- char groupSeparator = dfsyms.getGroupingSeparator();
- int groupSize = 3; // FIXME
- int offset = (decimalOffset == -1) ? builder.length() : decimalOffset;
- // We use '>' because we don't want to insert a separator
- // before the first digit.
- for (int i = offset - groupSize; i > 0; i -= groupSize)
- builder.insert(i, groupSeparator);
- }
-
- if ((flags & FormattableFlags.ZERO) != 0)
- {
- // Zero fill. Note that according to the algorithm we do not
- // insert grouping separators here.
- for (int i = width - builder.length(); i > 0; --i)
- builder.insert(0, zeroDigit);
- }
-
- if (isNegative)
- {
- if ((flags & FormattableFlags.PAREN) != 0)
- {
- builder.insert(0, '(');
- builder.append(')');
- }
- else
- builder.insert(0, '-');
- }
- else if ((flags & FormattableFlags.PLUS) != 0)
- builder.insert(0, '+');
- else if ((flags & FormattableFlags.SPACE) != 0)
- builder.insert(0, ' ');
- }
-
- /**
- * A helper method that handles emitting a String after applying
- * precision, width, justification, and upper case flags.
- *
- * @param arg the string to emit.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void genericFormat(String arg, int flags, int width, int precision)
- throws IOException
- {
- if ((flags & FormattableFlags.UPPERCASE) != 0)
- {
- if (fmtLocale == null)
- arg = arg.toUpperCase();
- else
- arg = arg.toUpperCase(fmtLocale);
- }
-
- if (precision >= 0 && arg.length() > precision)
- arg = arg.substring(0, precision);
-
- boolean leftJustify = (flags & FormattableFlags.LEFT_JUSTIFY) != 0;
- if (leftJustify && width == -1)
- throw new MissingFormatWidthException("fixme");
- if (! leftJustify && arg.length() < width)
- {
- for (int i = width - arg.length(); i > 0; --i)
- out.append(' ');
- }
- out.append(arg);
- if (leftJustify && arg.length() < width)
- {
- for (int i = width - arg.length(); i > 0; --i)
- out.append(' ');
- }
- }
-
- /**
- * Emit a boolean.
- *
- * @param arg the boolean to emit.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param conversion the conversion character.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void booleanFormat(Object arg, int flags, int width, int precision,
- char conversion)
- throws IOException
- {
- checkFlags(flags,
- FormattableFlags.LEFT_JUSTIFY | FormattableFlags.UPPERCASE,
- conversion);
- String result;
- if (arg instanceof Boolean)
- result = String.valueOf((Boolean) arg);
- else
- result = arg == null ? "false" : "true";
- genericFormat(result, flags, width, precision);
- }
-
- /**
- * Emit a hash code.
- *
- * @param arg the hash code to emit.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param conversion the conversion character.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void hashCodeFormat(Object arg, int flags, int width, int precision,
- char conversion)
- throws IOException
- {
- checkFlags(flags,
- FormattableFlags.LEFT_JUSTIFY | FormattableFlags.UPPERCASE,
- conversion);
- genericFormat(arg == null ? "null" : Integer.toHexString(arg.hashCode()),
- flags, width, precision);
- }
-
- /**
- * Emit a String or Formattable conversion.
- *
- * @param arg the String or Formattable to emit.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param conversion the conversion character.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void stringFormat(Object arg, int flags, int width, int precision,
- char conversion)
- throws IOException
- {
- if (arg instanceof Formattable)
- {
- checkFlags(flags,
- (FormattableFlags.LEFT_JUSTIFY
- | FormattableFlags.UPPERCASE
- | FormattableFlags.ALTERNATE),
- conversion);
- Formattable fmt = (Formattable) arg;
- fmt.formatTo(this, flags, width, precision);
- }
- else
- {
- checkFlags(flags,
- FormattableFlags.LEFT_JUSTIFY | FormattableFlags.UPPERCASE,
- conversion);
- genericFormat(arg == null ? "null" : arg.toString(), flags, width,
- precision);
- }
- }
-
- /**
- * Emit a character.
- *
- * @param arg the character to emit.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param conversion the conversion character.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void characterFormat(Object arg, int flags, int width, int precision,
- char conversion)
- throws IOException
- {
- checkFlags(flags,
- FormattableFlags.LEFT_JUSTIFY | FormattableFlags.UPPERCASE,
- conversion);
- noPrecision(precision);
-
- int theChar;
- if (arg instanceof Character)
- theChar = ((Character) arg).charValue();
- else if (arg instanceof Byte)
- theChar = (char) (((Byte) arg).byteValue ());
- else if (arg instanceof Short)
- theChar = (char) (((Short) arg).shortValue ());
- else if (arg instanceof Integer)
- {
- theChar = ((Integer) arg).intValue();
- if (! Character.isValidCodePoint(theChar))
- throw new IllegalFormatCodePointException(theChar);
- }
- else
- throw new IllegalFormatConversionException(conversion, arg.getClass());
- String result = new String(Character.toChars(theChar));
- genericFormat(result, flags, width, precision);
- }
-
- /**
- * Emit a '%'.
- *
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void percentFormat(int flags, int width, int precision)
- throws IOException
- {
- checkFlags(flags, FormattableFlags.LEFT_JUSTIFY, '%');
- noPrecision(precision);
- genericFormat("%", flags, width, precision);
- }
-
- /**
- * Emit a newline.
- *
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void newLineFormat(int flags, int width, int precision)
- throws IOException
- {
- checkFlags(flags, 0, 'n');
- noPrecision(precision);
- if (width != -1)
- throw new IllegalFormatWidthException(width);
- genericFormat(lineSeparator, flags, width, precision);
- }
-
- /**
- * Helper method to do initial formatting and checking for integral
- * conversions.
- *
- * @param arg the formatted argument.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param radix the radix of the number.
- * @param conversion the conversion character.
- * @return the result.
- */
- private StringBuilder basicIntegralConversion(Object arg, int flags,
- int width, int precision,
- int radix, char conversion)
- {
- assert radix == 8 || radix == 10 || radix == 16;
- noPrecision(precision);
-
- // Some error checking.
- if ((flags & FormattableFlags.PLUS) != 0
- && (flags & FormattableFlags.SPACE) != 0)
- throw new IllegalFormatFlagsException(getName(flags));
-
- if ((flags & FormattableFlags.LEFT_JUSTIFY) != 0 && width == -1)
- throw new MissingFormatWidthException("fixme");
-
- // Do the base translation of the value to a string.
- String result;
- int basicFlags = (FormattableFlags.LEFT_JUSTIFY
- // We already handled any possible error when
- // parsing.
- | FormattableFlags.UPPERCASE
- | FormattableFlags.ZERO);
- if (radix == 10)
- basicFlags |= (FormattableFlags.PLUS
- | FormattableFlags.SPACE
- | FormattableFlags.COMMA
- | FormattableFlags.PAREN);
- else
- basicFlags |= FormattableFlags.ALTERNATE;
-
- if (arg instanceof BigInteger)
- {
- checkFlags(flags,
- (basicFlags
- | FormattableFlags.PLUS
- | FormattableFlags.SPACE
- | FormattableFlags.PAREN),
- conversion);
- BigInteger bi = (BigInteger) arg;
- result = bi.toString(radix);
- }
- else if (arg instanceof Number
- && ! (arg instanceof Float)
- && ! (arg instanceof Double))
- {
- checkFlags(flags, basicFlags, conversion);
- long value = ((Number) arg).longValue ();
- if (radix == 8)
- result = Long.toOctalString(value);
- else if (radix == 16)
- result = Long.toHexString(value);
- else
- result = Long.toString(value);
- }
- else
- throw new IllegalFormatConversionException(conversion, arg.getClass());
-
- return new StringBuilder(result);
- }
-
- /**
- * Emit a hex or octal value.
- *
- * @param arg the hexadecimal or octal value.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param radix the radix of the number.
- * @param conversion the conversion character.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void hexOrOctalConversion(Object arg, int flags, int width,
- int precision, int radix,
- char conversion)
- throws IOException
- {
- assert radix == 8 || radix == 16;
-
- StringBuilder builder = basicIntegralConversion(arg, flags, width,
- precision, radix,
- conversion);
- int insertPoint = 0;
-
- // Insert the sign.
- if (builder.charAt(0) == '-')
- {
- // Already inserted. Note that we don't insert a sign, since
- // the only case where it is needed it BigInteger, and it has
- // already been inserted by toString.
- ++insertPoint;
- }
- else if ((flags & FormattableFlags.PLUS) != 0)
- {
- builder.insert(insertPoint, '+');
- ++insertPoint;
- }
- else if ((flags & FormattableFlags.SPACE) != 0)
- {
- builder.insert(insertPoint, ' ');
- ++insertPoint;
- }
-
- // Insert the radix prefix.
- if ((flags & FormattableFlags.ALTERNATE) != 0)
- {
- builder.insert(insertPoint, radix == 8 ? "0" : "0x");
- insertPoint += radix == 8 ? 1 : 2;
- }
-
- // Now justify the result.
- int resultWidth = builder.length();
- if (resultWidth < width)
- {
- char fill = ((flags & FormattableFlags.ZERO) != 0) ? '0' : ' ';
- if ((flags & FormattableFlags.LEFT_JUSTIFY) != 0)
- {
- // Left justify.
- if (fill == ' ')
- insertPoint = builder.length();
- }
- else
- {
- // Right justify. Insert spaces before the radix prefix
- // and sign.
- insertPoint = 0;
- }
- while (resultWidth++ < width)
- builder.insert(insertPoint, fill);
- }
-
- String result = builder.toString();
- if ((flags & FormattableFlags.UPPERCASE) != 0)
- {
- if (fmtLocale == null)
- result = result.toUpperCase();
- else
- result = result.toUpperCase(fmtLocale);
- }
-
- out.append(result);
- }
-
- /**
- * Emit a decimal value.
- *
- * @param arg the hexadecimal or octal value.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param conversion the conversion character.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void decimalConversion(Object arg, int flags, int width,
- int precision, char conversion)
- throws IOException
- {
- StringBuilder builder = basicIntegralConversion(arg, flags, width,
- precision, 10,
- conversion);
- boolean isNegative = false;
- if (builder.charAt(0) == '-')
- {
- // Sign handling is done during localization.
- builder.deleteCharAt(0);
- isNegative = true;
- }
-
- applyLocalization(builder, flags, width, isNegative);
- genericFormat(builder.toString(), flags, width, precision);
- }
-
- /**
- * Emit a single date or time conversion to a StringBuilder.
- *
- * @param builder the builder to write to.
- * @param cal the calendar to use in the conversion.
- * @param conversion the formatting character to specify the type of data.
- * @param syms the date formatting symbols.
- */
- private void singleDateTimeConversion(StringBuilder builder, Calendar cal,
- char conversion,
- DateFormatSymbols syms)
- {
- int oldLen = builder.length();
- int digits = -1;
- switch (conversion)
- {
- case 'H':
- builder.append(cal.get(Calendar.HOUR_OF_DAY));
- digits = 2;
- break;
- case 'I':
- builder.append(cal.get(Calendar.HOUR));
- digits = 2;
- break;
- case 'k':
- builder.append(cal.get(Calendar.HOUR_OF_DAY));
- break;
- case 'l':
- builder.append(cal.get(Calendar.HOUR));
- break;
- case 'M':
- builder.append(cal.get(Calendar.MINUTE));
- digits = 2;
- break;
- case 'S':
- builder.append(cal.get(Calendar.SECOND));
- digits = 2;
- break;
- case 'N':
- // FIXME: nanosecond ...
- digits = 9;
- break;
- case 'p':
- {
- int ampm = cal.get(Calendar.AM_PM);
- builder.append(syms.getAmPmStrings()[ampm]);
- }
- break;
- case 'z':
- {
- int zone = cal.get(Calendar.ZONE_OFFSET) / (1000 * 60);
- builder.append(zone);
- digits = 4;
- // Skip the '-' sign.
- if (zone < 0)
- ++oldLen;
- }
- break;
- case 'Z':
- {
- // FIXME: DST?
- int zone = cal.get(Calendar.ZONE_OFFSET) / (1000 * 60 * 60);
- String[][] zs = syms.getZoneStrings();
- builder.append(zs[zone + 12][1]);
- }
- break;
- case 's':
- {
- long val = cal.getTime().getTime();
- builder.append(val / 1000);
- }
- break;
- case 'Q':
- {
- long val = cal.getTime().getTime();
- builder.append(val);
- }
- break;
- case 'B':
- {
- int month = cal.get(Calendar.MONTH);
- builder.append(syms.getMonths()[month]);
- }
- break;
- case 'b':
- case 'h':
- {
- int month = cal.get(Calendar.MONTH);
- builder.append(syms.getShortMonths()[month]);
- }
- break;
- case 'A':
- {
- int day = cal.get(Calendar.DAY_OF_WEEK);
- builder.append(syms.getWeekdays()[day]);
- }
- break;
- case 'a':
- {
- int day = cal.get(Calendar.DAY_OF_WEEK);
- builder.append(syms.getShortWeekdays()[day]);
- }
- break;
- case 'C':
- builder.append(cal.get(Calendar.YEAR) / 100);
- digits = 2;
- break;
- case 'Y':
- builder.append(cal.get(Calendar.YEAR));
- digits = 4;
- break;
- case 'y':
- builder.append(cal.get(Calendar.YEAR) % 100);
- digits = 2;
- break;
- case 'j':
- builder.append(cal.get(Calendar.DAY_OF_YEAR));
- digits = 3;
- break;
- case 'm':
- builder.append(cal.get(Calendar.MONTH) + 1);
- digits = 2;
- break;
- case 'd':
- builder.append(cal.get(Calendar.DAY_OF_MONTH));
- digits = 2;
- break;
- case 'e':
- builder.append(cal.get(Calendar.DAY_OF_MONTH));
- break;
- case 'R':
- singleDateTimeConversion(builder, cal, 'H', syms);
- builder.append(':');
- singleDateTimeConversion(builder, cal, 'M', syms);
- break;
- case 'T':
- singleDateTimeConversion(builder, cal, 'H', syms);
- builder.append(':');
- singleDateTimeConversion(builder, cal, 'M', syms);
- builder.append(':');
- singleDateTimeConversion(builder, cal, 'S', syms);
- break;
- case 'r':
- singleDateTimeConversion(builder, cal, 'I', syms);
- builder.append(':');
- singleDateTimeConversion(builder, cal, 'M', syms);
- builder.append(':');
- singleDateTimeConversion(builder, cal, 'S', syms);
- builder.append(' ');
- singleDateTimeConversion(builder, cal, 'p', syms);
- break;
- case 'D':
- singleDateTimeConversion(builder, cal, 'm', syms);
- builder.append('/');
- singleDateTimeConversion(builder, cal, 'd', syms);
- builder.append('/');
- singleDateTimeConversion(builder, cal, 'y', syms);
- break;
- case 'F':
- singleDateTimeConversion(builder, cal, 'Y', syms);
- builder.append('-');
- singleDateTimeConversion(builder, cal, 'm', syms);
- builder.append('-');
- singleDateTimeConversion(builder, cal, 'd', syms);
- break;
- case 'c':
- singleDateTimeConversion(builder, cal, 'a', syms);
- builder.append(' ');
- singleDateTimeConversion(builder, cal, 'b', syms);
- builder.append(' ');
- singleDateTimeConversion(builder, cal, 'd', syms);
- builder.append(' ');
- singleDateTimeConversion(builder, cal, 'T', syms);
- builder.append(' ');
- singleDateTimeConversion(builder, cal, 'Z', syms);
- builder.append(' ');
- singleDateTimeConversion(builder, cal, 'Y', syms);
- break;
- default:
- throw new UnknownFormatConversionException(String.valueOf(conversion));
- }
-
- if (digits > 0)
- {
- int newLen = builder.length();
- int delta = newLen - oldLen;
- while (delta++ < digits)
- builder.insert(oldLen, '0');
- }
- }
-
- /**
- * Emit a date or time value.
- *
- * @param arg the date or time value.
- * @param flags the formatting flags to use.
- * @param width the width to use.
- * @param precision the precision to use.
- * @param conversion the conversion character.
- * @param subConversion the sub conversion character.
- * @throws IOException if the output stream throws an I/O error.
- */
- private void dateTimeConversion(Object arg, int flags, int width,
- int precision, char conversion,
- char subConversion)
- throws IOException
- {
- noPrecision(precision);
- checkFlags(flags,
- FormattableFlags.LEFT_JUSTIFY | FormattableFlags.UPPERCASE,
- conversion);
-
- Calendar cal;
- if (arg instanceof Calendar)
- cal = (Calendar) arg;
- else
- {
- Date date;
- if (arg instanceof Date)
- date = (Date) arg;
- else if (arg instanceof Long)
- date = new Date(((Long) arg).longValue());
- else
- throw new IllegalFormatConversionException(conversion,
- arg.getClass());
- if (fmtLocale == null)
- cal = Calendar.getInstance();
- else
- cal = Calendar.getInstance(fmtLocale);
- cal.setTime(date);
- }
-
- // We could try to be more efficient by computing this lazily.
- DateFormatSymbols syms;
- if (fmtLocale == null)
- syms = new DateFormatSymbols();
- else
- syms = new DateFormatSymbols(fmtLocale);
-
- StringBuilder result = new StringBuilder();
- singleDateTimeConversion(result, cal, subConversion, syms);
-
- genericFormat(result.toString(), flags, width, precision);
- }
-
- /**
- * Advance the internal parsing index, and throw an exception
- * on overrun.
- *
- * @throws IllegalArgumentException on overrun.
- */
- private void advance()
- {
- ++index;
- if (index >= length)
- {
- // FIXME: what exception here?
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Parse an integer appearing in the format string. Will return -1
- * if no integer was found.
- *
- * @return the parsed integer.
- */
- private int parseInt()
- {
- int start = index;
- while (Character.isDigit(format.charAt(index)))
- advance();
- if (start == index)
- return -1;
- return Integer.decode(format.substring(start, index));
- }
-
- /**
- * Parse the argument index. Returns -1 if there was no index, 0 if
- * we should re-use the previous index, and a positive integer to
- * indicate an absolute index.
- *
- * @return the parsed argument index.
- */
- private int parseArgumentIndex()
- {
- int result = -1;
- int start = index;
- if (format.charAt(index) == '<')
- {
- result = 0;
- advance();
- }
- else if (Character.isDigit(format.charAt(index)))
- {
- result = parseInt();
- if (format.charAt(index) == '$')
- advance();
- else
- {
- // Reset.
- index = start;
- result = -1;
- }
- }
- return result;
- }
-
- /**
- * Parse a set of flags and return a bit mask of values from
- * FormattableFlags. Will throw an exception if a flag is
- * duplicated.
- *
- * @return the parsed flags.
- */
- private int parseFlags()
- {
- int value = 0;
- int start = index;
- while (true)
- {
- int x = FLAGS.indexOf(format.charAt(index));
- if (x == -1)
- break;
- int newValue = 1 << x;
- if ((value & newValue) != 0)
- throw new DuplicateFormatFlagsException(format.substring(start,
- index + 1));
- value |= newValue;
- advance();
- }
- return value;
- }
-
- /**
- * Parse the width part of a format string. Returns -1 if no width
- * was specified.
- *
- * @return the parsed width.
- */
- private int parseWidth()
- {
- return parseInt();
- }
-
- /**
- * If the current character is '.', parses the precision part of a
- * format string. Returns -1 if no precision was specified.
- *
- * @return the parsed precision.
- */
- private int parsePrecision()
- {
- if (format.charAt(index) != '.')
- return -1;
- advance();
- int precision = parseInt();
- if (precision == -1)
- // FIXME
- throw new IllegalArgumentException();
- return precision;
- }
-
- /**
- * Outputs a formatted string based on the supplied specification,
- * <code>fmt</code>, and its arguments using the specified locale.
- * The locale of the formatter does not change as a result; the
- * specified locale is just used for this particular formatting
- * operation. If the locale is <code>null</code>, then no
- * localization is applied.
- *
- * @param loc the locale to use for this format.
- * @param fmt the format specification.
- * @param args the arguments to apply to the specification.
- * @throws IllegalFormatException if there is a problem with
- * the syntax of the format
- * specification or a mismatch
- * between it and the arguments.
- * @throws FormatterClosedException if the formatter is closed.
- */
- public Formatter format(Locale loc, String fmt, Object... args)
- {
- if (closed)
- throw new FormatterClosedException();
-
- // Note the arguments are indexed starting at 1.
- int implicitArgumentIndex = 1;
- int previousArgumentIndex = 0;
-
- try
- {
- fmtLocale = loc;
- format = fmt;
- length = format.length();
- for (index = 0; index < length; ++index)
- {
- char c = format.charAt(index);
- if (c != '%')
- {
- out.append(c);
- continue;
- }
-
- int start = index;
- advance();
-
- // We do the needed post-processing of this later, when we
- // determine whether an argument is actually needed by
- // this conversion.
- int argumentIndex = parseArgumentIndex();
-
- int flags = parseFlags();
- int width = parseWidth();
- int precision = parsePrecision();
- char origConversion = format.charAt(index);
- char conversion = origConversion;
- if (Character.isUpperCase(conversion))
- {
- flags |= FormattableFlags.UPPERCASE;
- conversion = Character.toLowerCase(conversion);
- }
-
- Object argument = null;
- if (conversion == '%' || conversion == 'n')
- {
- if (argumentIndex != -1)
- {
- // FIXME: not sure about this.
- throw new UnknownFormatConversionException("FIXME");
- }
- }
- else
- {
- if (argumentIndex == -1)
- argumentIndex = implicitArgumentIndex++;
- else if (argumentIndex == 0)
- argumentIndex = previousArgumentIndex;
- // Argument indices start at 1 but array indices at 0.
- --argumentIndex;
- if (argumentIndex < 0 || argumentIndex >= args.length)
- throw new MissingFormatArgumentException(format.substring(start, index));
- argument = args[argumentIndex];
- }
-
- switch (conversion)
- {
- case 'b':
- booleanFormat(argument, flags, width, precision,
- origConversion);
- break;
- case 'h':
- hashCodeFormat(argument, flags, width, precision,
- origConversion);
- break;
- case 's':
- stringFormat(argument, flags, width, precision,
- origConversion);
- break;
- case 'c':
- characterFormat(argument, flags, width, precision,
- origConversion);
- break;
- case 'd':
- checkFlags(flags & FormattableFlags.UPPERCASE, 0, 'd');
- decimalConversion(argument, flags, width, precision,
- origConversion);
- break;
- case 'o':
- checkFlags(flags & FormattableFlags.UPPERCASE, 0, 'o');
- hexOrOctalConversion(argument, flags, width, precision, 8,
- origConversion);
- break;
- case 'x':
- hexOrOctalConversion(argument, flags, width, precision, 16,
- origConversion);
- case 'e':
- // scientificNotationConversion();
- break;
- case 'f':
- // floatingDecimalConversion();
- break;
- case 'g':
- // smartFloatingConversion();
- break;
- case 'a':
- // hexFloatingConversion();
- break;
- case 't':
- advance();
- char subConversion = format.charAt(index);
- dateTimeConversion(argument, flags, width, precision,
- origConversion, subConversion);
- break;
- case '%':
- percentFormat(flags, width, precision);
- break;
- case 'n':
- newLineFormat(flags, width, precision);
- break;
- default:
- throw new UnknownFormatConversionException(String.valueOf(origConversion));
- }
- }
- }
- catch (IOException exc)
- {
- ioException = exc;
- }
- return this;
- }
-
- /**
- * Outputs a formatted string based on the supplied specification,
- * <code>fmt</code>, and its arguments using the formatter's locale.
- *
- * @param fmt the format specification.
- * @param args the arguments to apply to the specification.
- * @throws IllegalFormatException if there is a problem with
- * the syntax of the format
- * specification or a mismatch
- * between it and the arguments.
- * @throws FormatterClosedException if the formatter is closed.
- */
- public Formatter format(String format, Object... args)
- {
- return format(locale, format, args);
- }
-
- /**
- * Returns the last I/O exception thrown by the
- * <code>append()</code> operation of the underlying
- * output stream.
- *
- * @return the last I/O exception.
- */
- public IOException ioException()
- {
- return ioException;
- }
-
- /**
- * Returns the locale used by this formatter.
- *
- * @return the formatter's locale.
- * @throws FormatterClosedException if the formatter is closed.
- */
- public Locale locale()
- {
- if (closed)
- throw new FormatterClosedException();
- return locale;
- }
-
- /**
- * Returns the output stream used by this formatter.
- *
- * @return the formatter's output stream.
- * @throws FormatterClosedException if the formatter is closed.
- */
- public Appendable out()
- {
- if (closed)
- throw new FormatterClosedException();
- return out;
- }
-
- /**
- * Returns the result of applying {@link Object#toString()}
- * to the underlying output stream. The results returned
- * depend on the particular {@link Appendable} being used.
- * For example, a {@link StringBuilder} will return the
- * formatted output but an I/O stream will not.
- *
- * @throws FormatterClosedException if the formatter is closed.
- */
- public String toString()
- {
- if (closed)
- throw new FormatterClosedException();
- return out.toString();
- }
-}
Deleted: trunk/core/src/classpath/java/java/util/FormatterClosedException.java
===================================================================
--- trunk/core/src/classpath/java/java/util/FormatterClosedException.java 2007-06-17 10:56:12 UTC (rev 3276)
+++ trunk/core/src/classpath/java/java/util/FormatterClosedException.java 2007-06-17 12:15:58 UTC (rev 3277)
@@ -1,60 +0,0 @@
-/* FormatterClosedException.java
- Copyright (C) 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. ...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-17 10:56:14
|
Revision: 3276
http://jnode.svn.sourceforge.net/jnode/?rev=3276&view=rev
Author: lsantha
Date: 2007-06-17 03:56:12 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/sun/sun/reflect/misc/
trunk/core/src/openjdk/sun/sun/reflect/misc/ConstructorUtil.java
trunk/core/src/openjdk/sun/sun/reflect/misc/FieldUtil.java
trunk/core/src/openjdk/sun/sun/reflect/misc/MethodUtil.java
trunk/core/src/openjdk/sun/sun/reflect/misc/ReflectUtil.java
Added: trunk/core/src/openjdk/sun/sun/reflect/misc/ConstructorUtil.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/reflect/misc/ConstructorUtil.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/reflect/misc/ConstructorUtil.java 2007-06-17 10:56:12 UTC (rev 3276)
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.reflect.misc;
+
+import java.lang.reflect.Constructor;
+
+public final class ConstructorUtil {
+
+ private ConstructorUtil() {
+ }
+
+ public static Constructor getConstructor(Class cls, Class[] params)
+ throws NoSuchMethodException {
+ ReflectUtil.checkPackageAccess(cls);
+ return cls.getConstructor(params);
+ }
+
+ public static Constructor[] getConstructors(Class cls) {
+ ReflectUtil.checkPackageAccess(cls);
+ return cls.getConstructors();
+ }
+}
Added: trunk/core/src/openjdk/sun/sun/reflect/misc/FieldUtil.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/reflect/misc/FieldUtil.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/reflect/misc/FieldUtil.java 2007-06-17 10:56:12 UTC (rev 3276)
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.reflect.misc;
+
+import java.lang.reflect.Field;
+
+/*
+ * Create a trampoline class.
+ */
+public final class FieldUtil {
+
+ private FieldUtil() {
+ }
+
+ public static Field getField(Class cls, String name)
+ throws NoSuchFieldException {
+ ReflectUtil.checkPackageAccess(cls);
+ return cls.getField(name);
+ }
+
+ public static Field[] getFields(Class cls) {
+ ReflectUtil.checkPackageAccess(cls);
+ return cls.getFields();
+ }
+
+ public static Field[] getDeclaredFields(Class cls) {
+ ReflectUtil.checkPackageAccess(cls);
+ return cls.getDeclaredFields();
+ }
+}
Added: trunk/core/src/openjdk/sun/sun/reflect/misc/MethodUtil.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/reflect/misc/MethodUtil.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/reflect/misc/MethodUtil.java 2007-06-17 10:56:12 UTC (rev 3276)
@@ -0,0 +1,428 @@
+/*
+ * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package sun.reflect.misc;
+
+import java.security.AllPermission;
+import java.security.AccessController;
+import java.security.PermissionCollection;
+import java.security.SecureClassLoader;
+import java.security.PrivilegedExceptionAction;
+import java.security.CodeSource;
+import java.io.InputStream;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.HttpURLConnection;
+import java.lang.reflect.Method;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Modifier;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import sun.net.www.ParseUtil;
+import sun.security.util.SecurityConstants;
+
+
+class Trampoline {
+ private static Object invoke(Method m, Object obj, Object[] params)
+ throws InvocationTargetException, IllegalAccessException {
+ return m.invoke(obj, params);
+ }
+}
+
+/*
+ * Create a trampoline class.
+ */
+public final class MethodUtil extends SecureClassLoader {
+ private static String MISC_PKG = "sun.reflect.misc.";
+ private static String TRAMPOLINE = MISC_PKG + "Trampoline";
+ private static Method bounce = getTrampoline();
+
+ private MethodUtil() {
+ super();
+ }
+
+ public static Method getMethod(Class cls, String name, Class[] args)
+ throws NoSuchMethodException {
+ ReflectUtil.checkPackageAccess(cls);
+ return cls.getMethod(name, args);
+ }
+
+ public static Method[] getMethods(Class cls) {
+ ReflectUtil.checkPackageAccess(cls);
+ return cls.getMethods();
+ }
+
+ /*
+ * Discover the public methods on public classes
+ * and interfaces accessible to any caller by calling
+ * Class.getMethods() and walking towards Object until
+ * we're done.
+ */
+ public static Method[] getPublicMethods(Class cls) {
+ // compatibility for update release
+ if (System.getSecurityManager() == null) {
+ return cls.getMethods();
+ }
+ Map sigs = new HashMap();
+ while (cls != null) {
+ boolean done = getInternalPublicMethods(cls, sigs);
+ if (done) {
+ break;
+ }
+ getInterfaceMethods(cls, sigs);
+ cls = cls.getSuperclass();
+ }
+ Collection c = sigs.values();
+ return (Method[]) c.toArray(new Method[c.size()]);
+ }
+
+ /*
+ * Process the immediate interfaces of this class or interface.
+ */
+ private static void getInterfaceMethods(Class cls, Map sigs) {
+ Class[] intfs = cls.getInterfaces();
+ for (int i=0; i < intfs.length; i++) {
+ Class intf = intfs[i];
+ boolean done = getInternalPublicMethods(intf, sigs);
+ if (!done) {
+ getInterfaceMethods(intf, sigs);
+ }
+ }
+ }
+
+ /*
+ *
+ * Process the methods in this class or interface
+ */
+ private static boolean getInternalPublicMethods(Class cls, Map sigs) {
+ Method[] methods = null;
+ try {
+ /*
+ * This class or interface is non-public so we
+ * can't use any of it's methods. Go back and
+ * try again with a superclass or superinterface.
+ */
+ if (!Modifier.isPublic(cls.getModifiers())) {
+ return false;
+ }
+ if (!ReflectUtil.isPackageAccessible(cls)) {
+ return false;
+ }
+
+ methods = cls.getMethods();
+ } catch (SecurityException se) {
+ return false;
+ }
+
+ /*
+ * Check for inherited methods with non-public
+ * declaring classes. They might override and hide
+ * methods from their superclasses or
+ * superinterfaces.
+ */
+ boolean done = true;
+ for (int i=0; i < methods.length; i++) {
+ Class dc = methods[i].getDeclaringClass();
+ if (!Modifier.isPublic(dc.getModifiers())) {
+ done = false;
+ break;
+ }
+ }
+
+ if (done) {
+ /*
+ * We're done. Spray all the methods into
+ * the list and then we're out of here.
+ */
+ for (int i=0; i < methods.length; i++) {
+ addMethod(sigs, methods[i]);
+ }
+ } else {
+ /*
+ * Simulate cls.getDeclaredMethods() by
+ * stripping away inherited methods.
+ */
+ for (int i=0; i < methods.length; i++) {
+ Class dc = methods[i].getDeclaringClass();
+ if (cls.equals(dc)) {
+ addMethod(sigs, methods[i]);
+ }
+ }
+ }
+ return done;
+ }
+
+ private static void addMethod(Map sigs, Method method) {
+ Signature signature = new Signature(method);
+ if (!sigs.containsKey(signature)) {
+ sigs.put(signature, method);
+ } else if (!method.getDeclaringClass().isInterface()){
+ /*
+ * Superclasses beat interfaces.
+ */
+ Method old = (Method)sigs.get(signature);
+ if (old.getDeclaringClass().isInterface()) {
+ sigs.put(signature, method);
+ }
+ }
+ }
+
+ /**
+ * A class that represents the unique elements of a method that will be a
+ * key in the method cache.
+ */
+ private static class Signature {
+ private String methodName;
+ private Class[] argClasses;
+
+ private volatile int hashCode = 0;
+
+ Signature(Method m) {
+ this.methodName = m.getName();
+ this.argClasses = m.getParameterTypes();
+ }
+
+ public boolean equals(Object o2) {
+ if (this == o2) {
+ return true;
+ }
+ Signature that = (Signature)o2;
+ if (!(methodName.equals(that.methodName))) {
+ return false;
+ }
+ if (argClasses.length != that.argClasses.length) {
+ return false;
+ }
+ for (int i = 0; i < argClasses.length; i++) {
+ if (!(argClasses[i] == that.argClasses[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Hash code computed using algorithm suggested in
+ * Effective Java, Item 8.
+ */
+ public int hashCode() {
+ if (hashCode == 0) {
+ int result = 17;
+ result = 37 * result + methodName.hashCode();
+ if (argClasses != null) {
+ for (int i = 0; i < argClasses.length; i++) {
+ result = 37 * result + ((argClasses[i] == null) ? 0 :
+ argClasses[i].hashCode());
+ }
+ }
+ hashCode = result;
+ }
+ return hashCode;
+ }
+ }
+
+
+ /*
+ * Bounce through the trampoline.
+ */
+ public static Object invoke(Method m, Object obj, Object[] params)
+ throws InvocationTargetException, IllegalAccessException {
+ if (m.getDeclaringClass().equals(AccessController.class) ||
+ m.getDeclaringClass().equals(Method.class))
+ throw new InvocationTargetException(
+ new UnsupportedOperationException("invocation not supported"));
+ try {
+ return bounce.invoke(null, new Object[] {m, obj, params});
+ } catch (InvocationTargetException ie) {
+ Throwable t = ie.getCause();
+
+ if (t instanceof InvocationTargetException) {
+ throw (InvocationTargetException)t;
+ } else if (t instanceof IllegalAccessException) {
+ throw (IllegalAccessException)t;
+ } else if (t instanceof RuntimeException) {
+ throw (RuntimeException)t;
+ } else if (t instanceof Error) {
+ throw (Error)t;
+ } else {
+ throw new Error("Unexpected invocation error", t);
+ }
+ } catch (IllegalAccessException iae) {
+ // this can't happen
+ throw new Error("Unexpected invocation error", iae);
+ }
+ }
+
+ private static Method getTrampoline() {
+ Method tramp = null;
+
+ try {
+ tramp = (Method) AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ public Object run() throws Exception {
+ Class[] types;
+ Class t = getTrampolineClass();
+ Method b;
+
+ types = new Class[] {Method.class, Object.class, Object[].class};
+ b = t.getDeclaredMethod("invoke", types);
+ ((AccessibleObject)b).setAccessible(true);
+ return b;
+ }
+ });
+ } catch (Exception e) {
+ throw new InternalError("bouncer cannot be found");
+ }
+ return tramp;
+ }
+
+
+ protected synchronized Class loadClass(String name, boolean resolve)
+ throws ClassNotFoundException
+ {
+ // First, check if the class has already been loaded
+ ReflectUtil.checkPackageAccess(name);
+ Class c = findLoadedClass(name);
+ if (c == null) {
+ try {
+ c = findClass(name);
+ } catch (ClassNotFoundException e) {
+ // Fall through ...
+ }
+ if (c == null) {
+ c = getParent().loadClass(name);
+ }
+ }
+ if (resolve) {
+ resolveClass(c);
+ }
+ return c;
+ }
+
+
+ protected Class findClass(final String name)
+ throws ClassNotFoundException
+ {
+ if (!name.startsWith(MISC_PKG)) {
+ throw new ClassNotFoundException(name);
+ }
+ String path = name.replace('.', '/').concat(".class");
+ URL res = getResource(path);
+ if (res != null) {
+ try {
+ return defineClass(name, res);
+ } catch (IOException e) {
+ throw new ClassNotFoundException(name, e);
+ }
+ } else {
+ throw new ClassNotFoundException(name);
+ }
+ }
+
+
+ /*
+ * Define the proxy classes
+ */
+ private Class defineClass(String name, URL url) throws IOException {
+ byte[] b = getBytes(url);
+ CodeSource cs = new CodeSource(null, (java.security.cert.Certificate[])null);
+ if (!name.equals(TRAMPOLINE)) {
+ throw new IOException("MethodUtil: bad name " + name);
+ }
+ return defineClass(name, b, 0, b.length, cs);
+ }
+
+
+ /*
+ * Returns the contents of the specified URL as an array of bytes.
+ */
+ private static byte[] getBytes(URL url) throws IOException {
+ URLConnection uc = url.openConnection();
+ if (uc instanceof java.net.HttpURLConnection) {
+ java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
+ int code = huc.getResponseCode();
+ if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
+ throw new IOException("open HTTP connection failed.");
+ }
+ }
+ int len = uc.getContentLength();
+ InputStream in = new BufferedInputStream(uc.getInputStream());
+
+ byte[] b;
+ try {
+ if (len != -1) {
+ // Read exactly len bytes from the input stream
+ b = new byte[len];
+ while (len > 0) {
+ int n = in.read(b, b.length - len, len);
+ if (n == -1) {
+ throw new IOException("unexpected EOF");
+ }
+ len -= n;
+ }
+ } else {
+ b = new byte[8192];
+ int total = 0;
+ while ((len = in.read(b, total, b.length - total)) != -1) {
+ total += len;
+ if (total >= b.length) {
+ byte[] tmp = new byte[total * 2];
+ System.arraycopy(b, 0, tmp, 0, total);
+ b = tmp;
+ }
+ }
+ // Trim array to correct size, if necessary
+ if (total != b.length) {
+ byte[] tmp = new byte[total];
+ System.arraycopy(b, 0, tmp, 0, total);
+ b = tmp;
+ }
+ }
+ } finally {
+ in.close();
+ }
+ return b;
+ }
+
+
+ protected PermissionCollection getPermissions(CodeSource codesource)
+ {
+ PermissionCollection perms = super.getPermissions(codesource);
+ perms.add(new AllPermission());
+ return perms;
+ }
+
+ private static Class getTrampolineClass() {
+ try {
+ return Class.forName(TRAMPOLINE, true, new MethodUtil());
+ } catch (ClassNotFoundException e) {
+ }
+ return null;
+ }
+
+}
Added: trunk/core/src/openjdk/sun/sun/reflect/misc/ReflectUtil.java
===================================================================
--- trunk/core/src/openjdk/sun/sun/reflect/misc/ReflectUtil.java (rev 0)
+++ trunk/core/src/openjdk/sun/sun/reflect/misc/ReflectUtil.java 2007-06-17 10:56:12 UTC (rev 3276)
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+package sun.reflect.misc;
+
+import java.lang.reflect.Modifier;
+import sun.reflect.Reflection;
+
+public final class ReflectUtil {
+
+ private ReflectUtil() {
+ }
+
+ public static Class forName(String name)
+ throws ClassNotFoundException {
+ checkPackageAccess(name);
+ return Class.forName(name);
+ }
+
+ public static Object newInstance(Class cls)
+ throws InstantiationException, IllegalAccessException {
+ checkPackageAccess(cls);
+ return cls.newInstance();
+ }
+
+ /*
+ * Reflection.ensureMemberAccess is overly-restrictive
+ * due to a bug. We awkwardly work around it for now.
+ */
+ public static void ensureMemberAccess(Class currentClass,
+ Class memberClass,
+ Object target,
+ int modifiers)
+ throws IllegalAccessException
+ {
+ if (target == null && Modifier.isProtected(modifiers)) {
+ int mods = modifiers;
+ mods = mods & (~Modifier.PROTECTED);
+ mods = mods | Modifier.PUBLIC;
+
+ /*
+ * See if we fail because of class modifiers
+ */
+ Reflection.ensureMemberAccess(currentClass,
+ memberClass,
+ target,
+ mods);
+ try {
+ /*
+ * We're still here so class access was ok.
+ * Now try with default field access.
+ */
+ mods = mods & (~Modifier.PUBLIC);
+ Reflection.ensureMemberAccess(currentClass,
+ memberClass,
+ target,
+ mods);
+ /*
+ * We're still here so access is ok without
+ * checking for protected.
+ */
+ return;
+ } catch (IllegalAccessException e) {
+ /*
+ * Access failed but we're 'protected' so
+ * if the test below succeeds then we're ok.
+ */
+ if (isSubclassOf(currentClass, memberClass)) {
+ return;
+ } else {
+ throw e;
+ }
+ }
+ } else {
+ Reflection.ensureMemberAccess(currentClass,
+ memberClass,
+ target,
+ modifiers);
+ }
+ }
+
+ private static boolean isSubclassOf(Class queryClass,
+ Class ofClass)
+ {
+ while (queryClass != null) {
+ if (queryClass == ofClass) {
+ return true;
+ }
+ queryClass = queryClass.getSuperclass();
+ }
+ return false;
+ }
+
+
+ public static void checkPackageAccess(Class clazz) {
+ checkPackageAccess(clazz.getName());
+ }
+
+ public static void checkPackageAccess(String name) {
+ SecurityManager s = System.getSecurityManager();
+ if (s != null) {
+ String cname = name.replace('/', '.');
+ if (cname.startsWith("[")) {
+ int b = cname.lastIndexOf('[') + 2;
+ if (b > 1 && b < cname.length()) {
+ cname = cname.substring(b);
+ }
+ }
+ int i = cname.lastIndexOf('.');
+ if (i != -1) {
+ s.checkPackageAccess(cname.substring(0, i));
+ }
+ }
+ }
+
+ public static boolean isPackageAccessible(Class clazz) {
+ try {
+ checkPackageAccess(clazz);
+ } catch (SecurityException e) {
+ return false;
+ }
+ return true;
+ }
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-17 10:10:51
|
Revision: 3275
http://jnode.svn.sourceforge.net/jnode/?rev=3275&view=rev
Author: lsantha
Date: 2007-06-17 03:10:49 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Removed Paths:
-------------
trunk/core/src/classpath/gnu/gnu/java/rmi/registry/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-17 10:09:43
|
Revision: 3274
http://jnode.svn.sourceforge.net/jnode/?rev=3274&view=rev
Author: lsantha
Date: 2007-06-17 03:09:41 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/java/java/rmi/
trunk/core/src/openjdk/java/java/rmi/AccessException.java
trunk/core/src/openjdk/java/java/rmi/AlreadyBoundException.java
trunk/core/src/openjdk/java/java/rmi/ConnectException.java
trunk/core/src/openjdk/java/java/rmi/ConnectIOException.java
trunk/core/src/openjdk/java/java/rmi/MarshalException.java
trunk/core/src/openjdk/java/java/rmi/MarshalledObject.java
trunk/core/src/openjdk/java/java/rmi/Naming.java
trunk/core/src/openjdk/java/java/rmi/NoSuchObjectException.java
trunk/core/src/openjdk/java/java/rmi/NotBoundException.java
trunk/core/src/openjdk/java/java/rmi/RMISecurityException.java
trunk/core/src/openjdk/java/java/rmi/RMISecurityManager.java
trunk/core/src/openjdk/java/java/rmi/Remote.java
trunk/core/src/openjdk/java/java/rmi/RemoteException.java
trunk/core/src/openjdk/java/java/rmi/ServerError.java
trunk/core/src/openjdk/java/java/rmi/ServerException.java
trunk/core/src/openjdk/java/java/rmi/ServerRuntimeException.java
trunk/core/src/openjdk/java/java/rmi/StubNotFoundException.java
trunk/core/src/openjdk/java/java/rmi/UnexpectedException.java
trunk/core/src/openjdk/java/java/rmi/UnknownHostException.java
trunk/core/src/openjdk/java/java/rmi/UnmarshalException.java
trunk/core/src/openjdk/java/java/rmi/activation/
trunk/core/src/openjdk/java/java/rmi/activation/Activatable.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivateFailedException.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationDesc.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationException.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationGroup.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationGroupDesc.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationGroupID.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationID.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationInstantiator.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationMonitor.java
trunk/core/src/openjdk/java/java/rmi/activation/ActivationSystem.java
trunk/core/src/openjdk/java/java/rmi/activation/Activator.java
trunk/core/src/openjdk/java/java/rmi/activation/UnknownGroupException.java
trunk/core/src/openjdk/java/java/rmi/activation/UnknownObjectException.java
trunk/core/src/openjdk/java/java/rmi/activation/package.html
trunk/core/src/openjdk/java/java/rmi/dgc/
trunk/core/src/openjdk/java/java/rmi/dgc/DGC.java
trunk/core/src/openjdk/java/java/rmi/dgc/Lease.java
trunk/core/src/openjdk/java/java/rmi/dgc/VMID.java
trunk/core/src/openjdk/java/java/rmi/dgc/package.html
trunk/core/src/openjdk/java/java/rmi/package.html
trunk/core/src/openjdk/java/java/rmi/registry/
trunk/core/src/openjdk/java/java/rmi/registry/LocateRegistry.java
trunk/core/src/openjdk/java/java/rmi/registry/Registry.java
trunk/core/src/openjdk/java/java/rmi/registry/RegistryHandler.java
trunk/core/src/openjdk/java/java/rmi/registry/package.html
trunk/core/src/openjdk/java/java/rmi/server/
trunk/core/src/openjdk/java/java/rmi/server/ExportException.java
trunk/core/src/openjdk/java/java/rmi/server/LoaderHandler.java
trunk/core/src/openjdk/java/java/rmi/server/LogStream.java
trunk/core/src/openjdk/java/java/rmi/server/ObjID.java
trunk/core/src/openjdk/java/java/rmi/server/Operation.java
trunk/core/src/openjdk/java/java/rmi/server/RMIClassLoader.java
trunk/core/src/openjdk/java/java/rmi/server/RMIClassLoaderSpi.java
trunk/core/src/openjdk/java/java/rmi/server/RMIClientSocketFactory.java
trunk/core/src/openjdk/java/java/rmi/server/RMIFailureHandler.java
trunk/core/src/openjdk/java/java/rmi/server/RMIServerSocketFactory.java
trunk/core/src/openjdk/java/java/rmi/server/RMISocketFactory.java
trunk/core/src/openjdk/java/java/rmi/server/RemoteCall.java
trunk/core/src/openjdk/java/java/rmi/server/RemoteObject.java
trunk/core/src/openjdk/java/java/rmi/server/RemoteObjectInvocationHandler.java
trunk/core/src/openjdk/java/java/rmi/server/RemoteRef.java
trunk/core/src/openjdk/java/java/rmi/server/RemoteServer.java
trunk/core/src/openjdk/java/java/rmi/server/RemoteStub.java
trunk/core/src/openjdk/java/java/rmi/server/ServerCloneException.java
trunk/core/src/openjdk/java/java/rmi/server/ServerNotActiveException.java
trunk/core/src/openjdk/java/java/rmi/server/ServerRef.java
trunk/core/src/openjdk/java/java/rmi/server/Skeleton.java
trunk/core/src/openjdk/java/java/rmi/server/SkeletonMismatchException.java
trunk/core/src/openjdk/java/java/rmi/server/SkeletonNotFoundException.java
trunk/core/src/openjdk/java/java/rmi/server/SocketSecurityException.java
trunk/core/src/openjdk/java/java/rmi/server/UID.java
trunk/core/src/openjdk/java/java/rmi/server/UnicastRemoteObject.java
trunk/core/src/openjdk/java/java/rmi/server/Unreferenced.java
trunk/core/src/openjdk/java/java/rmi/server/package.html
trunk/core/src/openjdk/sun/sun/rmi/
trunk/core/src/openjdk/sun/sun/rmi/log/
trunk/core/src/openjdk/sun/sun/rmi/log/LogHandler.java
trunk/core/src/openjdk/sun/sun/rmi/log/LogInputStream.java
trunk/core/src/openjdk/sun/sun/rmi/log/LogOutputStream.java
trunk/core/src/openjdk/sun/sun/rmi/log/ReliableLog.java
trunk/core/src/openjdk/sun/sun/rmi/registry/
trunk/core/src/openjdk/sun/sun/rmi/registry/RegistryImpl.java
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_de.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_es.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_fr.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_it.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_ja.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_ko.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_sv.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_zh_CN.properties
trunk/core/src/openjdk/sun/sun/rmi/registry/resources/rmiregistry_zh_TW.properties
trunk/core/src/openjdk/sun/sun/rmi/runtime/
trunk/core/src/openjdk/sun/sun/rmi/runtime/Log.java
trunk/core/src/openjdk/sun/sun/rmi/runtime/NewThreadAction.java
trunk/core/src/openjdk/sun/sun/rmi/runtime/RuntimeUtil.java
trunk/core/src/openjdk/sun/sun/rmi/server/
trunk/core/src/openjdk/sun/sun/rmi/server/ActivatableRef.java
trunk/core/src/openjdk/sun/sun/rmi/server/ActivatableServerRef.java
trunk/core/src/openjdk/sun/sun/rmi/server/ActivationGroupImpl.java
trunk/core/src/openjdk/sun/sun/rmi/server/ActivationGroupInit.java
trunk/core/src/openjdk/sun/sun/rmi/server/Dispatcher.java
trunk/core/src/openjdk/sun/sun/rmi/server/InactiveGroupException.java
trunk/core/src/openjdk/sun/sun/rmi/server/LoaderHandler.java
trunk/core/src/openjdk/sun/sun/rmi/server/MarshalInputStream.java
trunk/core/src/openjdk/sun/sun/rmi/server/MarshalOutputStream.java
trunk/core/src/openjdk/sun/sun/rmi/server/UnicastRef.java
trunk/core/src/openjdk/sun/sun/rmi/server/UnicastRef2.java
trunk/core/src/openjdk/sun/sun/rmi/server/UnicastServerRef.java
trunk/core/src/openjdk/sun/sun/rmi/server/UnicastServerRef2.java
trunk/core/src/openjdk/sun/sun/rmi/server/Util.java
trunk/core/src/openjdk/sun/sun/rmi/server/WeakClassHashMap.java
trunk/core/src/openjdk/sun/sun/rmi/server/resources/
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_de.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_es.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_fr.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_it.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_ja.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_ko.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_sv.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_zh_CN.properties
trunk/core/src/openjdk/sun/sun/rmi/server/resources/rmid_zh_TW.properties
trunk/core/src/openjdk/sun/sun/rmi/transport/
trunk/core/src/openjdk/sun/sun/rmi/transport/Channel.java
trunk/core/src/openjdk/sun/sun/rmi/transport/Connection.java
trunk/core/src/openjdk/sun/sun/rmi/transport/ConnectionInputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/ConnectionOutputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/DGCAckHandler.java
trunk/core/src/openjdk/sun/sun/rmi/transport/DGCClient.java
trunk/core/src/openjdk/sun/sun/rmi/transport/DGCImpl.java
trunk/core/src/openjdk/sun/sun/rmi/transport/Endpoint.java
trunk/core/src/openjdk/sun/sun/rmi/transport/LiveRef.java
trunk/core/src/openjdk/sun/sun/rmi/transport/ObjectEndpoint.java
trunk/core/src/openjdk/sun/sun/rmi/transport/ObjectTable.java
trunk/core/src/openjdk/sun/sun/rmi/transport/StreamRemoteCall.java
trunk/core/src/openjdk/sun/sun/rmi/transport/Target.java
trunk/core/src/openjdk/sun/sun/rmi/transport/Transport.java
trunk/core/src/openjdk/sun/sun/rmi/transport/TransportConstants.java
trunk/core/src/openjdk/sun/sun/rmi/transport/WeakRef.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/CGIHandler.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/HttpAwareServerSocket.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/HttpInputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/HttpOutputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/HttpReceiveSocket.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/HttpSendInputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/HttpSendOutputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/HttpSendSocket.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/RMIDirectSocketFactory.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/RMIHttpToCGISocketFactory.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/RMIHttpToPortSocketFactory.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/RMIMasterSocketFactory.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/RMISocketInfo.java
trunk/core/src/openjdk/sun/sun/rmi/transport/proxy/WrappedSocket.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/ConnectionMultiplexer.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/MultiplexConnectionInfo.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/MultiplexInputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/MultiplexOutputStream.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/TCPChannel.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/TCPConnection.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/TCPEndpoint.java
trunk/core/src/openjdk/sun/sun/rmi/transport/tcp/TCPTransport.java
trunk/core/src/openjdk/sun/sun/security/action/LoadLibraryAction.java
trunk/core/src/openjdk/vm/sun/rmi/
trunk/core/src/openjdk/vm/sun/rmi/server/
trunk/core/src/openjdk/vm/sun/rmi/server/NativeMarshalInputStream.java
Added: trunk/core/src/openjdk/java/java/rmi/AccessException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/AccessException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/AccessException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,71 @@
+/*
+ * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.rmi;
+
+/**
+ * An <code>AccessException</code> is thrown by certain methods of the
+ * <code>java.rmi.Naming</code> class (specifically <code>bind</code>,
+ * <code>rebind</code>, and <code>unbind</code>) and methods of the
+ * <code>java.rmi.activation.ActivationSystem</code> interface to
+ * indicate that the caller does not have permission to perform the action
+ * requested by the method call. If the method was invoked from a non-local
+ * host, then an <code>AccessException</code> is thrown.
+ *
+ * @version 1.19, 05/05/07
+ * @author Ann Wollrath
+ * @author Roger Riggs
+ * @since JDK1.1
+ * @see java.rmi.Naming
+ * @see java.rmi.activation.ActivationSystem
+ */
+public class AccessException extends java.rmi.RemoteException {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = 6314925228044966088L;
+
+ /**
+ * Constructs an <code>AccessException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message
+ * @since JDK1.1
+ */
+ public AccessException(String s) {
+ super(s);
+ }
+
+ /**
+ * Constructs an <code>AccessException</code> with the specified
+ * detail message and nested exception.
+ *
+ * @param s the detail message
+ * @param ex the nested exception
+ * @since JDK1.1
+ */
+ public AccessException(String s, Exception ex) {
+ super(s, ex);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/AlreadyBoundException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/AlreadyBoundException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/AlreadyBoundException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,63 @@
+/*
+ * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package java.rmi;
+
+/**
+ * An <code>AlreadyBoundException</code> is thrown if an attempt
+ * is made to bind an object in the registry to a name that already
+ * has an associated binding.
+ *
+ * @version 1.19, 05/05/07
+ * @since JDK1.1
+ * @author Ann Wollrath
+ * @author Roger Riggs
+ * @see java.rmi.Naming#bind(String, java.rmi.Remote)
+ * @see java.rmi.registry.Registry#bind(String, java.rmi.Remote)
+ */
+public class AlreadyBoundException extends java.lang.Exception {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = 9218657361741657110L;
+
+ /**
+ * Constructs an <code>AlreadyBoundException</code> with no
+ * specified detail message.
+ * @since JDK1.1
+ */
+ public AlreadyBoundException() {
+ super();
+ }
+
+ /**
+ * Constructs an <code>AlreadyBoundException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message
+ * @since JDK1.1
+ */
+ public AlreadyBoundException(String s) {
+ super(s);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/ConnectException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/ConnectException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/ConnectException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,63 @@
+/*
+ * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.rmi;
+
+/**
+ * A <code>ConnectException</code> is thrown if a connection is refused
+ * to the remote host for a remote method call.
+ *
+ * @version 1.20, 05/05/07
+ * @author Ann Wollrath
+ * @since JDK1.1
+ */
+public class ConnectException extends RemoteException {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = 4863550261346652506L;
+
+ /**
+ * Constructs a <code>ConnectException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message
+ * @since JDK1.1
+ */
+ public ConnectException(String s) {
+ super(s);
+ }
+
+ /**
+ * Constructs a <code>ConnectException</code> with the specified
+ * detail message and nested exception.
+ *
+ * @param s the detail message
+ * @param ex the nested exception
+ * @since JDK1.1
+ */
+ public ConnectException(String s, Exception ex) {
+ super(s, ex);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/ConnectIOException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/ConnectIOException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/ConnectIOException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,65 @@
+/*
+ * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.rmi;
+
+/**
+ * A <code>ConnectIOException</code> is thrown if an
+ * <code>IOException</code> occurs while making a connection
+ * to the remote host for a remote method call.
+ *
+ * @version 1.19, 05/05/07
+ * @author Ann Wollrath
+ * @since JDK1.1
+ */
+public class ConnectIOException extends RemoteException {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = -8087809532704668744L;
+
+ /**
+ * Constructs a <code>ConnectIOException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message
+ * @since JDK1.1
+ */
+ public ConnectIOException(String s) {
+ super(s);
+ }
+
+
+ /**
+ * Constructs a <code>ConnectIOException</code> with the specified
+ * detail message and nested exception.
+ *
+ * @param s the detail message
+ * @param ex the nested exception
+ * @since JDK1.1
+ */
+ public ConnectIOException(String s, Exception ex) {
+ super(s, ex);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/MarshalException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/MarshalException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/MarshalException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,72 @@
+/*
+ * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.rmi;
+
+/**
+ * A <code>MarshalException</code> is thrown if a
+ * <code>java.io.IOException</code> occurs while marshalling the remote call
+ * header, arguments or return value for a remote method call. A
+ * <code>MarshalException</code> is also thrown if the receiver does not
+ * support the protocol version of the sender.
+ *
+ * <p>If a <code>MarshalException</code> occurs during a remote method call,
+ * the call may or may not have reached the server. If the call did reach the
+ * server, parameters may have been deserialized. A call may not be
+ * retransmitted after a <code>MarshalException</code> and reliably preserve
+ * "at most once" call semantics.
+ *
+ * @version 1.19, 05/05/07
+ * @author Ann Wollrath
+ * @since JDK1.1
+ */
+public class MarshalException extends RemoteException {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = 6223554758134037936L;
+
+ /**
+ * Constructs a <code>MarshalException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message
+ * @since JDK1.1
+ */
+ public MarshalException(String s) {
+ super(s);
+ }
+
+ /**
+ * Constructs a <code>MarshalException</code> with the specified
+ * detail message and nested exception.
+ *
+ * @param s the detail message
+ * @param ex the nested exception
+ * @since JDK1.1
+ */
+ public MarshalException(String s, Exception ex) {
+ super(s, ex);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/MarshalledObject.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/MarshalledObject.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/MarshalledObject.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,317 @@
+/*
+ * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.rmi;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamConstants;
+import java.io.OutputStream;
+import java.io.Serializable;
+import sun.rmi.server.MarshalInputStream;
+import sun.rmi.server.MarshalOutputStream;
+
+/**
+ * A <code>MarshalledObject</code> contains a byte stream with the serialized
+ * representation of an object given to its constructor. The <code>get</code>
+ * method returns a new copy of the original object, as deserialized from
+ * the contained byte stream. The contained object is serialized and
+ * deserialized with the same serialization semantics used for marshaling
+ * and unmarshaling parameters and return values of RMI calls: When the
+ * serialized form is created:
+ *
+ * <ul>
+ * <li> classes are annotated with a codebase URL from where the class
+ * can be loaded (if available), and
+ * <li> any remote object in the <code>MarshalledObject</code> is
+ * represented by a serialized instance of its stub.
+ * </ul>
+ *
+ * <p>When copy of the object is retrieved (via the <code>get</code> method),
+ * if the class is not available locally, it will be loaded from the
+ * appropriate location (specified the URL annotated with the class descriptor
+ * when the class was serialized.
+ *
+ * <p><code>MarshalledObject</code> facilitates passing objects in RMI calls
+ * that are not automatically deserialized immediately by the remote peer.
+ *
+ * @param <T> the type of the object contained in this
+ * <code>MarshalledObject</code>
+ *
+ * @version 1.41, 05/05/07
+ * @author Ann Wollrath
+ * @author Peter Jones
+ * @since 1.2
+ */
+public final class MarshalledObject<T> implements Serializable {
+ /**
+ * @serial Bytes of serialized representation. If <code>objBytes</code> is
+ * <code>null</code> then the object marshalled was a <code>null</code>
+ * reference.
+ */
+ private byte[] objBytes = null;
+
+ /**
+ * @serial Bytes of location annotations, which are ignored by
+ * <code>equals</code>. If <code>locBytes</code> is null, there were no
+ * non-<code>null</code> annotations during marshalling.
+ */
+ private byte[] locBytes = null;
+
+ /**
+ * @serial Stored hash code of contained object.
+ *
+ * @see #hashCode
+ */
+ private int hash;
+
+ /** Indicate compatibility with 1.2 version of class. */
+ private static final long serialVersionUID = 8988374069173025854L;
+
+ /**
+ * Creates a new <code>MarshalledObject</code> that contains the
+ * serialized representation of the current state of the supplied object.
+ * The object is serialized with the semantics used for marshaling
+ * parameters for RMI calls.
+ *
+ * @param obj the object to be serialized (must be serializable)
+ * @exception IOException if an <code>IOException</code> occurs; an
+ * <code>IOException</code> may occur if <code>obj</code> is not
+ * serializable.
+ * @since 1.2
+ */
+ public MarshalledObject(T obj) throws IOException {
+ if (obj == null) {
+ hash = 13;
+ return;
+ }
+
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ ByteArrayOutputStream lout = new ByteArrayOutputStream();
+ MarshalledObjectOutputStream out =
+ new MarshalledObjectOutputStream(bout, lout);
+ out.writeObject(obj);
+ out.flush();
+ objBytes = bout.toByteArray();
+ // locBytes is null if no annotations
+ locBytes = (out.hadAnnotations() ? lout.toByteArray() : null);
+
+ /*
+ * Calculate hash from the marshalled representation of object
+ * so the hashcode will be comparable when sent between VMs.
+ */
+ int h = 0;
+ for (int i = 0; i < objBytes.length; i++) {
+ h = 31 * h + objBytes[i];
+ }
+ hash = h;
+ }
+
+ /**
+ * Returns a new copy of the contained marshalledobject. The internal
+ * representation is deserialized with the semantics used for
+ * unmarshaling paramters for RMI calls.
+ *
+ * @return a copy of the contained object
+ * @exception IOException if an <code>IOException</code> occurs while
+ * deserializing the object from its internal representation.
+ * @exception ClassNotFoundException if a
+ * <code>ClassNotFoundException</code> occurs while deserializing the
+ * object from its internal representation.
+ * could not be found
+ * @since 1.2
+ */
+ public T get() throws IOException, ClassNotFoundException {
+ if (objBytes == null) // must have been a null object
+ return null;
+
+ ByteArrayInputStream bin = new ByteArrayInputStream(objBytes);
+ // locBytes is null if no annotations
+ ByteArrayInputStream lin =
+ (locBytes == null ? null : new ByteArrayInputStream(locBytes));
+ MarshalledObjectInputStream in =
+ new MarshalledObjectInputStream(bin, lin);
+ T obj = (T) in.readObject();
+ in.close();
+ return obj;
+ }
+
+ /**
+ * Return a hash code for this <code>MarshalledObject</code>.
+ *
+ * @return a hash code
+ */
+ public int hashCode() {
+ return hash;
+ }
+
+ /**
+ * Compares this <code>MarshalledObject</code> to another object.
+ * Returns true if and only if the argument refers to a
+ * <code>MarshalledObject</code> that contains exactly the same
+ * serialized representation of an object as this one does. The
+ * comparison ignores any class codebase annotation, meaning that
+ * two objects are equivalent if they have the same serialized
+ * representation <i>except</i> for the codebase of each class
+ * in the serialized representation.
+ *
+ * @param obj the object to compare with this <code>MarshalledObject</code>
+ * @return <code>true</code> if the argument contains an equaivalent
+ * serialized object; <code>false</code> otherwise
+ * @since 1.2
+ */
+ public boolean equals(Object obj) {
+ if (obj == this)
+ return true;
+
+ if (obj != null && obj instanceof MarshalledObject) {
+ MarshalledObject other = (MarshalledObject) obj;
+
+ // if either is a ref to null, both must be
+ if (objBytes == null || other.objBytes == null)
+ return objBytes == other.objBytes;
+
+ // quick, easy test
+ if (objBytes.length != other.objBytes.length)
+ return false;
+
+ //!! There is talk about adding an array comparision method
+ //!! at 1.2 -- if so, this should be rewritten. -arnold
+ for (int i = 0; i < objBytes.length; ++i) {
+ if (objBytes[i] != other.objBytes[i])
+ return false;
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * This class is used to marshal objects for
+ * <code>MarshalledObject</code>. It places the location annotations
+ * to one side so that two <code>MarshalledObject</code>s can be
+ * compared for equality if they differ only in location
+ * annotations. Objects written using this stream should be read back
+ * from a <code>MarshalledObjectInputStream</code>.
+ *
+ * @see java.rmi.MarshalledObject
+ * @see MarshalledObjectInputStream
+ */
+ private static class MarshalledObjectOutputStream
+ extends MarshalOutputStream
+ {
+ /** The stream on which location objects are written. */
+ private ObjectOutputStream locOut;
+
+ /** <code>true</code> if non-<code>null</code> annotations are
+ * written.
+ */
+ private boolean hadAnnotations;
+
+ /**
+ * Creates a new <code>MarshalledObjectOutputStream</code> whose
+ * non-location bytes will be written to <code>objOut</code> and whose
+ * location annotations (if any) will be written to
+ * <code>locOut</code>.
+ */
+ MarshalledObjectOutputStream(OutputStream objOut, OutputStream locOut)
+ throws IOException
+ {
+ super(objOut);
+ this.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2);
+ this.locOut = new ObjectOutputStream(locOut);
+ hadAnnotations = false;
+ }
+
+ /**
+ * Returns <code>true</code> if any non-<code>null</code> location
+ * annotations have been written to this stream.
+ */
+ boolean hadAnnotations() {
+ return hadAnnotations;
+ }
+
+ /**
+ * Overrides MarshalOutputStream.writeLocation implementation to write
+ * annotations to the location stream.
+ */
+ protected void writeLocation(String loc) throws IOException {
+ hadAnnotations |= (loc != null);
+ locOut.writeObject(loc);
+ }
+
+
+ public void flush() throws IOException {
+ super.flush();
+ locOut.flush();
+ }
+ }
+
+ /**
+ * The counterpart to <code>MarshalledObjectOutputStream</code>.
+ *
+ * @see MarshalledObjectOutputStream
+ */
+ private static class MarshalledObjectInputStream
+ extends MarshalInputStream
+ {
+ /**
+ * The stream from which annotations will be read. If this is
+ * <code>null</code>, then all annotations were <code>null</code>.
+ */
+ private ObjectInputStream locIn;
+
+ /**
+ * Creates a new <code>MarshalledObjectInputStream</code> that
+ * reads its objects from <code>objIn</code> and annotations
+ * from <code>locIn</code>. If <code>locIn</code> is
+ * <code>null</code>, then all annotations will be
+ * <code>null</code>.
+ */
+ MarshalledObjectInputStream(InputStream objIn, InputStream locIn)
+ throws IOException
+ {
+ super(objIn);
+ this.locIn = (locIn == null ? null : new ObjectInputStream(locIn));
+ }
+
+ /**
+ * Overrides MarshalInputStream.readLocation to return locations from
+ * the stream we were given, or <code>null</code> if we were given a
+ * <code>null</code> location stream.
+ */
+ protected Object readLocation()
+ throws IOException, ClassNotFoundException
+ {
+ return (locIn == null ? null : locIn.readObject());
+ }
+ }
+
+}
Added: trunk/core/src/openjdk/java/java/rmi/Naming.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/Naming.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/Naming.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,357 @@
+/*
+ * Copyright 1996-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package java.rmi;
+
+import java.rmi.registry.*;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+/**
+ * The <code>Naming</code> class provides methods for storing and obtaining
+ * references to remote objects in a remote object registry. Each method of
+ * the <code>Naming</code> class takes as one of its arguments a name that
+ * is a <code>java.lang.String</code> in URL format (without the
+ * scheme component) of the form:
+ *
+ * <PRE>
+ * //host:port/name
+ * </PRE>
+ *
+ * <P>where <code>host</code> is the host (remote or local) where the registry
+ * is located, <code>port</code> is the port number on which the registry
+ * accepts calls, and where <code>name</code> is a simple string uninterpreted
+ * by the registry. Both <code>host</code> and <code>port</code> are optional.
+ * If <code>host</code> is omitted, the host defaults to the local host. If
+ * <code>port</code> is omitted, then the port defaults to 1099, the
+ * "well-known" port that RMI's registry, <code>rmiregistry</code>, uses.
+ *
+ * <P><em>Binding</em> a name for a remote object is associating or
+ * registering a name for a remote object that can be used at a later time to
+ * look up that remote object. A remote object can be associated with a name
+ * using the <code>Naming</code> class's <code>bind</code> or
+ * <code>rebind</code> methods.
+ *
+ * <P>Once a remote object is registered (bound) with the RMI registry on the
+ * local host, callers on a remote (or local) host can lookup the remote
+ * object by name, obtain its reference, and then invoke remote methods on the
+ * object. A registry may be shared by all servers running on a host or an
+ * individual server process may create and use its own registry if desired
+ * (see <code>java.rmi.registry.LocateRegistry.createRegistry</code> method
+ * for details).
+ *
+ * @version 1.13, 09/05/99
+ * @author Ann Wollrath
+ * @author Roger Riggs
+ * @since JDK1.1
+ * @see java.rmi.registry.Registry
+ * @see java.rmi.registry.LocateRegistry
+ * @see java.rmi.registry.LocateRegistry#createRegistry(int)
+ */
+public final class Naming {
+ /**
+ * Disallow anyone from creating one of these
+ */
+ private Naming() {}
+
+ /**
+ * Returns a reference, a stub, for the remote object associated
+ * with the specified <code>name</code>.
+ *
+ * @param name a name in URL format (without the scheme component)
+ * @return a reference for a remote object
+ * @exception NotBoundException if name is not currently bound
+ * @exception RemoteException if registry could not be contacted
+ * @exception AccessException if this operation is not permitted
+ * @exception MalformedURLException if the name is not an appropriately
+ * formatted URL
+ * @since JDK1.1
+ */
+ public static Remote lookup(String name)
+ throws NotBoundException,
+ java.net.MalformedURLException,
+ RemoteException
+ {
+ ParsedNamingURL parsed = parseURL(name);
+ Registry registry = getRegistry(parsed);
+
+ if (parsed.name == null)
+ return registry;
+ return registry.lookup(parsed.name);
+ }
+
+ /**
+ * Binds the specified <code>name</code> to a remote object.
+ *
+ * @param name a name in URL format (without the scheme component)
+ * @param obj a reference for the remote object (usually a stub)
+ * @exception AlreadyBoundException if name is already bound
+ * @exception MalformedURLException if the name is not an appropriately
+ * formatted URL
+ * @exception RemoteException if registry could not be contacted
+ * @exception AccessException if this operation is not permitted (if
+ * originating from a non-local host, for example)
+ * @since JDK1.1
+ */
+ public static void bind(String name, Remote obj)
+ throws AlreadyBoundException,
+ java.net.MalformedURLException,
+ RemoteException
+ {
+ ParsedNamingURL parsed = parseURL(name);
+ Registry registry = getRegistry(parsed);
+
+ if (obj == null)
+ throw new NullPointerException("cannot bind to null");
+
+ registry.bind(parsed.name, obj);
+ }
+
+ /**
+ * Destroys the binding for the specified name that is associated
+ * with a remote object.
+ *
+ * @param name a name in URL format (without the scheme component)
+ * @exception NotBoundException if name is not currently bound
+ * @exception MalformedURLException if the name is not an appropriately
+ * formatted URL
+ * @exception RemoteException if registry could not be contacted
+ * @exception AccessException if this operation is not permitted (if
+ * originating from a non-local host, for example)
+ * @since JDK1.1
+ */
+ public static void unbind(String name)
+ throws RemoteException,
+ NotBoundException,
+ java.net.MalformedURLException
+ {
+ ParsedNamingURL parsed = parseURL(name);
+ Registry registry = getRegistry(parsed);
+
+ registry.unbind(parsed.name);
+ }
+
+ /**
+ * Rebinds the specified name to a new remote object. Any existing
+ * binding for the name is replaced.
+ *
+ * @param name a name in URL format (without the scheme component)
+ * @param obj new remote object to associate with the name
+ * @exception MalformedURLException if the name is not an appropriately
+ * formatted URL
+ * @exception RemoteException if registry could not be contacted
+ * @exception AccessException if this operation is not permitted (if
+ * originating from a non-local host, for example)
+ * @since JDK1.1
+ */
+ public static void rebind(String name, Remote obj)
+ throws RemoteException, java.net.MalformedURLException
+ {
+ ParsedNamingURL parsed = parseURL(name);
+ Registry registry = getRegistry(parsed);
+
+ if (obj == null)
+ throw new NullPointerException("cannot bind to null");
+
+ registry.rebind(parsed.name, obj);
+ }
+
+ /**
+ * Returns an array of the names bound in the registry. The names are
+ * URL-formatted (without the scheme component) strings. The array contains
+ * a snapshot of the names present in the registry at the time of the
+ * call.
+ *
+ * @param name a registry name in URL format (without the scheme
+ * component)
+ * @return an array of names (in the appropriate format) bound
+ * in the registry
+ * @exception MalformedURLException if the name is not an appropriately
+ * formatted URL
+ * @exception RemoteException if registry could not be contacted.
+ * @since JDK1.1
+ */
+ public static String[] list(String name)
+ throws RemoteException, java.net.MalformedURLException
+ {
+ ParsedNamingURL parsed = parseURL(name);
+ Registry registry = getRegistry(parsed);
+
+ String prefix = "";
+ if (parsed.port > 0 || !parsed.host.equals(""))
+ prefix += "//" + parsed.host;
+ if (parsed.port > 0)
+ prefix += ":" + parsed.port;
+ prefix += "/";
+
+ String[] names = registry.list();
+ for (int i = 0; i < names.length; i++) {
+ names[i] = prefix + names[i];
+ }
+ return names;
+ }
+
+ /**
+ * Returns a registry reference obtained from information in the URL.
+ */
+ private static Registry getRegistry(ParsedNamingURL parsed)
+ throws RemoteException
+ {
+ return LocateRegistry.getRegistry(parsed.host, parsed.port);
+ }
+
+ /**
+ * Dissect Naming URL strings to obtain referenced host, port and
+ * object name.
+ *
+ * @return an object which contains each of the above
+ * components.
+ *
+ * @exception MalformedURLException if given url string is malformed
+ */
+ private static ParsedNamingURL parseURL(String str)
+ throws MalformedURLException
+ {
+ try {
+ return intParseURL(str);
+ } catch (URISyntaxException ex) {
+ /* With RFC 3986 URI handling, 'rmi://:<port>' and
+ * '//:<port>' forms will result in a URI syntax exception
+ * Convert the authority to a localhost:<port> form
+ */
+ MalformedURLException mue = new MalformedURLException(
+ "invalid URL String: " + str);
+ mue.initCause(ex);
+ int indexSchemeEnd = str.indexOf(':');
+ int indexAuthorityBegin = str.indexOf("//:");
+ if (indexAuthorityBegin < 0) {
+ throw mue;
+ }
+ if ((indexAuthorityBegin == 0) ||
+ ((indexSchemeEnd > 0) &&
+ (indexAuthorityBegin == indexSchemeEnd + 1))) {
+ int indexHostBegin = indexAuthorityBegin + 2;
+ String newStr = str.substring(0, indexHostBegin) +
+ "localhost" +
+ str.substring(indexHostBegin);
+ try {
+ return intParseURL(newStr);
+ } catch (URISyntaxException inte) {
+ throw mue;
+ } catch (MalformedURLException inte) {
+ throw inte;
+ }
+ }
+ throw mue;
+ }
+ }
+
+ private static ParsedNamingURL intParseURL(String str)
+ throws MalformedURLException, URISyntaxException
+ {
+ URI uri = new URI(str);
+ if (uri.isOpaque()) {
+ throw new MalformedURLException(
+ "not a hierarchical URL: " + str);
+ }
+ if (uri.getFragment() != null) {
+ throw new MalformedURLException(
+ "invalid character, '#', in URL name: " + str);
+ } else if (uri.getQuery() != null) {
+ throw new MalformedURLException(
+ "invalid character, '?', in URL name: " + str);
+ } else if (uri.getUserInfo() != null) {
+ throw new MalformedURLException(
+ "invalid character, '@', in URL host: " + str);
+ }
+ String scheme = uri.getScheme();
+ if (scheme != null && !scheme.equals("rmi")) {
+ throw new MalformedURLException("invalid URL scheme: " + str);
+ }
+
+ String name = uri.getPath();
+ if (name != null) {
+ if (name.startsWith("/")) {
+ name = name.substring(1);
+ }
+ if (name.length() == 0) {
+ name = null;
+ }
+ }
+
+ String host = uri.getHost();
+ if (host == null) {
+ host = "";
+ try {
+ /*
+ * With 2396 URI handling, forms such as 'rmi://host:bar'
+ * or 'rmi://:<port>' are parsed into a registry based
+ * authority. We only want to allow server based naming
+ * authorities.
+ */
+ uri.parseServerAuthority();
+ } catch (URISyntaxException use) {
+ // Check if the authority is of form ':<port>'
+ String authority = uri.getAuthority();
+ if (authority != null && authority.startsWith(":")) {
+ // Convert the authority to 'localhost:<port>' form
+ authority = "localhost" + authority;
+ try {
+ uri = new URI(null, authority, null, null, null);
+ // Make sure it now parses to a valid server based
+ // naming authority
+ uri.parseServerAuthority();
+ } catch (URISyntaxException use2) {
+ throw new
+ MalformedURLException("invalid authority: " + str);
+ }
+ } else {
+ throw new
+ MalformedURLException("invalid authority: " + str);
+ }
+ }
+ }
+ int port = uri.getPort();
+ if (port == -1) {
+ port = Registry.REGISTRY_PORT;
+ }
+ return new ParsedNamingURL(host, port, name);
+ }
+
+ /**
+ * Simple class to enable multiple URL return values.
+ */
+ private static class ParsedNamingURL {
+ String host;
+ int port;
+ String name;
+
+ ParsedNamingURL(String host, int port, String name) {
+ this.host = host;
+ this.port = port;
+ this.name = name;
+ }
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/NoSuchObjectException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/NoSuchObjectException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/NoSuchObjectException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,63 @@
+/*
+ * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.rmi;
+
+/**
+ * A <code>NoSuchObjectException</code> is thrown if an attempt is made to
+ * invoke a method on an object that no longer exists in the remote virtual
+ * machine. If a <code>NoSuchObjectException</code> occurs attempting to
+ * invoke a method on a remote object, the call may be retransmitted and still
+ * preserve RMI's "at most once" call semantics.
+ *
+ * A <code>NoSuchObjectException</code> is also thrown by the method
+ * <code>java.rmi.server.RemoteObject.toStub</code> and by the
+ * <code>unexportObject</code> methods of
+ * <code>java.rmi.server.UnicastRemoteObject</code> and
+ * <code>java.rmi.activation.Activatable</code> and
+ *
+ * @version 1.19, 05/05/07
+ * @author Ann Wollrath
+ * @since JDK1.1
+ * @see java.rmi.server.RemoteObject#toStub(Remote)
+ * @see java.rmi.server.UnicastRemoteObject#unexportObject(Remote,boolean)
+ * @see java.rmi.activation.Activatable#unexportObject(Remote,boolean)
+ */
+public class NoSuchObjectException extends RemoteException {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = 6619395951570472985L;
+
+ /**
+ * Constructs a <code>NoSuchObjectException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message
+ * @since JDK1.1
+ */
+ public NoSuchObjectException(String s) {
+ super(s);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/NotBoundException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/NotBoundException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/NotBoundException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,65 @@
+/*
+ * Copyright 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package java.rmi;
+
+/**
+ * A <code>NotBoundException</code> is thrown if an attempt
+ * is made to lookup or unbind in the registry a name that has
+ * no associated binding.
+ *
+ * @version 1.19, 05/05/07
+ * @since JDK1.1
+ * @author Ann Wollrath
+ * @author Roger Riggs
+ * @see java.rmi.Naming#lookup(String)
+ * @see java.rmi.Naming#unbind(String)
+ * @see java.rmi.registry.Registry#lookup(String)
+ * @see java.rmi.registry.Registry#unbind(String)
+ */
+public class NotBoundException extends java.lang.Exception {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = -1857741824849069317L;
+
+ /**
+ * Constructs a <code>NotBoundException</code> with no
+ * specified detail message.
+ * @since JDK1.1
+ */
+ public NotBoundException() {
+ super();
+ }
+
+ /**
+ * Constructs a <code>NotBoundException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message
+ * @since JDK1.1
+ */
+ public NotBoundException(String s) {
+ super(s);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/RMISecurityException.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/RMISecurityException.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/RMISecurityException.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,68 @@
+/*
+ * Copyright 1996-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+package java.rmi;
+
+/**
+ * An <code>RMISecurityException</code> signals that a security exception
+ * has occurred during the execution of one of
+ * <code>java.rmi.RMISecurityManager</code>'s methods.
+ *
+ * @version 1.23, 05/05/07
+ * @author Roger Riggs
+ * @since JDK1.1
+ * @deprecated Use {@link java.lang.SecurityException} instead.
+ * Application code should never directly reference this class, and
+ * <code>RMISecurityManager</code> no longer throws this subclass of
+ * <code>java.lang.SecurityException</code>.
+ */
+@Deprecated
+public class RMISecurityException extends java.lang.SecurityException {
+
+ /* indicate compatibility with JDK 1.1.x version of class */
+ private static final long serialVersionUID = -8433406075740433514L;
+
+ /**
+ * Construct an <code>RMISecurityException</code> with a detail message.
+ * @param name the detail message
+ * @since JDK1.1
+ * @deprecated no replacement
+ */
+ @Deprecated
+ public RMISecurityException(String name) {
+ super(name);
+ }
+
+ /**
+ * Construct an <code>RMISecurityException</code> with a detail message.
+ * @param name the detail message
+ * @param arg ignored
+ * @since JDK1.1
+ * @deprecated no replacement
+ */
+ @Deprecated
+ public RMISecurityException(String name, String arg) {
+ this(name);
+ }
+}
Added: trunk/core/src/openjdk/java/java/rmi/RMISecurityManager.java
===================================================================
--- trunk/core/src/openjdk/java/java/rmi/RMISecurityManager.java (rev 0)
+++ trunk/core/src/openjdk/java/java/rmi/RMISecurityManager.java 2007-06-17 10:09:41 UTC (rev 3274)
@@ -0,0 +1,65 @@
+/*
+ * Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.rmi;
+
+import java.security.*;
+
+/**
+ * A subclass of {@link SecurityManager} used by RMI applications that use
+ * downloaded code. RMI's class loader will not download an...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-17 10:07:06
|
Revision: 3273
http://jnode.svn.sourceforge.net/jnode/?rev=3273&view=rev
Author: lsantha
Date: 2007-06-17 03:07:05 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Removed Paths:
-------------
trunk/core/src/classpath/java/java/rmi/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-17 10:06:24
|
Revision: 3272
http://jnode.svn.sourceforge.net/jnode/?rev=3272&view=rev
Author: lsantha
Date: 2007-06-17 03:06:23 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Improved Java 5 language support.
Modified Paths:
--------------
trunk/core/src/classpath/vm/java/lang/Class.java
Modified: trunk/core/src/classpath/vm/java/lang/Class.java
===================================================================
--- trunk/core/src/classpath/vm/java/lang/Class.java 2007-06-17 09:07:11 UTC (rev 3271)
+++ trunk/core/src/classpath/vm/java/lang/Class.java 2007-06-17 10:06:23 UTC (rev 3272)
@@ -803,7 +803,7 @@
return null;
}
- public Constructor getDeclaredConstructor(Class[] argTypes)
+ public Constructor<T> getDeclaredConstructor(Class<?>... argTypes)
throws NoSuchMethodException {
String signature = Signature.toSignature(null, argTypes);
final VmMethod vmMethod = getLinkedVmClass().getDeclaredMethod(
@@ -925,7 +925,7 @@
* @return Constructor
* @throws NoSuchMethodException
*/
- public Constructor getConstructor(Class[] argTypes)
+ public Constructor<T> getConstructor(Class<?>... argTypes)
throws NoSuchMethodException {
// Check security
memberAccessCheck(Member.PUBLIC);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ls...@us...> - 2007-06-17 09:07:17
|
Revision: 3271
http://jnode.svn.sourceforge.net/jnode/?rev=3271&view=rev
Author: lsantha
Date: 2007-06-17 02:07:11 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Added Paths:
-----------
trunk/core/src/openjdk/com/com/sun/activation/
trunk/core/src/openjdk/com/com/sun/activation/registries/
trunk/core/src/openjdk/com/com/sun/activation/registries/LogSupport.java
trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapFile.java
trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapParseException.java
trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapTokenizer.java
trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeEntry.java
trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeFile.java
trunk/core/src/openjdk/javax/javax/activation/
trunk/core/src/openjdk/javax/javax/activation/ActivationDataFlavor.java
trunk/core/src/openjdk/javax/javax/activation/CommandInfo.java
trunk/core/src/openjdk/javax/javax/activation/CommandMap.java
trunk/core/src/openjdk/javax/javax/activation/CommandObject.java
trunk/core/src/openjdk/javax/javax/activation/DataContentHandler.java
trunk/core/src/openjdk/javax/javax/activation/DataContentHandlerFactory.java
trunk/core/src/openjdk/javax/javax/activation/DataHandler.java
trunk/core/src/openjdk/javax/javax/activation/DataSource.java
trunk/core/src/openjdk/javax/javax/activation/FileDataSource.java
trunk/core/src/openjdk/javax/javax/activation/FileTypeMap.java
trunk/core/src/openjdk/javax/javax/activation/MailcapCommandMap.java
trunk/core/src/openjdk/javax/javax/activation/MimeType.java
trunk/core/src/openjdk/javax/javax/activation/MimeTypeParameterList.java
trunk/core/src/openjdk/javax/javax/activation/MimeTypeParseException.java
trunk/core/src/openjdk/javax/javax/activation/MimetypesFileTypeMap.java
trunk/core/src/openjdk/javax/javax/activation/SecuritySupport.java
trunk/core/src/openjdk/javax/javax/activation/URLDataSource.java
trunk/core/src/openjdk/javax/javax/activation/UnsupportedDataTypeException.java
trunk/core/src/openjdk/javax/javax/activity/
trunk/core/src/openjdk/javax/javax/activity/ActivityCompletedException.java
trunk/core/src/openjdk/javax/javax/activity/ActivityRequiredException.java
trunk/core/src/openjdk/javax/javax/activity/InvalidActivityException.java
trunk/core/src/openjdk/javax/javax/activity/package.html
trunk/core/src/openjdk/javax/javax/jws/
trunk/core/src/openjdk/javax/javax/jws/HandlerChain.java
trunk/core/src/openjdk/javax/javax/jws/Oneway.java
trunk/core/src/openjdk/javax/javax/jws/WebMethod.java
trunk/core/src/openjdk/javax/javax/jws/WebParam.java
trunk/core/src/openjdk/javax/javax/jws/WebResult.java
trunk/core/src/openjdk/javax/javax/jws/WebService.java
trunk/core/src/openjdk/javax/javax/jws/soap/
trunk/core/src/openjdk/javax/javax/jws/soap/InitParam.java
trunk/core/src/openjdk/javax/javax/jws/soap/SOAPBinding.java
trunk/core/src/openjdk/javax/javax/jws/soap/SOAPMessageHandler.java
trunk/core/src/openjdk/javax/javax/jws/soap/SOAPMessageHandlers.java
Added: trunk/core/src/openjdk/com/com/sun/activation/registries/LogSupport.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/activation/registries/LogSupport.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/activation/registries/LogSupport.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.activation.registries;
+
+import java.io.*;
+import java.util.logging.*;
+
+/**
+ * Logging related methods.
+ */
+public class LogSupport {
+ private static boolean debug = false;
+ private static Logger logger;
+ private static final Level level = Level.FINE;
+
+ static {
+ try {
+ debug = Boolean.getBoolean("javax.activation.debug");
+ } catch (Throwable t) {
+ // ignore any errors
+ }
+ logger = Logger.getLogger("javax.activation");
+ }
+
+ /**
+ * Constructor.
+ */
+ private LogSupport() {
+ // private constructor, can't create instances
+ }
+
+ public static void log(String msg) {
+ if (debug)
+ System.out.println(msg);
+ logger.log(level, msg);
+ }
+
+ public static void log(String msg, Throwable t) {
+ if (debug)
+ System.out.println(msg + "; Exception: " + t);
+ logger.log(level, msg, t);
+ }
+
+ public static boolean isLoggable() {
+ return debug || logger.isLoggable(level);
+ }
+}
Added: trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapFile.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapFile.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapFile.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,560 @@
+/*
+ * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.activation.registries;
+
+import java.io.*;
+import java.util.*;
+
+public class MailcapFile {
+
+ /**
+ * A Map indexed by MIME type (string) that references
+ * a Map of commands for each type. The comand Map
+ * is indexed by the command name and references a List of
+ * class names (strings) for each command.
+ */
+ private Map type_hash = new HashMap();
+
+ /**
+ * Another Map like above, but for fallback entries.
+ */
+ private Map fallback_hash = new HashMap();
+
+ /**
+ * A Map indexed by MIME type (string) that references
+ * a List of native commands (string) corresponding to the type.
+ */
+ private Map native_commands = new HashMap();
+
+ private static boolean addReverse = false;
+
+ static {
+ try {
+ addReverse = Boolean.getBoolean("javax.activation.addreverse");
+ } catch (Throwable t) {
+ // ignore any errors
+ }
+ }
+
+ /**
+ * The constructor that takes a filename as an argument.
+ *
+ * @param new_fname The file name of the mailcap file.
+ */
+ public MailcapFile(String new_fname) throws IOException {
+ if (LogSupport.isLoggable())
+ LogSupport.log("new MailcapFile: file " + new_fname);
+ FileReader reader = null;
+ try {
+ reader = new FileReader(new_fname);
+ parse(new BufferedReader(reader));
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException ex) { }
+ }
+ }
+ }
+
+ /**
+ * The constructor that takes an input stream as an argument.
+ *
+ * @param is the input stream
+ */
+ public MailcapFile(InputStream is) throws IOException {
+ if (LogSupport.isLoggable())
+ LogSupport.log("new MailcapFile: InputStream");
+ parse(new BufferedReader(new InputStreamReader(is, "iso-8859-1")));
+ }
+
+ /**
+ * Mailcap file default constructor.
+ */
+ public MailcapFile() {
+ if (LogSupport.isLoggable())
+ LogSupport.log("new MailcapFile: default");
+ }
+
+ /**
+ * Get the Map of MailcapEntries based on the MIME type.
+ *
+ * <p>
+ * <strong>Semantics:</strong> First check for the literal mime type,
+ * if that fails looks for wildcard <type>/\* and return that. Return the
+ * list of all that hit.
+ */
+ public Map getMailcapList(String mime_type) {
+ Map search_result = null;
+ Map wildcard_result = null;
+
+ // first try the literal
+ search_result = (Map)type_hash.get(mime_type);
+
+ // ok, now try the wildcard
+ int separator = mime_type.indexOf('/');
+ String subtype = mime_type.substring(separator + 1);
+ if (!subtype.equals("*")) {
+ String type = mime_type.substring(0, separator + 1) + "*";
+ wildcard_result = (Map)type_hash.get(type);
+
+ if (wildcard_result != null) { // damn, we have to merge!!!
+ if (search_result != null)
+ search_result =
+ mergeResults(search_result, wildcard_result);
+ else
+ search_result = wildcard_result;
+ }
+ }
+ return search_result;
+ }
+
+ /**
+ * Get the Map of fallback MailcapEntries based on the MIME type.
+ *
+ * <p>
+ * <strong>Semantics:</strong> First check for the literal mime type,
+ * if that fails looks for wildcard <type>/\* and return that. Return the
+ * list of all that hit.
+ */
+ public Map getMailcapFallbackList(String mime_type) {
+ Map search_result = null;
+ Map wildcard_result = null;
+
+ // first try the literal
+ search_result = (Map)fallback_hash.get(mime_type);
+
+ // ok, now try the wildcard
+ int separator = mime_type.indexOf('/');
+ String subtype = mime_type.substring(separator + 1);
+ if (!subtype.equals("*")) {
+ String type = mime_type.substring(0, separator + 1) + "*";
+ wildcard_result = (Map)fallback_hash.get(type);
+
+ if (wildcard_result != null) { // damn, we have to merge!!!
+ if (search_result != null)
+ search_result =
+ mergeResults(search_result, wildcard_result);
+ else
+ search_result = wildcard_result;
+ }
+ }
+ return search_result;
+ }
+
+ /**
+ * Return all the MIME types known to this mailcap file.
+ */
+ public String[] getMimeTypes() {
+ Set types = new HashSet(type_hash.keySet());
+ types.addAll(fallback_hash.keySet());
+ types.addAll(native_commands.keySet());
+ String[] mts = new String[types.size()];
+ mts = (String[])types.toArray(mts);
+ return mts;
+ }
+
+ /**
+ * Return all the native comands for the given MIME type.
+ */
+ public String[] getNativeCommands(String mime_type) {
+ String[] cmds = null;
+ List v = (List)native_commands.get(mime_type.toLowerCase());
+ if (v != null) {
+ cmds = new String[v.size()];
+ cmds = (String[])v.toArray(cmds);
+ }
+ return cmds;
+ }
+
+ /**
+ * Merge the first hash into the second.
+ * This merge will only effect the hashtable that is
+ * returned, we don't want to touch the one passed in since
+ * its integrity must be maintained.
+ */
+ private Map mergeResults(Map first, Map second) {
+ Iterator verb_enum = second.keySet().iterator();
+ Map clonedHash = new HashMap(first);
+
+ // iterate through the verbs in the second map
+ while (verb_enum.hasNext()) {
+ String verb = (String)verb_enum.next();
+ List cmdVector = (List)clonedHash.get(verb);
+ if (cmdVector == null) {
+ clonedHash.put(verb, second.get(verb));
+ } else {
+ // merge the two
+ List oldV = (List)second.get(verb);
+ cmdVector = new ArrayList(cmdVector);
+ cmdVector.addAll(oldV);
+ clonedHash.put(verb, cmdVector);
+ }
+ }
+ return clonedHash;
+ }
+
+ /**
+ * appendToMailcap: Append to this Mailcap DB, use the mailcap
+ * format:
+ * Comment == "# <i>comment string</i>
+ * Entry == "mimetype; javabeanclass<nl>
+ *
+ * Example:
+ * # this is a comment
+ * image/gif jaf.viewers.ImageViewer
+ */
+ public void appendToMailcap(String mail_cap) {
+ if (LogSupport.isLoggable())
+ LogSupport.log("appendToMailcap: " + mail_cap);
+ try {
+ parse(new StringReader(mail_cap));
+ } catch (IOException ex) {
+ // can't happen
+ }
+ }
+
+ /**
+ * parse file into a hash table of MC Type Entry Obj
+ */
+ private void parse(Reader reader) throws IOException {
+ BufferedReader buf_reader = new BufferedReader(reader);
+ String line = null;
+ String continued = null;
+
+ while ((line = buf_reader.readLine()) != null) {
+ // LogSupport.log("parsing line: " + line);
+
+ line = line.trim();
+
+ try {
+ if (line.charAt(0) == '#')
+ continue;
+ if (line.charAt(line.length() - 1) == '\\') {
+ if (continued != null)
+ continued += line.substring(0, line.length() - 1);
+ else
+ continued = line.substring(0, line.length() - 1);
+ } else if (continued != null) {
+ // handle the two strings
+ continued = continued + line;
+ // LogSupport.log("parse: " + continued);
+ try {
+ parseLine(continued);
+ } catch (MailcapParseException e) {
+ //e.printStackTrace();
+ }
+ continued = null;
+ }
+ else {
+ // LogSupport.log("parse: " + line);
+ try {
+ parseLine(line);
+ // LogSupport.log("hash.size = " + type_hash.size());
+ } catch (MailcapParseException e) {
+ //e.printStackTrace();
+ }
+ }
+ } catch (StringIndexOutOfBoundsException e) {}
+ }
+ }
+
+ /**
+ * A routine to parse individual entries in a Mailcap file.
+ *
+ * Note that this routine does not handle line continuations.
+ * They should have been handled prior to calling this routine.
+ */
+ protected void parseLine(String mailcapEntry)
+ throws MailcapParseException, IOException {
+ MailcapTokenizer tokenizer = new MailcapTokenizer(mailcapEntry);
+ tokenizer.setIsAutoquoting(false);
+
+ if (LogSupport.isLoggable())
+ LogSupport.log("parse: " + mailcapEntry);
+ // parse the primary type
+ int currentToken = tokenizer.nextToken();
+ if (currentToken != MailcapTokenizer.STRING_TOKEN) {
+ reportParseError(MailcapTokenizer.STRING_TOKEN, currentToken,
+ tokenizer.getCurrentTokenValue());
+ }
+ String primaryType = tokenizer.getCurrentTokenValue().toLowerCase();
+ String subType = "*";
+
+ // parse the '/' between primary and sub
+ // if it's not present that's ok, we just don't have a subtype
+ currentToken = tokenizer.nextToken();
+ if ((currentToken != MailcapTokenizer.SLASH_TOKEN) &&
+ (currentToken != MailcapTokenizer.SEMICOLON_TOKEN)) {
+ reportParseError(MailcapTokenizer.SLASH_TOKEN,
+ MailcapTokenizer.SEMICOLON_TOKEN, currentToken,
+ tokenizer.getCurrentTokenValue());
+ }
+
+ // only need to look for a sub type if we got a '/'
+ if (currentToken == MailcapTokenizer.SLASH_TOKEN) {
+ // parse the sub type
+ currentToken = tokenizer.nextToken();
+ if (currentToken != MailcapTokenizer.STRING_TOKEN) {
+ reportParseError(MailcapTokenizer.STRING_TOKEN,
+ currentToken, tokenizer.getCurrentTokenValue());
+ }
+ subType = tokenizer.getCurrentTokenValue().toLowerCase();
+
+ // get the next token to simplify the next step
+ currentToken = tokenizer.nextToken();
+ }
+
+ String mimeType = primaryType + "/" + subType;
+
+ if (LogSupport.isLoggable())
+ LogSupport.log(" Type: " + mimeType);
+
+ // now setup the commands hashtable
+ Map commands = new LinkedHashMap(); // keep commands in order found
+
+ // parse the ';' that separates the type from the parameters
+ if (currentToken != MailcapTokenizer.SEMICOLON_TOKEN) {
+ reportParseError(MailcapTokenizer.SEMICOLON_TOKEN,
+ currentToken, tokenizer.getCurrentTokenValue());
+ }
+ // eat it
+
+ // parse the required view command
+ tokenizer.setIsAutoquoting(true);
+ currentToken = tokenizer.nextToken();
+ tokenizer.setIsAutoquoting(false);
+ if ((currentToken != MailcapTokenizer.STRING_TOKEN) &&
+ (currentToken != MailcapTokenizer.SEMICOLON_TOKEN)) {
+ reportParseError(MailcapTokenizer.STRING_TOKEN,
+ MailcapTokenizer.SEMICOLON_TOKEN, currentToken,
+ tokenizer.getCurrentTokenValue());
+ }
+
+ if (currentToken == MailcapTokenizer.STRING_TOKEN) {
+ // have a native comand, save the entire mailcap entry
+ //String nativeCommand = tokenizer.getCurrentTokenValue();
+ List v = (List)native_commands.get(mimeType);
+ if (v == null) {
+ v = new ArrayList();
+ v.add(mailcapEntry);
+ native_commands.put(mimeType, v);
+ } else {
+ // XXX - check for duplicates?
+ v.add(mailcapEntry);
+ }
+ }
+
+ // only have to get the next token if the current one isn't a ';'
+ if (currentToken != MailcapTokenizer.SEMICOLON_TOKEN) {
+ currentToken = tokenizer.nextToken();
+ }
+
+ // look for a ';' which will indicate whether
+ // a parameter list is present or not
+ if (currentToken == MailcapTokenizer.SEMICOLON_TOKEN) {
+ boolean isFallback = false;
+ do {
+ // eat the ';'
+
+ // parse the parameter name
+ currentToken = tokenizer.nextToken();
+ if (currentToken != MailcapTokenizer.STRING_TOKEN) {
+ reportParseError(MailcapTokenizer.STRING_TOKEN,
+ currentToken, tokenizer.getCurrentTokenValue());
+ }
+ String paramName =
+ tokenizer.getCurrentTokenValue().toLowerCase();
+
+ // parse the '=' which separates the name from the value
+ currentToken = tokenizer.nextToken();
+ if ((currentToken != MailcapTokenizer.EQUALS_TOKEN) &&
+ (currentToken != MailcapTokenizer.SEMICOLON_TOKEN) &&
+ (currentToken != MailcapTokenizer.EOI_TOKEN)) {
+ reportParseError(MailcapTokenizer.EQUALS_TOKEN,
+ MailcapTokenizer.SEMICOLON_TOKEN,
+ MailcapTokenizer.EOI_TOKEN,
+ currentToken, tokenizer.getCurrentTokenValue());
+ }
+
+ // we only have a useful command if it is named
+ if (currentToken == MailcapTokenizer.EQUALS_TOKEN) {
+ // eat it
+
+ // parse the parameter value (which is autoquoted)
+ tokenizer.setIsAutoquoting(true);
+ currentToken = tokenizer.nextToken();
+ tokenizer.setIsAutoquoting(false);
+ if (currentToken != MailcapTokenizer.STRING_TOKEN) {
+ reportParseError(MailcapTokenizer.STRING_TOKEN,
+ currentToken, tokenizer.getCurrentTokenValue());
+ }
+ String paramValue =
+ tokenizer.getCurrentTokenValue();
+
+ // add the class to the list iff it is one we care about
+ if (paramName.startsWith("x-java-")) {
+ String commandName = paramName.substring(7);
+ // 7 == "x-java-".length
+
+ if (commandName.equals("fallback-entry") &&
+ paramValue.equalsIgnoreCase("true")) {
+ isFallback = true;
+ } else {
+
+ // setup the class entry list
+ if (LogSupport.isLoggable())
+ LogSupport.log(" Command: " + commandName +
+ ", Class: " + paramValue);
+ List classes = (List)commands.get(commandName);
+ if (classes == null) {
+ classes = new ArrayList();
+ commands.put(commandName, classes);
+ }
+ if (addReverse)
+ classes.add(0, paramValue);
+ else
+ classes.add(paramValue);
+ }
+ }
+
+ // set up the next iteration
+ currentToken = tokenizer.nextToken();
+ }
+ } while (currentToken == MailcapTokenizer.SEMICOLON_TOKEN);
+
+ Map masterHash = isFallback ? fallback_hash : type_hash;
+ Map curcommands =
+ (Map)masterHash.get(mimeType);
+ if (curcommands == null) {
+ masterHash.put(mimeType, commands);
+ } else {
+ if (LogSupport.isLoggable())
+ LogSupport.log("Merging commands for type " + mimeType);
+ // have to merge current and new commands
+ // first, merge list of classes for commands already known
+ Iterator cn = curcommands.keySet().iterator();
+ while (cn.hasNext()) {
+ String cmdName = (String)cn.next();
+ List ccv = (List)curcommands.get(cmdName);
+ List cv = (List)commands.get(cmdName);
+ if (cv == null)
+ continue;
+ // add everything in cv to ccv, if it's not already there
+ Iterator cvn = cv.iterator();
+ while (cvn.hasNext()) {
+ String clazz = (String)cvn.next();
+ if (!ccv.contains(clazz))
+ if (addReverse)
+ ccv.add(0, clazz);
+ else
+ ccv.add(clazz);
+ }
+ }
+ // now, add commands not previously known
+ cn = commands.keySet().iterator();
+ while (cn.hasNext()) {
+ String cmdName = (String)cn.next();
+ if (curcommands.containsKey(cmdName))
+ continue;
+ List cv = (List)commands.get(cmdName);
+ curcommands.put(cmdName, cv);
+ }
+ }
+ } else if (currentToken != MailcapTokenizer.EOI_TOKEN) {
+ reportParseError(MailcapTokenizer.EOI_TOKEN,
+ MailcapTokenizer.SEMICOLON_TOKEN,
+ currentToken, tokenizer.getCurrentTokenValue());
+ }
+ }
+
+ protected static void reportParseError(int expectedToken, int actualToken,
+ String actualTokenValue) throws MailcapParseException {
+ throw new MailcapParseException("Encountered a " +
+ MailcapTokenizer.nameForToken(actualToken) + " token (" +
+ actualTokenValue + ") while expecting a " +
+ MailcapTokenizer.nameForToken(expectedToken) + " token.");
+ }
+
+ protected static void reportParseError(int expectedToken,
+ int otherExpectedToken, int actualToken, String actualTokenValue)
+ throws MailcapParseException {
+ throw new MailcapParseException("Encountered a " +
+ MailcapTokenizer.nameForToken(actualToken) + " token (" +
+ actualTokenValue + ") while expecting a " +
+ MailcapTokenizer.nameForToken(expectedToken) + " or a " +
+ MailcapTokenizer.nameForToken(otherExpectedToken) + " token.");
+ }
+
+ protected static void reportParseError(int expectedToken,
+ int otherExpectedToken, int anotherExpectedToken, int actualToken,
+ String actualTokenValue) throws MailcapParseException {
+ if (LogSupport.isLoggable())
+ LogSupport.log("PARSE ERROR: " + "Encountered a " +
+ MailcapTokenizer.nameForToken(actualToken) + " token (" +
+ actualTokenValue + ") while expecting a " +
+ MailcapTokenizer.nameForToken(expectedToken) + ", a " +
+ MailcapTokenizer.nameForToken(otherExpectedToken) + ", or a " +
+ MailcapTokenizer.nameForToken(anotherExpectedToken) + " token.");
+ throw new MailcapParseException("Encountered a " +
+ MailcapTokenizer.nameForToken(actualToken) + " token (" +
+ actualTokenValue + ") while expecting a " +
+ MailcapTokenizer.nameForToken(expectedToken) + ", a " +
+ MailcapTokenizer.nameForToken(otherExpectedToken) + ", or a " +
+ MailcapTokenizer.nameForToken(anotherExpectedToken) + " token.");
+ }
+
+ /** for debugging
+ public static void main(String[] args) throws Exception {
+ Map masterHash = new HashMap();
+ for (int i = 0; i < args.length; ++i) {
+ System.out.println("Entry " + i + ": " + args[i]);
+ parseLine(args[i], masterHash);
+ }
+
+ Enumeration types = masterHash.keys();
+ while (types.hasMoreElements()) {
+ String key = (String)types.nextElement();
+ System.out.println("MIME Type: " + key);
+
+ Map commandHash = (Map)masterHash.get(key);
+ Enumeration commands = commandHash.keys();
+ while (commands.hasMoreElements()) {
+ String command = (String)commands.nextElement();
+ System.out.println(" Command: " + command);
+
+ Vector classes = (Vector)commandHash.get(command);
+ for (int i = 0; i < classes.size(); ++i) {
+ System.out.println(" Class: " +
+ (String)classes.elementAt(i));
+ }
+ }
+
+ System.out.println("");
+ }
+ }
+ */
+}
Added: trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapParseException.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapParseException.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapParseException.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,40 @@
+/*
+ * Copyright 1997 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.activation.registries;
+
+/**
+ * A class to encapsulate Mailcap parsing related exceptions
+ */
+public class MailcapParseException extends Exception {
+
+ public MailcapParseException() {
+ super();
+ }
+
+ public MailcapParseException(String inInfo) {
+ super(inInfo);
+ }
+}
Added: trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapTokenizer.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapTokenizer.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/activation/registries/MailcapTokenizer.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,321 @@
+/*
+ * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.activation.registries;
+
+/**
+ * A tokenizer for strings in the form of "foo/bar; prop1=val1; ... ".
+ * Useful for parsing MIME content types.
+ */
+public class MailcapTokenizer {
+
+ public static final int UNKNOWN_TOKEN = 0;
+ public static final int START_TOKEN = 1;
+ public static final int STRING_TOKEN = 2;
+ public static final int EOI_TOKEN = 5;
+ public static final int SLASH_TOKEN = '/';
+ public static final int SEMICOLON_TOKEN = ';';
+ public static final int EQUALS_TOKEN = '=';
+
+ /**
+ * Constructor
+ *
+ * @parameter inputString the string to tokenize
+ */
+ public MailcapTokenizer(String inputString) {
+ data = inputString;
+ dataIndex = 0;
+ dataLength = inputString.length();
+
+ currentToken = START_TOKEN;
+ currentTokenValue = "";
+
+ isAutoquoting = false;
+ autoquoteChar = ';';
+ }
+
+ /**
+ * Set whether auto-quoting is on or off.
+ *
+ * Auto-quoting means that all characters after the first
+ * non-whitespace, non-control character up to the auto-quote
+ * terminator character or EOI (minus any whitespace immediatley
+ * preceeding it) is considered a token.
+ *
+ * This is required for handling command strings in a mailcap entry.
+ */
+ public void setIsAutoquoting(boolean value) {
+ isAutoquoting = value;
+ }
+
+ /**
+ * Retrieve current token.
+ *
+ * @returns The current token value
+ */
+ public int getCurrentToken() {
+ return currentToken;
+ }
+
+ /*
+ * Get a String that describes the given token.
+ */
+ public static String nameForToken(int token) {
+ String name = "really unknown";
+
+ switch(token) {
+ case UNKNOWN_TOKEN:
+ name = "unknown";
+ break;
+ case START_TOKEN:
+ name = "start";
+ break;
+ case STRING_TOKEN:
+ name = "string";
+ break;
+ case EOI_TOKEN:
+ name = "EOI";
+ break;
+ case SLASH_TOKEN:
+ name = "'/'";
+ break;
+ case SEMICOLON_TOKEN:
+ name = "';'";
+ break;
+ case EQUALS_TOKEN:
+ name = "'='";
+ break;
+ }
+
+ return name;
+ }
+
+ /*
+ * Retrieve current token value.
+ *
+ * @returns A String containing the current token value
+ */
+ public String getCurrentTokenValue() {
+ return currentTokenValue;
+ }
+ /*
+ * Process the next token.
+ *
+ * @returns the next token
+ */
+ public int nextToken() {
+ if (dataIndex < dataLength) {
+ // skip white space
+ while ((dataIndex < dataLength) &&
+ (isWhiteSpaceChar(data.charAt(dataIndex)))) {
+ ++dataIndex;
+ }
+
+ if (dataIndex < dataLength) {
+ // examine the current character and see what kind of token we have
+ char c = data.charAt(dataIndex);
+ if (isAutoquoting) {
+ if (c == ';' || c == '=') {
+ currentToken = c;
+ currentTokenValue = new Character(c).toString();
+ ++dataIndex;
+ } else {
+ processAutoquoteToken();
+ }
+ } else {
+ if (isStringTokenChar(c)) {
+ processStringToken();
+ } else if ((c == '/') || (c == ';') || (c == '=')) {
+ currentToken = c;
+ currentTokenValue = new Character(c).toString();
+ ++dataIndex;
+ } else {
+ currentToken = UNKNOWN_TOKEN;
+ currentTokenValue = new Character(c).toString();
+ ++dataIndex;
+ }
+ }
+ } else {
+ currentToken = EOI_TOKEN;
+ currentTokenValue = null;
+ }
+ } else {
+ currentToken = EOI_TOKEN;
+ currentTokenValue = null;
+ }
+
+ return currentToken;
+ }
+
+ private void processStringToken() {
+ // capture the initial index
+ int initialIndex = dataIndex;
+
+ // skip to 1st non string token character
+ while ((dataIndex < dataLength) &&
+ isStringTokenChar(data.charAt(dataIndex))) {
+ ++dataIndex;
+ }
+
+ currentToken = STRING_TOKEN;
+ currentTokenValue = data.substring(initialIndex, dataIndex);
+ }
+
+ private void processAutoquoteToken() {
+ // capture the initial index
+ int initialIndex = dataIndex;
+
+ // now skip to the 1st non-escaped autoquote termination character
+ // XXX - doesn't actually consider escaping
+ boolean foundTerminator = false;
+ while ((dataIndex < dataLength) && !foundTerminator) {
+ char c = data.charAt(dataIndex);
+ if (c != autoquoteChar) {
+ ++dataIndex;
+ } else {
+ foundTerminator = true;
+ }
+ }
+
+ currentToken = STRING_TOKEN;
+ currentTokenValue =
+ fixEscapeSequences(data.substring(initialIndex, dataIndex));
+ }
+
+ private static boolean isSpecialChar(char c) {
+ boolean lAnswer = false;
+
+ switch(c) {
+ case '(':
+ case ')':
+ case '<':
+ case '>':
+ case '@':
+ case ',':
+ case ';':
+ case ':':
+ case '\\':
+ case '"':
+ case '/':
+ case '[':
+ case ']':
+ case '?':
+ case '=':
+ lAnswer = true;
+ break;
+ }
+
+ return lAnswer;
+ }
+
+ private static boolean isControlChar(char c) {
+ return Character.isISOControl(c);
+ }
+
+ private static boolean isWhiteSpaceChar(char c) {
+ return Character.isWhitespace(c);
+ }
+
+ private static boolean isStringTokenChar(char c) {
+ return !isSpecialChar(c) && !isControlChar(c) && !isWhiteSpaceChar(c);
+ }
+
+ private static String fixEscapeSequences(String inputString) {
+ int inputLength = inputString.length();
+ StringBuffer buffer = new StringBuffer();
+ buffer.ensureCapacity(inputLength);
+
+ for (int i = 0; i < inputLength; ++i) {
+ char currentChar = inputString.charAt(i);
+ if (currentChar != '\\') {
+ buffer.append(currentChar);
+ } else {
+ if (i < inputLength - 1) {
+ char nextChar = inputString.charAt(i + 1);
+ buffer.append(nextChar);
+
+ // force a skip over the next character too
+ ++i;
+ } else {
+ buffer.append(currentChar);
+ }
+ }
+ }
+
+ return buffer.toString();
+ }
+
+ private String data;
+ private int dataIndex;
+ private int dataLength;
+ private int currentToken;
+ private String currentTokenValue;
+ private boolean isAutoquoting;
+ private char autoquoteChar;
+
+ /*
+ public static void main(String[] args) {
+ for (int i = 0; i < args.length; ++i) {
+ MailcapTokenizer tokenizer = new MailcapTokenizer(args[i]);
+
+ System.out.println("Original: |" + args[i] + "|");
+
+ int currentToken = tokenizer.nextToken();
+ while (currentToken != EOI_TOKEN) {
+ switch(currentToken) {
+ case UNKNOWN_TOKEN:
+ System.out.println(" Unknown Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ case START_TOKEN:
+ System.out.println(" Start Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ case STRING_TOKEN:
+ System.out.println(" String Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ case EOI_TOKEN:
+ System.out.println(" EOI Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ case SLASH_TOKEN:
+ System.out.println(" Slash Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ case SEMICOLON_TOKEN:
+ System.out.println(" Semicolon Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ case EQUALS_TOKEN:
+ System.out.println(" Equals Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ default:
+ System.out.println(" Really Unknown Token: |" + tokenizer.getCurrentTokenValue() + "|");
+ break;
+ }
+
+ currentToken = tokenizer.nextToken();
+ }
+
+ System.out.println("");
+ }
+ }
+ */
+}
Added: trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeEntry.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeEntry.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeEntry.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,50 @@
+/*
+ * Copyright 1997-1998 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.activation.registries;
+
+import java.lang.*;
+
+public class MimeTypeEntry {
+ private String type;
+ private String extension;
+
+ public MimeTypeEntry(String mime_type, String file_ext) {
+ type = mime_type;
+ extension = file_ext;
+ }
+
+ public String getMIMEType() {
+ return type;
+ }
+
+ public String getFileExtension() {
+ return extension;
+ }
+
+ public String toString() {
+ return "MIMETypeEntry: " + type + ", " + extension;
+ }
+}
Added: trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeFile.java
===================================================================
--- trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeFile.java (rev 0)
+++ trunk/core/src/openjdk/com/com/sun/activation/registries/MimeTypeFile.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,317 @@
+/*
+ * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package com.sun.activation.registries;
+
+import java.io.*;
+import java.util.*;
+
+public class MimeTypeFile {
+ private String fname = null;
+ private Hashtable type_hash = new Hashtable();
+
+ /**
+ * The construtor that takes a filename as an argument.
+ *
+ * @param new_fname The file name of the mime types file.
+ */
+ public MimeTypeFile(String new_fname) throws IOException {
+ File mime_file = null;
+ FileReader fr = null;
+
+ fname = new_fname; // remember the file name
+
+ mime_file = new File(fname); // get a file object
+
+ fr = new FileReader(mime_file);
+
+ try {
+ parse(new BufferedReader(fr));
+ } finally {
+ try {
+ fr.close(); // close it
+ } catch (IOException e) {
+ // ignore it
+ }
+ }
+ }
+
+ public MimeTypeFile(InputStream is) throws IOException {
+ parse(new BufferedReader(new InputStreamReader(is, "iso-8859-1")));
+ }
+
+ /**
+ * Creates an empty DB.
+ */
+ public MimeTypeFile() {
+ }
+
+ /**
+ * get the MimeTypeEntry based on the file extension
+ */
+ public MimeTypeEntry getMimeTypeEntry(String file_ext) {
+ return (MimeTypeEntry)type_hash.get((Object)file_ext);
+ }
+
+ /**
+ * Get the MIME type string corresponding to the file extension.
+ */
+ public String getMIMETypeString(String file_ext) {
+ MimeTypeEntry entry = this.getMimeTypeEntry(file_ext);
+
+ if (entry != null)
+ return entry.getMIMEType();
+ else
+ return null;
+ }
+
+ /**
+ * Appends string of entries to the types registry, must be valid
+ * .mime.types format.
+ * A mime.types entry is one of two forms:
+ *
+ * type/subtype ext1 ext2 ...
+ * or
+ * type=type/subtype desc="description of type" exts=ext1,ext2,...
+ *
+ * Example:
+ * # this is a test
+ * audio/basic au
+ * text/plain txt text
+ * type=application/postscript exts=ps,eps
+ */
+ public void appendToRegistry(String mime_types) {
+ try {
+ parse(new BufferedReader(new StringReader(mime_types)));
+ } catch (IOException ex) {
+ // can't happen
+ }
+ }
+
+ /**
+ * Parse a stream of mime.types entries.
+ */
+ private void parse(BufferedReader buf_reader) throws IOException {
+ String line = null, prev = null;
+
+ while ((line = buf_reader.readLine()) != null) {
+ if (prev == null)
+ prev = line;
+ else
+ prev += line;
+ int end = prev.length();
+ if (prev.length() > 0 && prev.charAt(end - 1) == '\\') {
+ prev = prev.substring(0, end - 1);
+ continue;
+ }
+ this.parseEntry(prev);
+ prev = null;
+ }
+ if (prev != null)
+ this.parseEntry(prev);
+ }
+
+ /**
+ * Parse single mime.types entry.
+ */
+ private void parseEntry(String line) {
+ String mime_type = null;
+ String file_ext = null;
+ line = line.trim();
+
+ if (line.length() == 0) // empty line...
+ return; // BAIL!
+
+ // check to see if this is a comment line?
+ if (line.charAt(0) == '#')
+ return; // then we are done!
+
+ // is it a new format line or old format?
+ if (line.indexOf('=') > 0) {
+ // new format
+ LineTokenizer lt = new LineTokenizer(line);
+ while (lt.hasMoreTokens()) {
+ String name = lt.nextToken();
+ String value = null;
+ if (lt.hasMoreTokens() && lt.nextToken().equals("=") &&
+ lt.hasMoreTokens())
+ value = lt.nextToken();
+ if (value == null) {
+ if (LogSupport.isLoggable())
+ LogSupport.log("Bad .mime.types entry: " + line);
+ return;
+ }
+ if (name.equals("type"))
+ mime_type = value;
+ else if (name.equals("exts")) {
+ StringTokenizer st = new StringTokenizer(value, ",");
+ while (st.hasMoreTokens()) {
+ file_ext = st.nextToken();
+ MimeTypeEntry entry =
+ new MimeTypeEntry(mime_type, file_ext);
+ type_hash.put(file_ext, entry);
+ if (LogSupport.isLoggable())
+ LogSupport.log("Added: " + entry.toString());
+ }
+ }
+ }
+ } else {
+ // old format
+ // count the tokens
+ StringTokenizer strtok = new StringTokenizer(line);
+ int num_tok = strtok.countTokens();
+
+ if (num_tok == 0) // empty line
+ return;
+
+ mime_type = strtok.nextToken(); // get the MIME type
+
+ while (strtok.hasMoreTokens()) {
+ MimeTypeEntry entry = null;
+
+ file_ext = strtok.nextToken();
+ entry = new MimeTypeEntry(mime_type, file_ext);
+ type_hash.put(file_ext, entry);
+ if (LogSupport.isLoggable())
+ LogSupport.log("Added: " + entry.toString());
+ }
+ }
+ }
+
+ // for debugging
+ /*
+ public static void main(String[] argv) throws Exception {
+ MimeTypeFile mf = new MimeTypeFile(argv[0]);
+ System.out.println("ext " + argv[1] + " type " +
+ mf.getMIMETypeString(argv[1]));
+ System.exit(0);
+ }
+ */
+}
+
+class LineTokenizer {
+ private int currentPosition;
+ private int maxPosition;
+ private String str;
+ private Vector stack = new Vector();
+ private static final String singles = "="; // single character tokens
+
+ /**
+ * Constructs a tokenizer for the specified string.
+ * <p>
+ *
+ * @param str a string to be parsed.
+ */
+ public LineTokenizer(String str) {
+ currentPosition = 0;
+ this.str = str;
+ maxPosition = str.length();
+ }
+
+ /**
+ * Skips white space.
+ */
+ private void skipWhiteSpace() {
+ while ((currentPosition < maxPosition) &&
+ Character.isWhitespace(str.charAt(currentPosition))) {
+ currentPosition++;
+ }
+ }
+
+ /**
+ * Tests if there are more tokens available from this tokenizer's string.
+ *
+ * @return <code>true</code> if there are more tokens available from this
+ * tokenizer's string; <code>false</code> otherwise.
+ */
+ public boolean hasMoreTokens() {
+ if (stack.size() > 0)
+ return true;
+ skipWhiteSpace();
+ return (currentPosition < maxPosition);
+ }
+
+ /**
+ * Returns the next token from this tokenizer.
+ *
+ * @return the next token from this tokenizer.
+ * @exception NoSuchElementException if there are no more tokens in this
+ * tokenizer's string.
+ */
+ public String nextToken() {
+ int size = stack.size();
+ if (size > 0) {
+ String t = (String)stack.elementAt(size - 1);
+ stack.removeElementAt(size - 1);
+ return t;
+ }
+ skipWhiteSpace();
+
+ if (currentPosition >= maxPosition) {
+ throw new NoSuchElementException();
+ }
+
+ int start = currentPosition;
+ char c = str.charAt(start);
+ if (c == '"') {
+ currentPosition++;
+ boolean filter = false;
+ while (currentPosition < maxPosition) {
+ c = str.charAt(currentPosition++);
+ if (c == '\\') {
+ currentPosition++;
+ filter = true;
+ } else if (c == '"') {
+ String s;
+
+ if (filter) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = start + 1; i < currentPosition - 1; i++) {
+ c = str.charAt(i);
+ if (c != '\\')
+ sb.append(c);
+ }
+ s = sb.toString();
+ } else
+ s = str.substring(start + 1, currentPosition - 1);
+ return s;
+ }
+ }
+ } else if (singles.indexOf(c) >= 0) {
+ currentPosition++;
+ } else {
+ while ((currentPosition < maxPosition) &&
+ singles.indexOf(str.charAt(currentPosition)) < 0 &&
+ !Character.isWhitespace(str.charAt(currentPosition))) {
+ currentPosition++;
+ }
+ }
+ return str.substring(start, currentPosition);
+ }
+
+ public void pushToken(String token) {
+ stack.addElement(token);
+ }
+}
Added: trunk/core/src/openjdk/javax/javax/activation/ActivationDataFlavor.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/activation/ActivationDataFlavor.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/activation/ActivationDataFlavor.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,247 @@
+/*
+ * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.activation;
+
+import java.awt.datatransfer.DataFlavor;
+import java.io.IOException;
+import javax.activation.MimeType;
+
+/**
+ * The ActivationDataFlavor class is a special subclass of
+ * <code>java.awt.datatransfer.DataFlavor</code>. It allows the JAF to
+ * set all three values stored by the DataFlavor class via a new
+ * constructor. It also contains improved MIME parsing in the <code>equals
+ * </code> method. Except for the improved parsing, its semantics are
+ * identical to that of the JDK's DataFlavor class.
+ *
+ * @since 1.6
+ */
+
+public class ActivationDataFlavor extends DataFlavor {
+
+ /*
+ * Raison d'etre:
+ *
+ * The DataFlavor class included in JDK 1.1 has several limitations
+ * including piss poor MIME type parsing, and the limitation of
+ * only supporting serialized objects and InputStreams as
+ * representation objects. This class 'fixes' that.
+ */
+
+ // I think for now I'll keep copies of all the variables and
+ // then later I may choose try to better coexist with the base
+ // class *sigh*
+ private String mimeType = null;
+ private MimeType mimeObject = null;
+ private String humanPresentableName = null;
+ private Class representationClass = null;
+
+ /**
+ * Construct a DataFlavor that represents an arbitrary
+ * Java object. This constructor is an extension of the
+ * JDK's DataFlavor in that it allows the explicit setting
+ * of all three DataFlavor attributes.
+ * <p>
+ * The returned DataFlavor will have the following characteristics:
+ * <p>
+ * representationClass = representationClass<br>
+ * mimeType = mimeType<br>
+ * humanName = humanName
+ * <p>
+ *
+ * @param representationClass the class used in this DataFlavor
+ * @param mimeType the MIME type of the data represented by this class
+ * @param humanPresentableName the human presentable name of the flavor
+ */
+ public ActivationDataFlavor(Class representationClass,
+ String mimeType, String humanPresentableName) {
+ super(mimeType, humanPresentableName); // need to call super
+
+ // init private variables:
+ this.mimeType = mimeType;
+ this.humanPresentableName = humanPresentableName;
+ this.representationClass = representationClass;
+ }
+
+ /**
+ * Construct a DataFlavor that represents a MimeType.
+ * <p>
+ * The returned DataFlavor will have the following characteristics:
+ * <p>
+ * If the mimeType is "application/x-java-serialized-object;
+ * class=", the result is the same as calling new
+ * DataFlavor(Class.forName()) as above.
+ * <p>
+ * otherwise:
+ * <p>
+ * representationClass = InputStream<p>
+ * mimeType = mimeType<p>
+ *
+ * @param representationClass the class used in this DataFlavor
+ * @param humanPresentableName the human presentable name of the flavor
+ */
+ public ActivationDataFlavor(Class representationClass,
+ String humanPresentableName) {
+ super(representationClass, humanPresentableName);
+ this.mimeType = super.getMimeType();
+ this.representationClass = representationClass;
+ this.humanPresentableName = humanPresentableName;
+ }
+
+ /**
+ * Construct a DataFlavor that represents a MimeType.
+ * <p>
+ * The returned DataFlavor will have the following characteristics:
+ * <p>
+ * If the mimeType is "application/x-java-serialized-object; class=",
+ * the result is the same as calling new DataFlavor(Class.forName()) as
+ * above, otherwise:
+ * <p>
+ * representationClass = InputStream<p>
+ * mimeType = mimeType
+ *
+ * @param mimeType the MIME type of the data represented by this class
+ * @param humanPresentableName the human presentable name of the flavor
+ */
+ public ActivationDataFlavor(String mimeType, String humanPresentableName) {
+ super(mimeType, humanPresentableName);
+ this.mimeType = mimeType;
+ try {
+ this.representationClass = Class.forName("java.io.InputStream");
+ } catch (ClassNotFoundException ex) {
+ // XXX - should never happen, ignore it
+ }
+ this.humanPresentableName = humanPresentableName;
+ }
+
+ /**
+ * Return the MIME type for this DataFlavor.
+ *
+ * @return the MIME type
+ */
+ public String getMimeType() {
+ return mimeType;
+ }
+
+ /**
+ * Return the representation class.
+ *
+ * @return the representation class
+ */
+ public Class getRepresentationClass() {
+ return representationClass;
+ }
+
+ /**
+ * Return the Human Presentable name.
+ *
+ * @return the human presentable name
+ */
+ public String getHumanPresentableName() {
+ return humanPresentableName;
+ }
+
+ /**
+ * Set the human presentable name.
+ *
+ * @param humanPresentableName the name to set
+ */
+ public void setHumanPresentableName(String humanPresentableName) {
+ this.humanPresentableName = humanPresentableName;
+ }
+
+ /**
+ * Compares the DataFlavor passed in with this DataFlavor; calls
+ * the <code>isMimeTypeEqual</code> method.
+ *
+ * @param dataFlavor the DataFlavor to compare with
+ * @return true if the MIME type and representation class
+ * are the same
+ */
+ public boolean equals(DataFlavor dataFlavor) {
+ return (isMimeTypeEqual(dataFlavor) &&
+ dataFlavor.getRepresentationClass() == representationClass);
+ }
+
+ /**
+ * Is the string representation of the MIME type passed in equivalent
+ * to the MIME type of this DataFlavor. <p>
+ *
+ * ActivationDataFlavor delegates the comparison of MIME types to
+ * the MimeType class included as part of the JavaBeans Activation
+ * Framework. This provides a more robust comparison than is normally
+ * available in the DataFlavor class.
+ *
+ * @param mimeType the MIME type
+ * @return true if the same MIME type
+ */
+ public boolean isMimeTypeEqual(String mimeType) {
+ MimeType mt = null;
+ try {
+ if (mimeObject == null)
+ mimeObject = new MimeType(this.mimeType);
+ mt = new MimeType(mimeType);
+ } catch (MimeTypeParseException e) {}
+
+ return mimeObject.match(mt);
+ }
+
+ /**
+ * Called on DataFlavor for every MIME Type parameter to allow DataFlavor
+ * subclasses to handle special parameters like the text/plain charset
+ * parameters, whose values are case insensitive. (MIME type parameter
+ * values are supposed to be case sensitive).
+ * <p>
+ * This method is called for each parameter name/value pair and should
+ * return the normalized representation of the parameterValue.
+ * This method is never invoked by this implementation.
+ *
+ * @param parameterName the parameter name
+ * @param parameterValue the parameter value
+ * @return the normalized parameter value
+ * @deprecated
+ */
+ protected String normalizeMimeTypeParameter(String parameterName,
+ String parameterValue) {
+ return parameterValue;
+ }
+
+ /**
+ * Called for each MIME type string to give DataFlavor subtypes the
+ * opportunity to change how the normalization of MIME types is
+ * accomplished.
+ * One possible use would be to add default parameter/value pairs in cases
+ * where none are present in the MIME type string passed in.
+ * This method is never invoked by this implementation.
+ *
+ * @param mimeType the MIME type
+ * @return the normalized MIME type
+ * @deprecated
+ */
+ protected String normalizeMimeType(String mimeType) {
+ return mimeType;
+ }
+}
Added: trunk/core/src/openjdk/javax/javax/activation/CommandInfo.java
===================================================================
--- trunk/core/src/openjdk/javax/javax/activation/CommandInfo.java (rev 0)
+++ trunk/core/src/openjdk/javax/javax/activation/CommandInfo.java 2007-06-17 09:07:11 UTC (rev 3271)
@@ -0,0 +1,138 @@
+/*
+ * Copyright 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.activation;
+
+import java.io.*;
+import java.beans.Beans;
+
+/**
+ * The CommandInfo class is used by CommandMap implementations to
+ * describe the results of command requests. It provides the requestor
+ * with both the verb requested, as well as an instance of the
+ * bean. There is also a method that will return the name of the
+ * class that implements the command but <i>it is not guaranteed to
+ * return a valid value</i>. The reason for this is to allow CommandMap
+ * implmentations that subclass CommandInfo to provide special
+ * behavior. For example a CommandMap could dynamically generate
+ * JavaBeans. In this case, it might not be possible to create an
+ * object with all the correct state information solely from the class
+ * name.
+ *
+ * @since 1.6
+ */
+
+public class CommandInfo {
+ private String verb;
+ private String className;
+
+ /**
+ * The Constructor for CommandInfo.
+ * @param verb The command verb this CommandInfo decribes.
+ * @param className The command's fully qualified class name.
+ */
+ public CommandInfo(String verb, String className) {
+ this.verb = verb;
+ this.className = className;
+ }
+
+ /**
+ * Return the command verb.
+ *
+ * @return the command verb.
+ */
+ public String getCommandName() {
+ return verb;
+ }
+
+ /**
+ * Return the command's class name. <i>This method MAY return null in
+ * cases where a CommandMap subclassed CommandInfo for its
+ * own purposes.</i> In other words, it might not be possible to
+ * create the correct state in the command by merely knowing
+ * its class name. <b>DO NOT DEPEND ON THIS METHOD RETURNING
+ * A VALID VALUE!</b>
+ *
+ * @return The class name of the command, or <i>null</i>
+ */...
[truncated message content] |
|
From: <ls...@us...> - 2007-06-17 09:05:50
|
Revision: 3270
http://jnode.svn.sourceforge.net/jnode/?rev=3270&view=rev
Author: lsantha
Date: 2007-06-17 02:05:48 -0700 (Sun, 17 Jun 2007)
Log Message:
-----------
Openjdk integration.
Removed Paths:
-------------
trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java
Deleted: trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java
===================================================================
--- trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java 2007-06-17 07:38:28 UTC (rev 3269)
+++ trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java 2007-06-17 09:05:48 UTC (rev 3270)
@@ -1,113 +0,0 @@
-/* ReflectUtil.java - JSR 166 reflection hooks
- Copyright (C) 2006 Free Software Foundation
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package sun.reflect.misc;
-
-import java.lang.reflect.Modifier;
-
-public class ReflectUtil
-{
- // We use this inaccessible inner class as an argument type
- // in verifyMemberAccess. All current users of this method
- // in the JSR 166 RI pass 'null' for this argument, and
- // consequently we don't know what it means. Using a funny
- // type like this for the argument means that if the RI changes,
- // we will see a compilation error.
- private static class MustBeNull
- {
- }
-
- /**
- * Check if the current thread is allowed to access the package of
- * the declaringClass.
- *
- * @param declaringClass class name to check access to
- * @throws SecurityException if permission is denied
- * @throws NullPointerException if declaringClass is null
- */
- public static void checkPackageAccess(Class declaringClass)
- {
- SecurityManager sm;
- if ((sm = System.getSecurityManager()) != null)
- {
- while (declaringClass.isArray())
- declaringClass = declaringClass.getComponentType();
- String name = declaringClass.getName();
- int i = name.lastIndexOf('.');
- if (i != -1) // if declaringClass is a member of a package
- {
- name = name.substring(0, i);
- sm.checkPackageAccess(name);
- }
- }
- }
-
- /**
- * Perform access checks on a member of a class. This API is
- * derived from the public domain code in the JSR 166 reference
- * implementation.
- * @param caller the class requesting access to the member
- * @param declarer the declaring class of the member
- * @param ignored unknown parameter; always null
- * @param modifiers the modifiers on the member
- * @return true if access is granted, false otherwise
- */
- public static void ensureMemberAccess(Class caller,
- Class declarer,
- MustBeNull ignored,
- int modifiers)
- {
- // Same class, always ok.
- if (caller == declarer)
- return;
- // Public access is ok.
- if ((modifiers & Modifier.PUBLIC) != 0)
- return;
- // Protected access and request comes from
- // a subclass of the declarer -- ok.
- if ((modifiers & Modifier.PROTECTED) != 0
- && declarer.isAssignableFrom(caller))
- return;
- // Package-private access, or protected access,
- // and the packages are the same --ok.
- if ((modifiers & Modifier.PRIVATE) == 0
- && caller.getPackage() == declarer.getPackage())
- return;
- // Otherwise, no.
- throw new IllegalAccessError();
- }
-}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|